Fix `org-set-visibility-according-to-property'
[org-mode/org-kjn.git] / lisp / org.el
blob1222a6979fc97971dcd971eb4f4d0f285d4e1ee3
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-calc-current-TBLFM "org-table" (&optional arg))
150 (declare-function org-id-get-create "org-id" (&optional force))
151 (declare-function org-add-archive-files "org-archive" (files))
152 (declare-function org-id-find-id-file "org-id" (id))
153 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
154 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
155 (declare-function org-agenda-redo "org-agenda" (&optional all))
156 (declare-function org-table-align "org-table" ())
157 (declare-function org-table-begin "org-table" (&optional table-type))
158 (declare-function org-table-blank-field "org-table" ())
159 (declare-function org-table-end "org-table" (&optional table-type))
160 (declare-function org-table-end-of-field "org-table" (&optional n))
161 (declare-function org-table-insert-row "org-table" (&optional arg))
162 (declare-function org-table-paste-rectangle "org-table" ())
163 (declare-function org-table-maybe-eval-formula "org-table" ())
164 (declare-function org-table-maybe-recalculate-line "org-table" ())
165 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
166 (declare-function org-plot/gnuplot "org-plot" (&optional params))
168 (declare-function org-element-at-point "org-element" ())
169 (declare-function org-element-cache-reset "org-element" (&optional all))
170 (declare-function org-element-cache-refresh "org-element" (pos))
171 (declare-function org-element-contents "org-element" (element))
172 (declare-function org-element-context "org-element" (&optional element))
173 (declare-function org-element-interpret-data "org-element"
174 (data &optional parent))
175 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
176 (declare-function org-element-parse-buffer "org-element"
177 (&optional granularity visible-only))
178 (declare-function org-element-property "org-element" (property element))
179 (declare-function org-element-put-property "org-element"
180 (element property value))
181 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
182 (declare-function org-element-parse-buffer "org-element"
183 (&optional granularity visible-only))
184 (declare-function org-element-type "org-element" (element))
186 (defsubst org-uniquify (list)
187 "Non-destructively remove duplicate elements from LIST."
188 (let ((res (copy-sequence list))) (delete-dups res)))
190 (defsubst org-get-at-bol (property)
191 "Get text property PROPERTY at the beginning of line."
192 (get-text-property (point-at-bol) property))
194 (defsubst org-trim (s)
195 "Remove whitespace at the beginning and the end of string S."
196 (replace-regexp-in-string
197 "\\`[ \t\n\r]+" ""
198 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
200 ;; load languages based on value of `org-babel-load-languages'
201 (defvar org-babel-load-languages)
203 ;;;###autoload
204 (defun org-babel-do-load-languages (sym value)
205 "Load the languages defined in `org-babel-load-languages'."
206 (set-default sym value)
207 (mapc (lambda (pair)
208 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
209 (if active
210 (progn
211 (require (intern (concat "ob-" lang))))
212 (progn
213 (funcall 'fmakunbound
214 (intern (concat "org-babel-execute:" lang)))
215 (funcall 'fmakunbound
216 (intern (concat "org-babel-expand-body:" lang)))))))
217 org-babel-load-languages))
219 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
220 ;;;###autoload
221 (defun org-babel-load-file (file &optional compile)
222 "Load Emacs Lisp source code blocks in the Org-mode FILE.
223 This function exports the source code using `org-babel-tangle'
224 and then loads the resulting file using `load-file'. With prefix
225 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
226 file to byte-code before it is loaded."
227 (interactive "fFile to load: \nP")
228 (let* ((age (lambda (file)
229 (float-time
230 (time-subtract (current-time)
231 (nth 5 (or (file-attributes (file-truename file))
232 (file-attributes file)))))))
233 (base-name (file-name-sans-extension file))
234 (exported-file (concat base-name ".el")))
235 ;; tangle if the org-mode file is newer than the elisp file
236 (unless (and (file-exists-p exported-file)
237 (> (funcall age file) (funcall age exported-file)))
238 (setq exported-file
239 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
240 (message "%s %s"
241 (if compile
242 (progn (byte-compile-file exported-file 'load)
243 "Compiled and loaded")
244 (progn (load-file exported-file) "Loaded"))
245 exported-file)))
247 (defcustom org-babel-load-languages '((emacs-lisp . t))
248 "Languages which can be evaluated in Org-mode buffers.
249 This list can be used to load support for any of the languages
250 below, note that each language will depend on a different set of
251 system executables and/or Emacs modes. When a language is
252 \"loaded\", then code blocks in that language can be evaluated
253 with `org-babel-execute-src-block' bound by default to C-c
254 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
255 be set to remove code block evaluation from the C-c C-c
256 keybinding. By default only Emacs Lisp (which has no
257 requirements) is loaded."
258 :group 'org-babel
259 :set 'org-babel-do-load-languages
260 :version "24.1"
261 :type '(alist :tag "Babel Languages"
262 :key-type
263 (choice
264 (const :tag "Awk" awk)
265 (const :tag "C" C)
266 (const :tag "R" R)
267 (const :tag "Asymptote" asymptote)
268 (const :tag "Calc" calc)
269 (const :tag "Clojure" clojure)
270 (const :tag "CSS" css)
271 (const :tag "Ditaa" ditaa)
272 (const :tag "Dot" dot)
273 (const :tag "Emacs Lisp" emacs-lisp)
274 (const :tag "Forth" forth)
275 (const :tag "Fortran" fortran)
276 (const :tag "Gnuplot" gnuplot)
277 (const :tag "Haskell" haskell)
278 (const :tag "IO" io)
279 (const :tag "J" J)
280 (const :tag "Java" java)
281 (const :tag "Javascript" js)
282 (const :tag "LaTeX" latex)
283 (const :tag "Ledger" ledger)
284 (const :tag "Lilypond" lilypond)
285 (const :tag "Lisp" lisp)
286 (const :tag "Makefile" makefile)
287 (const :tag "Maxima" maxima)
288 (const :tag "Matlab" matlab)
289 (const :tag "Mscgen" mscgen)
290 (const :tag "Ocaml" ocaml)
291 (const :tag "Octave" octave)
292 (const :tag "Org" org)
293 (const :tag "Perl" perl)
294 (const :tag "Pico Lisp" picolisp)
295 (const :tag "PlantUML" plantuml)
296 (const :tag "Python" python)
297 (const :tag "Ruby" ruby)
298 (const :tag "Sass" sass)
299 (const :tag "Scala" scala)
300 (const :tag "Scheme" scheme)
301 (const :tag "Screen" screen)
302 (const :tag "Shell Script" shell)
303 (const :tag "Shen" shen)
304 (const :tag "Sql" sql)
305 (const :tag "Sqlite" sqlite)
306 (const :tag "ebnf2ps" ebnf2ps))
307 :value-type (boolean :tag "Activate" :value t)))
309 ;;;; Customization variables
310 (defcustom org-clone-delete-id nil
311 "Remove ID property of clones of a subtree.
312 When non-nil, clones of a subtree don't inherit the ID property.
313 Otherwise they inherit the ID property with a new unique
314 identifier."
315 :type 'boolean
316 :version "24.1"
317 :group 'org-id)
319 ;;; Version
320 (org-check-version)
322 ;;;###autoload
323 (defun org-version (&optional here full message)
324 "Show the org-mode version.
325 Interactively, or when MESSAGE is non-nil, show it in echo area.
326 With prefix argument, or when HERE is non-nil, insert it at point.
327 In non-interactive uses, a reduced version string is output unless
328 FULL is given."
329 (interactive (list current-prefix-arg t (not current-prefix-arg)))
330 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
331 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
332 (load-suffixes (list ".el"))
333 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
334 (org-trash (or
335 (and (fboundp 'org-release) (fboundp 'org-git-version))
336 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
337 (load-suffixes save-load-suffixes)
338 (org-version (org-release))
339 (git-version (org-git-version))
340 (version (format "Org-mode version %s (%s @ %s)"
341 org-version
342 git-version
343 (if org-install-dir
344 (if (string= org-dir org-install-dir)
345 org-install-dir
346 (concat "mixed installation! " org-install-dir " and " org-dir))
347 "org-loaddefs.el can not be found!")))
348 (version1 (if full version org-version)))
349 (when here (insert version1))
350 (when message (message "%s" version1))
351 version1))
353 (defconst org-version (org-version))
356 ;;; Syntax Constants
358 ;;;; Block
360 (defconst org-block-regexp
361 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
362 "Regular expression for hiding blocks.")
364 (defconst org-dblock-start-re
365 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
366 "Matches the start line of a dynamic block, with parameters.")
368 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
369 "Matches the end of a dynamic block.")
371 ;;;; Clock and Planning
373 (defconst org-clock-string "CLOCK:"
374 "String used as prefix for timestamps clocking work hours on an item.")
376 (defconst org-closed-string "CLOSED:"
377 "String used as the prefix for timestamps logging closing a TODO entry.")
379 (defconst org-deadline-string "DEADLINE:"
380 "String to mark deadline entries.
381 A deadline is this string, followed by a time stamp. Should be a word,
382 terminated by a colon. You can insert a schedule keyword and
383 a timestamp with \\[org-deadline].")
385 (defconst org-scheduled-string "SCHEDULED:"
386 "String to mark scheduled TODO entries.
387 A schedule is this string, followed by a time stamp. Should be a word,
388 terminated by a colon. You can insert a schedule keyword and
389 a timestamp with \\[org-schedule].")
391 (defconst org-ds-keyword-length
392 (+ 2
393 (apply #'max
394 (mapcar #'length
395 (list org-deadline-string org-scheduled-string
396 org-clock-string org-closed-string))))
397 "Maximum length of the DEADLINE and SCHEDULED keywords.")
399 (defconst org-planning-line-re
400 (concat "^[ \t]*"
401 (regexp-opt
402 (list org-closed-string org-deadline-string org-scheduled-string)
404 "Matches a line with planning info.
405 Matched keyword is in group 1.")
407 (defconst org-clock-line-re
408 (concat "^[ \t]*" org-clock-string)
409 "Matches a line with clock info.")
411 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
412 "Matches the DEADLINE keyword.")
414 (defconst org-deadline-time-regexp
415 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
416 "Matches the DEADLINE keyword together with a time stamp.")
418 (defconst org-deadline-time-hour-regexp
419 (concat "\\<" org-deadline-string
420 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
421 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
423 (defconst org-deadline-line-regexp
424 (concat "\\<\\(" org-deadline-string "\\).*")
425 "Matches the DEADLINE keyword and the rest of the line.")
427 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
428 "Matches the SCHEDULED keyword.")
430 (defconst org-scheduled-time-regexp
431 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
432 "Matches the SCHEDULED keyword together with a time stamp.")
434 (defconst org-scheduled-time-hour-regexp
435 (concat "\\<" org-scheduled-string
436 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
437 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
439 (defconst org-closed-time-regexp
440 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
441 "Matches the CLOSED keyword together with a time stamp.")
443 (defconst org-keyword-time-regexp
444 (concat "\\<"
445 (regexp-opt
446 (list org-scheduled-string org-deadline-string org-closed-string
447 org-clock-string)
449 " *[[<]\\([^]>]+\\)[]>]")
450 "Matches any of the 4 keywords, together with the time stamp.")
452 (defconst org-keyword-time-not-clock-regexp
453 (concat
454 "\\<"
455 (regexp-opt
456 (list org-scheduled-string org-deadline-string org-closed-string) t)
457 " *[[<]\\([^]>]+\\)[]>]")
458 "Matches any of the 3 keywords, together with the time stamp.")
460 (defconst org-maybe-keyword-time-regexp
461 (concat "\\(\\<"
462 (regexp-opt
463 (list org-scheduled-string org-deadline-string org-closed-string
464 org-clock-string)
466 "\\)?"
467 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
468 "\\|"
469 "<%%([^\r\n>]*>\\)")
470 "Matches a timestamp, possibly preceded by a keyword.")
472 (defconst org-all-time-keywords
473 (mapcar (lambda (w) (substring w 0 -1))
474 (list org-scheduled-string org-deadline-string
475 org-clock-string org-closed-string))
476 "List of time keywords.")
478 ;;;; Drawer
480 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
481 "Matches first or last line of a hidden block.
482 Group 1 contains drawer's name or \"END\".")
484 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
485 "Regular expression matching the first line of a property drawer.")
487 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
488 "Regular expression matching the last line of a property drawer.")
490 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
491 "Regular expression matching the first line of a clock drawer.")
493 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
494 "Regular expression matching the last line of a clock drawer.")
496 (defconst org-property-drawer-re
497 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
498 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*"
499 "[ \t]*:END:[ \t]*$")
500 "Matches an entire property drawer.")
502 (defconst org-clock-drawer-re
503 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
504 org-clock-drawer-end-re "\\)\n?")
505 "Matches an entire clock drawer.")
507 ;;;; Headline
509 (defconst org-heading-keyword-regexp-format
510 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
511 "Printf format for a regexp matching a headline with some keyword.
512 This regexp will match the headline of any node which has the
513 exact keyword that is put into the format. The keyword isn't in
514 any group by default, but the stars and the body are.")
516 (defconst org-heading-keyword-maybe-regexp-format
517 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
518 "Printf format for a regexp matching a headline, possibly with some keyword.
519 This regexp can match any headline with the specified keyword, or
520 without a keyword. The keyword isn't in any group by default,
521 but the stars and the body are.")
523 (defconst org-archive-tag "ARCHIVE"
524 "The tag that marks a subtree as archived.
525 An archived subtree does not open during visibility cycling, and does
526 not contribute to the agenda listings.")
528 (defconst org-comment-string "COMMENT"
529 "Entries starting with this keyword will never be exported.
530 An entry can be toggled between COMMENT and normal with
531 \\[org-toggle-comment].")
534 ;;;; LaTeX Environments and Fragments
536 (defconst org-latex-regexps
537 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
538 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
539 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
540 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
541 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
542 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
543 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
544 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
545 "Regular expressions for matching embedded LaTeX.")
547 ;;;; Node Property
549 (defconst org-effort-property "Effort"
550 "The property that is being used to keep track of effort estimates.
551 Effort estimates given in this property need to have the format H:MM.")
553 ;;;; Table
555 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
556 "Detect an org-type or table-type table.")
558 (defconst org-table-line-regexp "^[ \t]*|"
559 "Detect an org-type table line.")
561 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
562 "Detect an org-type table line.")
564 (defconst org-table-hline-regexp "^[ \t]*|-"
565 "Detect an org-type table hline.")
567 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
568 "Detect a table-type table hline.")
570 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
571 "Detect the first line outside a table when searching from within it.
572 This works for both table types.")
574 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
575 "Detect a #+TBLFM line.")
577 ;;;; Timestamp
579 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
580 "Regular expression for fast time stamp matching.")
582 (defconst org-ts-regexp-inactive
583 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
584 "Regular expression for fast inactive time stamp matching.")
586 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
587 "Regular expression for fast time stamp matching.")
589 (defconst org-ts-regexp0
590 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
591 "Regular expression matching time strings for analysis.
592 This one does not require the space after the date, so it can be used
593 on a string that terminates immediately after the date.")
595 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
596 "Regular expression matching time strings for analysis.")
598 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
599 "Regular expression matching time stamps, with groups.")
601 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
602 "Regular expression matching time stamps (also [..]), with groups.")
604 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
605 "Regular expression matching a time stamp range.")
607 (defconst org-tr-regexp-both
608 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
609 "Regular expression matching a time stamp range.")
611 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
612 org-ts-regexp "\\)?")
613 "Regular expression matching a time stamp or time stamp range.")
615 (defconst org-tsr-regexp-both
616 (concat org-ts-regexp-both "\\(--?-?"
617 org-ts-regexp-both "\\)?")
618 "Regular expression matching a time stamp or time stamp range.
619 The time stamps may be either active or inactive.")
621 (defconst org-repeat-re
622 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
623 "Regular expression for specifying repeated events.
624 After a match, group 1 contains the repeat expression.")
626 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
627 "Formats for `format-time-string' which are used for time stamps.")
630 ;;; The custom variables
632 (defgroup org nil
633 "Outline-based notes management and organizer."
634 :tag "Org"
635 :group 'outlines
636 :group 'calendar)
638 (defcustom org-mode-hook nil
639 "Mode hook for Org-mode, run after the mode was turned on."
640 :group 'org
641 :type 'hook)
643 (defcustom org-load-hook nil
644 "Hook that is run after org.el has been loaded."
645 :group 'org
646 :type 'hook)
648 (defcustom org-log-buffer-setup-hook nil
649 "Hook that is run after an Org log buffer is created."
650 :group 'org
651 :version "24.1"
652 :type 'hook)
654 (defvar org-modules) ; defined below
655 (defvar org-modules-loaded nil
656 "Have the modules been loaded already?")
658 (defun org-load-modules-maybe (&optional force)
659 "Load all extensions listed in `org-modules'."
660 (when (or force (not org-modules-loaded))
661 (mapc (lambda (ext)
662 (condition-case nil (require ext)
663 (error (message "Problems while trying to load feature `%s'" ext))))
664 org-modules)
665 (setq org-modules-loaded t)))
667 (defun org-set-modules (var value)
668 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
669 (set var value)
670 (when (featurep 'org)
671 (org-load-modules-maybe 'force)
672 (org-element-cache-reset 'all)))
674 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
675 "Modules that should always be loaded together with org.el.
677 If a description starts with <C>, the file is not part of Emacs
678 and loading it will require that you have downloaded and properly
679 installed the Org mode distribution.
681 You can also use this system to load external packages (i.e. neither Org
682 core modules, nor modules from the CONTRIB directory). Just add symbols
683 to the end of the list. If the package is called org-xyz.el, then you need
684 to add the symbol `xyz', and the package must have a call to:
686 \(provide 'org-xyz)
688 For export specific modules, see also `org-export-backends'."
689 :group 'org
690 :set 'org-set-modules
691 :version "24.4"
692 :package-version '(Org . "8.0")
693 :type
694 '(set :greedy t
695 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
696 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
697 (const :tag " crypt: Encryption of subtrees" org-crypt)
698 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
699 (const :tag " docview: Links to doc-view buffers" org-docview)
700 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
701 (const :tag " habit: Track your consistency with habits" org-habit)
702 (const :tag " id: Global IDs for identifying entries" org-id)
703 (const :tag " info: Links to Info nodes" org-info)
704 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
705 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
706 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
707 (const :tag " mouse: Additional mouse support" org-mouse)
708 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
709 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
710 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
712 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
713 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
714 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
715 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
716 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
717 (const :tag "C collector: Collect properties into tables" org-collector)
718 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
719 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
720 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
721 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
722 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
723 (const :tag "C eval: Include command output as text" org-eval)
724 (const :tag "C eww: Store link to url of eww" org-eww)
725 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
726 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
727 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
728 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
729 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
730 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
731 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
732 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
733 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
734 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
735 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
736 (const :tag "C mew: Links to Mew folders/messages" org-mew)
737 (const :tag "C mtags: Support for muse-like tags" org-mtags)
738 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
739 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
740 (const :tag "C registry: A registry for Org-mode links" org-registry)
741 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
742 (const :tag "C secretary: Team management with org-mode" org-secretary)
743 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
744 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
745 (const :tag "C track: Keep up with Org-mode development" org-track)
746 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
747 (const :tag "C vm: Links to VM folders/messages" org-vm)
748 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
749 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
750 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
752 (defvar org-export--registered-backends) ; From ox.el.
753 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
754 (declare-function org-export-backend-name "ox" (backend))
755 (defcustom org-export-backends '(ascii html icalendar latex)
756 "List of export back-ends that should be always available.
758 If a description starts with <C>, the file is not part of Emacs
759 and loading it will require that you have downloaded and properly
760 installed the Org mode distribution.
762 Unlike to `org-modules', libraries in this list will not be
763 loaded along with Org, but only once the export framework is
764 needed.
766 This variable needs to be set before org.el is loaded. If you
767 need to make a change while Emacs is running, use the customize
768 interface or run the following code, where VAL stands for the new
769 value of the variable, after updating it:
771 \(progn
772 \(setq org-export--registered-backends
773 \(org-remove-if-not
774 \(lambda (backend)
775 \(let ((name (org-export-backend-name backend)))
776 \(or (memq name val)
777 \(catch 'parentp
778 \(dolist (b val)
779 \(and (org-export-derived-backend-p b name)
780 \(throw 'parentp t)))))))
781 org-export--registered-backends))
782 \(let ((new-list (mapcar 'org-export-backend-name
783 org-export--registered-backends)))
784 \(dolist (backend val)
785 \(cond
786 \((not (load (format \"ox-%s\" backend) t t))
787 \(message \"Problems while trying to load export back-end `%s'\"
788 backend))
789 \((not (memq backend new-list)) (push backend new-list))))
790 \(set-default 'org-export-backends new-list)))
792 Adding a back-end to this list will also pull the back-end it
793 depends on, if any."
794 :group 'org
795 :group 'org-export
796 :version "24.4"
797 :package-version '(Org . "8.0")
798 :initialize 'custom-initialize-set
799 :set (lambda (var val)
800 (if (not (featurep 'ox)) (set-default var val)
801 ;; Any back-end not required anymore (not present in VAL and not
802 ;; a parent of any back-end in the new value) is removed from the
803 ;; list of registered back-ends.
804 (setq org-export--registered-backends
805 (org-remove-if-not
806 (lambda (backend)
807 (let ((name (org-export-backend-name backend)))
808 (or (memq name val)
809 (catch 'parentp
810 (dolist (b val)
811 (and (org-export-derived-backend-p b name)
812 (throw 'parentp t)))))))
813 org-export--registered-backends))
814 ;; Now build NEW-LIST of both new back-ends and required
815 ;; parents.
816 (let ((new-list (mapcar 'org-export-backend-name
817 org-export--registered-backends)))
818 (dolist (backend val)
819 (cond
820 ((not (load (format "ox-%s" backend) t t))
821 (message "Problems while trying to load export back-end `%s'"
822 backend))
823 ((not (memq backend new-list)) (push backend new-list))))
824 ;; Set VAR to that list with fixed dependencies.
825 (set-default var new-list))))
826 :type '(set :greedy t
827 (const :tag " ascii Export buffer to ASCII format" ascii)
828 (const :tag " beamer Export buffer to Beamer presentation" beamer)
829 (const :tag " html Export buffer to HTML format" html)
830 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
831 (const :tag " latex Export buffer to LaTeX format" latex)
832 (const :tag " man Export buffer to MAN format" man)
833 (const :tag " md Export buffer to Markdown format" md)
834 (const :tag " odt Export buffer to ODT format" odt)
835 (const :tag " org Export buffer to Org format" org)
836 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
837 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
838 (const :tag "C deck Export buffer to deck.js presentations" deck)
839 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
840 (const :tag "C groff Export buffer to Groff format" groff)
841 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
842 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
843 (const :tag "C s5 Export buffer to s5 presentations" s5)
844 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
846 (eval-after-load 'ox
847 '(mapc
848 (lambda (backend)
849 (condition-case nil (require (intern (format "ox-%s" backend)))
850 (error (message "Problems while trying to load export back-end `%s'"
851 backend))))
852 org-export-backends))
854 (defcustom org-support-shift-select nil
855 "Non-nil means make shift-cursor commands select text when possible.
857 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
858 start selecting a region, or enlarge regions started in this way.
859 In Org-mode, in special contexts, these same keys are used for
860 other purposes, important enough to compete with shift selection.
861 Org tries to balance these needs by supporting `shift-select-mode'
862 outside these special contexts, under control of this variable.
864 The default of this variable is nil, to avoid confusing behavior. Shifted
865 cursor keys will then execute Org commands in the following contexts:
866 - on a headline, changing TODO state (left/right) and priority (up/down)
867 - on a time stamp, changing the time
868 - in a plain list item, changing the bullet type
869 - in a property definition line, switching between allowed values
870 - in the BEGIN line of a clock table (changing the time block).
871 Outside these contexts, the commands will throw an error.
873 When this variable is t and the cursor is not in a special
874 context, Org-mode will support shift-selection for making and
875 enlarging regions. To make this more effective, the bullet
876 cycling will no longer happen anywhere in an item line, but only
877 if the cursor is exactly on the bullet.
879 If you set this variable to the symbol `always', then the keys
880 will not be special in headlines, property lines, and item lines,
881 to make shift selection work there as well. If this is what you
882 want, you can use the following alternative commands: `C-c C-t'
883 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
884 can be used to switch TODO sets, `C-c -' to cycle item bullet
885 types, and properties can be edited by hand or in column view.
887 However, when the cursor is on a timestamp, shift-cursor commands
888 will still edit the time stamp - this is just too good to give up.
890 XEmacs user should have this variable set to nil, because
891 `shift-select-mode' is in Emacs 23 or later only."
892 :group 'org
893 :type '(choice
894 (const :tag "Never" nil)
895 (const :tag "When outside special context" t)
896 (const :tag "Everywhere except timestamps" always)))
898 (defcustom org-loop-over-headlines-in-active-region nil
899 "Shall some commands act upon headlines in the active region?
901 When set to `t', some commands will be performed in all headlines
902 within the active region.
904 When set to `start-level', some commands will be performed in all
905 headlines within the active region, provided that these headlines
906 are of the same level than the first one.
908 When set to a string, those commands will be performed on the
909 matching headlines within the active region. Such string must be
910 a tags/property/todo match as it is used in the agenda tags view.
912 The list of commands is: `org-schedule', `org-deadline',
913 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
914 `org-archive-to-archive-sibling'. The archiving commands skip
915 already archived entries."
916 :type '(choice (const :tag "Don't loop" nil)
917 (const :tag "All headlines in active region" t)
918 (const :tag "In active region, headlines at the same level than the first one" start-level)
919 (string :tag "Tags/Property/Todo matcher"))
920 :version "24.1"
921 :group 'org-todo
922 :group 'org-archive)
924 (defgroup org-startup nil
925 "Options concerning startup of Org-mode."
926 :tag "Org Startup"
927 :group 'org)
929 (defcustom org-startup-folded t
930 "Non-nil means entering Org-mode will switch to OVERVIEW.
931 This can also be configured on a per-file basis by adding one of
932 the following lines anywhere in the buffer:
934 #+STARTUP: fold (or `overview', this is equivalent)
935 #+STARTUP: nofold (or `showall', this is equivalent)
936 #+STARTUP: content
937 #+STARTUP: showeverything
939 By default, this option is ignored when Org opens agenda files
940 for the first time. If you want the agenda to honor the startup
941 option, set `org-agenda-inhibit-startup' to nil."
942 :group 'org-startup
943 :type '(choice
944 (const :tag "nofold: show all" nil)
945 (const :tag "fold: overview" t)
946 (const :tag "content: all headlines" content)
947 (const :tag "show everything, even drawers" showeverything)))
949 (defcustom org-startup-truncated t
950 "Non-nil means entering Org-mode will set `truncate-lines'.
951 This is useful since some lines containing links can be very long and
952 uninteresting. Also tables look terrible when wrapped."
953 :group 'org-startup
954 :type 'boolean)
956 (defcustom org-startup-indented nil
957 "Non-nil means turn on `org-indent-mode' on startup.
958 This can also be configured on a per-file basis by adding one of
959 the following lines anywhere in the buffer:
961 #+STARTUP: indent
962 #+STARTUP: noindent"
963 :group 'org-structure
964 :type '(choice
965 (const :tag "Not" nil)
966 (const :tag "Globally (slow on startup in large files)" t)))
968 (defcustom org-use-sub-superscripts t
969 "Non-nil means interpret \"_\" and \"^\" for display.
971 If you want to control how Org exports those characters, see
972 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
973 used to be an alias for `org-export-with-sub-superscripts' in
974 Org <8.0, it is not anymore.
976 When this option is turned on, you can use TeX-like syntax for
977 sub- and superscripts within the buffer. Several characters after
978 \"_\" or \"^\" will be considered as a single item - so grouping
979 with {} is normally not needed. For example, the following things
980 will be parsed as single sub- or superscripts:
982 10^24 or 10^tau several digits will be considered 1 item.
983 10^-12 or 10^-tau a leading sign with digits or a word
984 x^2-y^3 will be read as x^2 - y^3, because items are
985 terminated by almost any nonword/nondigit char.
986 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
988 Still, ambiguity is possible. So when in doubt, use {} to enclose
989 the sub/superscript. If you set this variable to the symbol `{}',
990 the braces are *required* in order to trigger interpretations as
991 sub/superscript. This can be helpful in documents that need \"_\"
992 frequently in plain text."
993 :group 'org-startup
994 :version "24.4"
995 :package-version '(Org . "8.0")
996 :type '(choice
997 (const :tag "Always interpret" t)
998 (const :tag "Only with braces" {})
999 (const :tag "Never interpret" nil)))
1001 (defcustom org-startup-with-beamer-mode nil
1002 "Non-nil means turn on `org-beamer-mode' on startup.
1003 This can also be configured on a per-file basis by adding one of
1004 the following lines anywhere in the buffer:
1006 #+STARTUP: beamer"
1007 :group 'org-startup
1008 :version "24.1"
1009 :type 'boolean)
1011 (defcustom org-startup-align-all-tables nil
1012 "Non-nil means align all tables when visiting a file.
1013 This is useful when the column width in tables is forced with <N> cookies
1014 in table fields. Such tables will look correct only after the first re-align.
1015 This can also be configured on a per-file basis by adding one of
1016 the following lines anywhere in the buffer:
1017 #+STARTUP: align
1018 #+STARTUP: noalign"
1019 :group 'org-startup
1020 :type 'boolean)
1022 (defcustom org-startup-with-inline-images nil
1023 "Non-nil means show inline images when loading a new Org file.
1024 This can also be configured on a per-file basis by adding one of
1025 the following lines anywhere in the buffer:
1026 #+STARTUP: inlineimages
1027 #+STARTUP: noinlineimages"
1028 :group 'org-startup
1029 :version "24.1"
1030 :type 'boolean)
1032 (defcustom org-startup-with-latex-preview nil
1033 "Non-nil means preview LaTeX fragments when loading a new Org file.
1035 This can also be configured on a per-file basis by adding one of
1036 the following lines anywhere in the buffer:
1037 #+STARTUP: latexpreview
1038 #+STARTUP: nolatexpreview"
1039 :group 'org-startup
1040 :version "24.4"
1041 :package-version '(Org . "8.0")
1042 :type 'boolean)
1044 (defcustom org-insert-mode-line-in-empty-file nil
1045 "Non-nil means insert the first line setting Org-mode in empty files.
1046 When the function `org-mode' is called interactively in an empty file, this
1047 normally means that the file name does not automatically trigger Org-mode.
1048 To ensure that the file will always be in Org-mode in the future, a
1049 line enforcing Org-mode will be inserted into the buffer, if this option
1050 has been set."
1051 :group 'org-startup
1052 :type 'boolean)
1054 (defcustom org-replace-disputed-keys nil
1055 "Non-nil means use alternative key bindings for some keys.
1056 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1057 These keys are also used by other packages like shift-selection-mode'
1058 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1059 If you want to use Org-mode together with one of these other modes,
1060 or more generally if you would like to move some Org-mode commands to
1061 other keys, set this variable and configure the keys with the variable
1062 `org-disputed-keys'.
1064 This option is only relevant at load-time of Org-mode, and must be set
1065 *before* org.el is loaded. Changing it requires a restart of Emacs to
1066 become effective."
1067 :group 'org-startup
1068 :type 'boolean)
1070 (defcustom org-use-extra-keys nil
1071 "Non-nil means use extra key sequence definitions for certain commands.
1072 This happens automatically if you run XEmacs or if `window-system'
1073 is nil. This variable lets you do the same manually. You must
1074 set it before loading org.
1076 Example: on Carbon Emacs 22 running graphically, with an external
1077 keyboard on a Powerbook, the default way of setting M-left might
1078 not work for either Alt or ESC. Setting this variable will make
1079 it work for ESC."
1080 :group 'org-startup
1081 :type 'boolean)
1083 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1085 (defcustom org-disputed-keys
1086 '(([(shift up)] . [(meta p)])
1087 ([(shift down)] . [(meta n)])
1088 ([(shift left)] . [(meta -)])
1089 ([(shift right)] . [(meta +)])
1090 ([(control shift right)] . [(meta shift +)])
1091 ([(control shift left)] . [(meta shift -)]))
1092 "Keys for which Org-mode and other modes compete.
1093 This is an alist, cars are the default keys, second element specifies
1094 the alternative to use when `org-replace-disputed-keys' is t.
1096 Keys can be specified in any syntax supported by `define-key'.
1097 The value of this option takes effect only at Org-mode's startup,
1098 therefore you'll have to restart Emacs to apply it after changing."
1099 :group 'org-startup
1100 :type 'alist)
1102 (defun org-key (key)
1103 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1104 Or return the original if not disputed.
1105 Also apply the translations defined in `org-xemacs-key-equivalents'."
1106 (when org-replace-disputed-keys
1107 (let* ((nkey (key-description key))
1108 (x (org-find-if (lambda (x)
1109 (equal (key-description (car x)) nkey))
1110 org-disputed-keys)))
1111 (setq key (if x (cdr x) key))))
1112 (when (featurep 'xemacs)
1113 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1114 key)
1116 (defun org-find-if (predicate seq)
1117 (catch 'exit
1118 (while seq
1119 (if (funcall predicate (car seq))
1120 (throw 'exit (car seq))
1121 (pop seq)))))
1123 (defun org-defkey (keymap key def)
1124 "Define a key, possibly translated, as returned by `org-key'."
1125 (define-key keymap (org-key key) def))
1127 (defcustom org-ellipsis nil
1128 "The ellipsis to use in the Org-mode outline.
1129 When nil, just use the standard three dots.
1130 When a string, use that string instead.
1131 When a face, use the standard 3 dots, but with the specified face.
1132 The change affects only Org-mode (which will then use its own display table).
1133 Changing this requires executing \\[org-mode] in a buffer to become
1134 effective."
1135 :group 'org-startup
1136 :type '(choice (const :tag "Default" nil)
1137 (face :tag "Face" :value org-warning)
1138 (string :tag "String" :value "...#")))
1140 (defvar org-display-table nil
1141 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1143 (defgroup org-keywords nil
1144 "Keywords in Org-mode."
1145 :tag "Org Keywords"
1146 :group 'org)
1148 (defcustom org-closed-keep-when-no-todo nil
1149 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1150 :group 'org-todo
1151 :group 'org-keywords
1152 :version "24.4"
1153 :package-version '(Org . "8.0")
1154 :type 'boolean)
1156 (defgroup org-structure nil
1157 "Options concerning the general structure of Org-mode files."
1158 :tag "Org Structure"
1159 :group 'org)
1161 (defgroup org-reveal-location nil
1162 "Options about how to make context of a location visible."
1163 :tag "Org Reveal Location"
1164 :group 'org-structure)
1166 (defconst org-context-choice
1167 '(choice
1168 (const :tag "Always" t)
1169 (const :tag "Never" nil)
1170 (repeat :greedy t :tag "Individual contexts"
1171 (cons
1172 (choice :tag "Context"
1173 (const agenda)
1174 (const org-goto)
1175 (const occur-tree)
1176 (const tags-tree)
1177 (const link-search)
1178 (const mark-goto)
1179 (const bookmark-jump)
1180 (const isearch)
1181 (const default))
1182 (boolean))))
1183 "Contexts for the reveal options.")
1185 (defcustom org-show-hierarchy-above '((default . t))
1186 "Non-nil means show full hierarchy when revealing a location.
1187 Org-mode often shows locations in an org-mode file which might have
1188 been invisible before. When this is set, the hierarchy of headings
1189 above the exposed location is shown.
1190 Turning this off for example for sparse trees makes them very compact.
1191 Instead of t, this can also be an alist specifying this option for different
1192 contexts. Valid contexts are
1193 agenda when exposing an entry from the agenda
1194 org-goto when using the command `org-goto' on key C-c C-j
1195 occur-tree when using the command `org-occur' on key C-c /
1196 tags-tree when constructing a sparse tree based on tags matches
1197 link-search when exposing search matches associated with a link
1198 mark-goto when exposing the jump goal of a mark
1199 bookmark-jump when exposing a bookmark location
1200 isearch when exiting from an incremental search
1201 default default for all contexts not set explicitly"
1202 :group 'org-reveal-location
1203 :type org-context-choice)
1205 (defcustom org-show-following-heading '((default . nil))
1206 "Non-nil means show following heading when revealing a location.
1207 Org-mode often shows locations in an org-mode file which might have
1208 been invisible before. When this is set, the heading following the
1209 match is shown.
1210 Turning this off for example for sparse trees makes them very compact,
1211 but makes it harder to edit the location of the match. In such a case,
1212 use the command \\[org-reveal] to show more context.
1213 Instead of t, this can also be an alist specifying this option for different
1214 contexts. See `org-show-hierarchy-above' for valid contexts."
1215 :group 'org-reveal-location
1216 :type org-context-choice)
1218 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1219 "Non-nil means show all sibling heading when revealing a location.
1220 Org-mode often shows locations in an org-mode file which might have
1221 been invisible before. When this is set, the sibling of the current entry
1222 heading are all made visible. If `org-show-hierarchy-above' is t,
1223 the same happens on each level of the hierarchy above the current entry.
1225 By default this is on for the isearch context, off for all other contexts.
1226 Turning this off for example for sparse trees makes them very compact,
1227 but makes it harder to edit the location of the match. In such a case,
1228 use the command \\[org-reveal] to show more context.
1229 Instead of t, this can also be an alist specifying this option for different
1230 contexts. See `org-show-hierarchy-above' for valid contexts."
1231 :group 'org-reveal-location
1232 :type org-context-choice
1233 :version "24.4"
1234 :package-version '(Org . "8.0"))
1236 (defcustom org-show-entry-below '((default . nil))
1237 "Non-nil means show the entry below a headline when revealing a location.
1238 Org-mode often shows locations in an org-mode file which might have
1239 been invisible before. When this is set, the text below the headline that is
1240 exposed is also shown.
1242 By default this is off for all contexts.
1243 Instead of t, this can also be an alist specifying this option for different
1244 contexts. See `org-show-hierarchy-above' for valid contexts."
1245 :group 'org-reveal-location
1246 :type org-context-choice)
1248 (defcustom org-indirect-buffer-display 'other-window
1249 "How should indirect tree buffers be displayed?
1250 This applies to indirect buffers created with the commands
1251 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1252 Valid values are:
1253 current-window Display in the current window
1254 other-window Just display in another window.
1255 dedicated-frame Create one new frame, and re-use it each time.
1256 new-frame Make a new frame each time. Note that in this case
1257 previously-made indirect buffers are kept, and you need to
1258 kill these buffers yourself."
1259 :group 'org-structure
1260 :group 'org-agenda-windows
1261 :type '(choice
1262 (const :tag "In current window" current-window)
1263 (const :tag "In current frame, other window" other-window)
1264 (const :tag "Each time a new frame" new-frame)
1265 (const :tag "One dedicated frame" dedicated-frame)))
1267 (defcustom org-use-speed-commands nil
1268 "Non-nil means activate single letter commands at beginning of a headline.
1269 This may also be a function to test for appropriate locations where speed
1270 commands should be active.
1272 For example, to activate speed commands when the point is on any
1273 star at the beginning of the headline, you can do this:
1275 (setq org-use-speed-commands
1276 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1277 :group 'org-structure
1278 :type '(choice
1279 (const :tag "Never" nil)
1280 (const :tag "At beginning of headline stars" t)
1281 (function)))
1283 (defcustom org-speed-commands-user nil
1284 "Alist of additional speed commands.
1285 This list will be checked before `org-speed-commands-default'
1286 when the variable `org-use-speed-commands' is non-nil
1287 and when the cursor is at the beginning of a headline.
1288 The car if each entry is a string with a single letter, which must
1289 be assigned to `self-insert-command' in the global map.
1290 The cdr is either a command to be called interactively, a function
1291 to be called, or a form to be evaluated.
1292 An entry that is just a list with a single string will be interpreted
1293 as a descriptive headline that will be added when listing the speed
1294 commands in the Help buffer using the `?' speed command."
1295 :group 'org-structure
1296 :type '(repeat :value ("k" . ignore)
1297 (choice :value ("k" . ignore)
1298 (list :tag "Descriptive Headline" (string :tag "Headline"))
1299 (cons :tag "Letter and Command"
1300 (string :tag "Command letter")
1301 (choice
1302 (function)
1303 (sexp))))))
1305 (defcustom org-bookmark-names-plist
1306 '(:last-capture "org-capture-last-stored"
1307 :last-refile "org-refile-last-stored"
1308 :last-capture-marker "org-capture-last-stored-marker")
1309 "Names for bookmarks automatically set by some Org commands.
1310 This can provide strings as names for a number of bookmarks Org sets
1311 automatically. The following keys are currently implemented:
1312 :last-capture
1313 :last-capture-marker
1314 :last-refile
1315 When a key does not show up in the property list, the corresponding bookmark
1316 is not set."
1317 :group 'org-structure
1318 :type 'plist)
1320 (defgroup org-cycle nil
1321 "Options concerning visibility cycling in Org-mode."
1322 :tag "Org Cycle"
1323 :group 'org-structure)
1325 (defcustom org-cycle-skip-children-state-if-no-children t
1326 "Non-nil means skip CHILDREN state in entries that don't have any."
1327 :group 'org-cycle
1328 :type 'boolean)
1330 (defcustom org-cycle-max-level nil
1331 "Maximum level which should still be subject to visibility cycling.
1332 Levels higher than this will, for cycling, be treated as text, not a headline.
1333 When `org-odd-levels-only' is set, a value of N in this variable actually
1334 means 2N-1 stars as the limiting headline.
1335 When nil, cycle all levels.
1336 Note that the limiting level of cycling is also influenced by
1337 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1338 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1339 than its value."
1340 :group 'org-cycle
1341 :type '(choice
1342 (const :tag "No limit" nil)
1343 (integer :tag "Maximum level")))
1345 (defcustom org-hide-block-startup nil
1346 "Non-nil means entering Org-mode will fold all blocks.
1347 This can also be set in on a per-file basis with
1349 #+STARTUP: hideblocks
1350 #+STARTUP: showblocks"
1351 :group 'org-startup
1352 :group 'org-cycle
1353 :type 'boolean)
1355 (defcustom org-cycle-global-at-bob nil
1356 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1357 This makes it possible to do global cycling without having to use S-TAB or
1358 \\[universal-argument] TAB. For this special case to work, the first line
1359 of the buffer must not be a headline -- it may be empty or some other text.
1360 When used in this way, `org-cycle-hook' is disabled temporarily to make
1361 sure the cursor stays at the beginning of the buffer. When this option is
1362 nil, don't do anything special at the beginning of the buffer."
1363 :group 'org-cycle
1364 :type 'boolean)
1366 (defcustom org-cycle-level-after-item/entry-creation t
1367 "Non-nil means cycle entry level or item indentation in new empty entries.
1369 When the cursor is at the end of an empty headline, i.e., with only stars
1370 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1371 and then all possible ancestor states, before returning to the original state.
1372 This makes data entry extremely fast: M-RET to create a new headline,
1373 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1375 When the cursor is at the end of an empty plain list item, one TAB will
1376 make it a subitem, two or more tabs will back up to make this an item
1377 higher up in the item hierarchy."
1378 :group 'org-cycle
1379 :type 'boolean)
1381 (defcustom org-cycle-emulate-tab t
1382 "Where should `org-cycle' emulate TAB.
1383 nil Never
1384 white Only in completely white lines
1385 whitestart Only at the beginning of lines, before the first non-white char
1386 t Everywhere except in headlines
1387 exc-hl-bol Everywhere except at the start of a headline
1388 If TAB is used in a place where it does not emulate TAB, the current subtree
1389 visibility is cycled."
1390 :group 'org-cycle
1391 :type '(choice (const :tag "Never" nil)
1392 (const :tag "Only in completely white lines" white)
1393 (const :tag "Before first char in a line" whitestart)
1394 (const :tag "Everywhere except in headlines" t)
1395 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1397 (defcustom org-cycle-separator-lines 2
1398 "Number of empty lines needed to keep an empty line between collapsed trees.
1399 If you leave an empty line between the end of a subtree and the following
1400 headline, this empty line is hidden when the subtree is folded.
1401 Org-mode will leave (exactly) one empty line visible if the number of
1402 empty lines is equal or larger to the number given in this variable.
1403 So the default 2 means at least 2 empty lines after the end of a subtree
1404 are needed to produce free space between a collapsed subtree and the
1405 following headline.
1407 If the number is negative, and the number of empty lines is at least -N,
1408 all empty lines are shown.
1410 Special case: when 0, never leave empty lines in collapsed view."
1411 :group 'org-cycle
1412 :type 'integer)
1413 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1415 (defcustom org-pre-cycle-hook nil
1416 "Hook that is run before visibility cycling is happening.
1417 The function(s) in this hook must accept a single argument which indicates
1418 the new state that will be set right after running this hook. The
1419 argument is a symbol. Before a global state change, it can have the values
1420 `overview', `content', or `all'. Before a local state change, it can have
1421 the values `folded', `children', or `subtree'."
1422 :group 'org-cycle
1423 :type 'hook)
1425 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1426 org-cycle-hide-drawers
1427 org-cycle-hide-inline-tasks
1428 org-cycle-show-empty-lines
1429 org-optimize-window-after-visibility-change)
1430 "Hook that is run after `org-cycle' has changed the buffer visibility.
1431 The function(s) in this hook must accept a single argument which indicates
1432 the new state that was set by the most recent `org-cycle' command. The
1433 argument is a symbol. After a global state change, it can have the values
1434 `overview', `contents', or `all'. After a local state change, it can have
1435 the values `folded', `children', or `subtree'."
1436 :group 'org-cycle
1437 :type 'hook)
1439 (defgroup org-edit-structure nil
1440 "Options concerning structure editing in Org-mode."
1441 :tag "Org Edit Structure"
1442 :group 'org-structure)
1444 (defcustom org-odd-levels-only nil
1445 "Non-nil means skip even levels and only use odd levels for the outline.
1446 This has the effect that two stars are being added/taken away in
1447 promotion/demotion commands. It also influences how levels are
1448 handled by the exporters.
1449 Changing it requires restart of `font-lock-mode' to become effective
1450 for fontification also in regions already fontified.
1451 You may also set this on a per-file basis by adding one of the following
1452 lines to the buffer:
1454 #+STARTUP: odd
1455 #+STARTUP: oddeven"
1456 :group 'org-edit-structure
1457 :group 'org-appearance
1458 :type 'boolean)
1460 (defcustom org-adapt-indentation t
1461 "Non-nil means adapt indentation to outline node level.
1463 When this variable is set, Org assumes that you write outlines by
1464 indenting text in each node to align with the headline (after the
1465 stars). The following issues are influenced by this variable:
1467 - The indentation is increased by one space in a demotion
1468 command, and decreased by one in a promotion command. However,
1469 in the latter case, if shifting some line in the entry body
1470 would alter document structure (e.g., insert a new headline),
1471 indentation is not changed at all.
1473 - Property drawers and planning information is inserted indented
1474 when this variable is set. When nil, they will not be indented.
1476 - TAB indents a line relative to current level. The lines below
1477 a headline will be indented when this variable is set.
1479 Note that this is all about true indentation, by adding and
1480 removing space characters. See also `org-indent.el' which does
1481 level-dependent indentation in a virtual way, i.e. at display
1482 time in Emacs."
1483 :group 'org-edit-structure
1484 :type 'boolean)
1486 (defcustom org-special-ctrl-a/e nil
1487 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1489 When t, `C-a' will bring back the cursor to the beginning of the
1490 headline text, i.e. after the stars and after a possible TODO
1491 keyword. In an item, this will be the position after bullet and
1492 check-box, if any. When the cursor is already at that position,
1493 another `C-a' will bring it to the beginning of the line.
1495 `C-e' will jump to the end of the headline, ignoring the presence
1496 of tags in the headline. A second `C-e' will then jump to the
1497 true end of the line, after any tags. This also means that, when
1498 this variable is non-nil, `C-e' also will never jump beyond the
1499 end of the heading of a folded section, i.e. not after the
1500 ellipses.
1502 When set to the symbol `reversed', the first `C-a' or `C-e' works
1503 normally, going to the true line boundary first. Only a directly
1504 following, identical keypress will bring the cursor to the
1505 special positions.
1507 This may also be a cons cell where the behavior for `C-a' and
1508 `C-e' is set separately."
1509 :group 'org-edit-structure
1510 :type '(choice
1511 (const :tag "off" nil)
1512 (const :tag "on: after stars/bullet and before tags first" t)
1513 (const :tag "reversed: true line boundary first" reversed)
1514 (cons :tag "Set C-a and C-e separately"
1515 (choice :tag "Special C-a"
1516 (const :tag "off" nil)
1517 (const :tag "on: after stars/bullet first" t)
1518 (const :tag "reversed: before stars/bullet first" reversed))
1519 (choice :tag "Special C-e"
1520 (const :tag "off" nil)
1521 (const :tag "on: before tags first" t)
1522 (const :tag "reversed: after tags first" reversed)))))
1523 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1525 (defcustom org-special-ctrl-k nil
1526 "Non-nil means `C-k' will behave specially in headlines.
1527 When nil, `C-k' will call the default `kill-line' command.
1528 When t, the following will happen while the cursor is in the headline:
1530 - When the cursor is at the beginning of a headline, kill the entire
1531 line and possible the folded subtree below the line.
1532 - When in the middle of the headline text, kill the headline up to the tags.
1533 - When after the headline text, kill the tags."
1534 :group 'org-edit-structure
1535 :type 'boolean)
1537 (defcustom org-ctrl-k-protect-subtree nil
1538 "Non-nil means, do not delete a hidden subtree with C-k.
1539 When set to the symbol `error', simply throw an error when C-k is
1540 used to kill (part-of) a headline that has hidden text behind it.
1541 Any other non-nil value will result in a query to the user, if it is
1542 OK to kill that hidden subtree. When nil, kill without remorse."
1543 :group 'org-edit-structure
1544 :version "24.1"
1545 :type '(choice
1546 (const :tag "Do not protect hidden subtrees" nil)
1547 (const :tag "Protect hidden subtrees with a security query" t)
1548 (const :tag "Never kill a hidden subtree with C-k" error)))
1550 (defcustom org-special-ctrl-o t
1551 "Non-nil means, make `C-o' insert a row in tables."
1552 :group 'org-edit-structure
1553 :type 'boolean)
1555 (defcustom org-catch-invisible-edits nil
1556 "Check if in invisible region before inserting or deleting a character.
1557 Valid values are:
1559 nil Do not check, so just do invisible edits.
1560 error Throw an error and do nothing.
1561 show Make point visible, and do the requested edit.
1562 show-and-error Make point visible, then throw an error and abort the edit.
1563 smart Make point visible, and do insertion/deletion if it is
1564 adjacent to visible text and the change feels predictable.
1565 Never delete a previously invisible character or add in the
1566 middle or right after an invisible region. Basically, this
1567 allows insertion and backward-delete right before ellipses.
1568 FIXME: maybe in this case we should not even show?"
1569 :group 'org-edit-structure
1570 :version "24.1"
1571 :type '(choice
1572 (const :tag "Do not check" nil)
1573 (const :tag "Throw error when trying to edit" error)
1574 (const :tag "Unhide, but do not do the edit" show-and-error)
1575 (const :tag "Show invisible part and do the edit" show)
1576 (const :tag "Be smart and do the right thing" smart)))
1578 (defcustom org-yank-folded-subtrees t
1579 "Non-nil means when yanking subtrees, fold them.
1580 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1581 it starts with a heading and all other headings in it are either children
1582 or siblings, then fold all the subtrees. However, do this only if no
1583 text after the yank would be swallowed into a folded tree by this action."
1584 :group 'org-edit-structure
1585 :type 'boolean)
1587 (defcustom org-yank-adjusted-subtrees nil
1588 "Non-nil means when yanking subtrees, adjust the level.
1589 With this setting, `org-paste-subtree' is used to insert the subtree, see
1590 this function for details."
1591 :group 'org-edit-structure
1592 :type 'boolean)
1594 (defcustom org-M-RET-may-split-line '((default . t))
1595 "Non-nil means M-RET will split the line at the cursor position.
1596 When nil, it will go to the end of the line before making a
1597 new line.
1598 You may also set this option in a different way for different
1599 contexts. Valid contexts are:
1601 headline when creating a new headline
1602 item when creating a new item
1603 table in a table field
1604 default the value to be used for all contexts not explicitly
1605 customized"
1606 :group 'org-structure
1607 :group 'org-table
1608 :type '(choice
1609 (const :tag "Always" t)
1610 (const :tag "Never" nil)
1611 (repeat :greedy t :tag "Individual contexts"
1612 (cons
1613 (choice :tag "Context"
1614 (const headline)
1615 (const item)
1616 (const table)
1617 (const default))
1618 (boolean)))))
1621 (defcustom org-insert-heading-respect-content nil
1622 "Non-nil means insert new headings after the current subtree.
1623 When nil, the new heading is created directly after the current line.
1624 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1625 this variable on for the duration of the command."
1626 :group 'org-structure
1627 :type 'boolean)
1629 (defcustom org-blank-before-new-entry '((heading . auto)
1630 (plain-list-item . auto))
1631 "Should `org-insert-heading' leave a blank line before new heading/item?
1632 The value is an alist, with `heading' and `plain-list-item' as CAR,
1633 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1634 which case Org will look at the surrounding headings/items and try to
1635 make an intelligent decision whether to insert a blank line or not.
1637 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1638 the setting here is ignored and no empty line is inserted to avoid breaking
1639 the list structure."
1640 :group 'org-edit-structure
1641 :type '(list
1642 (cons (const heading)
1643 (choice (const :tag "Never" nil)
1644 (const :tag "Always" t)
1645 (const :tag "Auto" auto)))
1646 (cons (const plain-list-item)
1647 (choice (const :tag "Never" nil)
1648 (const :tag "Always" t)
1649 (const :tag "Auto" auto)))))
1651 (defcustom org-insert-heading-hook nil
1652 "Hook being run after inserting a new heading."
1653 :group 'org-edit-structure
1654 :type 'hook)
1656 (defcustom org-enable-fixed-width-editor t
1657 "Non-nil means lines starting with \":\" are treated as fixed-width.
1658 This currently only means they are never auto-wrapped.
1659 When nil, such lines will be treated like ordinary lines."
1660 :group 'org-edit-structure
1661 :type 'boolean)
1663 (defcustom org-goto-auto-isearch t
1664 "Non-nil means typing characters in `org-goto' starts incremental search.
1665 When nil, you can use these keybindings to navigate the buffer:
1667 q Quit the org-goto interface
1668 n Go to the next visible heading
1669 p Go to the previous visible heading
1670 f Go one heading forward on same level
1671 b Go one heading backward on same level
1672 u Go one heading up"
1673 :group 'org-edit-structure
1674 :type 'boolean)
1676 (defgroup org-sparse-trees nil
1677 "Options concerning sparse trees in Org-mode."
1678 :tag "Org Sparse Trees"
1679 :group 'org-structure)
1681 (defcustom org-highlight-sparse-tree-matches t
1682 "Non-nil means highlight all matches that define a sparse tree.
1683 The highlights will automatically disappear the next time the buffer is
1684 changed by an edit command."
1685 :group 'org-sparse-trees
1686 :type 'boolean)
1688 (defcustom org-remove-highlights-with-change t
1689 "Non-nil means any change to the buffer will remove temporary highlights.
1690 Such highlights are created by `org-occur' and `org-clock-display'.
1691 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1692 The highlights created by `org-toggle-latex-fragment' always need
1693 `C-c C-x C-l' to be removed."
1694 :group 'org-sparse-trees
1695 :group 'org-time
1696 :type 'boolean)
1699 (defcustom org-occur-hook '(org-first-headline-recenter)
1700 "Hook that is run after `org-occur' has constructed a sparse tree.
1701 This can be used to recenter the window to show as much of the structure
1702 as possible."
1703 :group 'org-sparse-trees
1704 :type 'hook)
1706 (defgroup org-imenu-and-speedbar nil
1707 "Options concerning imenu and speedbar in Org-mode."
1708 :tag "Org Imenu and Speedbar"
1709 :group 'org-structure)
1711 (defcustom org-imenu-depth 2
1712 "The maximum level for Imenu access to Org-mode headlines.
1713 This also applied for speedbar access."
1714 :group 'org-imenu-and-speedbar
1715 :type 'integer)
1717 (defgroup org-table nil
1718 "Options concerning tables in Org-mode."
1719 :tag "Org Table"
1720 :group 'org)
1722 (defcustom org-enable-table-editor 'optimized
1723 "Non-nil means lines starting with \"|\" are handled by the table editor.
1724 When nil, such lines will be treated like ordinary lines.
1726 When equal to the symbol `optimized', the table editor will be optimized to
1727 do the following:
1728 - Automatic overwrite mode in front of whitespace in table fields.
1729 This makes the structure of the table stay in tact as long as the edited
1730 field does not exceed the column width.
1731 - Minimize the number of realigns. Normally, the table is aligned each time
1732 TAB or RET are pressed to move to another field. With optimization this
1733 happens only if changes to a field might have changed the column width.
1734 Optimization requires replacing the functions `self-insert-command',
1735 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1736 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1737 very good at guessing when a re-align will be necessary, but you can always
1738 force one with \\[org-ctrl-c-ctrl-c].
1740 If you would like to use the optimized version in Org-mode, but the
1741 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1743 This variable can be used to turn on and off the table editor during a session,
1744 but in order to toggle optimization, a restart is required.
1746 See also the variable `org-table-auto-blank-field'."
1747 :group 'org-table
1748 :type '(choice
1749 (const :tag "off" nil)
1750 (const :tag "on" t)
1751 (const :tag "on, optimized" optimized)))
1753 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1754 (version<= emacs-version "24.1"))
1755 "Non-nil means cluster self-insert commands for undo when possible.
1756 If this is set, then, like in the Emacs command loop, 20 consecutive
1757 characters will be undone together.
1758 This is configurable, because there is some impact on typing performance."
1759 :group 'org-table
1760 :type 'boolean)
1762 (defcustom org-table-tab-recognizes-table.el t
1763 "Non-nil means TAB will automatically notice a table.el table.
1764 When it sees such a table, it moves point into it and - if necessary -
1765 calls `table-recognize-table'."
1766 :group 'org-table-editing
1767 :type 'boolean)
1769 (defgroup org-link nil
1770 "Options concerning links in Org-mode."
1771 :tag "Org Link"
1772 :group 'org)
1774 (defvar org-link-abbrev-alist-local nil
1775 "Buffer-local version of `org-link-abbrev-alist', which see.
1776 The value of this is taken from the #+LINK lines.")
1777 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1779 (defcustom org-link-abbrev-alist nil
1780 "Alist of link abbreviations.
1781 The car of each element is a string, to be replaced at the start of a link.
1782 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1783 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1785 [[linkkey:tag][description]]
1787 The 'linkkey' must be a word word, starting with a letter, followed
1788 by letters, numbers, '-' or '_'.
1790 If REPLACE is a string, the tag will simply be appended to create the link.
1791 If the string contains \"%s\", the tag will be inserted there. If the string
1792 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1793 at that point (see the function `url-hexify-string'). If the string contains
1794 the specifier \"%(my-function)\", then the custom function `my-function' will
1795 be invoked: this function takes the tag as its only argument and must return
1796 a string.
1798 REPLACE may also be a function that will be called with the tag as the
1799 only argument to create the link, which should be returned as a string.
1801 See the manual for examples."
1802 :group 'org-link
1803 :type '(repeat
1804 (cons
1805 (string :tag "Protocol")
1806 (choice
1807 (string :tag "Format")
1808 (function)))))
1810 (defcustom org-descriptive-links t
1811 "Non-nil means Org will display descriptive links.
1812 E.g. [[http://orgmode.org][Org website]] will be displayed as
1813 \"Org Website\", hiding the link itself and just displaying its
1814 description. When set to `nil', Org will display the full links
1815 literally.
1817 You can interactively set the value of this variable by calling
1818 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1819 :group 'org-link
1820 :type 'boolean)
1822 (defcustom org-link-file-path-type 'adaptive
1823 "How the path name in file links should be stored.
1824 Valid values are:
1826 relative Relative to the current directory, i.e. the directory of the file
1827 into which the link is being inserted.
1828 absolute Absolute path, if possible with ~ for home directory.
1829 noabbrev Absolute path, no abbreviation of home directory.
1830 adaptive Use relative path for files in the current directory and sub-
1831 directories of it. For other files, use an absolute path."
1832 :group 'org-link
1833 :type '(choice
1834 (const relative)
1835 (const absolute)
1836 (const noabbrev)
1837 (const adaptive)))
1839 (defvaralias 'org-activate-links 'org-highlight-links)
1840 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1841 "Types of links that should be highlighted in Org-mode files.
1843 This is a list of symbols, each one of them leading to the
1844 highlighting of a certain link type.
1846 You can still open links that are not highlighted.
1848 In principle, it does not hurt to turn on highlighting for all
1849 link types. There may be a small gain when turning off unused
1850 link types. The types are:
1852 bracket The recommended [[link][description]] or [[link]] links with hiding.
1853 angle Links in angular brackets that may contain whitespace like
1854 <bbdb:Carsten Dominik>.
1855 plain Plain links in normal text, no whitespace, like http://google.com.
1856 radio Text that is matched by a radio target, see manual for details.
1857 tag Tag settings in a headline (link to tag search).
1858 date Time stamps (link to calendar).
1859 footnote Footnote labels.
1861 If you set this variable during an Emacs session, use `org-mode-restart'
1862 in the Org buffer so that the change takes effect."
1863 :group 'org-link
1864 :group 'org-appearance
1865 :type '(set :greedy t
1866 (const :tag "Double bracket links" bracket)
1867 (const :tag "Angular bracket links" angle)
1868 (const :tag "Plain text links" plain)
1869 (const :tag "Radio target matches" radio)
1870 (const :tag "Tags" tag)
1871 (const :tag "Timestamps" date)
1872 (const :tag "Footnotes" footnote)))
1874 (defcustom org-make-link-description-function nil
1875 "Function to use for generating link descriptions from links.
1876 When nil, the link location will be used. This function must take
1877 two parameters: the first one is the link, the second one is the
1878 description generated by `org-insert-link'. The function should
1879 return the description to use."
1880 :group 'org-link
1881 :type '(choice (const nil) (function)))
1883 (defgroup org-link-store nil
1884 "Options concerning storing links in Org-mode."
1885 :tag "Org Store Link"
1886 :group 'org-link)
1888 (defcustom org-url-hexify-p t
1889 "When non-nil, hexify URL when creating a link."
1890 :type 'boolean
1891 :version "24.3"
1892 :group 'org-link-store)
1894 (defcustom org-email-link-description-format "Email %c: %.30s"
1895 "Format of the description part of a link to an email or usenet message.
1896 The following %-escapes will be replaced by corresponding information:
1898 %F full \"From\" field
1899 %f name, taken from \"From\" field, address if no name
1900 %T full \"To\" field
1901 %t first name in \"To\" field, address if no name
1902 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1903 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1904 %s subject
1905 %d date
1906 %m message-id.
1908 You may use normal field width specification between the % and the letter.
1909 This is for example useful to limit the length of the subject.
1911 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1912 :group 'org-link-store
1913 :type 'string)
1915 (defcustom org-from-is-user-regexp
1916 (let (r1 r2)
1917 (when (and user-mail-address (not (string= user-mail-address "")))
1918 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1919 (when (and user-full-name (not (string= user-full-name "")))
1920 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1921 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1922 "Regexp matched against the \"From:\" header of an email or usenet message.
1923 It should match if the message is from the user him/herself."
1924 :group 'org-link-store
1925 :type 'regexp)
1927 (defcustom org-context-in-file-links t
1928 "Non-nil means file links from `org-store-link' contain context.
1929 A search string will be added to the file name with :: as separator and
1930 used to find the context when the link is activated by the command
1931 `org-open-at-point'. When this option is t, the entire active region
1932 will be placed in the search string of the file link. If set to a
1933 positive integer, only the first n lines of context will be stored.
1935 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1936 negates this setting for the duration of the command."
1937 :group 'org-link-store
1938 :type '(choice boolean integer))
1940 (defcustom org-keep-stored-link-after-insertion nil
1941 "Non-nil means keep link in list for entire session.
1943 The command `org-store-link' adds a link pointing to the current
1944 location to an internal list. These links accumulate during a session.
1945 The command `org-insert-link' can be used to insert links into any
1946 Org-mode file (offering completion for all stored links). When this
1947 option is nil, every link which has been inserted once using \\[org-insert-link]
1948 will be removed from the list, to make completing the unused links
1949 more efficient."
1950 :group 'org-link-store
1951 :type 'boolean)
1953 (defgroup org-link-follow nil
1954 "Options concerning following links in Org-mode."
1955 :tag "Org Follow Link"
1956 :group 'org-link)
1958 (defcustom org-link-translation-function nil
1959 "Function to translate links with different syntax to Org syntax.
1960 This can be used to translate links created for example by the Planner
1961 or emacs-wiki packages to Org syntax.
1962 The function must accept two parameters, a TYPE containing the link
1963 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1964 which is everything after the link protocol. It should return a cons
1965 with possibly modified values of type and path.
1966 Org contains a function for this, so if you set this variable to
1967 `org-translate-link-from-planner', you should be able follow many
1968 links created by planner."
1969 :group 'org-link-follow
1970 :type '(choice (const nil) (function)))
1972 (defcustom org-follow-link-hook nil
1973 "Hook that is run after a link has been followed."
1974 :group 'org-link-follow
1975 :type 'hook)
1977 (defcustom org-tab-follows-link nil
1978 "Non-nil means on links TAB will follow the link.
1979 Needs to be set before org.el is loaded.
1980 This really should not be used, it does not make sense, and the
1981 implementation is bad."
1982 :group 'org-link-follow
1983 :type 'boolean)
1985 (defcustom org-return-follows-link nil
1986 "Non-nil means on links RET will follow the link.
1987 In tables, the special behavior of RET has precedence."
1988 :group 'org-link-follow
1989 :type 'boolean)
1991 (defcustom org-mouse-1-follows-link
1992 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1993 "Non-nil means mouse-1 on a link will follow the link.
1994 A longer mouse click will still set point. Does not work on XEmacs.
1995 Needs to be set before org.el is loaded."
1996 :group 'org-link-follow
1997 :version "24.4"
1998 :package-version '(Org . "8.3")
1999 :type '(choice
2000 (const :tag "A double click follows the link" double)
2001 (const :tag "Unconditionally follow the link with mouse-1" t)
2002 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2004 (defcustom org-mark-ring-length 4
2005 "Number of different positions to be recorded in the ring.
2006 Changing this requires a restart of Emacs to work correctly."
2007 :group 'org-link-follow
2008 :type 'integer)
2010 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2011 "Non-nil means internal links in Org files must exactly match a headline.
2012 When nil, the link search tries to match a phrase with all words
2013 in the search text."
2014 :group 'org-link-follow
2015 :version "24.1"
2016 :type '(choice
2017 (const :tag "Use fuzzy text search" nil)
2018 (const :tag "Match only exact headline" t)
2019 (const :tag "Match exact headline or query to create it"
2020 query-to-create)))
2022 (defcustom org-link-frame-setup
2023 '((vm . vm-visit-folder-other-frame)
2024 (vm-imap . vm-visit-imap-folder-other-frame)
2025 (gnus . org-gnus-no-new-news)
2026 (file . find-file-other-window)
2027 (wl . wl-other-frame))
2028 "Setup the frame configuration for following links.
2029 When following a link with Emacs, it may often be useful to display
2030 this link in another window or frame. This variable can be used to
2031 set this up for the different types of links.
2032 For VM, use any of
2033 `vm-visit-folder'
2034 `vm-visit-folder-other-window'
2035 `vm-visit-folder-other-frame'
2036 For Gnus, use any of
2037 `gnus'
2038 `gnus-other-frame'
2039 `org-gnus-no-new-news'
2040 For FILE, use any of
2041 `find-file'
2042 `find-file-other-window'
2043 `find-file-other-frame'
2044 For Wanderlust use any of
2045 `wl'
2046 `wl-other-frame'
2047 For the calendar, use the variable `calendar-setup'.
2048 For BBDB, it is currently only possible to display the matches in
2049 another window."
2050 :group 'org-link-follow
2051 :type '(list
2052 (cons (const vm)
2053 (choice
2054 (const vm-visit-folder)
2055 (const vm-visit-folder-other-window)
2056 (const vm-visit-folder-other-frame)))
2057 (cons (const vm-imap)
2058 (choice
2059 (const vm-visit-imap-folder)
2060 (const vm-visit-imap-folder-other-window)
2061 (const vm-visit-imap-folder-other-frame)))
2062 (cons (const gnus)
2063 (choice
2064 (const gnus)
2065 (const gnus-other-frame)
2066 (const org-gnus-no-new-news)))
2067 (cons (const file)
2068 (choice
2069 (const find-file)
2070 (const find-file-other-window)
2071 (const find-file-other-frame)))
2072 (cons (const wl)
2073 (choice
2074 (const wl)
2075 (const wl-other-frame)))))
2077 (defcustom org-display-internal-link-with-indirect-buffer nil
2078 "Non-nil means use indirect buffer to display infile links.
2079 Activating internal links (from one location in a file to another location
2080 in the same file) normally just jumps to the location. When the link is
2081 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2082 is displayed in
2083 another window. When this option is set, the other window actually displays
2084 an indirect buffer clone of the current buffer, to avoid any visibility
2085 changes to the current buffer."
2086 :group 'org-link-follow
2087 :type 'boolean)
2089 (defcustom org-open-non-existing-files nil
2090 "Non-nil means `org-open-file' will open non-existing files.
2091 When nil, an error will be generated.
2092 This variable applies only to external applications because they
2093 might choke on non-existing files. If the link is to a file that
2094 will be opened in Emacs, the variable is ignored."
2095 :group 'org-link-follow
2096 :type 'boolean)
2098 (defcustom org-open-directory-means-index-dot-org nil
2099 "Non-nil means a link to a directory really means to index.org.
2100 When nil, following a directory link will run dired or open a finder/explorer
2101 window on that directory."
2102 :group 'org-link-follow
2103 :type 'boolean)
2105 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2106 "Non-nil means ask for confirmation before executing shell links.
2107 Shell links can be dangerous: just think about a link
2109 [[shell:rm -rf ~/*][Google Search]]
2111 This link would show up in your Org-mode document as \"Google Search\",
2112 but really it would remove your entire home directory.
2113 Therefore we advise against setting this variable to nil.
2114 Just change it to `y-or-n-p' if you want to confirm with a
2115 single keystroke rather than having to type \"yes\"."
2116 :group 'org-link-follow
2117 :type '(choice
2118 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2119 (const :tag "with y-or-n (faster)" y-or-n-p)
2120 (const :tag "no confirmation (dangerous)" nil)))
2121 (put 'org-confirm-shell-link-function
2122 'safe-local-variable
2123 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2125 (defcustom org-confirm-shell-link-not-regexp ""
2126 "A regexp to skip confirmation for shell links."
2127 :group 'org-link-follow
2128 :version "24.1"
2129 :type 'regexp)
2131 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2132 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2133 Elisp links can be dangerous: just think about a link
2135 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2137 This link would show up in your Org-mode document as \"Google Search\",
2138 but really it would remove your entire home directory.
2139 Therefore we advise against setting this variable to nil.
2140 Just change it to `y-or-n-p' if you want to confirm with a
2141 single keystroke rather than having to type \"yes\"."
2142 :group 'org-link-follow
2143 :type '(choice
2144 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2145 (const :tag "with y-or-n (faster)" y-or-n-p)
2146 (const :tag "no confirmation (dangerous)" nil)))
2147 (put 'org-confirm-shell-link-function
2148 'safe-local-variable
2149 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2151 (defcustom org-confirm-elisp-link-not-regexp ""
2152 "A regexp to skip confirmation for Elisp links."
2153 :group 'org-link-follow
2154 :version "24.1"
2155 :type 'regexp)
2157 (defconst org-file-apps-defaults-gnu
2158 '((remote . emacs)
2159 (system . mailcap)
2160 (t . mailcap))
2161 "Default file applications on a UNIX or GNU/Linux system.
2162 See `org-file-apps'.")
2164 (defconst org-file-apps-defaults-macosx
2165 '((remote . emacs)
2166 (t . "open %s")
2167 (system . "open %s")
2168 ("ps.gz" . "gv %s")
2169 ("eps.gz" . "gv %s")
2170 ("dvi" . "xdvi %s")
2171 ("fig" . "xfig %s"))
2172 "Default file applications on a MacOS X system.
2173 The system \"open\" is known as a default, but we use X11 applications
2174 for some files for which the OS does not have a good default.
2175 See `org-file-apps'.")
2177 (defconst org-file-apps-defaults-windowsnt
2178 (list
2179 '(remote . emacs)
2180 (cons t
2181 (list (if (featurep 'xemacs)
2182 'mswindows-shell-execute
2183 'w32-shell-execute)
2184 "open" 'file))
2185 (cons 'system
2186 (list (if (featurep 'xemacs)
2187 'mswindows-shell-execute
2188 'w32-shell-execute)
2189 "open" 'file)))
2190 "Default file applications on a Windows NT system.
2191 The system \"open\" is used for most files.
2192 See `org-file-apps'.")
2194 (defcustom org-file-apps
2195 '((auto-mode . emacs)
2196 ("\\.mm\\'" . default)
2197 ("\\.x?html?\\'" . default)
2198 ("\\.pdf\\'" . default))
2199 "External applications for opening `file:path' items in a document.
2200 Org-mode uses system defaults for different file types, but
2201 you can use this variable to set the application for a given file
2202 extension. The entries in this list are cons cells where the car identifies
2203 files and the cdr the corresponding command. Possible values for the
2204 file identifier are
2205 \"string\" A string as a file identifier can be interpreted in different
2206 ways, depending on its contents:
2208 - Alphanumeric characters only:
2209 Match links with this file extension.
2210 Example: (\"pdf\" . \"evince %s\")
2211 to open PDFs with evince.
2213 - Regular expression: Match links where the
2214 filename matches the regexp. If you want to
2215 use groups here, use shy groups.
2217 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2218 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2219 to open *.html and *.xhtml with firefox.
2221 - Regular expression which contains (non-shy) groups:
2222 Match links where the whole link, including \"::\", and
2223 anything after that, matches the regexp.
2224 In a custom command string, %1, %2, etc. are replaced with
2225 the parts of the link that were matched by the groups.
2226 For backwards compatibility, if a command string is given
2227 that does not use any of the group matches, this case is
2228 handled identically to the second one (i.e. match against
2229 file name only).
2230 In a custom lisp form, you can access the group matches with
2231 (match-string n link).
2233 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2234 to open [[file:document.pdf::5]] with evince at page 5.
2236 `directory' Matches a directory
2237 `remote' Matches a remote file, accessible through tramp or efs.
2238 Remote files most likely should be visited through Emacs
2239 because external applications cannot handle such paths.
2240 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2241 so all files Emacs knows how to handle. Using this with
2242 command `emacs' will open most files in Emacs. Beware that this
2243 will also open html files inside Emacs, unless you add
2244 (\"html\" . default) to the list as well.
2245 t Default for files not matched by any of the other options.
2246 `system' The system command to open files, like `open' on Windows
2247 and Mac OS X, and mailcap under GNU/Linux. This is the command
2248 that will be selected if you call `C-c C-o' with a double
2249 \\[universal-argument] \\[universal-argument] prefix.
2251 Possible values for the command are:
2252 `emacs' The file will be visited by the current Emacs process.
2253 `default' Use the default application for this file type, which is the
2254 association for t in the list, most likely in the system-specific
2255 part.
2256 This can be used to overrule an unwanted setting in the
2257 system-specific variable.
2258 `system' Use the system command for opening files, like \"open\".
2259 This command is specified by the entry whose car is `system'.
2260 Most likely, the system-specific version of this variable
2261 does define this command, but you can overrule/replace it
2262 here.
2263 string A command to be executed by a shell; %s will be replaced
2264 by the path to the file.
2265 sexp A Lisp form which will be evaluated. The file path will
2266 be available in the Lisp variable `file'.
2267 For more examples, see the system specific constants
2268 `org-file-apps-defaults-macosx'
2269 `org-file-apps-defaults-windowsnt'
2270 `org-file-apps-defaults-gnu'."
2271 :group 'org-link-follow
2272 :type '(repeat
2273 (cons (choice :value ""
2274 (string :tag "Extension")
2275 (const :tag "System command to open files" system)
2276 (const :tag "Default for unrecognized files" t)
2277 (const :tag "Remote file" remote)
2278 (const :tag "Links to a directory" directory)
2279 (const :tag "Any files that have Emacs modes"
2280 auto-mode))
2281 (choice :value ""
2282 (const :tag "Visit with Emacs" emacs)
2283 (const :tag "Use default" default)
2284 (const :tag "Use the system command" system)
2285 (string :tag "Command")
2286 (sexp :tag "Lisp form")))))
2288 (defcustom org-doi-server-url "http://dx.doi.org/"
2289 "The URL of the DOI server."
2290 :type 'string
2291 :version "24.3"
2292 :group 'org-link-follow)
2294 (defgroup org-refile nil
2295 "Options concerning refiling entries in Org-mode."
2296 :tag "Org Refile"
2297 :group 'org)
2299 (defcustom org-directory "~/org"
2300 "Directory with org files.
2301 This is just a default location to look for Org files. There is no need
2302 at all to put your files into this directory. It is only used in the
2303 following situations:
2305 1. When a capture template specifies a target file that is not an
2306 absolute path. The path will then be interpreted relative to
2307 `org-directory'
2308 2. When a capture note is filed away in an interactive way (when exiting the
2309 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2310 with `org-directory' as the default path."
2311 :group 'org-refile
2312 :group 'org-capture
2313 :type 'directory)
2315 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2316 "Default target for storing notes.
2317 Used as a fall back file for org-capture.el, for templates that
2318 do not specify a target file."
2319 :group 'org-refile
2320 :group 'org-capture
2321 :type '(choice
2322 (const :tag "Default from remember-data-file" nil)
2323 file))
2325 (defcustom org-goto-interface 'outline
2326 "The default interface to be used for `org-goto'.
2327 Allowed values are:
2328 outline The interface shows an outline of the relevant file
2329 and the correct heading is found by moving through
2330 the outline or by searching with incremental search.
2331 outline-path-completion Headlines in the current buffer are offered via
2332 completion. This is the interface also used by
2333 the refile command."
2334 :group 'org-refile
2335 :type '(choice
2336 (const :tag "Outline" outline)
2337 (const :tag "Outline-path-completion" outline-path-completion)))
2339 (defcustom org-goto-max-level 5
2340 "Maximum target level when running `org-goto' with refile interface."
2341 :group 'org-refile
2342 :type 'integer)
2344 (defcustom org-reverse-note-order nil
2345 "Non-nil means store new notes at the beginning of a file or entry.
2346 When nil, new notes will be filed to the end of a file or entry.
2347 This can also be a list with cons cells of regular expressions that
2348 are matched against file names, and values."
2349 :group 'org-capture
2350 :group 'org-refile
2351 :type '(choice
2352 (const :tag "Reverse always" t)
2353 (const :tag "Reverse never" nil)
2354 (repeat :tag "By file name regexp"
2355 (cons regexp boolean))))
2357 (defcustom org-log-refile nil
2358 "Information to record when a task is refiled.
2360 Possible values are:
2362 nil Don't add anything
2363 time Add a time stamp to the task
2364 note Prompt for a note and add it with template `org-log-note-headings'
2366 This option can also be set with on a per-file-basis with
2368 #+STARTUP: nologrefile
2369 #+STARTUP: logrefile
2370 #+STARTUP: lognoterefile
2372 You can have local logging settings for a subtree by setting the LOGGING
2373 property to one or more of these keywords.
2375 When bulk-refiling from the agenda, the value `note' is forbidden and
2376 will temporarily be changed to `time'."
2377 :group 'org-refile
2378 :group 'org-progress
2379 :version "24.1"
2380 :type '(choice
2381 (const :tag "No logging" nil)
2382 (const :tag "Record timestamp" time)
2383 (const :tag "Record timestamp with note." note)))
2385 (defcustom org-refile-targets nil
2386 "Targets for refiling entries with \\[org-refile].
2387 This is a list of cons cells. Each cell contains:
2388 - a specification of the files to be considered, either a list of files,
2389 or a symbol whose function or variable value will be used to retrieve
2390 a file name or a list of file names. If you use `org-agenda-files' for
2391 that, all agenda files will be scanned for targets. Nil means consider
2392 headings in the current buffer.
2393 - A specification of how to find candidate refile targets. This may be
2394 any of:
2395 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2396 This tag has to be present in all target headlines, inheritance will
2397 not be considered.
2398 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2399 todo keyword.
2400 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2401 headlines that are refiling targets.
2402 - a cons cell (:level . N). Any headline of level N is considered a target.
2403 Note that, when `org-odd-levels-only' is set, level corresponds to
2404 order in hierarchy, not to the number of stars.
2405 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2406 Note that, when `org-odd-levels-only' is set, level corresponds to
2407 order in hierarchy, not to the number of stars.
2409 Each element of this list generates a set of possible targets.
2410 The union of these sets is presented (with completion) to
2411 the user by `org-refile'.
2413 You can set the variable `org-refile-target-verify-function' to a function
2414 to verify each headline found by the simple criteria above.
2416 When this variable is nil, all top-level headlines in the current buffer
2417 are used, equivalent to the value `((nil . (:level . 1))'."
2418 :group 'org-refile
2419 :type '(repeat
2420 (cons
2421 (choice :value org-agenda-files
2422 (const :tag "All agenda files" org-agenda-files)
2423 (const :tag "Current buffer" nil)
2424 (function) (variable) (file))
2425 (choice :tag "Identify target headline by"
2426 (cons :tag "Specific tag" (const :value :tag) (string))
2427 (cons :tag "TODO keyword" (const :value :todo) (string))
2428 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2429 (cons :tag "Level number" (const :value :level) (integer))
2430 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2432 (defcustom org-refile-target-verify-function nil
2433 "Function to verify if the headline at point should be a refile target.
2434 The function will be called without arguments, with point at the
2435 beginning of the headline. It should return t and leave point
2436 where it is if the headline is a valid target for refiling.
2438 If the target should not be selected, the function must return nil.
2439 In addition to this, it may move point to a place from where the search
2440 should be continued. For example, the function may decide that the entire
2441 subtree of the current entry should be excluded and move point to the end
2442 of the subtree."
2443 :group 'org-refile
2444 :type '(choice
2445 (const nil)
2446 (function)))
2448 (defcustom org-refile-use-cache nil
2449 "Non-nil means cache refile targets to speed up the process.
2450 The cache for a particular file will be updated automatically when
2451 the buffer has been killed, or when any of the marker used for flagging
2452 refile targets no longer points at a live buffer.
2453 If you have added new entries to a buffer that might themselves be targets,
2454 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2455 find that easier, `C-u C-u C-u C-c C-w'."
2456 :group 'org-refile
2457 :version "24.1"
2458 :type 'boolean)
2460 (defcustom org-refile-use-outline-path nil
2461 "Non-nil means provide refile targets as paths.
2462 So a level 3 headline will be available as level1/level2/level3.
2464 When the value is `file', also include the file name (without directory)
2465 into the path. In this case, you can also stop the completion after
2466 the file name, to get entries inserted as top level in the file.
2468 When `full-file-path', include the full file path."
2469 :group 'org-refile
2470 :type '(choice
2471 (const :tag "Not" nil)
2472 (const :tag "Yes" t)
2473 (const :tag "Start with file name" file)
2474 (const :tag "Start with full file path" full-file-path)))
2476 (defcustom org-outline-path-complete-in-steps t
2477 "Non-nil means complete the outline path in hierarchical steps.
2478 When Org-mode uses the refile interface to select an outline path
2479 \(see variable `org-refile-use-outline-path'), the completion of
2480 the path can be done is a single go, or if can be done in steps down
2481 the headline hierarchy. Going in steps is probably the best if you
2482 do not use a special completion package like `ido' or `icicles'.
2483 However, when using these packages, going in one step can be very
2484 fast, while still showing the whole path to the entry."
2485 :group 'org-refile
2486 :type 'boolean)
2488 (defcustom org-refile-allow-creating-parent-nodes nil
2489 "Non-nil means allow to create new nodes as refile targets.
2490 New nodes are then created by adding \"/new node name\" to the completion
2491 of an existing node. When the value of this variable is `confirm',
2492 new node creation must be confirmed by the user (recommended).
2493 When nil, the completion must match an existing entry.
2495 Note that, if the new heading is not seen by the criteria
2496 listed in `org-refile-targets', multiple instances of the same
2497 heading would be created by trying again to file under the new
2498 heading."
2499 :group 'org-refile
2500 :type '(choice
2501 (const :tag "Never" nil)
2502 (const :tag "Always" t)
2503 (const :tag "Prompt for confirmation" confirm)))
2505 (defcustom org-refile-active-region-within-subtree nil
2506 "Non-nil means also refile active region within a subtree.
2508 By default `org-refile' doesn't allow refiling regions if they
2509 don't contain a set of subtrees, but it might be convenient to
2510 do so sometimes: in that case, the first line of the region is
2511 converted to a headline before refiling."
2512 :group 'org-refile
2513 :version "24.1"
2514 :type 'boolean)
2516 (defgroup org-todo nil
2517 "Options concerning TODO items in Org-mode."
2518 :tag "Org TODO"
2519 :group 'org)
2521 (defgroup org-progress nil
2522 "Options concerning Progress logging in Org-mode."
2523 :tag "Org Progress"
2524 :group 'org-time)
2526 (defvar org-todo-interpretation-widgets
2527 '((:tag "Sequence (cycling hits every state)" sequence)
2528 (:tag "Type (cycling directly to DONE)" type))
2529 "The available interpretation symbols for customizing `org-todo-keywords'.
2530 Interested libraries should add to this list.")
2532 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2533 "List of TODO entry keyword sequences and their interpretation.
2534 \\<org-mode-map>This is a list of sequences.
2536 Each sequence starts with a symbol, either `sequence' or `type',
2537 indicating if the keywords should be interpreted as a sequence of
2538 action steps, or as different types of TODO items. The first
2539 keywords are states requiring action - these states will select a headline
2540 for inclusion into the global TODO list Org-mode produces. If one of
2541 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2542 signify that no further action is necessary. If \"|\" is not found,
2543 the last keyword is treated as the only DONE state of the sequence.
2545 The command \\[org-todo] cycles an entry through these states, and one
2546 additional state where no keyword is present. For details about this
2547 cycling, see the manual.
2549 TODO keywords and interpretation can also be set on a per-file basis with
2550 the special #+SEQ_TODO and #+TYP_TODO lines.
2552 Each keyword can optionally specify a character for fast state selection
2553 \(in combination with the variable `org-use-fast-todo-selection')
2554 and specifiers for state change logging, using the same syntax that
2555 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2556 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2557 indicates to record a time stamp each time this state is selected.
2559 Each keyword may also specify if a timestamp or a note should be
2560 recorded when entering or leaving the state, by adding additional
2561 characters in the parenthesis after the keyword. This looks like this:
2562 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2563 record only the time of the state change. With X and Y being either
2564 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2565 Y when leaving the state if and only if the *target* state does not
2566 define X. You may omit any of the fast-selection key or X or /Y,
2567 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2569 For backward compatibility, this variable may also be just a list
2570 of keywords. In this case the interpretation (sequence or type) will be
2571 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2572 :group 'org-todo
2573 :group 'org-keywords
2574 :type '(choice
2575 (repeat :tag "Old syntax, just keywords"
2576 (string :tag "Keyword"))
2577 (repeat :tag "New syntax"
2578 (cons
2579 (choice
2580 :tag "Interpretation"
2581 ;;Quick and dirty way to see
2582 ;;`org-todo-interpretations'. This takes the
2583 ;;place of item arguments
2584 :convert-widget
2585 (lambda (widget)
2586 (widget-put widget
2587 :args (mapcar
2588 (lambda (x)
2589 (widget-convert
2590 (cons 'const x)))
2591 org-todo-interpretation-widgets))
2592 widget))
2593 (repeat
2594 (string :tag "Keyword"))))))
2596 (defvar org-todo-keywords-1 nil
2597 "All TODO and DONE keywords active in a buffer.")
2598 (make-variable-buffer-local 'org-todo-keywords-1)
2599 (defvar org-todo-keywords-for-agenda nil)
2600 (defvar org-done-keywords-for-agenda nil)
2601 (defvar org-todo-keyword-alist-for-agenda nil)
2602 (defvar org-tag-alist-for-agenda nil
2603 "Alist of all tags from all agenda files.")
2604 (defvar org-tag-groups-alist-for-agenda nil
2605 "Alist of all groups tags from all current agenda files.")
2606 (defvar org-tag-groups-alist nil)
2607 (make-variable-buffer-local 'org-tag-groups-alist)
2608 (defvar org-agenda-contributing-files nil)
2609 (defvar org-not-done-keywords nil)
2610 (make-variable-buffer-local 'org-not-done-keywords)
2611 (defvar org-done-keywords nil)
2612 (make-variable-buffer-local 'org-done-keywords)
2613 (defvar org-todo-heads nil)
2614 (make-variable-buffer-local 'org-todo-heads)
2615 (defvar org-todo-sets nil)
2616 (make-variable-buffer-local 'org-todo-sets)
2617 (defvar org-todo-log-states nil)
2618 (make-variable-buffer-local 'org-todo-log-states)
2619 (defvar org-todo-kwd-alist nil)
2620 (make-variable-buffer-local 'org-todo-kwd-alist)
2621 (defvar org-todo-key-alist nil)
2622 (make-variable-buffer-local 'org-todo-key-alist)
2623 (defvar org-todo-key-trigger nil)
2624 (make-variable-buffer-local 'org-todo-key-trigger)
2626 (defcustom org-todo-interpretation 'sequence
2627 "Controls how TODO keywords are interpreted.
2628 This variable is in principle obsolete and is only used for
2629 backward compatibility, if the interpretation of todo keywords is
2630 not given already in `org-todo-keywords'. See that variable for
2631 more information."
2632 :group 'org-todo
2633 :group 'org-keywords
2634 :type '(choice (const sequence)
2635 (const type)))
2637 (defcustom org-use-fast-todo-selection t
2638 "Non-nil means use the fast todo selection scheme with C-c C-t.
2639 This variable describes if and under what circumstances the cycling
2640 mechanism for TODO keywords will be replaced by a single-key, direct
2641 selection scheme.
2643 When nil, fast selection is never used.
2645 When the symbol `prefix', it will be used when `org-todo' is called
2646 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2647 `C-u t' in an agenda buffer.
2649 When t, fast selection is used by default. In this case, the prefix
2650 argument forces cycling instead.
2652 In all cases, the special interface is only used if access keys have
2653 actually been assigned by the user, i.e. if keywords in the configuration
2654 are followed by a letter in parenthesis, like TODO(t)."
2655 :group 'org-todo
2656 :type '(choice
2657 (const :tag "Never" nil)
2658 (const :tag "By default" t)
2659 (const :tag "Only with C-u C-c C-t" prefix)))
2661 (defcustom org-provide-todo-statistics t
2662 "Non-nil means update todo statistics after insert and toggle.
2663 ALL-HEADLINES means update todo statistics by including headlines
2664 with no TODO keyword as well, counting them as not done.
2665 A list of TODO keywords means the same, but skip keywords that are
2666 not in this list.
2667 When set to a list of two lists, the first list contains keywords
2668 to consider as TODO keywords, the second list contains keywords
2669 to consider as DONE keywords.
2671 When this is set, todo statistics is updated in the parent of the
2672 current entry each time a todo state is changed."
2673 :group 'org-todo
2674 :type '(choice
2675 (const :tag "Yes, only for TODO entries" t)
2676 (const :tag "Yes, including all entries" all-headlines)
2677 (repeat :tag "Yes, for TODOs in this list"
2678 (string :tag "TODO keyword"))
2679 (list :tag "Yes, for TODOs and DONEs in these lists"
2680 (repeat (string :tag "TODO keyword"))
2681 (repeat (string :tag "DONE keyword")))
2682 (other :tag "No TODO statistics" nil)))
2684 (defcustom org-hierarchical-todo-statistics t
2685 "Non-nil means TODO statistics covers just direct children.
2686 When nil, all entries in the subtree are considered.
2687 This has only an effect if `org-provide-todo-statistics' is set.
2688 To set this to nil for only a single subtree, use a COOKIE_DATA
2689 property and include the word \"recursive\" into the value."
2690 :group 'org-todo
2691 :type 'boolean)
2693 (defcustom org-after-todo-state-change-hook nil
2694 "Hook which is run after the state of a TODO item was changed.
2695 The new state (a string with a TODO keyword, or nil) is available in the
2696 Lisp variable `org-state'."
2697 :group 'org-todo
2698 :type 'hook)
2700 (defvar org-blocker-hook nil
2701 "Hook for functions that are allowed to block a state change.
2703 Functions in this hook should not modify the buffer.
2704 Each function gets as its single argument a property list,
2705 see `org-trigger-hook' for more information about this list.
2707 If any of the functions in this hook returns nil, the state change
2708 is blocked.")
2710 (defvar org-trigger-hook nil
2711 "Hook for functions that are triggered by a state change.
2713 Each function gets as its single argument a property list with at
2714 least the following elements:
2716 (:type type-of-change :position pos-at-entry-start
2717 :from old-state :to new-state)
2719 Depending on the type, more properties may be present.
2721 This mechanism is currently implemented for:
2723 TODO state changes
2724 ------------------
2725 :type todo-state-change
2726 :from previous state (keyword as a string), or nil, or a symbol
2727 'todo' or 'done', to indicate the general type of state.
2728 :to new state, like in :from")
2730 (defcustom org-enforce-todo-dependencies nil
2731 "Non-nil means undone TODO entries will block switching the parent to DONE.
2732 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2733 be blocked if any prior sibling is not yet done.
2734 Finally, if the parent is blocked because of ordered siblings of its own,
2735 the child will also be blocked."
2736 :set (lambda (var val)
2737 (set var val)
2738 (if val
2739 (add-hook 'org-blocker-hook
2740 'org-block-todo-from-children-or-siblings-or-parent)
2741 (remove-hook 'org-blocker-hook
2742 'org-block-todo-from-children-or-siblings-or-parent)))
2743 :group 'org-todo
2744 :type 'boolean)
2746 (defcustom org-enforce-todo-checkbox-dependencies nil
2747 "Non-nil means unchecked boxes will block switching the parent to DONE.
2748 When this is nil, checkboxes have no influence on switching TODO states.
2749 When non-nil, you first need to check off all check boxes before the TODO
2750 entry can be switched to DONE.
2751 This variable needs to be set before org.el is loaded, and you need to
2752 restart Emacs after a change to make the change effective. The only way
2753 to change is while Emacs is running is through the customize interface."
2754 :set (lambda (var val)
2755 (set var val)
2756 (if val
2757 (add-hook 'org-blocker-hook
2758 'org-block-todo-from-checkboxes)
2759 (remove-hook 'org-blocker-hook
2760 'org-block-todo-from-checkboxes)))
2761 :group 'org-todo
2762 :type 'boolean)
2764 (defcustom org-treat-insert-todo-heading-as-state-change nil
2765 "Non-nil means inserting a TODO heading is treated as state change.
2766 So when the command \\[org-insert-todo-heading] is used, state change
2767 logging will apply if appropriate. When nil, the new TODO item will
2768 be inserted directly, and no logging will take place."
2769 :group 'org-todo
2770 :type 'boolean)
2772 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2773 "Non-nil means switching TODO states with S-cursor counts as state change.
2774 This is the default behavior. However, setting this to nil allows a
2775 convenient way to select a TODO state and bypass any logging associated
2776 with that."
2777 :group 'org-todo
2778 :type 'boolean)
2780 (defcustom org-todo-state-tags-triggers nil
2781 "Tag changes that should be triggered by TODO state changes.
2782 This is a list. Each entry is
2784 (state-change (tag . flag) .......)
2786 State-change can be a string with a state, and empty string to indicate the
2787 state that has no TODO keyword, or it can be one of the symbols `todo'
2788 or `done', meaning any not-done or done state, respectively."
2789 :group 'org-todo
2790 :group 'org-tags
2791 :type '(repeat
2792 (cons (choice :tag "When changing to"
2793 (const :tag "Not-done state" todo)
2794 (const :tag "Done state" done)
2795 (string :tag "State"))
2796 (repeat
2797 (cons :tag "Tag action"
2798 (string :tag "Tag")
2799 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2801 (defcustom org-log-done nil
2802 "Information to record when a task moves to the DONE state.
2804 Possible values are:
2806 nil Don't add anything, just change the keyword
2807 time Add a time stamp to the task
2808 note Prompt for a note and add it with template `org-log-note-headings'
2810 This option can also be set with on a per-file-basis with
2812 #+STARTUP: nologdone
2813 #+STARTUP: logdone
2814 #+STARTUP: lognotedone
2816 You can have local logging settings for a subtree by setting the LOGGING
2817 property to one or more of these keywords."
2818 :group 'org-todo
2819 :group 'org-progress
2820 :type '(choice
2821 (const :tag "No logging" nil)
2822 (const :tag "Record CLOSED timestamp" time)
2823 (const :tag "Record CLOSED timestamp with note." note)))
2825 ;; Normalize old uses of org-log-done.
2826 (cond
2827 ((eq org-log-done t) (setq org-log-done 'time))
2828 ((and (listp org-log-done) (memq 'done org-log-done))
2829 (setq org-log-done 'note)))
2831 (defcustom org-log-reschedule nil
2832 "Information to record when the scheduling date of a tasks is modified.
2834 Possible values are:
2836 nil Don't add anything, just change the date
2837 time Add a time stamp to the task
2838 note Prompt for a note and add it with template `org-log-note-headings'
2840 This option can also be set with on a per-file-basis with
2842 #+STARTUP: nologreschedule
2843 #+STARTUP: logreschedule
2844 #+STARTUP: lognotereschedule"
2845 :group 'org-todo
2846 :group 'org-progress
2847 :type '(choice
2848 (const :tag "No logging" nil)
2849 (const :tag "Record timestamp" time)
2850 (const :tag "Record timestamp with note." note)))
2852 (defcustom org-log-redeadline nil
2853 "Information to record when the deadline date of a tasks is modified.
2855 Possible values are:
2857 nil Don't add anything, just change the date
2858 time Add a time stamp to the task
2859 note Prompt for a note and add it with template `org-log-note-headings'
2861 This option can also be set with on a per-file-basis with
2863 #+STARTUP: nologredeadline
2864 #+STARTUP: logredeadline
2865 #+STARTUP: lognoteredeadline
2867 You can have local logging settings for a subtree by setting the LOGGING
2868 property to one or more of these keywords."
2869 :group 'org-todo
2870 :group 'org-progress
2871 :type '(choice
2872 (const :tag "No logging" nil)
2873 (const :tag "Record timestamp" time)
2874 (const :tag "Record timestamp with note." note)))
2876 (defcustom org-log-note-clock-out nil
2877 "Non-nil means record a note when clocking out of an item.
2878 This can also be configured on a per-file basis by adding one of
2879 the following lines anywhere in the buffer:
2881 #+STARTUP: lognoteclock-out
2882 #+STARTUP: nolognoteclock-out"
2883 :group 'org-todo
2884 :group 'org-progress
2885 :type 'boolean)
2887 (defcustom org-log-done-with-time t
2888 "Non-nil means the CLOSED time stamp will contain date and time.
2889 When nil, only the date will be recorded."
2890 :group 'org-progress
2891 :type 'boolean)
2893 (defcustom org-log-note-headings
2894 '((done . "CLOSING NOTE %t")
2895 (state . "State %-12s from %-12S %t")
2896 (note . "Note taken on %t")
2897 (reschedule . "Rescheduled from %S on %t")
2898 (delschedule . "Not scheduled, was %S on %t")
2899 (redeadline . "New deadline from %S on %t")
2900 (deldeadline . "Removed deadline, was %S on %t")
2901 (refile . "Refiled on %t")
2902 (clock-out . ""))
2903 "Headings for notes added to entries.
2904 The value is an alist, with the car being a symbol indicating the note
2905 context, and the cdr is the heading to be used. The heading may also be the
2906 empty string.
2907 %t in the heading will be replaced by a time stamp.
2908 %T will be an active time stamp instead the default inactive one
2909 %d will be replaced by a short-format time stamp.
2910 %D will be replaced by an active short-format time stamp.
2911 %s will be replaced by the new TODO state, in double quotes.
2912 %S will be replaced by the old TODO state, in double quotes.
2913 %u will be replaced by the user name.
2914 %U will be replaced by the full user name.
2916 In fact, it is not a good idea to change the `state' entry, because
2917 agenda log mode depends on the format of these entries."
2918 :group 'org-todo
2919 :group 'org-progress
2920 :type '(list :greedy t
2921 (cons (const :tag "Heading when closing an item" done) string)
2922 (cons (const :tag
2923 "Heading when changing todo state (todo sequence only)"
2924 state) string)
2925 (cons (const :tag "Heading when just taking a note" note) string)
2926 (cons (const :tag "Heading when rescheduling" reschedule) string)
2927 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2928 (cons (const :tag "Heading when changing deadline" redeadline) string)
2929 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2930 (cons (const :tag "Heading when refiling" refile) string)
2931 (cons (const :tag "Heading when clocking out" clock-out) string)))
2933 (unless (assq 'note org-log-note-headings)
2934 (push '(note . "%t") org-log-note-headings))
2936 (defcustom org-log-into-drawer nil
2937 "Non-nil means insert state change notes and time stamps into a drawer.
2938 When nil, state changes notes will be inserted after the headline and
2939 any scheduling and clock lines, but not inside a drawer.
2941 The value of this variable should be the name of the drawer to use.
2942 LOGBOOK is proposed as the default drawer for this purpose, you can
2943 also set this to a string to define the drawer of your choice.
2945 A value of t is also allowed, representing \"LOGBOOK\".
2947 A value of t or nil can also be set with on a per-file-basis with
2949 #+STARTUP: logdrawer
2950 #+STARTUP: nologdrawer
2952 If this variable is set, `org-log-state-notes-insert-after-drawers'
2953 will be ignored.
2955 You can set the property LOG_INTO_DRAWER to overrule this setting for
2956 a subtree.
2958 Do not check directly this variable in a Lisp program. Call
2959 function `org-log-into-drawer' instead."
2960 :group 'org-todo
2961 :group 'org-progress
2962 :type '(choice
2963 (const :tag "Not into a drawer" nil)
2964 (const :tag "LOGBOOK" t)
2965 (string :tag "Other")))
2967 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2969 (defun org-log-into-drawer ()
2970 "Name of the log drawer, as a string, or nil.
2971 This is the value of `org-log-into-drawer'. However, if the
2972 current entry has or inherits a LOG_INTO_DRAWER property, it will
2973 be used instead of the default value."
2974 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2975 (cond ((equal p "nil") nil)
2976 ((equal p "t") "LOGBOOK")
2977 ((stringp p) p)
2978 (p "LOGBOOK")
2979 ((stringp org-log-into-drawer) org-log-into-drawer)
2980 (org-log-into-drawer "LOGBOOK"))))
2982 (defcustom org-log-state-notes-insert-after-drawers nil
2983 "Non-nil means insert state change notes after any drawers in entry.
2984 Only the drawers that *immediately* follow the headline and the
2985 deadline/scheduled line are skipped.
2986 When nil, insert notes right after the heading and perhaps the line
2987 with deadline/scheduling if present.
2989 This variable will have no effect if `org-log-into-drawer' is
2990 set."
2991 :group 'org-todo
2992 :group 'org-progress
2993 :type 'boolean)
2995 (defcustom org-log-states-order-reversed t
2996 "Non-nil means the latest state note will be directly after heading.
2997 When nil, the state change notes will be ordered according to time.
2999 This option can also be set with on a per-file-basis with
3001 #+STARTUP: logstatesreversed
3002 #+STARTUP: nologstatesreversed"
3003 :group 'org-todo
3004 :group 'org-progress
3005 :type 'boolean)
3007 (defcustom org-todo-repeat-to-state nil
3008 "The TODO state to which a repeater should return the repeating task.
3009 By default this is the first task in a TODO sequence, or the previous state
3010 in a TODO_TYP set. But you can specify another task here.
3011 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3012 :group 'org-todo
3013 :version "24.1"
3014 :type '(choice (const :tag "Head of sequence" nil)
3015 (string :tag "Specific state")))
3017 (defcustom org-log-repeat 'time
3018 "Non-nil means record moving through the DONE state when triggering repeat.
3019 An auto-repeating task is immediately switched back to TODO when
3020 marked DONE. If you are not logging state changes (by adding \"@\"
3021 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3022 record a closing note, there will be no record of the task moving
3023 through DONE. This variable forces taking a note anyway.
3025 nil Don't force a record
3026 time Record a time stamp
3027 note Prompt for a note and add it with template `org-log-note-headings'
3029 This option can also be set with on a per-file-basis with
3031 #+STARTUP: nologrepeat
3032 #+STARTUP: logrepeat
3033 #+STARTUP: lognoterepeat
3035 You can have local logging settings for a subtree by setting the LOGGING
3036 property to one or more of these keywords."
3037 :group 'org-todo
3038 :group 'org-progress
3039 :type '(choice
3040 (const :tag "Don't force a record" nil)
3041 (const :tag "Force recording the DONE state" time)
3042 (const :tag "Force recording a note with the DONE state" note)))
3045 (defgroup org-priorities nil
3046 "Priorities in Org-mode."
3047 :tag "Org Priorities"
3048 :group 'org-todo)
3050 (defcustom org-enable-priority-commands t
3051 "Non-nil means priority commands are active.
3052 When nil, these commands will be disabled, so that you never accidentally
3053 set a priority."
3054 :group 'org-priorities
3055 :type 'boolean)
3057 (defcustom org-highest-priority ?A
3058 "The highest priority of TODO items. A character like ?A, ?B etc.
3059 Must have a smaller ASCII number than `org-lowest-priority'."
3060 :group 'org-priorities
3061 :type 'character)
3063 (defcustom org-lowest-priority ?C
3064 "The lowest priority of TODO items. A character like ?A, ?B etc.
3065 Must have a larger ASCII number than `org-highest-priority'."
3066 :group 'org-priorities
3067 :type 'character)
3069 (defcustom org-default-priority ?B
3070 "The default priority of TODO items.
3071 This is the priority an item gets if no explicit priority is given.
3072 When starting to cycle on an empty priority the first step in the cycle
3073 depends on `org-priority-start-cycle-with-default'. The resulting first
3074 step priority must not exceed the range from `org-highest-priority' to
3075 `org-lowest-priority' which means that `org-default-priority' has to be
3076 in this range exclusive or inclusive the range boundaries. Else the
3077 first step refuses to set the default and the second will fall back
3078 to (depending on the command used) the highest or lowest priority."
3079 :group 'org-priorities
3080 :type 'character)
3082 (defcustom org-priority-start-cycle-with-default t
3083 "Non-nil means start with default priority when starting to cycle.
3084 When this is nil, the first step in the cycle will be (depending on the
3085 command used) one higher or lower than the default priority.
3086 See also `org-default-priority'."
3087 :group 'org-priorities
3088 :type 'boolean)
3090 (defcustom org-get-priority-function nil
3091 "Function to extract the priority from a string.
3092 The string is normally the headline. If this is nil Org computes the
3093 priority from the priority cookie like [#A] in the headline. It returns
3094 an integer, increasing by 1000 for each priority level.
3095 The user can set a different function here, which should take a string
3096 as an argument and return the numeric priority."
3097 :group 'org-priorities
3098 :version "24.1"
3099 :type '(choice
3100 (const nil)
3101 (function)))
3103 (defgroup org-time nil
3104 "Options concerning time stamps and deadlines in Org-mode."
3105 :tag "Org Time"
3106 :group 'org)
3108 (defcustom org-time-stamp-rounding-minutes '(0 5)
3109 "Number of minutes to round time stamps to.
3110 These are two values, the first applies when first creating a time stamp.
3111 The second applies when changing it with the commands `S-up' and `S-down'.
3112 When changing the time stamp, this means that it will change in steps
3113 of N minutes, as given by the second value.
3115 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3116 numbers should be factors of 60, so for example 5, 10, 15.
3118 When this is larger than 1, you can still force an exact time stamp by using
3119 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3120 and by using a prefix arg to `S-up/down' to specify the exact number
3121 of minutes to shift."
3122 :group 'org-time
3123 :get (lambda (var) ; Make sure both elements are there
3124 (if (integerp (default-value var))
3125 (list (default-value var) 5)
3126 (default-value var)))
3127 :type '(list
3128 (integer :tag "when inserting times")
3129 (integer :tag "when modifying times")))
3131 ;; Normalize old customizations of this variable.
3132 (when (integerp org-time-stamp-rounding-minutes)
3133 (setq org-time-stamp-rounding-minutes
3134 (list org-time-stamp-rounding-minutes
3135 org-time-stamp-rounding-minutes)))
3137 (defcustom org-display-custom-times nil
3138 "Non-nil means overlay custom formats over all time stamps.
3139 The formats are defined through the variable `org-time-stamp-custom-formats'.
3140 To turn this on on a per-file basis, insert anywhere in the file:
3141 #+STARTUP: customtime"
3142 :group 'org-time
3143 :set 'set-default
3144 :type 'sexp)
3145 (make-variable-buffer-local 'org-display-custom-times)
3147 (defcustom org-time-stamp-custom-formats
3148 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3149 "Custom formats for time stamps. See `format-time-string' for the syntax.
3150 These are overlaid over the default ISO format if the variable
3151 `org-display-custom-times' is set. Time like %H:%M should be at the
3152 end of the second format. The custom formats are also honored by export
3153 commands, if custom time display is turned on at the time of export."
3154 :group 'org-time
3155 :type 'sexp)
3157 (defun org-time-stamp-format (&optional long inactive)
3158 "Get the right format for a time string."
3159 (let ((f (if long (cdr org-time-stamp-formats)
3160 (car org-time-stamp-formats))))
3161 (if inactive
3162 (concat "[" (substring f 1 -1) "]")
3163 f)))
3165 (defcustom org-time-clocksum-format
3166 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3167 "The format string used when creating CLOCKSUM lines.
3168 This is also used when Org mode generates a time duration.
3170 The value can be a single format string containing two
3171 %-sequences, which will be filled with the number of hours and
3172 minutes in that order.
3174 Alternatively, the value can be a plist associating any of the
3175 keys :years, :months, :weeks, :days, :hours or :minutes with
3176 format strings. The time duration is formatted using only the
3177 time components that are needed and concatenating the results.
3178 If a time unit in absent, it falls back to the next smallest
3179 unit.
3181 The keys :require-years, :require-months, :require-days,
3182 :require-weeks, :require-hours, :require-minutes are also
3183 meaningful. A non-nil value for these keys indicates that the
3184 corresponding time component should always be included, even if
3185 its value is 0.
3188 For example,
3190 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3191 :require-minutes t)
3193 means durations longer than a day will be expressed in days,
3194 hours and minutes, and durations less than a day will always be
3195 expressed in hours and minutes (even for durations less than an
3196 hour).
3198 The value
3200 \(:days \"%dd\" :minutes \"%dm\")
3202 means durations longer than a day will be expressed in days and
3203 minutes, and durations less than a day will be expressed entirely
3204 in minutes (even for durations longer than an hour)."
3205 :group 'org-time
3206 :group 'org-clock
3207 :version "24.4"
3208 :package-version '(Org . "8.0")
3209 :type '(choice (string :tag "Format string")
3210 (set :tag "Plist"
3211 (group :inline t (const :tag "Years" :years)
3212 (string :tag "Format string"))
3213 (group :inline t
3214 (const :tag "Always show years" :require-years)
3215 (const t))
3216 (group :inline t (const :tag "Months" :months)
3217 (string :tag "Format string"))
3218 (group :inline t
3219 (const :tag "Always show months" :require-months)
3220 (const t))
3221 (group :inline t (const :tag "Weeks" :weeks)
3222 (string :tag "Format string"))
3223 (group :inline t
3224 (const :tag "Always show weeks" :require-weeks)
3225 (const t))
3226 (group :inline t (const :tag "Days" :days)
3227 (string :tag "Format string"))
3228 (group :inline t
3229 (const :tag "Always show days" :require-days)
3230 (const t))
3231 (group :inline t (const :tag "Hours" :hours)
3232 (string :tag "Format string"))
3233 (group :inline t
3234 (const :tag "Always show hours" :require-hours)
3235 (const t))
3236 (group :inline t (const :tag "Minutes" :minutes)
3237 (string :tag "Format string"))
3238 (group :inline t
3239 (const :tag "Always show minutes" :require-minutes)
3240 (const t)))))
3242 (defcustom org-time-clocksum-use-fractional nil
3243 "When non-nil, \\[org-clock-display] uses fractional times.
3244 See `org-time-clocksum-format' for more on time clock formats."
3245 :group 'org-time
3246 :group 'org-clock
3247 :version "24.3"
3248 :type 'boolean)
3250 (defcustom org-time-clocksum-use-effort-durations nil
3251 "When non-nil, \\[org-clock-display] uses effort durations.
3252 E.g. by default, one day is considered to be a 8 hours effort,
3253 so a task that has been clocked for 16 hours will be displayed
3254 as during 2 days in the clock display or in the clocktable.
3256 See `org-effort-durations' on how to set effort durations
3257 and `org-time-clocksum-format' for more on time clock formats."
3258 :group 'org-time
3259 :group 'org-clock
3260 :version "24.4"
3261 :package-version '(Org . "8.0")
3262 :type 'boolean)
3264 (defcustom org-time-clocksum-fractional-format "%.2f"
3265 "The format string used when creating CLOCKSUM lines,
3266 or when Org mode generates a time duration, if
3267 `org-time-clocksum-use-fractional' is enabled.
3269 The value can be a single format string containing one
3270 %-sequence, which will be filled with the number of hours as
3271 a float.
3273 Alternatively, the value can be a plist associating any of the
3274 keys :years, :months, :weeks, :days, :hours or :minutes with
3275 a format string. The time duration is formatted using the
3276 largest time unit which gives a non-zero integer part. If all
3277 specified formats have zero integer part, the smallest time unit
3278 is used."
3279 :group 'org-time
3280 :type '(choice (string :tag "Format string")
3281 (set (group :inline t (const :tag "Years" :years)
3282 (string :tag "Format string"))
3283 (group :inline t (const :tag "Months" :months)
3284 (string :tag "Format string"))
3285 (group :inline t (const :tag "Weeks" :weeks)
3286 (string :tag "Format string"))
3287 (group :inline t (const :tag "Days" :days)
3288 (string :tag "Format string"))
3289 (group :inline t (const :tag "Hours" :hours)
3290 (string :tag "Format string"))
3291 (group :inline t (const :tag "Minutes" :minutes)
3292 (string :tag "Format string")))))
3294 (defcustom org-deadline-warning-days 14
3295 "Number of days before expiration during which a deadline becomes active.
3296 This variable governs the display in sparse trees and in the agenda.
3297 When 0 or negative, it means use this number (the absolute value of it)
3298 even if a deadline has a different individual lead time specified.
3300 Custom commands can set this variable in the options section."
3301 :group 'org-time
3302 :group 'org-agenda-daily/weekly
3303 :type 'integer)
3305 (defcustom org-scheduled-delay-days 0
3306 "Number of days before a scheduled item becomes active.
3307 This variable governs the display in sparse trees and in the agenda.
3308 The default value (i.e. 0) means: don't delay scheduled item.
3309 When negative, it means use this number (the absolute value of it)
3310 even if a scheduled item has a different individual delay time
3311 specified.
3313 Custom commands can set this variable in the options section."
3314 :group 'org-time
3315 :group 'org-agenda-daily/weekly
3316 :version "24.4"
3317 :package-version '(Org . "8.0")
3318 :type 'integer)
3320 (defcustom org-read-date-prefer-future t
3321 "Non-nil means assume future for incomplete date input from user.
3322 This affects the following situations:
3323 1. The user gives a month but not a year.
3324 For example, if it is April and you enter \"feb 2\", this will be read
3325 as Feb 2, *next* year. \"May 5\", however, will be this year.
3326 2. The user gives a day, but no month.
3327 For example, if today is the 15th, and you enter \"3\", Org-mode will
3328 read this as the third of *next* month. However, if you enter \"17\",
3329 it will be considered as *this* month.
3331 If you set this variable to the symbol `time', then also the following
3332 will work:
3334 3. If the user gives a time.
3335 If the time is before now, it will be interpreted as tomorrow.
3337 Currently none of this works for ISO week specifications.
3339 When this option is nil, the current day, month and year will always be
3340 used as defaults.
3342 See also `org-agenda-jump-prefer-future'."
3343 :group 'org-time
3344 :type '(choice
3345 (const :tag "Never" nil)
3346 (const :tag "Check month and day" t)
3347 (const :tag "Check month, day, and time" time)))
3349 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3350 "Should the agenda jump command prefer the future for incomplete dates?
3351 The default is to do the same as configured in `org-read-date-prefer-future'.
3352 But you can also set a deviating value here.
3353 This may t or nil, or the symbol `org-read-date-prefer-future'."
3354 :group 'org-agenda
3355 :group 'org-time
3356 :version "24.1"
3357 :type '(choice
3358 (const :tag "Use org-read-date-prefer-future"
3359 org-read-date-prefer-future)
3360 (const :tag "Never" nil)
3361 (const :tag "Always" t)))
3363 (defcustom org-read-date-force-compatible-dates t
3364 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3366 Depending on the system Emacs is running on, certain dates cannot
3367 be represented with the type used internally to represent time.
3368 Dates between 1970-1-1 and 2038-1-1 can always be represented
3369 correctly. Some systems allow for earlier dates, some for later,
3370 some for both. One way to find out it to insert any date into an
3371 Org buffer, putting the cursor on the year and hitting S-up and
3372 S-down to test the range.
3374 When this variable is set to t, the date/time prompt will not let
3375 you specify dates outside the 1970-2037 range, so it is certain that
3376 these dates will work in whatever version of Emacs you are
3377 running, and also that you can move a file from one Emacs implementation
3378 to another. WHenever Org is forcing the year for you, it will display
3379 a message and beep.
3381 When this variable is nil, Org will check if the date is
3382 representable in the specific Emacs implementation you are using.
3383 If not, it will force a year, usually the current year, and beep
3384 to remind you. Currently this setting is not recommended because
3385 the likelihood that you will open your Org files in an Emacs that
3386 has limited date range is not negligible.
3388 A workaround for this problem is to use diary sexp dates for time
3389 stamps outside of this range."
3390 :group 'org-time
3391 :version "24.1"
3392 :type 'boolean)
3394 (defcustom org-read-date-display-live t
3395 "Non-nil means display current interpretation of date prompt live.
3396 This display will be in an overlay, in the minibuffer."
3397 :group 'org-time
3398 :type 'boolean)
3400 (defcustom org-read-date-popup-calendar t
3401 "Non-nil means pop up a calendar when prompting for a date.
3402 In the calendar, the date can be selected with mouse-1. However, the
3403 minibuffer will also be active, and you can simply enter the date as well.
3404 When nil, only the minibuffer will be available."
3405 :group 'org-time
3406 :type 'boolean)
3407 (org-defvaralias 'org-popup-calendar-for-date-prompt
3408 'org-read-date-popup-calendar)
3410 (make-obsolete-variable
3411 'org-read-date-minibuffer-setup-hook
3412 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3413 (defcustom org-read-date-minibuffer-setup-hook nil
3414 "Hook to be used to set up keys for the date/time interface.
3415 Add key definitions to `minibuffer-local-map', which will be a
3416 temporary copy.
3418 WARNING: This option is obsolete, you should use
3419 `org-read-date-minibuffer-local-map' to set up keys."
3420 :group 'org-time
3421 :type 'hook)
3423 (defcustom org-extend-today-until 0
3424 "The hour when your day really ends. Must be an integer.
3425 This has influence for the following applications:
3426 - When switching the agenda to \"today\". It it is still earlier than
3427 the time given here, the day recognized as TODAY is actually yesterday.
3428 - When a date is read from the user and it is still before the time given
3429 here, the current date and time will be assumed to be yesterday, 23:59.
3430 Also, timestamps inserted in capture templates follow this rule.
3432 IMPORTANT: This is a feature whose implementation is and likely will
3433 remain incomplete. Really, it is only here because past midnight seems to
3434 be the favorite working time of John Wiegley :-)"
3435 :group 'org-time
3436 :type 'integer)
3438 (defcustom org-use-effective-time nil
3439 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3440 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3441 \"effective time\" of any timestamps between midnight and 8am will be
3442 23:59 of the previous day."
3443 :group 'org-time
3444 :version "24.1"
3445 :type 'boolean)
3447 (defcustom org-use-last-clock-out-time-as-effective-time nil
3448 "When non-nil, use the last clock out time for `org-todo'.
3449 Note that this option has precedence over the combined use of
3450 `org-use-effective-time' and `org-extend-today-until'."
3451 :group 'org-time
3452 :version "24.4"
3453 :package-version '(Org . "8.0")
3454 :type 'boolean)
3456 (defcustom org-edit-timestamp-down-means-later nil
3457 "Non-nil means S-down will increase the time in a time stamp.
3458 When nil, S-up will increase."
3459 :group 'org-time
3460 :type 'boolean)
3462 (defcustom org-calendar-follow-timestamp-change t
3463 "Non-nil means make the calendar window follow timestamp changes.
3464 When a timestamp is modified and the calendar window is visible, it will be
3465 moved to the new date."
3466 :group 'org-time
3467 :type 'boolean)
3469 (defgroup org-tags nil
3470 "Options concerning tags in Org-mode."
3471 :tag "Org Tags"
3472 :group 'org)
3474 (defcustom org-tag-alist nil
3475 "List of tags allowed in Org-mode files.
3476 When this list is nil, Org-mode will base TAG input on what is already in the
3477 buffer.
3478 The value of this variable is an alist, the car of each entry must be a
3479 keyword as a string, the cdr may be a character that is used to select
3480 that tag through the fast-tag-selection interface.
3481 See the manual for details."
3482 :group 'org-tags
3483 :type '(repeat
3484 (choice
3485 (cons (string :tag "Tag name")
3486 (character :tag "Access char"))
3487 (list :tag "Start radio group"
3488 (const :startgroup)
3489 (option (string :tag "Group description")))
3490 (list :tag "Group tags delimiter"
3491 (const :grouptags))
3492 (list :tag "End radio group"
3493 (const :endgroup)
3494 (option (string :tag "Group description")))
3495 (const :tag "New line" (:newline)))))
3497 (defcustom org-tag-persistent-alist nil
3498 "List of tags that will always appear in all Org-mode files.
3499 This is in addition to any in buffer settings or customizations
3500 of `org-tag-alist'.
3501 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3502 The value of this variable is an alist, the car of each entry must be a
3503 keyword as a string, the cdr may be a character that is used to select
3504 that tag through the fast-tag-selection interface.
3505 See the manual for details.
3506 To disable these tags on a per-file basis, insert anywhere in the file:
3507 #+STARTUP: noptag"
3508 :group 'org-tags
3509 :type '(repeat
3510 (choice
3511 (cons (string :tag "Tag name")
3512 (character :tag "Access char"))
3513 (const :tag "Start radio group" (:startgroup))
3514 (const :tag "Group tags delimiter" (:grouptags))
3515 (const :tag "End radio group" (:endgroup))
3516 (const :tag "New line" (:newline)))))
3518 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3519 "If non-nil, always offer completion for all tags of all agenda files.
3520 Instead of customizing this variable directly, you might want to
3521 set it locally for capture buffers, because there no list of
3522 tags in that file can be created dynamically (there are none).
3524 (add-hook 'org-capture-mode-hook
3525 (lambda ()
3526 (set (make-local-variable
3527 'org-complete-tags-always-offer-all-agenda-tags)
3528 t)))"
3529 :group 'org-tags
3530 :version "24.1"
3531 :type 'boolean)
3533 (defvar org-file-tags nil
3534 "List of tags that can be inherited by all entries in the file.
3535 The tags will be inherited if the variable `org-use-tag-inheritance'
3536 says they should be.
3537 This variable is populated from #+FILETAGS lines.")
3539 (defcustom org-use-fast-tag-selection 'auto
3540 "Non-nil means use fast tag selection scheme.
3541 This is a special interface to select and deselect tags with single keys.
3542 When nil, fast selection is never used.
3543 When the symbol `auto', fast selection is used if and only if selection
3544 characters for tags have been configured, either through the variable
3545 `org-tag-alist' or through a #+TAGS line in the buffer.
3546 When t, fast selection is always used and selection keys are assigned
3547 automatically if necessary."
3548 :group 'org-tags
3549 :type '(choice
3550 (const :tag "Always" t)
3551 (const :tag "Never" nil)
3552 (const :tag "When selection characters are configured" auto)))
3554 (defcustom org-fast-tag-selection-single-key nil
3555 "Non-nil means fast tag selection exits after first change.
3556 When nil, you have to press RET to exit it.
3557 During fast tag selection, you can toggle this flag with `C-c'.
3558 This variable can also have the value `expert'. In this case, the window
3559 displaying the tags menu is not even shown, until you press C-c again."
3560 :group 'org-tags
3561 :type '(choice
3562 (const :tag "No" nil)
3563 (const :tag "Yes" t)
3564 (const :tag "Expert" expert)))
3566 (defvar org-fast-tag-selection-include-todo nil
3567 "Non-nil means fast tags selection interface will also offer TODO states.
3568 This is an undocumented feature, you should not rely on it.")
3570 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3571 "The column to which tags should be indented in a headline.
3572 If this number is positive, it specifies the column. If it is negative,
3573 it means that the tags should be flushright to that column. For example,
3574 -80 works well for a normal 80 character screen.
3575 When 0, place tags directly after headline text, with only one space in
3576 between."
3577 :group 'org-tags
3578 :type 'integer)
3580 (defcustom org-auto-align-tags t
3581 "Non-nil keeps tags aligned when modifying headlines.
3582 Some operations (i.e. demoting) change the length of a headline and
3583 therefore shift the tags around. With this option turned on, after
3584 each such operation the tags are again aligned to `org-tags-column'."
3585 :group 'org-tags
3586 :type 'boolean)
3588 (defcustom org-use-tag-inheritance t
3589 "Non-nil means tags in levels apply also for sublevels.
3590 When nil, only the tags directly given in a specific line apply there.
3591 This may also be a list of tags that should be inherited, or a regexp that
3592 matches tags that should be inherited. Additional control is possible
3593 with the variable `org-tags-exclude-from-inheritance' which gives an
3594 explicit list of tags to be excluded from inheritance, even if the value of
3595 `org-use-tag-inheritance' would select it for inheritance.
3597 If this option is t, a match early-on in a tree can lead to a large
3598 number of matches in the subtree when constructing the agenda or creating
3599 a sparse tree. If you only want to see the first match in a tree during
3600 a search, check out the variable `org-tags-match-list-sublevels'."
3601 :group 'org-tags
3602 :type '(choice
3603 (const :tag "Not" nil)
3604 (const :tag "Always" t)
3605 (repeat :tag "Specific tags" (string :tag "Tag"))
3606 (regexp :tag "Tags matched by regexp")))
3608 (defcustom org-tags-exclude-from-inheritance nil
3609 "List of tags that should never be inherited.
3610 This is a way to exclude a few tags from inheritance. For way to do
3611 the opposite, to actively allow inheritance for selected tags,
3612 see the variable `org-use-tag-inheritance'."
3613 :group 'org-tags
3614 :type '(repeat (string :tag "Tag")))
3616 (defun org-tag-inherit-p (tag)
3617 "Check if TAG is one that should be inherited."
3618 (cond
3619 ((member tag org-tags-exclude-from-inheritance) nil)
3620 ((eq org-use-tag-inheritance t) t)
3621 ((not org-use-tag-inheritance) nil)
3622 ((stringp org-use-tag-inheritance)
3623 (string-match org-use-tag-inheritance tag))
3624 ((listp org-use-tag-inheritance)
3625 (member tag org-use-tag-inheritance))
3626 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3628 (defcustom org-tags-match-list-sublevels t
3629 "Non-nil means list also sublevels of headlines matching a search.
3630 This variable applies to tags/property searches, and also to stuck
3631 projects because this search is based on a tags match as well.
3633 When set to the symbol `indented', sublevels are indented with
3634 leading dots.
3636 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3637 the sublevels of a headline matching a tag search often also match
3638 the same search. Listing all of them can create very long lists.
3639 Setting this variable to nil causes subtrees of a match to be skipped.
3641 This variable is semi-obsolete and probably should always be true. It
3642 is better to limit inheritance to certain tags using the variables
3643 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3644 :group 'org-tags
3645 :type '(choice
3646 (const :tag "No, don't list them" nil)
3647 (const :tag "Yes, do list them" t)
3648 (const :tag "List them, indented with leading dots" indented)))
3650 (defcustom org-tags-sort-function nil
3651 "When set, tags are sorted using this function as a comparator."
3652 :group 'org-tags
3653 :type '(choice
3654 (const :tag "No sorting" nil)
3655 (const :tag "Alphabetical" string<)
3656 (const :tag "Reverse alphabetical" string>)
3657 (function :tag "Custom function" nil)))
3659 (defvar org-tags-history nil
3660 "History of minibuffer reads for tags.")
3661 (defvar org-last-tags-completion-table nil
3662 "The last used completion table for tags.")
3663 (defvar org-after-tags-change-hook nil
3664 "Hook that is run after the tags in a line have changed.")
3666 (defgroup org-properties nil
3667 "Options concerning properties in Org-mode."
3668 :tag "Org Properties"
3669 :group 'org)
3671 (defcustom org-property-format "%-10s %s"
3672 "How property key/value pairs should be formatted by `indent-line'.
3673 When `indent-line' hits a property definition, it will format the line
3674 according to this format, mainly to make sure that the values are
3675 lined-up with respect to each other."
3676 :group 'org-properties
3677 :type 'string)
3679 (defcustom org-properties-postprocess-alist nil
3680 "Alist of properties and functions to adjust inserted values.
3681 Elements of this alist must be of the form
3683 ([string] [function])
3685 where [string] must be a property name and [function] must be a
3686 lambda expression: this lambda expression must take one argument,
3687 the value to adjust, and return the new value as a string.
3689 For example, this element will allow the property \"Remaining\"
3690 to be updated wrt the relation between the \"Effort\" property
3691 and the clock summary:
3693 ((\"Remaining\" (lambda(value)
3694 (let ((clocksum (org-clock-sum-current-item))
3695 (effort (org-duration-string-to-minutes
3696 (org-entry-get (point) \"Effort\"))))
3697 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3698 :group 'org-properties
3699 :version "24.1"
3700 :type '(alist :key-type (string :tag "Property")
3701 :value-type (function :tag "Function")))
3703 (defcustom org-use-property-inheritance nil
3704 "Non-nil means properties apply also for sublevels.
3706 This setting is chiefly used during property searches. Turning it on can
3707 cause significant overhead when doing a search, which is why it is not
3708 on by default.
3710 When nil, only the properties directly given in the current entry count.
3711 When t, every property is inherited. The value may also be a list of
3712 properties that should have inheritance, or a regular expression matching
3713 properties that should be inherited.
3715 However, note that some special properties use inheritance under special
3716 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3717 and the properties ending in \"_ALL\" when they are used as descriptor
3718 for valid values of a property.
3720 Note for programmers:
3721 When querying an entry with `org-entry-get', you can control if inheritance
3722 should be used. By default, `org-entry-get' looks only at the local
3723 properties. You can request inheritance by setting the inherit argument
3724 to t (to force inheritance) or to `selective' (to respect the setting
3725 in this variable)."
3726 :group 'org-properties
3727 :type '(choice
3728 (const :tag "Not" nil)
3729 (const :tag "Always" t)
3730 (repeat :tag "Specific properties" (string :tag "Property"))
3731 (regexp :tag "Properties matched by regexp")))
3733 (defun org-property-inherit-p (property)
3734 "Check if PROPERTY is one that should be inherited."
3735 (cond
3736 ((eq org-use-property-inheritance t) t)
3737 ((not org-use-property-inheritance) nil)
3738 ((stringp org-use-property-inheritance)
3739 (string-match org-use-property-inheritance property))
3740 ((listp org-use-property-inheritance)
3741 (member property org-use-property-inheritance))
3742 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3744 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3745 "The default column format, if no other format has been defined.
3746 This variable can be set on the per-file basis by inserting a line
3748 #+COLUMNS: %25ITEM ....."
3749 :group 'org-properties
3750 :type 'string)
3752 (defcustom org-columns-ellipses ".."
3753 "The ellipses to be used when a field in column view is truncated.
3754 When this is the empty string, as many characters as possible are shown,
3755 but then there will be no visual indication that the field has been truncated.
3756 When this is a string of length N, the last N characters of a truncated
3757 field are replaced by this string. If the column is narrower than the
3758 ellipses string, only part of the ellipses string will be shown."
3759 :group 'org-properties
3760 :type 'string)
3762 (defcustom org-columns-modify-value-for-display-function nil
3763 "Function that modifies values for display in column view.
3764 For example, it can be used to cut out a certain part from a time stamp.
3765 The function must take 2 arguments:
3767 column-title The title of the column (*not* the property name)
3768 value The value that should be modified.
3770 The function should return the value that should be displayed,
3771 or nil if the normal value should be used."
3772 :group 'org-properties
3773 :type '(choice (const nil) (function)))
3775 (defconst org-global-properties-fixed
3776 '(("VISIBILITY_ALL" . "folded children content all")
3777 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3778 "List of property/value pairs that can be inherited by any entry.
3780 These are fixed values, for the preset properties. The user variable
3781 that can be used to add to this list is `org-global-properties'.
3783 The entries in this list are cons cells where the car is a property
3784 name and cdr is a string with the value. If the value represents
3785 multiple items like an \"_ALL\" property, separate the items by
3786 spaces.")
3788 (defcustom org-global-properties nil
3789 "List of property/value pairs that can be inherited by any entry.
3791 This list will be combined with the constant `org-global-properties-fixed'.
3793 The entries in this list are cons cells where the car is a property
3794 name and cdr is a string with the value.
3796 You can set buffer-local values for the same purpose in the variable
3797 `org-file-properties' this by adding lines like
3799 #+PROPERTY: NAME VALUE"
3800 :group 'org-properties
3801 :type '(repeat
3802 (cons (string :tag "Property")
3803 (string :tag "Value"))))
3805 (defvar org-file-properties nil
3806 "List of property/value pairs that can be inherited by any entry.
3807 Valid for the current buffer.
3808 This variable is populated from #+PROPERTY lines.")
3809 (make-variable-buffer-local 'org-file-properties)
3811 (defgroup org-agenda nil
3812 "Options concerning agenda views in Org-mode."
3813 :tag "Org Agenda"
3814 :group 'org)
3816 (defvar org-category nil
3817 "Variable used by org files to set a category for agenda display.
3818 Such files should use a file variable to set it, for example
3820 # -*- mode: org; org-category: \"ELisp\"
3822 or contain a special line
3824 #+CATEGORY: ELisp
3826 If the file does not specify a category, then file's base name
3827 is used instead.")
3828 (make-variable-buffer-local 'org-category)
3829 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3831 (defcustom org-agenda-files nil
3832 "The files to be used for agenda display.
3833 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3834 \\[org-remove-file]. You can also use customize to edit the list.
3836 If an entry is a directory, all files in that directory that are matched by
3837 `org-agenda-file-regexp' will be part of the file list.
3839 If the value of the variable is not a list but a single file name, then
3840 the list of agenda files is actually stored and maintained in that file, one
3841 agenda file per line. In this file paths can be given relative to
3842 `org-directory'. Tilde expansion and environment variable substitution
3843 are also made."
3844 :group 'org-agenda
3845 :type '(choice
3846 (repeat :tag "List of files and directories" file)
3847 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3849 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3850 "Regular expression to match files for `org-agenda-files'.
3851 If any element in the list in that variable contains a directory instead
3852 of a normal file, all files in that directory that are matched by this
3853 regular expression will be included."
3854 :group 'org-agenda
3855 :type 'regexp)
3857 (defcustom org-agenda-text-search-extra-files nil
3858 "List of extra files to be searched by text search commands.
3859 These files will be searched in addition to the agenda files by the
3860 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3861 Note that these files will only be searched for text search commands,
3862 not for the other agenda views like todo lists, tag searches or the weekly
3863 agenda. This variable is intended to list notes and possibly archive files
3864 that should also be searched by these two commands.
3865 In fact, if the first element in the list is the symbol `agenda-archives',
3866 then all archive files of all agenda files will be added to the search
3867 scope."
3868 :group 'org-agenda
3869 :type '(set :greedy t
3870 (const :tag "Agenda Archives" agenda-archives)
3871 (repeat :inline t (file))))
3873 (org-defvaralias 'org-agenda-multi-occur-extra-files
3874 'org-agenda-text-search-extra-files)
3876 (defcustom org-agenda-skip-unavailable-files nil
3877 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3878 A nil value means to remove them, after a query, from the list."
3879 :group 'org-agenda
3880 :type 'boolean)
3882 (defcustom org-calendar-to-agenda-key [?c]
3883 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3884 The command `org-calendar-goto-agenda' will be bound to this key. The
3885 default is the character `c' because then `c' can be used to switch back and
3886 forth between agenda and calendar."
3887 :group 'org-agenda
3888 :type 'sexp)
3890 (defcustom org-calendar-insert-diary-entry-key [?i]
3891 "The key to be installed in `calendar-mode-map' for adding diary entries.
3892 This option is irrelevant until `org-agenda-diary-file' has been configured
3893 to point to an Org-mode file. When that is the case, the command
3894 `org-agenda-diary-entry' will be bound to the key given here, by default
3895 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3896 if you want to continue doing this, you need to change this to a different
3897 key."
3898 :group 'org-agenda
3899 :type 'sexp)
3901 (defcustom org-agenda-diary-file 'diary-file
3902 "File to which to add new entries with the `i' key in agenda and calendar.
3903 When this is the symbol `diary-file', the functionality in the Emacs
3904 calendar will be used to add entries to the `diary-file'. But when this
3905 points to a file, `org-agenda-diary-entry' will be used instead."
3906 :group 'org-agenda
3907 :type '(choice
3908 (const :tag "The standard Emacs diary file" diary-file)
3909 (file :tag "Special Org file diary entries")))
3911 (eval-after-load "calendar"
3912 '(progn
3913 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3914 'org-calendar-goto-agenda)
3915 (add-hook 'calendar-mode-hook
3916 (lambda ()
3917 (unless (eq org-agenda-diary-file 'diary-file)
3918 (define-key calendar-mode-map
3919 org-calendar-insert-diary-entry-key
3920 'org-agenda-diary-entry))))))
3922 (defgroup org-latex nil
3923 "Options for embedding LaTeX code into Org-mode."
3924 :tag "Org LaTeX"
3925 :group 'org)
3927 (defcustom org-format-latex-options
3928 '(:foreground default :background default :scale 1.0
3929 :html-foreground "Black" :html-background "Transparent"
3930 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3931 "Options for creating images from LaTeX fragments.
3932 This is a property list with the following properties:
3933 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3934 `default' means use the foreground of the default face.
3935 `auto' means use the foreground from the text face.
3936 :background the background color, or \"Transparent\".
3937 `default' means use the background of the default face.
3938 `auto' means use the background from the text face.
3939 :scale a scaling factor for the size of the images, to get more pixels
3940 :html-foreground, :html-background, :html-scale
3941 the same numbers for HTML export.
3942 :matchers a list indicating which matchers should be used to
3943 find LaTeX fragments. Valid members of this list are:
3944 \"begin\" find environments
3945 \"$1\" find single characters surrounded by $.$
3946 \"$\" find math expressions surrounded by $...$
3947 \"$$\" find math expressions surrounded by $$....$$
3948 \"\\(\" find math expressions surrounded by \\(...\\)
3949 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3950 :group 'org-latex
3951 :type 'plist)
3953 (defcustom org-format-latex-signal-error t
3954 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3955 When nil, just push out a message."
3956 :group 'org-latex
3957 :version "24.1"
3958 :type 'boolean)
3960 (defcustom org-latex-to-mathml-jar-file nil
3961 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3962 Use this to specify additional executable file say a jar file.
3964 When using MathToWeb as the converter, specify the full-path to
3965 your mathtoweb.jar file."
3966 :group 'org-latex
3967 :version "24.1"
3968 :type '(choice
3969 (const :tag "None" nil)
3970 (file :tag "JAR file" :must-match t)))
3972 (defcustom org-latex-to-mathml-convert-command nil
3973 "Command to convert LaTeX fragments to MathML.
3974 Replace format-specifiers in the command as noted below and use
3975 `shell-command' to convert LaTeX to MathML.
3976 %j: Executable file in fully expanded form as specified by
3977 `org-latex-to-mathml-jar-file'.
3978 %I: Input LaTeX file in fully expanded form
3979 %o: Output MathML file
3980 This command is used by `org-create-math-formula'.
3982 When using MathToWeb as the converter, set this to
3983 \"java -jar %j -unicode -force -df %o %I\"."
3984 :group 'org-latex
3985 :version "24.1"
3986 :type '(choice
3987 (const :tag "None" nil)
3988 (string :tag "\nShell command")))
3990 (defcustom org-latex-create-formula-image-program 'dvipng
3991 "Program to convert LaTeX fragments with.
3993 dvipng Process the LaTeX fragments to dvi file, then convert
3994 dvi files to png files using dvipng.
3995 This will also include processing of non-math environments.
3996 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3997 to convert pdf files to png files"
3998 :group 'org-latex
3999 :version "24.1"
4000 :type '(choice
4001 (const :tag "dvipng" dvipng)
4002 (const :tag "imagemagick" imagemagick)))
4004 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
4005 "Path to store latex preview images.
4006 A relative path here creates many directories relative to the
4007 processed org files paths. An absolute path puts all preview
4008 images at the same place."
4009 :group 'org-latex
4010 :version "24.3"
4011 :type 'string)
4013 (defun org-format-latex-mathml-available-p ()
4014 "Return t if `org-latex-to-mathml-convert-command' is usable."
4015 (save-match-data
4016 (when (and (boundp 'org-latex-to-mathml-convert-command)
4017 org-latex-to-mathml-convert-command)
4018 (let ((executable (car (split-string
4019 org-latex-to-mathml-convert-command))))
4020 (when (executable-find executable)
4021 (if (string-match
4022 "%j" org-latex-to-mathml-convert-command)
4023 (file-readable-p org-latex-to-mathml-jar-file)
4024 t))))))
4026 (defcustom org-format-latex-header "\\documentclass{article}
4027 \\usepackage[usenames]{color}
4028 \[PACKAGES]
4029 \[DEFAULT-PACKAGES]
4030 \\pagestyle{empty} % do not remove
4031 % The settings below are copied from fullpage.sty
4032 \\setlength{\\textwidth}{\\paperwidth}
4033 \\addtolength{\\textwidth}{-3cm}
4034 \\setlength{\\oddsidemargin}{1.5cm}
4035 \\addtolength{\\oddsidemargin}{-2.54cm}
4036 \\setlength{\\evensidemargin}{\\oddsidemargin}
4037 \\setlength{\\textheight}{\\paperheight}
4038 \\addtolength{\\textheight}{-\\headheight}
4039 \\addtolength{\\textheight}{-\\headsep}
4040 \\addtolength{\\textheight}{-\\footskip}
4041 \\addtolength{\\textheight}{-3cm}
4042 \\setlength{\\topmargin}{1.5cm}
4043 \\addtolength{\\topmargin}{-2.54cm}"
4044 "The document header used for processing LaTeX fragments.
4045 It is imperative that this header make sure that no page number
4046 appears on the page. The package defined in the variables
4047 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4048 will either replace the placeholder \"[PACKAGES]\" in this
4049 header, or they will be appended."
4050 :group 'org-latex
4051 :type 'string)
4053 (defun org-set-packages-alist (var val)
4054 "Set the packages alist and make sure it has 3 elements per entry."
4055 (set var (mapcar (lambda (x)
4056 (if (and (consp x) (= (length x) 2))
4057 (list (car x) (nth 1 x) t)
4059 val)))
4061 (defun org-get-packages-alist (var)
4062 "Get the packages alist and make sure it has 3 elements per entry."
4063 (mapcar (lambda (x)
4064 (if (and (consp x) (= (length x) 2))
4065 (list (car x) (nth 1 x) t)
4067 (default-value var)))
4069 (defcustom org-latex-default-packages-alist
4070 '(("AUTO" "inputenc" t)
4071 ("T1" "fontenc" t)
4072 ("" "fixltx2e" nil)
4073 ("" "graphicx" t)
4074 ("" "longtable" nil)
4075 ("" "float" nil)
4076 ("" "wrapfig" nil)
4077 ("" "rotating" nil)
4078 ("normalem" "ulem" t)
4079 ("" "amsmath" t)
4080 ("" "textcomp" t)
4081 ("" "marvosym" t)
4082 ("" "wasysym" t)
4083 ("" "amssymb" t)
4084 ("" "capt-of" nil)
4085 ("" "hyperref" nil)
4086 "\\tolerance=1000")
4087 "Alist of default packages to be inserted in the header.
4089 Change this only if one of the packages here causes an
4090 incompatibility with another package you are using.
4092 The packages in this list are needed by one part or another of
4093 Org mode to function properly:
4095 - inputenc, fontenc: for basic font and character selection
4096 - fixltx2e: Important patches of LaTeX itself
4097 - graphicx: for including images
4098 - longtable: For multipage tables
4099 - float, wrapfig: for figure placement
4100 - rotating: for sideways figures and tables
4101 - ulem: for underline and strike-through
4102 - amsmath: for subscript and superscript and math environments
4103 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4104 for interpreting the entities in `org-entities'. You can skip
4105 some of these packages if you don't use any of their symbols.
4106 - capt-of: for captions outside of floats
4107 - hyperref: for cross references
4109 Therefore you should not modify this variable unless you know
4110 what you are doing. The one reason to change it anyway is that
4111 you might be loading some other package that conflicts with one
4112 of the default packages. Each element is either a cell or
4113 a string.
4115 A cell is of the format:
4117 \( \"options\" \"package\" SNIPPET-FLAG).
4119 If SNIPPET-FLAG is non-nil, the package also needs to be included
4120 when compiling LaTeX snippets into images for inclusion into
4121 non-LaTeX output.
4123 A string will be inserted as-is in the header of the document."
4124 :group 'org-latex
4125 :group 'org-export-latex
4126 :set 'org-set-packages-alist
4127 :get 'org-get-packages-alist
4128 :version "24.1"
4129 :type '(repeat
4130 (choice
4131 (list :tag "options/package pair"
4132 (string :tag "options")
4133 (string :tag "package")
4134 (boolean :tag "Snippet"))
4135 (string :tag "A line of LaTeX"))))
4137 (defcustom org-latex-packages-alist nil
4138 "Alist of packages to be inserted in every LaTeX header.
4140 These will be inserted after `org-latex-default-packages-alist'.
4141 Each element is either a cell or a string.
4143 A cell is of the format:
4145 \(\"options\" \"package\" SNIPPET-FLAG)
4147 SNIPPET-FLAG, when non-nil, indicates that this package is also
4148 needed when turning LaTeX snippets into images for inclusion into
4149 non-LaTeX output.
4151 A string will be inserted as-is in the header of the document.
4153 Make sure that you only list packages here which:
4155 - you want in every file;
4156 - do not conflict with the setup in `org-format-latex-header';
4157 - do not conflict with the default packages in
4158 `org-latex-default-packages-alist'."
4159 :group 'org-latex
4160 :group 'org-export-latex
4161 :set 'org-set-packages-alist
4162 :get 'org-get-packages-alist
4163 :type '(repeat
4164 (choice
4165 (list :tag "options/package pair"
4166 (string :tag "options")
4167 (string :tag "package")
4168 (boolean :tag "Snippet"))
4169 (string :tag "A line of LaTeX"))))
4171 (defgroup org-appearance nil
4172 "Settings for Org-mode appearance."
4173 :tag "Org Appearance"
4174 :group 'org)
4176 (defcustom org-level-color-stars-only nil
4177 "Non-nil means fontify only the stars in each headline.
4178 When nil, the entire headline is fontified.
4179 Changing it requires restart of `font-lock-mode' to become effective
4180 also in regions already fontified."
4181 :group 'org-appearance
4182 :type 'boolean)
4184 (defcustom org-hide-leading-stars nil
4185 "Non-nil means hide the first N-1 stars in a headline.
4186 This works by using the face `org-hide' for these stars. This
4187 face is white for a light background, and black for a dark
4188 background. You may have to customize the face `org-hide' to
4189 make this work.
4190 Changing it requires restart of `font-lock-mode' to become effective
4191 also in regions already fontified.
4192 You may also set this on a per-file basis by adding one of the following
4193 lines to the buffer:
4195 #+STARTUP: hidestars
4196 #+STARTUP: showstars"
4197 :group 'org-appearance
4198 :type 'boolean)
4200 (defcustom org-hidden-keywords nil
4201 "List of symbols corresponding to keywords to be hidden the org buffer.
4202 For example, a value '(title) for this list will make the document's title
4203 appear in the buffer without the initial #+TITLE: keyword."
4204 :group 'org-appearance
4205 :version "24.1"
4206 :type '(set (const :tag "#+AUTHOR" author)
4207 (const :tag "#+DATE" date)
4208 (const :tag "#+EMAIL" email)
4209 (const :tag "#+TITLE" title)))
4211 (defcustom org-custom-properties nil
4212 "List of properties (as strings) with a special meaning.
4213 The default use of these custom properties is to let the user
4214 hide them with `org-toggle-custom-properties-visibility'."
4215 :group 'org-properties
4216 :group 'org-appearance
4217 :version "24.3"
4218 :type '(repeat (string :tag "Property Name")))
4220 (defcustom org-fontify-done-headline nil
4221 "Non-nil means change the face of a headline if it is marked DONE.
4222 Normally, only the TODO/DONE keyword indicates the state of a headline.
4223 When this is non-nil, the headline after the keyword is set to the
4224 `org-headline-done' as an additional indication."
4225 :group 'org-appearance
4226 :type 'boolean)
4228 (defcustom org-fontify-emphasized-text t
4229 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4230 Changing this variable requires a restart of Emacs to take effect."
4231 :group 'org-appearance
4232 :type 'boolean)
4234 (defcustom org-fontify-whole-heading-line nil
4235 "Non-nil means fontify the whole line for headings.
4236 This is useful when setting a background color for the
4237 org-level-* faces."
4238 :group 'org-appearance
4239 :type 'boolean)
4241 (defcustom org-highlight-latex-and-related nil
4242 "Non-nil means highlight LaTeX related syntax in the buffer.
4243 When non nil, the value should be a list containing any of the
4244 following symbols:
4245 `latex' Highlight LaTeX snippets and environments.
4246 `script' Highlight subscript and superscript.
4247 `entities' Highlight entities."
4248 :group 'org-appearance
4249 :version "24.4"
4250 :package-version '(Org . "8.0")
4251 :type '(choice
4252 (const :tag "No highlighting" nil)
4253 (set :greedy t :tag "Highlight"
4254 (const :tag "LaTeX snippets and environments" latex)
4255 (const :tag "Subscript and superscript" script)
4256 (const :tag "Entities" entities))))
4258 (defcustom org-hide-emphasis-markers nil
4259 "Non-nil mean font-lock should hide the emphasis marker characters."
4260 :group 'org-appearance
4261 :type 'boolean)
4263 (defcustom org-hide-macro-markers nil
4264 "Non-nil mean font-lock should hide the brackets marking macro calls."
4265 :group 'org-appearance
4266 :type 'boolean)
4268 (defcustom org-pretty-entities nil
4269 "Non-nil means show entities as UTF8 characters.
4270 When nil, the \\name form remains in the buffer."
4271 :group 'org-appearance
4272 :version "24.1"
4273 :type 'boolean)
4275 (defcustom org-pretty-entities-include-sub-superscripts t
4276 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4277 :group 'org-appearance
4278 :version "24.1"
4279 :type 'boolean)
4281 (defvar org-emph-re nil
4282 "Regular expression for matching emphasis.
4283 After a match, the match groups contain these elements:
4284 0 The match of the full regular expression, including the characters
4285 before and after the proper match
4286 1 The character before the proper match, or empty at beginning of line
4287 2 The proper match, including the leading and trailing markers
4288 3 The leading marker like * or /, indicating the type of highlighting
4289 4 The text between the emphasis markers, not including the markers
4290 5 The character after the match, empty at the end of a line")
4291 (defvar org-verbatim-re nil
4292 "Regular expression for matching verbatim text.")
4293 (defvar org-emphasis-regexp-components) ; defined just below
4294 (defvar org-emphasis-alist) ; defined just below
4295 (defun org-set-emph-re (var val)
4296 "Set variable and compute the emphasis regular expression."
4297 (set var val)
4298 (when (and (boundp 'org-emphasis-alist)
4299 (boundp 'org-emphasis-regexp-components)
4300 org-emphasis-alist org-emphasis-regexp-components)
4301 (let* ((e org-emphasis-regexp-components)
4302 (pre (car e))
4303 (post (nth 1 e))
4304 (border (nth 2 e))
4305 (body (nth 3 e))
4306 (nl (nth 4 e))
4307 (body1 (concat body "*?"))
4308 (markers (mapconcat 'car org-emphasis-alist ""))
4309 (vmarkers (mapconcat
4310 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4311 org-emphasis-alist "")))
4312 ;; make sure special characters appear at the right position in the class
4313 (if (string-match "\\^" markers)
4314 (setq markers (concat (replace-match "" t t markers) "^")))
4315 (if (string-match "-" markers)
4316 (setq markers (concat (replace-match "" t t markers) "-")))
4317 (if (string-match "\\^" vmarkers)
4318 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4319 (if (string-match "-" vmarkers)
4320 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4321 (if (> nl 0)
4322 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4323 (int-to-string nl) "\\}")))
4324 ;; Make the regexp
4325 (setq org-emph-re
4326 (concat "\\([" pre "]\\|^\\)"
4327 "\\("
4328 "\\([" markers "]\\)"
4329 "\\("
4330 "[^" border "]\\|"
4331 "[^" border "]"
4332 body1
4333 "[^" border "]"
4334 "\\)"
4335 "\\3\\)"
4336 "\\([" post "]\\|$\\)"))
4337 (setq org-verbatim-re
4338 (concat "\\([" pre "]\\|^\\)"
4339 "\\("
4340 "\\([" vmarkers "]\\)"
4341 "\\("
4342 "[^" border "]\\|"
4343 "[^" border "]"
4344 body1
4345 "[^" border "]"
4346 "\\)"
4347 "\\3\\)"
4348 "\\([" post "]\\|$\\)")))))
4350 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4351 ;; set this option proved cumbersome. See this message/thread:
4352 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4353 (defvar org-emphasis-regexp-components
4354 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4355 "Components used to build the regular expression for emphasis.
4356 This is a list with five entries. Terminology: In an emphasis string
4357 like \" *strong word* \", we call the initial space PREMATCH, the final
4358 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4359 and \"trong wor\" is the body. The different components in this variable
4360 specify what is allowed/forbidden in each part:
4362 pre Chars allowed as prematch. Beginning of line will be allowed too.
4363 post Chars allowed as postmatch. End of line will be allowed too.
4364 border The chars *forbidden* as border characters.
4365 body-regexp A regexp like \".\" to match a body character. Don't use
4366 non-shy groups here, and don't allow newline here.
4367 newline The maximum number of newlines allowed in an emphasis exp.
4369 You need to reload Org or to restart Emacs after customizing this.")
4371 (defcustom org-emphasis-alist
4372 `(("*" bold)
4373 ("/" italic)
4374 ("_" underline)
4375 ("=" org-verbatim verbatim)
4376 ("~" org-code verbatim)
4377 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4378 "Alist of characters and faces to emphasize text.
4379 Text starting and ending with a special character will be emphasized,
4380 for example *bold*, _underlined_ and /italic/. This variable sets the
4381 marker characters and the face to be used by font-lock for highlighting
4382 in Org-mode Emacs buffers.
4384 You need to reload Org or to restart Emacs after customizing this."
4385 :group 'org-appearance
4386 :set 'org-set-emph-re
4387 :version "24.4"
4388 :package-version '(Org . "8.0")
4389 :type '(repeat
4390 (list
4391 (string :tag "Marker character")
4392 (choice
4393 (face :tag "Font-lock-face")
4394 (plist :tag "Face property list"))
4395 (option (const verbatim)))))
4397 (defvar org-protecting-blocks
4398 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4399 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4400 This is needed for font-lock setup.")
4402 ;;; Miscellaneous options
4404 (defgroup org-completion nil
4405 "Completion in Org-mode."
4406 :tag "Org Completion"
4407 :group 'org)
4409 (defcustom org-completion-use-ido nil
4410 "Non-nil means use ido completion wherever possible.
4411 Note that `ido-mode' must be active for this variable to be relevant.
4412 If you decide to turn this variable on, you might well want to turn off
4413 `org-outline-path-complete-in-steps'.
4414 See also `org-completion-use-iswitchb'."
4415 :group 'org-completion
4416 :type 'boolean)
4418 (defcustom org-completion-use-iswitchb nil
4419 "Non-nil means use iswitchb completion wherever possible.
4420 Note that `iswitchb-mode' must be active for this variable to be relevant.
4421 If you decide to turn this variable on, you might well want to turn off
4422 `org-outline-path-complete-in-steps'.
4423 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4424 :group 'org-completion
4425 :type 'boolean)
4427 (defcustom org-completion-fallback-command 'hippie-expand
4428 "The expansion command called by \\[pcomplete] in normal context.
4429 Normal means, no org-mode-specific context."
4430 :group 'org-completion
4431 :type 'function)
4433 ;;; Functions and variables from their packages
4434 ;; Declared here to avoid compiler warnings
4436 ;; XEmacs only
4437 (defvar outline-mode-menu-heading)
4438 (defvar outline-mode-menu-show)
4439 (defvar outline-mode-menu-hide)
4440 (defvar zmacs-regions) ; XEmacs regions
4442 ;; Emacs only
4443 (defvar mark-active)
4445 ;; Various packages
4446 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4447 (declare-function calendar-forward-day "cal-move" (arg))
4448 (declare-function calendar-goto-date "cal-move" (date))
4449 (declare-function calendar-goto-today "cal-move" ())
4450 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4451 (defvar calc-embedded-close-formula)
4452 (defvar calc-embedded-open-formula)
4453 (declare-function cdlatex-tab "ext:cdlatex" ())
4454 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4455 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4456 (defvar font-lock-unfontify-region-function)
4457 (declare-function iswitchb-read-buffer "iswitchb"
4458 (prompt &optional default require-match start matches-set))
4459 (defvar iswitchb-temp-buflist)
4460 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4461 (defvar org-agenda-tags-todo-honor-ignore-options)
4462 (declare-function org-agenda-skip "org-agenda" ())
4463 (declare-function
4464 org-agenda-format-item "org-agenda"
4465 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4466 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4467 (declare-function org-agenda-change-all-lines "org-agenda"
4468 (newhead hdmarker &optional fixface just-this))
4469 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4470 (declare-function org-agenda-maybe-redo "org-agenda" ())
4471 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4472 (beg end))
4473 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4474 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4475 "org-agenda" (&optional end))
4476 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4477 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4478 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4479 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4480 (declare-function org-indent-mode "org-indent" (&optional arg))
4481 (declare-function parse-time-string "parse-time" (string))
4482 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4483 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4484 (defvar remember-data-file)
4485 (defvar texmathp-why)
4486 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4487 (declare-function table--at-cell-p "table" (position &optional object at-column))
4488 (declare-function calc-eval "calc" (str &optional separator &rest args))
4490 ;;;###autoload
4491 (defun turn-on-orgtbl ()
4492 "Unconditionally turn on `orgtbl-mode'."
4493 (require 'org-table)
4494 (orgtbl-mode 1))
4496 (defun org-at-table-p (&optional table-type)
4497 "Return t if the cursor is inside an org-type table.
4498 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4499 (if org-enable-table-editor
4500 (save-excursion
4501 (beginning-of-line 1)
4502 (looking-at (if table-type org-table-any-line-regexp
4503 org-table-line-regexp)))
4504 nil))
4505 (defsubst org-table-p () (org-at-table-p))
4507 (defun org-at-table.el-p ()
4508 "Return t if and only if we are at a table.el table."
4509 (and (org-at-table-p 'any)
4510 (save-excursion
4511 (goto-char (org-table-begin 'any))
4512 (looking-at org-table1-hline-regexp))))
4514 (defun org-table-recognize-table.el ()
4515 "If there is a table.el table nearby, recognize it and move into it."
4516 (if org-table-tab-recognizes-table.el
4517 (if (org-at-table.el-p)
4518 (progn
4519 (beginning-of-line 1)
4520 (if (looking-at org-table-dataline-regexp)
4522 (if (looking-at org-table1-hline-regexp)
4523 (progn
4524 (beginning-of-line 2)
4525 (if (looking-at org-table-any-border-regexp)
4526 (beginning-of-line -1)))))
4527 (if (re-search-forward "|" (org-table-end t) t)
4528 (progn
4529 (require 'table)
4530 (if (table--at-cell-p (point))
4532 (message "recognizing table.el table...")
4533 (table-recognize-table)
4534 (message "recognizing table.el table...done")))
4535 (error "This should not happen"))
4537 nil)
4538 nil))
4540 (defun org-at-table-hline-p ()
4541 "Return t if the cursor is inside a hline in a table."
4542 (if org-enable-table-editor
4543 (save-excursion
4544 (beginning-of-line 1)
4545 (looking-at org-table-hline-regexp))
4546 nil))
4548 (defun org-table-map-tables (function &optional quietly)
4549 "Apply FUNCTION to the start of all tables in the buffer."
4550 (save-excursion
4551 (save-restriction
4552 (widen)
4553 (goto-char (point-min))
4554 (while (re-search-forward org-table-any-line-regexp nil t)
4555 (unless quietly
4556 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4557 (beginning-of-line 1)
4558 (when (and (looking-at org-table-line-regexp)
4559 ;; Exclude tables in src/example/verbatim/clocktable blocks
4560 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4561 (save-excursion (funcall function))
4562 (or (looking-at org-table-line-regexp)
4563 (forward-char 1)))
4564 (re-search-forward org-table-any-border-regexp nil 1))))
4565 (unless quietly (message "Mapping tables: done")))
4567 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4568 (declare-function org-clock-update-mode-line "org-clock" ())
4569 (declare-function org-resolve-clocks "org-clock"
4570 (&optional also-non-dangling-p prompt last-valid))
4572 (defun org-at-TBLFM-p (&optional pos)
4573 "Return t when point (or POS) is in #+TBLFM line."
4574 (save-excursion
4575 (let ((pos pos)))
4576 (goto-char (or pos (point)))
4577 (beginning-of-line 1)
4578 (looking-at org-TBLFM-regexp)))
4580 (defvar org-clock-start-time)
4581 (defvar org-clock-marker (make-marker)
4582 "Marker recording the last clock-in.")
4583 (defvar org-clock-hd-marker (make-marker)
4584 "Marker recording the last clock-in, but the headline position.")
4585 (defvar org-clock-heading ""
4586 "The heading of the current clock entry.")
4587 (defun org-clock-is-active ()
4588 "Return the buffer where the clock is currently running.
4589 Return nil if no clock is running."
4590 (marker-buffer org-clock-marker))
4592 (defun org-check-running-clock ()
4593 "Check if the current buffer contains the running clock.
4594 If yes, offer to stop it and to save the buffer with the changes."
4595 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4596 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4597 (buffer-name))))
4598 (org-clock-out)
4599 (when (y-or-n-p "Save changed buffer?")
4600 (save-buffer))))
4602 (defun org-clocktable-try-shift (dir n)
4603 "Check if this line starts a clock table, if yes, shift the time block."
4604 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4605 (org-clocktable-shift dir n)))
4607 ;;;###autoload
4608 (defun org-clock-persistence-insinuate ()
4609 "Set up hooks for clock persistence."
4610 (require 'org-clock)
4611 (add-hook 'org-mode-hook 'org-clock-load)
4612 (add-hook 'kill-emacs-hook 'org-clock-save))
4614 (defgroup org-archive nil
4615 "Options concerning archiving in Org-mode."
4616 :tag "Org Archive"
4617 :group 'org-structure)
4619 (defcustom org-archive-location "%s_archive::"
4620 "The location where subtrees should be archived.
4622 The value of this variable is a string, consisting of two parts,
4623 separated by a double-colon. The first part is a filename and
4624 the second part is a headline.
4626 When the filename is omitted, archiving happens in the same file.
4627 %s in the filename will be replaced by the current file
4628 name (without the directory part). Archiving to a different file
4629 is useful to keep archived entries from contributing to the
4630 Org-mode Agenda.
4632 The archived entries will be filed as subtrees of the specified
4633 headline. When the headline is omitted, the subtrees are simply
4634 filed away at the end of the file, as top-level entries. Also in
4635 the heading you can use %s to represent the file name, this can be
4636 useful when using the same archive for a number of different files.
4638 Here are a few examples:
4639 \"%s_archive::\"
4640 If the current file is Projects.org, archive in file
4641 Projects.org_archive, as top-level trees. This is the default.
4643 \"::* Archived Tasks\"
4644 Archive in the current file, under the top-level headline
4645 \"* Archived Tasks\".
4647 \"~/org/archive.org::\"
4648 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4650 \"~/org/archive.org::* From %s\"
4651 Archive in file ~/org/archive.org (absolute path), under headlines
4652 \"From FILENAME\" where file name is the current file name.
4654 \"~/org/datetree.org::datetree/* Finished Tasks\"
4655 The \"datetree/\" string is special, signifying to archive
4656 items to the datetree. Items are placed in either the CLOSED
4657 date of the item, or the current date if there is no CLOSED date.
4658 The heading will be a subentry to the current date. There doesn't
4659 need to be a heading, but there always needs to be a slash after
4660 datetree. For example, to store archived items directly in the
4661 datetree, use \"~/org/datetree.org::datetree/\".
4663 \"basement::** Finished Tasks\"
4664 Archive in file ./basement (relative path), as level 3 trees
4665 below the level 2 heading \"** Finished Tasks\".
4667 You may set this option on a per-file basis by adding to the buffer a
4668 line like
4670 #+ARCHIVE: basement::** Finished Tasks
4672 You may also define it locally for a subtree by setting an ARCHIVE property
4673 in the entry. If such a property is found in an entry, or anywhere up
4674 the hierarchy, it will be used."
4675 :group 'org-archive
4676 :type 'string)
4678 (defcustom org-agenda-skip-archived-trees t
4679 "Non-nil means the agenda will skip any items located in archived trees.
4680 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4681 variable is no longer recommended, you should leave it at the value t.
4682 Instead, use the key `v' to cycle the archives-mode in the agenda."
4683 :group 'org-archive
4684 :group 'org-agenda-skip
4685 :type 'boolean)
4687 (defcustom org-columns-skip-archived-trees t
4688 "Non-nil means ignore archived trees when creating column view."
4689 :group 'org-archive
4690 :group 'org-properties
4691 :type 'boolean)
4693 (defcustom org-cycle-open-archived-trees nil
4694 "Non-nil means `org-cycle' will open archived trees.
4695 An archived tree is a tree marked with the tag ARCHIVE.
4696 When nil, archived trees will stay folded. You can still open them with
4697 normal outline commands like `show-all', but not with the cycling commands."
4698 :group 'org-archive
4699 :group 'org-cycle
4700 :type 'boolean)
4702 (defcustom org-sparse-tree-open-archived-trees nil
4703 "Non-nil means sparse tree construction shows matches in archived trees.
4704 When nil, matches in these trees are highlighted, but the trees are kept in
4705 collapsed state."
4706 :group 'org-archive
4707 :group 'org-sparse-trees
4708 :type 'boolean)
4710 (defcustom org-sparse-tree-default-date-type nil
4711 "The default date type when building a sparse tree.
4712 When this is nil, a date is a scheduled or a deadline timestamp.
4713 Otherwise, these types are allowed:
4715 all: all timestamps
4716 active: only active timestamps (<...>)
4717 inactive: only inactive timestamps ([...])
4718 scheduled: only scheduled timestamps
4719 deadline: only deadline timestamps"
4720 :type '(choice (const :tag "Scheduled or deadline" nil)
4721 (const :tag "All timestamps" all)
4722 (const :tag "Only active timestamps" active)
4723 (const :tag "Only inactive timestamps" inactive)
4724 (const :tag "Only scheduled timestamps" scheduled)
4725 (const :tag "Only deadline timestamps" deadline)
4726 (const :tag "Only closed timestamps" closed))
4727 :version "25.1"
4728 :package-version '(Org . "8.3")
4729 :group 'org-sparse-trees)
4731 (defun org-cycle-hide-archived-subtrees (state)
4732 "Re-hide all archived subtrees after a visibility state change."
4733 (when (and (not org-cycle-open-archived-trees)
4734 (not (memq state '(overview folded))))
4735 (save-excursion
4736 (let* ((globalp (memq state '(contents all)))
4737 (beg (if globalp (point-min) (point)))
4738 (end (if globalp (point-max) (org-end-of-subtree t))))
4739 (org-hide-archived-subtrees beg end)
4740 (goto-char beg)
4741 (if (looking-at (concat ".*:" org-archive-tag ":"))
4742 (message "%s" (substitute-command-keys
4743 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4745 (defun org-force-cycle-archived ()
4746 "Cycle subtree even if it is archived."
4747 (interactive)
4748 (setq this-command 'org-cycle)
4749 (let ((org-cycle-open-archived-trees t))
4750 (call-interactively 'org-cycle)))
4752 (defun org-hide-archived-subtrees (beg end)
4753 "Re-hide all archived subtrees after a visibility state change."
4754 (org-with-wide-buffer
4755 (let ((case-fold-search nil)
4756 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4757 (goto-char beg)
4758 (while (and (< (point) end) (re-search-forward re end t))
4759 (when (member org-archive-tag (org-get-tags))
4760 (org-flag-subtree t)
4761 (org-end-of-subtree t))))))
4763 (declare-function outline-end-of-heading "outline" ())
4764 (declare-function outline-flag-region "outline" (from to flag))
4765 (defun org-flag-subtree (flag)
4766 (save-excursion
4767 (org-back-to-heading t)
4768 (outline-end-of-heading)
4769 (outline-flag-region (point)
4770 (progn (org-end-of-subtree t) (point))
4771 flag)))
4773 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4775 ;; Declare Column View Code
4777 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4778 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4779 (declare-function org-columns-compute "org-colview" (property))
4781 ;; Declare ID code
4783 (declare-function org-id-store-link "org-id")
4784 (declare-function org-id-locations-load "org-id")
4785 (declare-function org-id-locations-save "org-id")
4786 (defvar org-id-track-globally)
4788 ;;; Variables for pre-computed regular expressions, all buffer local
4790 (defvar org-todo-regexp nil
4791 "Matches any of the TODO state keywords.")
4792 (make-variable-buffer-local 'org-todo-regexp)
4793 (defvar org-not-done-regexp nil
4794 "Matches any of the TODO state keywords except the last one.")
4795 (make-variable-buffer-local 'org-not-done-regexp)
4796 (defvar org-not-done-heading-regexp nil
4797 "Matches a TODO headline that is not done.")
4798 (make-variable-buffer-local 'org-not-done-regexp)
4799 (defvar org-todo-line-regexp nil
4800 "Matches a headline and puts TODO state into group 2 if present.")
4801 (make-variable-buffer-local 'org-todo-line-regexp)
4802 (defvar org-complex-heading-regexp nil
4803 "Matches a headline and puts everything into groups:
4804 group 1: the stars
4805 group 2: The todo keyword, maybe
4806 group 3: Priority cookie
4807 group 4: True headline
4808 group 5: Tags")
4809 (make-variable-buffer-local 'org-complex-heading-regexp)
4810 (defvar org-complex-heading-regexp-format nil
4811 "Printf format to make regexp to match an exact headline.
4812 This regexp will match the headline of any node which has the
4813 exact headline text that is put into the format, but may have any
4814 TODO state, priority and tags.")
4815 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4816 (defvar org-todo-line-tags-regexp nil
4817 "Matches a headline and puts TODO state into group 2 if present.
4818 Also put tags into group 4 if tags are present.")
4819 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4821 (defconst org-plain-time-of-day-regexp
4822 (concat
4823 "\\(\\<[012]?[0-9]"
4824 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4825 "\\(--?"
4826 "\\(\\<[012]?[0-9]"
4827 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4828 "\\)?")
4829 "Regular expression to match a plain time or time range.
4830 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4831 groups carry important information:
4832 0 the full match
4833 1 the first time, range or not
4834 8 the second time, if it is a range.")
4836 (defconst org-plain-time-extension-regexp
4837 (concat
4838 "\\(\\<[012]?[0-9]"
4839 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4840 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4841 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4842 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4843 groups carry important information:
4844 0 the full match
4845 7 hours of duration
4846 9 minutes of duration")
4848 (defconst org-stamp-time-of-day-regexp
4849 (concat
4850 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4851 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4852 "\\(--?"
4853 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4854 "Regular expression to match a timestamp time or time range.
4855 After a match, the following groups carry important information:
4856 0 the full match
4857 1 date plus weekday, for back referencing to make sure both times are on the same day
4858 2 the first time, range or not
4859 4 the second time, if it is a range.")
4861 (defconst org-startup-options
4862 '(("fold" org-startup-folded t)
4863 ("overview" org-startup-folded t)
4864 ("nofold" org-startup-folded nil)
4865 ("showall" org-startup-folded nil)
4866 ("showeverything" org-startup-folded showeverything)
4867 ("content" org-startup-folded content)
4868 ("indent" org-startup-indented t)
4869 ("noindent" org-startup-indented nil)
4870 ("hidestars" org-hide-leading-stars t)
4871 ("showstars" org-hide-leading-stars nil)
4872 ("odd" org-odd-levels-only t)
4873 ("oddeven" org-odd-levels-only nil)
4874 ("align" org-startup-align-all-tables t)
4875 ("noalign" org-startup-align-all-tables nil)
4876 ("inlineimages" org-startup-with-inline-images t)
4877 ("noinlineimages" org-startup-with-inline-images nil)
4878 ("latexpreview" org-startup-with-latex-preview t)
4879 ("nolatexpreview" org-startup-with-latex-preview nil)
4880 ("customtime" org-display-custom-times t)
4881 ("logdone" org-log-done time)
4882 ("lognotedone" org-log-done note)
4883 ("nologdone" org-log-done nil)
4884 ("lognoteclock-out" org-log-note-clock-out t)
4885 ("nolognoteclock-out" org-log-note-clock-out nil)
4886 ("logrepeat" org-log-repeat state)
4887 ("lognoterepeat" org-log-repeat note)
4888 ("logdrawer" org-log-into-drawer t)
4889 ("nologdrawer" org-log-into-drawer nil)
4890 ("logstatesreversed" org-log-states-order-reversed t)
4891 ("nologstatesreversed" org-log-states-order-reversed nil)
4892 ("nologrepeat" org-log-repeat nil)
4893 ("logreschedule" org-log-reschedule time)
4894 ("lognotereschedule" org-log-reschedule note)
4895 ("nologreschedule" org-log-reschedule nil)
4896 ("logredeadline" org-log-redeadline time)
4897 ("lognoteredeadline" org-log-redeadline note)
4898 ("nologredeadline" org-log-redeadline nil)
4899 ("logrefile" org-log-refile time)
4900 ("lognoterefile" org-log-refile note)
4901 ("nologrefile" org-log-refile nil)
4902 ("fninline" org-footnote-define-inline t)
4903 ("nofninline" org-footnote-define-inline nil)
4904 ("fnlocal" org-footnote-section nil)
4905 ("fnauto" org-footnote-auto-label t)
4906 ("fnprompt" org-footnote-auto-label nil)
4907 ("fnconfirm" org-footnote-auto-label confirm)
4908 ("fnplain" org-footnote-auto-label plain)
4909 ("fnadjust" org-footnote-auto-adjust t)
4910 ("nofnadjust" org-footnote-auto-adjust nil)
4911 ("constcgs" constants-unit-system cgs)
4912 ("constSI" constants-unit-system SI)
4913 ("noptag" org-tag-persistent-alist nil)
4914 ("hideblocks" org-hide-block-startup t)
4915 ("nohideblocks" org-hide-block-startup nil)
4916 ("beamer" org-startup-with-beamer-mode t)
4917 ("entitiespretty" org-pretty-entities t)
4918 ("entitiesplain" org-pretty-entities nil))
4919 "Variable associated with STARTUP options for org-mode.
4920 Each element is a list of three items: the startup options (as written
4921 in the #+STARTUP line), the corresponding variable, and the value to set
4922 this variable to if the option is found. An optional forth element PUSH
4923 means to push this value onto the list in the variable.")
4925 (defcustom org-group-tags t
4926 "When non-nil (the default), use group tags.
4927 This can be turned on/off through `org-toggle-tags-groups'."
4928 :group 'org-tags
4929 :group 'org-startup
4930 :type 'boolean)
4932 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4934 (defun org-toggle-tags-groups ()
4935 "Toggle support for group tags.
4936 Support for group tags is controlled by the option
4937 `org-group-tags', which is non-nil by default."
4938 (interactive)
4939 (setq org-group-tags (not org-group-tags))
4940 (cond ((and (derived-mode-p 'org-agenda-mode)
4941 org-group-tags)
4942 (org-agenda-redo))
4943 ((derived-mode-p 'org-mode)
4944 (let ((org-inhibit-startup t)) (org-mode))))
4945 (message "Groups tags support has been turned %s"
4946 (if org-group-tags "on" "off")))
4948 (defun org-set-regexps-and-options (&optional tags-only)
4949 "Precompute regular expressions used in the current buffer.
4950 When optional argument TAGS-ONLY is non-nil, only compute tags
4951 related expressions."
4952 (when (derived-mode-p 'org-mode)
4953 (let ((alist (org--setup-collect-keywords
4954 (org-make-options-regexp
4955 (append '("FILETAGS" "TAGS" "SETUPFILE")
4956 (and (not tags-only)
4957 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4958 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4959 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4960 (org--setup-process-tags
4961 (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
4962 (unless tags-only
4963 ;; File properties.
4964 (org-set-local 'org-file-properties (cdr (assq 'property alist)))
4965 ;; Archive location.
4966 (let ((archive (cdr (assq 'archive alist))))
4967 (when archive (org-set-local 'org-archive-location archive)))
4968 ;; Category.
4969 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4970 (when cat
4971 (org-set-local 'org-category (intern cat))
4972 (org-set-local 'org-file-properties
4973 (org--update-property-plist
4974 "CATEGORY" cat org-file-properties))))
4975 ;; Columns.
4976 (let ((column (cdr (assq 'columns alist))))
4977 (when column (org-set-local 'org-columns-default-format column)))
4978 ;; Constants.
4979 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4980 ;; Link abbreviations.
4981 (let ((links (cdr (assq 'link alist))))
4982 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4983 ;; Priorities.
4984 (let ((priorities (cdr (assq 'priorities alist))))
4985 (when priorities
4986 (org-set-local 'org-highest-priority (nth 0 priorities))
4987 (org-set-local 'org-lowest-priority (nth 1 priorities))
4988 (org-set-local 'org-default-priority (nth 2 priorities))))
4989 ;; Scripts.
4990 (let ((scripts (assq 'scripts alist)))
4991 (when scripts
4992 (org-set-local 'org-use-sub-superscripts (cdr scripts))))
4993 ;; Startup options.
4994 (let ((startup (cdr (assq 'startup alist))))
4995 (dolist (option startup)
4996 (let ((entry (assoc-string option org-startup-options t)))
4997 (when entry
4998 (let ((var (nth 1 entry))
4999 (val (nth 2 entry)))
5000 (if (not (nth 3 entry)) (org-set-local var val)
5001 (unless (listp (symbol-value var))
5002 (org-set-local var nil))
5003 (add-to-list var val)))))))
5004 ;; TODO keywords.
5005 (org-set-local 'org-todo-kwd-alist nil)
5006 (org-set-local 'org-todo-key-alist nil)
5007 (org-set-local 'org-todo-key-trigger nil)
5008 (org-set-local 'org-todo-keywords-1 nil)
5009 (org-set-local 'org-done-keywords nil)
5010 (org-set-local 'org-todo-heads nil)
5011 (org-set-local 'org-todo-sets nil)
5012 (org-set-local 'org-todo-log-states nil)
5013 (let ((todo-sequences
5014 (or (nreverse (cdr (assq 'todo alist)))
5015 (let ((d (default-value 'org-todo-keywords)))
5016 (if (not (stringp (car d))) d
5017 ;; XXX: Backward compatibility code.
5018 (list (cons org-todo-interpretation d)))))))
5019 (dolist (sequence todo-sequences)
5020 (let* ((sequence (or (run-hook-with-args-until-success
5021 'org-todo-setup-filter-hook sequence)
5022 sequence))
5023 (sequence-type (car sequence))
5024 (keywords (cdr sequence))
5025 (sep (member "|" keywords))
5026 names alist)
5027 (dolist (k (remove "|" keywords))
5028 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5030 (error "Invalid TODO keyword %s" k))
5031 (let ((name (match-string 1 k))
5032 (key (match-string 2 k))
5033 (log (org-extract-log-state-settings k)))
5034 (push name names)
5035 (push (cons name (and key (string-to-char key))) alist)
5036 (when log (push log org-todo-log-states))))
5037 (let* ((names (nreverse names))
5038 (done (if sep (org-remove-keyword-keys (cdr sep))
5039 (last names)))
5040 (head (car names))
5041 (tail (list sequence-type head (car done) (org-last done))))
5042 (add-to-list 'org-todo-heads head 'append)
5043 (push names org-todo-sets)
5044 (setq org-done-keywords (append org-done-keywords done nil))
5045 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5046 (setq org-todo-key-alist
5047 (append org-todo-key-alist
5048 (and alist
5049 (append '((:startgroup))
5050 (nreverse alist)
5051 '((:endgroup))))))
5052 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5053 (setq org-todo-sets (nreverse org-todo-sets)
5054 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5055 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5056 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5057 ;; Compute the regular expressions and other local variables.
5058 ;; Using `org-outline-regexp-bol' would complicate them much,
5059 ;; because of the fixed white space at the end of that string.
5060 (if (not org-done-keywords)
5061 (setq org-done-keywords
5062 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5063 (setq org-not-done-keywords
5064 (org-delete-all org-done-keywords
5065 (copy-sequence org-todo-keywords-1))
5066 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5067 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5068 org-not-done-heading-regexp
5069 (format org-heading-keyword-regexp-format org-not-done-regexp)
5070 org-todo-line-regexp
5071 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5072 org-complex-heading-regexp
5073 (concat "^\\(\\*+\\)"
5074 "\\(?: +" org-todo-regexp "\\)?"
5075 "\\(?: +\\(\\[#.\\]\\)\\)?"
5076 "\\(?: +\\(.*?\\)\\)??"
5077 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5078 "[ \t]*$")
5079 org-complex-heading-regexp-format
5080 (concat "^\\(\\*+\\)"
5081 "\\(?: +" org-todo-regexp "\\)?"
5082 "\\(?: +\\(\\[#.\\]\\)\\)?"
5083 "\\(?: +"
5084 ;; Stats cookies can be stuck to body.
5085 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5086 "\\(%s\\)"
5087 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5088 "\\)"
5089 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5090 "[ \t]*$")
5091 org-todo-line-tags-regexp
5092 (concat "^\\(\\*+\\)"
5093 "\\(?: +" org-todo-regexp "\\)?"
5094 "\\(?: +\\(.*?\\)\\)??"
5095 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5096 "[ \t]*$"))
5097 (org-compute-latex-and-related-regexp)))))
5099 (defun org--setup-collect-keywords (regexp &optional files alist)
5100 "Return setup keywords values as an alist.
5102 REGEXP matches a subset of setup keywords. FILES is a list of
5103 file names already visited. It is used to avoid circular setup
5104 files. ALIST, when non-nil, is the alist computed so far.
5106 Return value contains the following keys: `archive', `category',
5107 `columns', `constants', `filetags', `link', `priorities',
5108 `property', `scripts', `startup', `tags' and `todo'."
5109 (org-with-wide-buffer
5110 (goto-char (point-min))
5111 (let ((case-fold-search t))
5112 (while (re-search-forward regexp nil t)
5113 (let ((element (org-element-at-point)))
5114 (when (eq (org-element-type element) 'keyword)
5115 (let ((key (org-element-property :key element))
5116 (value (org-element-property :value element)))
5117 (cond
5118 ((equal key "ARCHIVE")
5119 (when (org-string-nw-p value)
5120 (push (cons 'archive value) alist)))
5121 ((equal key "CATEGORY") (push (cons 'category value) alist))
5122 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5123 ((equal key "CONSTANTS")
5124 (let* ((constants (assq 'constants alist))
5125 (store (cdr constants)))
5126 (dolist (pair (org-split-string value))
5127 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5128 pair)
5129 (let* ((name (match-string 1 pair))
5130 (value (match-string 2 pair))
5131 (old (assoc name store)))
5132 (if old (setcdr old value)
5133 (push (cons name value) store)))))
5134 (if constants (setcdr constants store)
5135 (push (cons 'constants store) alist))))
5136 ((equal key "FILETAGS")
5137 (when (org-string-nw-p value)
5138 (let ((old (assq 'filetags alist))
5139 (new (apply #'nconc
5140 (mapcar (lambda (x) (org-split-string x ":"))
5141 (org-split-string value)))))
5142 (if old (setcdr old (append new (cdr old)))
5143 (push (cons 'filetags new) alist)))))
5144 ((equal key "LINK")
5145 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5146 (let ((links (assq 'link alist))
5147 (pair (cons (org-match-string-no-properties 1 value)
5148 (org-match-string-no-properties 2 value))))
5149 (if links (push pair (cdr links))
5150 (push (list 'link pair) alist)))))
5151 ((equal key "OPTIONS")
5152 (when (and (org-string-nw-p value)
5153 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5154 (push (cons 'scripts (read (match-string 1 value))) alist)))
5155 ((equal key "PRIORITIES")
5156 (push (cons 'priorities
5157 (let ((prio (org-split-string value)))
5158 (if (< (length prio) 3) '(?A ?C ?B)
5159 (mapcar #'string-to-char prio))))
5160 alist))
5161 ((equal key "PROPERTY")
5162 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5163 (let* ((property (assq 'property alist))
5164 (value (org--update-property-plist
5165 (org-match-string-no-properties 1 value)
5166 (org-match-string-no-properties 2 value)
5167 (cdr property))))
5168 (if property (setcdr property value)
5169 (push (cons 'property value) alist)))))
5170 ((equal key "STARTUP")
5171 (let ((startup (assq 'startup alist)))
5172 (if startup
5173 (setcdr startup
5174 (append (cdr startup) (org-split-string value)))
5175 (push (cons 'startup (org-split-string value)) alist))))
5176 ((equal key "TAGS")
5177 (let ((tag-cell (assq 'tags alist)))
5178 (if tag-cell
5179 (setcdr tag-cell
5180 (append (cdr tag-cell)
5181 '("\\n")
5182 (org-split-string value)))
5183 (push (cons 'tags (org-split-string value)) alist))))
5184 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5185 (let ((todo (assq 'todo alist))
5186 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5187 (org-split-string value))))
5188 (if todo (push value (cdr todo))
5189 (push (list 'todo value) alist))))
5190 ((equal key "SETUPFILE")
5191 (unless buffer-read-only ; Do not check in Gnus messages.
5192 (let ((f (and (org-string-nw-p value)
5193 (expand-file-name
5194 (org-remove-double-quotes value)))))
5195 (when (and f (file-readable-p f) (not (member f files)))
5196 (with-temp-buffer
5197 (insert-file-contents f)
5198 (setq alist
5199 ;; Fake Org mode to benefit from cache
5200 ;; without recurring needlessly.
5201 (let ((major-mode 'org-mode))
5202 (org--setup-collect-keywords
5203 regexp (cons f files) alist)))))))))))))))
5204 alist)
5206 (defun org--setup-process-tags (tags filetags)
5207 "Precompute variables used for tags.
5208 TAGS is a list of tags and tag group symbols, as strings.
5209 FILETAGS is a list of tags, as strings."
5210 ;; Process the file tags.
5211 (org-set-local 'org-file-tags
5212 (mapcar #'org-add-prop-inherited filetags))
5213 ;; Provide default tags if no local tags are found.
5214 (when (and (not tags) org-tag-alist)
5215 (setq tags
5216 (mapcar (lambda (tag)
5217 (case (car tag)
5218 (:startgroup "{")
5219 (:endgroup "}")
5220 (:grouptags ":")
5221 (:newline "\\n")
5222 (otherwise (concat (car tag)
5223 (and (characterp (cdr tag))
5224 (format "(%c)" (cdr tag)))))))
5225 org-tag-alist)))
5226 ;; Process the tags.
5227 (org-set-local 'org-tag-groups-alist nil)
5228 (org-set-local 'org-tag-alist nil)
5229 (let (group-flag)
5230 (while tags
5231 (let ((e (car tags)))
5232 (setq tags (cdr tags))
5233 (cond
5234 ((equal e "{")
5235 (push '(:startgroup) org-tag-alist)
5236 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5237 ((equal e "}")
5238 (push '(:endgroup) org-tag-alist)
5239 (setq group-flag nil))
5240 ((equal e ":")
5241 (push '(:grouptags) org-tag-alist)
5242 (setq group-flag 'append))
5243 ((equal e "\\n") (push '(:newline) org-tag-alist))
5244 ((string-match
5245 (org-re "\\`\\([[:alnum:]_@#%]+\\)\\(?:(\\(.\\))\\)?\\'") e)
5246 (let ((tag (match-string 1 e))
5247 (key (and (match-beginning 2)
5248 (string-to-char (match-string 2 e)))))
5249 (cond ((eq group-flag 'append)
5250 (setcar org-tag-groups-alist
5251 (append (car org-tag-groups-alist) (list tag))))
5252 (group-flag (push (list tag) org-tag-groups-alist)))
5253 (unless (assoc tag org-tag-alist)
5254 (push (cons tag key) org-tag-alist))))))))
5255 (setq org-tag-alist (nreverse org-tag-alist)))
5257 (defun org-file-contents (file &optional noerror)
5258 "Return the contents of FILE, as a string."
5259 (if (and file (file-readable-p file))
5260 (with-temp-buffer
5261 (insert-file-contents file)
5262 (buffer-string))
5263 (funcall (if noerror 'message 'error)
5264 "Cannot read file \"%s\"%s"
5265 file
5266 (let ((from (buffer-file-name (buffer-base-buffer))))
5267 (if from (concat " (referenced in file \"" from "\")") "")))))
5269 (defun org-extract-log-state-settings (x)
5270 "Extract the log state setting from a TODO keyword string.
5271 This will extract info from a string like \"WAIT(w@/!)\"."
5272 (let (kw key log1 log2)
5273 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5274 (setq kw (match-string 1 x)
5275 key (and (match-end 2) (match-string 2 x))
5276 log1 (and (match-end 3) (match-string 3 x))
5277 log2 (and (match-end 4) (match-string 4 x)))
5278 (and (or log1 log2)
5279 (list kw
5280 (and log1 (if (equal log1 "!") 'time 'note))
5281 (and log2 (if (equal log2 "!") 'time 'note)))))))
5283 (defun org-remove-keyword-keys (list)
5284 "Remove a pair of parenthesis at the end of each string in LIST."
5285 (mapcar (lambda (x)
5286 (if (string-match "(.*)$" x)
5287 (substring x 0 (match-beginning 0))
5289 list))
5291 (defun org-assign-fast-keys (alist)
5292 "Assign fast keys to a keyword-key alist.
5293 Respect keys that are already there."
5294 (let (new e (alt ?0))
5295 (while (setq e (pop alist))
5296 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5297 (cdr e)) ;; Key already assigned.
5298 (push e new)
5299 (let ((clist (string-to-list (downcase (car e))))
5300 (used (append new alist)))
5301 (when (= (car clist) ?@)
5302 (pop clist))
5303 (while (and clist (rassoc (car clist) used))
5304 (pop clist))
5305 (unless clist
5306 (while (rassoc alt used)
5307 (incf alt)))
5308 (push (cons (car e) (or (car clist) alt)) new))))
5309 (nreverse new)))
5311 ;;; Some variables used in various places
5313 (defvar org-window-configuration nil
5314 "Used in various places to store a window configuration.")
5315 (defvar org-selected-window nil
5316 "Used in various places to store a window configuration.")
5317 (defvar org-finish-function nil
5318 "Function to be called when `C-c C-c' is used.
5319 This is for getting out of special buffers like capture.")
5322 ;; FIXME: Occasionally check by commenting these, to make sure
5323 ;; no other functions uses these, forgetting to let-bind them.
5324 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5325 (defvar org-last-state)
5326 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5328 ;; Defined somewhere in this file, but used before definition.
5329 (defvar org-entities) ;; defined in org-entities.el
5330 (defvar org-struct-menu)
5331 (defvar org-org-menu)
5332 (defvar org-tbl-menu)
5334 ;;;; Define the Org-mode
5336 ;; We use a before-change function to check if a table might need
5337 ;; an update.
5338 (defvar org-table-may-need-update t
5339 "Indicates that a table might need an update.
5340 This variable is set by `org-before-change-function'.
5341 `org-table-align' sets it back to nil.")
5342 (defun org-before-change-function (beg end)
5343 "Every change indicates that a table might need an update."
5344 (setq org-table-may-need-update t))
5345 (defvar org-mode-map)
5346 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5347 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5348 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5349 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5350 (defvar org-table-buffer-is-an nil)
5352 (defvar bidi-paragraph-direction)
5353 (defvar buffer-face-mode-face)
5355 (require 'outline)
5356 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5357 (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"))
5358 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5360 ;; Other stuff we need.
5361 (require 'time-date)
5362 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5363 (require 'easymenu)
5364 (require 'overlay)
5366 ;; (require 'org-macs) moved higher up in the file before it is first used
5367 (require 'org-entities)
5368 ;; (require 'org-compat) moved higher up in the file before it is first used
5369 (require 'org-faces)
5370 (require 'org-list)
5371 (require 'org-pcomplete)
5372 (require 'org-src)
5373 (require 'org-footnote)
5374 (require 'org-macro)
5376 ;; babel
5377 (require 'ob)
5379 ;;;###autoload
5380 (define-derived-mode org-mode outline-mode "Org"
5381 "Outline-based notes management and organizer, alias
5382 \"Carsten's outline-mode for keeping track of everything.\"
5384 Org-mode develops organizational tasks around a NOTES file which
5385 contains information about projects as plain text. Org-mode is
5386 implemented on top of outline-mode, which is ideal to keep the content
5387 of large files well structured. It supports ToDo items, deadlines and
5388 time stamps, which magically appear in the diary listing of the Emacs
5389 calendar. Tables are easily created with a built-in table editor.
5390 Plain text URL-like links connect to websites, emails (VM), Usenet
5391 messages (Gnus), BBDB entries, and any files related to the project.
5392 For printing and sharing of notes, an Org-mode file (or a part of it)
5393 can be exported as a structured ASCII or HTML file.
5395 The following commands are available:
5397 \\{org-mode-map}"
5399 ;; Get rid of Outline menus, they are not needed
5400 ;; Need to do this here because define-derived-mode sets up
5401 ;; the keymap so late. Still, it is a waste to call this each time
5402 ;; we switch another buffer into org-mode.
5403 (if (featurep 'xemacs)
5404 (when (boundp 'outline-mode-menu-heading)
5405 ;; Assume this is Greg's port, it uses easymenu
5406 (easy-menu-remove outline-mode-menu-heading)
5407 (easy-menu-remove outline-mode-menu-show)
5408 (easy-menu-remove outline-mode-menu-hide))
5409 (define-key org-mode-map [menu-bar headings] 'undefined)
5410 (define-key org-mode-map [menu-bar hide] 'undefined)
5411 (define-key org-mode-map [menu-bar show] 'undefined))
5413 (org-load-modules-maybe)
5414 (easy-menu-add org-org-menu)
5415 (easy-menu-add org-tbl-menu)
5416 (org-install-agenda-files-menu)
5417 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5418 (add-to-invisibility-spec '(org-cwidth))
5419 (add-to-invisibility-spec '(org-hide-block . t))
5420 (when (featurep 'xemacs)
5421 (org-set-local 'line-move-ignore-invisible t))
5422 (org-set-local 'outline-regexp org-outline-regexp)
5423 (org-set-local 'outline-level 'org-outline-level)
5424 (setq bidi-paragraph-direction 'left-to-right)
5425 (when (and org-ellipsis
5426 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5427 (fboundp 'make-glyph-code))
5428 (unless org-display-table
5429 (setq org-display-table (make-display-table)))
5430 (set-display-table-slot
5431 org-display-table 4
5432 (vconcat (mapcar
5433 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5434 org-ellipsis)))
5435 (if (stringp org-ellipsis) org-ellipsis "..."))))
5436 (setq buffer-display-table org-display-table))
5437 (org-set-regexps-and-options)
5438 (org-set-font-lock-defaults)
5439 (when (and org-tag-faces (not org-tags-special-faces-re))
5440 ;; tag faces set outside customize.... force initialization.
5441 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5442 ;; Calc embedded
5443 (org-set-local 'calc-embedded-open-mode "# ")
5444 ;; Modify a few syntax entries
5445 (modify-syntax-entry ?@ "w")
5446 (modify-syntax-entry ?\" "\"")
5447 (modify-syntax-entry ?\\ "_")
5448 (modify-syntax-entry ?~ "_")
5449 (if org-startup-truncated (setq truncate-lines t))
5450 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5451 (org-set-local 'font-lock-unfontify-region-function
5452 'org-unfontify-region)
5453 ;; Activate before-change-function
5454 (org-set-local 'org-table-may-need-update t)
5455 (org-add-hook 'before-change-functions 'org-before-change-function nil
5456 'local)
5457 ;; Check for running clock before killing a buffer
5458 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5459 ;; Initialize macros templates.
5460 (org-macro-initialize-templates)
5461 ;; Initialize radio targets.
5462 (org-update-radio-target-regexp)
5463 ;; Indentation.
5464 (org-set-local 'indent-line-function 'org-indent-line)
5465 (org-set-local 'indent-region-function 'org-indent-region)
5466 ;; Filling and auto-filling.
5467 (org-setup-filling)
5468 ;; Comments.
5469 (org-setup-comments-handling)
5470 ;; Initialize cache.
5471 (org-element-cache-reset)
5472 ;; Beginning/end of defun
5473 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5474 (org-set-local 'end-of-defun-function
5475 (lambda ()
5476 (if (not (org-at-heading-p))
5477 (org-forward-element)
5478 (org-forward-element)
5479 (forward-char -1))))
5480 ;; Next error for sparse trees
5481 (org-set-local 'next-error-function 'org-occur-next-match)
5482 ;; Make sure dependence stuff works reliably, even for users who set it
5483 ;; too late :-(
5484 (if org-enforce-todo-dependencies
5485 (add-hook 'org-blocker-hook
5486 'org-block-todo-from-children-or-siblings-or-parent)
5487 (remove-hook 'org-blocker-hook
5488 'org-block-todo-from-children-or-siblings-or-parent))
5489 (if org-enforce-todo-checkbox-dependencies
5490 (add-hook 'org-blocker-hook
5491 'org-block-todo-from-checkboxes)
5492 (remove-hook 'org-blocker-hook
5493 'org-block-todo-from-checkboxes))
5495 ;; Align options lines
5496 (org-set-local
5497 'align-mode-rules-list
5498 '((org-in-buffer-settings
5499 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5500 (modes . '(org-mode)))))
5502 ;; Imenu
5503 (org-set-local 'imenu-create-index-function
5504 'org-imenu-get-tree)
5506 ;; Make isearch reveal context
5507 (if (or (featurep 'xemacs)
5508 (not (boundp 'outline-isearch-open-invisible-function)))
5509 ;; Emacs 21 and XEmacs make use of the hook
5510 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5511 ;; Emacs 22 deals with this through a special variable
5512 (org-set-local 'outline-isearch-open-invisible-function
5513 (lambda (&rest ignore) (org-show-context 'isearch))))
5515 ;; Setup the pcomplete hooks
5516 (set (make-local-variable 'pcomplete-command-completion-function)
5517 'org-pcomplete-initial)
5518 (set (make-local-variable 'pcomplete-command-name-function)
5519 'org-command-at-point)
5520 (set (make-local-variable 'pcomplete-default-completion-function)
5521 'ignore)
5522 (set (make-local-variable 'pcomplete-parse-arguments-function)
5523 'org-parse-arguments)
5524 (set (make-local-variable 'pcomplete-termination-string) "")
5525 (when (>= emacs-major-version 23)
5526 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5528 ;; If empty file that did not turn on org-mode automatically, make it to.
5529 (if (and org-insert-mode-line-in-empty-file
5530 (org-called-interactively-p 'any)
5531 (= (point-min) (point-max)))
5532 (insert "# -*- mode: org -*-\n\n"))
5533 (unless org-inhibit-startup
5534 (org-unmodified
5535 (and org-startup-with-beamer-mode (org-beamer-mode))
5536 (when org-startup-align-all-tables
5537 (org-table-map-tables 'org-table-align 'quietly))
5538 (when org-startup-with-inline-images
5539 (org-display-inline-images))
5540 (when org-startup-with-latex-preview
5541 (org-toggle-latex-fragment))
5542 (unless org-inhibit-startup-visibility-stuff
5543 (org-set-startup-visibility))
5544 (org-refresh-effort-properties)))
5545 ;; Try to set org-hide correctly
5546 (let ((foreground (org-find-invisible-foreground)))
5547 (if foreground
5548 (set-face-foreground 'org-hide foreground))))
5550 ;; Update `customize-package-emacs-version-alist'
5551 (add-to-list 'customize-package-emacs-version-alist
5552 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5553 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5554 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5556 (defvar org-mode-transpose-word-syntax-table
5557 (let ((st (make-syntax-table text-mode-syntax-table)))
5558 (mapc (lambda(c) (modify-syntax-entry
5559 (string-to-char (car c)) "w p" st))
5560 org-emphasis-alist)
5561 st))
5563 (when (fboundp 'abbrev-table-put)
5564 (abbrev-table-put org-mode-abbrev-table
5565 :parents (list text-mode-abbrev-table)))
5567 (defun org-find-invisible-foreground ()
5568 (let ((candidates (remove
5569 "unspecified-bg"
5570 (nconc
5571 (list (face-background 'default)
5572 (face-background 'org-default))
5573 (mapcar
5574 (lambda (alist)
5575 (when (boundp alist)
5576 (cdr (assoc 'background-color (symbol-value alist)))))
5577 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5578 (list (face-foreground 'org-hide))))))
5579 (car (remove nil candidates))))
5581 (defun org-current-time (&optional rounding-minutes past)
5582 "Current time, possibly rounded to ROUNDING-MINUTES.
5583 When ROUNDING-MINUTES is not an integer, fall back on the car of
5584 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5585 the rounding returns a past time."
5586 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5587 (car org-time-stamp-rounding-minutes)))
5588 (time (decode-time)) res)
5589 (if (< r 1)
5590 (current-time)
5591 (setq res
5592 (apply 'encode-time
5593 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5594 (nthcdr 2 time))))
5595 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5596 (seconds-to-time (- (org-float-time res) (* r 60)))
5597 res))))
5599 (defun org-today ()
5600 "Return today date, considering `org-extend-today-until'."
5601 (time-to-days
5602 (time-subtract (current-time)
5603 (list 0 (* 3600 org-extend-today-until) 0))))
5605 ;;;; Font-Lock stuff, including the activators
5607 (defvar org-mouse-map (make-sparse-keymap))
5608 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5609 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5610 (when org-mouse-1-follows-link
5611 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5612 (when org-tab-follows-link
5613 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5614 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5616 (require 'font-lock)
5618 (defconst org-non-link-chars "]\t\n\r<>")
5619 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5620 "file+sys" "news" "shell" "elisp" "doi" "message"
5621 "help"))
5622 (defvar org-link-types-re nil
5623 "Matches a link that has a url-like prefix like \"http:\"")
5624 (defvar org-link-re-with-space nil
5625 "Matches a link with spaces, optional angular brackets around it.")
5626 (defvar org-link-re-with-space2 nil
5627 "Matches a link with spaces, optional angular brackets around it.")
5628 (defvar org-link-re-with-space3 nil
5629 "Matches a link with spaces, only for internal part in bracket links.")
5630 (defvar org-angle-link-re nil
5631 "Matches link with angular brackets, spaces are allowed.")
5632 (defvar org-plain-link-re nil
5633 "Matches plain link, without spaces.")
5634 (defvar org-bracket-link-regexp nil
5635 "Matches a link in double brackets.")
5636 (defvar org-bracket-link-analytic-regexp nil
5637 "Regular expression used to analyze links.
5638 Here is what the match groups contain after a match:
5639 1: http:
5640 2: http
5641 3: path
5642 4: [desc]
5643 5: desc")
5644 (defvar org-bracket-link-analytic-regexp++ nil
5645 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5646 (defvar org-any-link-re nil
5647 "Regular expression matching any link.")
5649 (defconst org-match-sexp-depth 3
5650 "Number of stacked braces for sub/superscript matching.")
5652 (defun org-create-multibrace-regexp (left right n)
5653 "Create a regular expression which will match a balanced sexp.
5654 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5655 as single character strings.
5656 The regexp returned will match the entire expression including the
5657 delimiters. It will also define a single group which contains the
5658 match except for the outermost delimiters. The maximum depth of
5659 stacked delimiters is N. Escaping delimiters is not possible."
5660 (let* ((nothing (concat "[^" left right "]*?"))
5661 (or "\\|")
5662 (re nothing)
5663 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5664 (while (> n 1)
5665 (setq n (1- n)
5666 re (concat re or next)
5667 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5668 (concat left "\\(" re "\\)" right)))
5670 (defconst org-match-substring-regexp
5671 (concat
5672 "\\(\\S-\\)\\([_^]\\)\\("
5673 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5674 "\\|"
5675 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5676 "\\|"
5677 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5678 "The regular expression matching a sub- or superscript.")
5680 (defconst org-match-substring-with-braces-regexp
5681 (concat
5682 "\\(\\S-\\)\\([_^]\\)"
5683 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5684 "The regular expression matching a sub- or superscript, forcing braces.")
5686 (defun org-make-link-regexps ()
5687 "Update the link regular expressions.
5688 This should be called after the variable `org-link-types' has changed."
5689 (let ((types-re (regexp-opt org-link-types t)))
5690 (setq org-link-types-re
5691 (concat "\\`" types-re ":")
5692 org-link-re-with-space
5693 (concat "<?" types-re ":"
5694 "\\([^" org-non-link-chars " ]"
5695 "[^" org-non-link-chars "]*"
5696 "[^" org-non-link-chars " ]\\)>?")
5697 org-link-re-with-space2
5698 (concat "<?" types-re ":"
5699 "\\([^" org-non-link-chars " ]"
5700 "[^\t\n\r]*"
5701 "[^" org-non-link-chars " ]\\)>?")
5702 org-link-re-with-space3
5703 (concat "<?" types-re ":"
5704 "\\([^" org-non-link-chars " ]"
5705 "[^\t\n\r]*\\)")
5706 org-angle-link-re
5707 (concat "<" types-re ":"
5708 "\\([^" org-non-link-chars " ]"
5709 "[^" org-non-link-chars "]*"
5710 "\\)>")
5711 org-plain-link-re
5712 (concat
5713 "\\<" types-re ":"
5714 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5715 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5716 org-bracket-link-regexp
5717 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5718 org-bracket-link-analytic-regexp
5719 (concat
5720 "\\[\\["
5721 "\\(" types-re ":\\)?"
5722 "\\([^]]+\\)"
5723 "\\]"
5724 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5725 "\\]")
5726 org-bracket-link-analytic-regexp++
5727 (concat
5728 "\\[\\["
5729 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5730 "\\([^]]+\\)"
5731 "\\]"
5732 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5733 "\\]")
5734 org-any-link-re
5735 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5736 org-angle-link-re "\\)\\|\\("
5737 org-plain-link-re "\\)"))))
5739 (org-make-link-regexps)
5741 (defvar org-emph-face nil)
5743 (defun org-do-emphasis-faces (limit)
5744 "Run through the buffer and emphasize strings."
5745 (let (rtn a)
5746 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5747 (let* ((border (char-after (match-beginning 3)))
5748 (bre (regexp-quote (char-to-string border))))
5749 (if (and (not (= border (char-after (match-beginning 4))))
5750 (not (save-match-data
5751 (string-match (concat bre ".*" bre)
5752 (replace-regexp-in-string
5753 "\n" " "
5754 (substring (match-string 2) 1 -1))))))
5755 (progn
5756 (setq rtn t)
5757 (setq a (assoc (match-string 3) org-emphasis-alist))
5758 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5759 'face
5760 (nth 1 a))
5761 (and (nth 2 a)
5762 (org-remove-flyspell-overlays-in
5763 (match-beginning 0) (match-end 0)))
5764 (add-text-properties (match-beginning 2) (match-end 2)
5765 '(font-lock-multiline t org-emphasis t))
5766 (when org-hide-emphasis-markers
5767 (add-text-properties (match-end 4) (match-beginning 5)
5768 '(invisible org-link))
5769 (add-text-properties (match-beginning 3) (match-end 3)
5770 '(invisible org-link))))))
5771 (goto-char (1+ (match-beginning 0))))
5772 rtn))
5774 (defun org-emphasize (&optional char)
5775 "Insert or change an emphasis, i.e. a font like bold or italic.
5776 If there is an active region, change that region to a new emphasis.
5777 If there is no region, just insert the marker characters and position
5778 the cursor between them.
5779 CHAR should be the marker character. If it is a space, it means to
5780 remove the emphasis of the selected region.
5781 If CHAR is not given (for example in an interactive call) it will be
5782 prompted for."
5783 (interactive)
5784 (let ((erc org-emphasis-regexp-components)
5785 (prompt "")
5786 (string "") beg end move c s)
5787 (if (org-region-active-p)
5788 (setq beg (region-beginning) end (region-end)
5789 string (buffer-substring beg end))
5790 (setq move t))
5792 (unless char
5793 (message "Emphasis marker or tag: [%s]"
5794 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5795 (setq char (read-char-exclusive)))
5796 (if (equal char ?\ )
5797 (setq s "" move nil)
5798 (unless (assoc (char-to-string char) org-emphasis-alist)
5799 (user-error "No such emphasis marker: \"%c\"" char))
5800 (setq s (char-to-string char)))
5801 (while (and (> (length string) 1)
5802 (equal (substring string 0 1) (substring string -1))
5803 (assoc (substring string 0 1) org-emphasis-alist))
5804 (setq string (substring string 1 -1)))
5805 (setq string (concat s string s))
5806 (if beg (delete-region beg end))
5807 (unless (or (bolp)
5808 (string-match (concat "[" (nth 0 erc) "\n]")
5809 (char-to-string (char-before (point)))))
5810 (insert " "))
5811 (unless (or (eobp)
5812 (string-match (concat "[" (nth 1 erc) "\n]")
5813 (char-to-string (char-after (point)))))
5814 (insert " ") (backward-char 1))
5815 (insert string)
5816 (and move (backward-char 1))))
5818 (defconst org-nonsticky-props
5819 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5821 (defsubst org-rear-nonsticky-at (pos)
5822 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5824 (defun org-activate-plain-links (limit)
5825 "Add link properties for plain links."
5826 (let (f hl)
5827 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5828 (not (member 'org-tag
5829 (get-text-property (1- (match-beginning 0)) 'face)))
5830 (not (org-in-src-block-p)))
5831 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5832 (setq f (get-text-property (match-beginning 0) 'face))
5833 (setq hl (org-match-string-no-properties 0))
5834 (if (or (eq f 'org-tag)
5835 (and (listp f) (memq 'org-tag f)))
5837 (add-text-properties (match-beginning 0) (match-end 0)
5838 (list 'mouse-face 'highlight
5839 'face 'org-link
5840 'htmlize-link `(:uri ,hl)
5841 'keymap org-mouse-map))
5842 (org-rear-nonsticky-at (match-end 0)))
5843 t)))
5845 (defun org-activate-code (limit)
5846 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5847 (progn
5848 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5849 (remove-text-properties (match-beginning 0) (match-end 0)
5850 '(display t invisible t intangible t))
5851 t)))
5853 (defcustom org-src-fontify-natively t
5854 "When non-nil, fontify code in code blocks."
5855 :type 'boolean
5856 :version "24.4"
5857 :package-version '(Org . "8.3")
5858 :group 'org-appearance
5859 :group 'org-babel)
5861 (defcustom org-allow-promoting-top-level-subtree nil
5862 "When non-nil, allow promoting a top level subtree.
5863 The leading star of the top level headline will be replaced
5864 by a #."
5865 :type 'boolean
5866 :version "24.1"
5867 :group 'org-appearance)
5869 (defun org-fontify-meta-lines-and-blocks (limit)
5870 (condition-case nil
5871 (org-fontify-meta-lines-and-blocks-1 limit)
5872 (error (message "org-mode fontification error"))))
5874 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5875 "Fontify #+ lines and blocks."
5876 (let ((case-fold-search t))
5877 (if (re-search-forward
5878 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5879 limit t)
5880 (let ((beg (match-beginning 0))
5881 (block-start (match-end 0))
5882 (block-end nil)
5883 (lang (match-string 7))
5884 (beg1 (line-beginning-position 2))
5885 (dc1 (downcase (match-string 2)))
5886 (dc3 (downcase (match-string 3)))
5887 end end1 quoting block-type ovl)
5888 (cond
5889 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5890 ;; a single line of backend-specific content
5891 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5892 (remove-text-properties (match-beginning 0) (match-end 0)
5893 '(display t invisible t intangible t))
5894 (add-text-properties (match-beginning 1) (match-end 3)
5895 '(font-lock-fontified t face org-meta-line))
5896 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5897 '(font-lock-fontified t face org-block))
5898 ; for backend-specific code
5900 ((and (match-end 4) (equal dc3 "+begin"))
5901 ;; Truly a block
5902 (setq block-type (downcase (match-string 5))
5903 quoting (member block-type org-protecting-blocks))
5904 (when (re-search-forward
5905 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5906 nil t) ;; on purpose, we look further than LIMIT
5907 (setq end (min (point-max) (match-end 0))
5908 end1 (min (point-max) (1- (match-beginning 0))))
5909 (setq block-end (match-beginning 0))
5910 (when quoting
5911 (org-remove-flyspell-overlays-in beg1 end1)
5912 (remove-text-properties beg end
5913 '(display t invisible t intangible t)))
5914 (add-text-properties
5915 beg end '(font-lock-fontified t font-lock-multiline t))
5916 (add-text-properties beg beg1 '(face org-meta-line))
5917 (org-remove-flyspell-overlays-in beg beg1)
5918 (add-text-properties ; For end_src
5919 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5920 (org-remove-flyspell-overlays-in end1 end)
5921 (cond
5922 ((and lang (not (string= lang "")) org-src-fontify-natively)
5923 (org-src-font-lock-fontify-block lang block-start block-end)
5924 (add-text-properties beg1 block-end '(src-block t)))
5925 (quoting
5926 (add-text-properties beg1 (min (point-max) (1+ end1))
5927 '(face org-block))) ; end of source block
5928 ((not org-fontify-quote-and-verse-blocks))
5929 ((string= block-type "quote")
5930 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5931 ((string= block-type "verse")
5932 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5933 (add-text-properties beg beg1 '(face org-block-begin-line))
5934 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5935 '(face org-block-end-line))
5937 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5938 (org-remove-flyspell-overlays-in
5939 (match-beginning 0)
5940 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5941 (add-text-properties
5942 beg (match-end 3)
5943 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5944 '(font-lock-fontified t invisible t)
5945 '(font-lock-fontified t face org-document-info-keyword)))
5946 (add-text-properties
5947 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5948 (if (string-equal dc1 "+title:")
5949 '(font-lock-fontified t face org-document-title)
5950 '(font-lock-fontified t face org-document-info))))
5951 ((or (equal dc1 "+results")
5952 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5953 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5954 "+call:" "+header:" "+headers:" "+name:"))
5955 (and (match-end 4) (equal dc3 "+attr")))
5956 (org-remove-flyspell-overlays-in
5957 (match-beginning 0)
5958 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5959 (add-text-properties
5960 beg (match-end 0)
5961 '(font-lock-fontified t face org-meta-line))
5963 ((member dc3 '(" " ""))
5964 (org-remove-flyspell-overlays-in beg (match-end 0))
5965 (add-text-properties
5966 beg (match-end 0)
5967 '(font-lock-fontified t face font-lock-comment-face)))
5968 (t ;; just any other in-buffer setting, but not indented
5969 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5970 (add-text-properties
5971 beg (match-end 0)
5972 '(font-lock-fontified t face org-meta-line))
5973 t))))))
5975 (defun org-fontify-drawers (limit)
5976 "Fontify drawers."
5977 (when (re-search-forward org-drawer-regexp limit t)
5978 (add-text-properties
5979 (match-beginning 0) (match-end 0)
5980 '(font-lock-fontified t face org-special-keyword))
5981 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5984 (defun org-fontify-macros (limit)
5985 "Fontify macros."
5986 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5987 (add-text-properties
5988 (match-beginning 0) (match-end 0)
5989 '(font-lock-fontified t face org-macro))
5990 (when org-hide-macro-markers
5991 (add-text-properties (match-end 2) (match-beginning 2)
5992 '(invisible t))
5993 (add-text-properties (match-beginning 1) (match-end 1)
5994 '(invisible t)))
5995 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5998 (defun org-activate-angle-links (limit)
5999 "Add text properties for angle links."
6000 (if (and (re-search-forward org-angle-link-re limit t)
6001 (not (org-in-src-block-p)))
6002 (progn
6003 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6004 (add-text-properties (match-beginning 0) (match-end 0)
6005 (list 'mouse-face 'highlight
6006 'keymap org-mouse-map))
6007 (org-rear-nonsticky-at (match-end 0))
6008 t)))
6010 (defun org-activate-footnote-links (limit)
6011 "Add text properties for footnotes."
6012 (let ((fn (org-footnote-next-reference-or-definition limit)))
6013 (when fn
6014 (let* ((beg (nth 1 fn))
6015 (end (nth 2 fn))
6016 (label (car fn))
6017 (referencep (/= (line-beginning-position) beg)))
6018 (when (and referencep (nth 3 fn))
6019 (save-excursion
6020 (goto-char beg)
6021 (search-forward (or label "fn:"))
6022 (org-remove-flyspell-overlays-in beg (match-end 0))))
6023 (add-text-properties beg end
6024 (list 'mouse-face 'highlight
6025 'keymap org-mouse-map
6026 'help-echo
6027 (if referencep "Footnote reference"
6028 "Footnote definition")
6029 'font-lock-fontified t
6030 'font-lock-multiline t
6031 'face 'org-footnote))))))
6033 (defun org-activate-bracket-links (limit)
6034 "Add text properties for bracketed links."
6035 (if (and (re-search-forward org-bracket-link-regexp limit t)
6036 (not (org-in-src-block-p)))
6037 (let* ((hl (org-match-string-no-properties 1))
6038 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6039 (ip (org-maybe-intangible
6040 (list 'invisible 'org-link
6041 'keymap org-mouse-map 'mouse-face 'highlight
6042 'font-lock-multiline t 'help-echo help
6043 'htmlize-link `(:uri ,hl))))
6044 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6045 'font-lock-multiline t 'help-echo help
6046 'htmlize-link `(:uri ,hl))))
6047 ;; We need to remove the invisible property here. Table narrowing
6048 ;; may have made some of this invisible.
6049 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6050 (remove-text-properties (match-beginning 0) (match-end 0)
6051 '(invisible nil))
6052 (if (match-end 3)
6053 (progn
6054 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6055 (org-rear-nonsticky-at (match-beginning 3))
6056 (add-text-properties (match-beginning 3) (match-end 3) vp)
6057 (org-rear-nonsticky-at (match-end 3))
6058 (add-text-properties (match-end 3) (match-end 0) ip)
6059 (org-rear-nonsticky-at (match-end 0)))
6060 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6061 (org-rear-nonsticky-at (match-beginning 1))
6062 (add-text-properties (match-beginning 1) (match-end 1) vp)
6063 (org-rear-nonsticky-at (match-end 1))
6064 (add-text-properties (match-end 1) (match-end 0) ip)
6065 (org-rear-nonsticky-at (match-end 0)))
6066 t)))
6068 (defun org-activate-dates (limit)
6069 "Add text properties for dates."
6070 (if (and (re-search-forward org-tsr-regexp-both limit t)
6071 (not (equal (char-before (match-beginning 0)) 91)))
6072 (progn
6073 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6074 (add-text-properties (match-beginning 0) (match-end 0)
6075 (list 'mouse-face 'highlight
6076 'keymap org-mouse-map))
6077 (org-rear-nonsticky-at (match-end 0))
6078 (when org-display-custom-times
6079 (if (match-end 3)
6080 (org-display-custom-time (match-beginning 3) (match-end 3)))
6081 (org-display-custom-time (match-beginning 1) (match-end 1)))
6082 t)))
6084 (defvar org-target-link-regexp nil
6085 "Regular expression matching radio targets in plain text.")
6086 (make-variable-buffer-local 'org-target-link-regexp)
6088 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6089 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6090 border border border))
6091 "Regular expression matching a link target.")
6093 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6094 "Regular expression matching a radio target.")
6096 (defconst org-any-target-regexp
6097 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6098 "Regular expression matching any target.")
6100 (defun org-activate-target-links (limit)
6101 "Add text properties for target matches."
6102 (when org-target-link-regexp
6103 (let ((case-fold-search t))
6104 (if (re-search-forward org-target-link-regexp limit t)
6105 (progn
6106 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6107 (add-text-properties (match-beginning 1) (match-end 1)
6108 (list 'mouse-face 'highlight
6109 'keymap org-mouse-map
6110 'help-echo "Radio target link"
6111 'org-linked-text t))
6112 (org-rear-nonsticky-at (match-end 1))
6113 t)))))
6115 (defun org-update-radio-target-regexp ()
6116 "Find all radio targets in this file and update the regular expression.
6117 Also refresh fontification if needed."
6118 (interactive)
6119 (let ((old-regexp org-target-link-regexp)
6120 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6121 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6122 (targets
6123 (org-with-wide-buffer
6124 (goto-char (point-min))
6125 (let (rtn)
6126 (while (re-search-forward org-radio-target-regexp nil t)
6127 ;; Make sure point is really within the object.
6128 (backward-char)
6129 (let ((obj (org-element-context)))
6130 (when (eq (org-element-type obj) 'radio-target)
6131 (add-to-list 'rtn (org-element-property :value obj)))))
6132 rtn))))
6133 (setq org-target-link-regexp
6134 (and targets
6135 (concat before-re
6136 (mapconcat
6137 (lambda (x)
6138 (replace-regexp-in-string
6139 " +" "\\s-+" (regexp-quote x) t t))
6140 targets
6141 "\\|")
6142 after-re)))
6143 (unless (equal old-regexp org-target-link-regexp)
6144 ;; Clean-up cache.
6145 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6146 ((not org-target-link-regexp) old-regexp)
6148 (concat before-re
6149 (mapconcat
6150 (lambda (re)
6151 (substring re (length before-re)
6152 (- (length after-re))))
6153 (list old-regexp org-target-link-regexp)
6154 "\\|")
6155 after-re)))))
6156 (org-with-wide-buffer
6157 (goto-char (point-min))
6158 (while (re-search-forward regexp nil t)
6159 (org-element-cache-refresh (match-beginning 1)))))
6160 ;; Re fontify buffer.
6161 (when (memq 'radio org-highlight-links)
6162 (org-restart-font-lock)))))
6164 (defun org-hide-wide-columns (limit)
6165 (let (s e)
6166 (setq s (text-property-any (point) (or limit (point-max))
6167 'org-cwidth t))
6168 (when s
6169 (setq e (next-single-property-change s 'org-cwidth))
6170 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6171 (goto-char e)
6172 t)))
6174 (defvar org-latex-and-related-regexp nil
6175 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6177 (defun org-compute-latex-and-related-regexp ()
6178 "Compute regular expression for LaTeX, entities and sub/superscript.
6179 Result depends on variable `org-highlight-latex-and-related'."
6180 (org-set-local
6181 'org-latex-and-related-regexp
6182 (let* ((re-sub
6183 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6184 ((eq org-use-sub-superscripts '{})
6185 (list org-match-substring-with-braces-regexp))
6186 (org-use-sub-superscripts (list org-match-substring-regexp))))
6187 (re-latex
6188 (when (memq 'latex org-highlight-latex-and-related)
6189 (let ((matchers (plist-get org-format-latex-options :matchers)))
6190 (delq nil
6191 (mapcar (lambda (x)
6192 (and (member (car x) matchers) (nth 1 x)))
6193 org-latex-regexps)))))
6194 (re-entities
6195 (when (memq 'entities org-highlight-latex-and-related)
6196 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6197 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6199 (defun org-do-latex-and-related (limit)
6200 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6201 LIMIT bounds the search for syntax to highlight. Stop at first
6202 highlighted object, if any. Return t if some highlighting was
6203 done, nil otherwise."
6204 (when (org-string-nw-p org-latex-and-related-regexp)
6205 (catch 'found
6206 (while (re-search-forward org-latex-and-related-regexp limit t)
6207 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6208 'face))
6209 '(org-code org-verbatim underline))
6210 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6211 '(?_ ?^))
6213 0)))
6214 (font-lock-prepend-text-property
6215 (+ offset (match-beginning 0)) (match-end 0)
6216 'face 'org-latex-and-related)
6217 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6218 '(font-lock-multiline t)))
6219 (throw 'found t)))
6220 nil)))
6222 (defun org-restart-font-lock ()
6223 "Restart `font-lock-mode', to force refontification."
6224 (when (and (boundp 'font-lock-mode) font-lock-mode)
6225 (font-lock-mode -1)
6226 (font-lock-mode 1)))
6228 (defun org-activate-tags (limit)
6229 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6230 (progn
6231 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6232 (add-text-properties (match-beginning 1) (match-end 1)
6233 (list 'mouse-face 'highlight
6234 'keymap org-mouse-map))
6235 (org-rear-nonsticky-at (match-end 1))
6236 t)))
6238 (defun org-outline-level ()
6239 "Compute the outline level of the heading at point.
6241 If this is called at a normal headline, the level is the number
6242 of stars. Use `org-reduced-level' to remove the effect of
6243 `org-odd-levels'. Unlike to `org-current-level', this function
6244 takes into consideration inlinetasks."
6245 (org-with-wide-buffer
6246 (end-of-line)
6247 (if (re-search-backward org-outline-regexp-bol nil t)
6248 (1- (- (match-end 0) (match-beginning 0)))
6249 0)))
6251 (defvar org-font-lock-keywords nil)
6253 (defsubst org-re-property (property &optional literal allow-null)
6254 "Return a regexp matching a PROPERTY line.
6256 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6257 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6258 non-nil, match properties even without a value.
6260 Match group 3 is set to the value when it exists. If there is no
6261 value and ALLOW-NULL is non-nil, it is set to the empty string."
6262 (concat
6263 "^\\(?4:[ \t]*\\)"
6264 (format "\\(?1::\\(?2:%s\\):\\)"
6265 (if literal property (regexp-quote property)))
6266 (if allow-null
6267 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$"
6268 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))
6270 (defconst org-property-re
6271 (org-re-property "\\S-+" 'literal t)
6272 "Regular expression matching a property line.
6273 There are four matching groups:
6274 1: :PROPKEY: including the leading and trailing colon,
6275 2: PROPKEY without the leading and trailing colon,
6276 3: PROPVAL without leading or trailing spaces,
6277 4: the indentation of the current line,
6278 5: trailing whitespace.")
6280 (defvar org-font-lock-hook nil
6281 "Functions to be called for special font lock stuff.")
6283 (defvar org-font-lock-set-keywords-hook nil
6284 "Functions that can manipulate `org-font-lock-extra-keywords'.
6285 This is called after `org-font-lock-extra-keywords' is defined, but before
6286 it is installed to be used by font lock. This can be useful if something
6287 needs to be inserted at a specific position in the font-lock sequence.")
6289 (defun org-font-lock-hook (limit)
6290 "Run `org-font-lock-hook' within LIMIT."
6291 (run-hook-with-args 'org-font-lock-hook limit))
6293 (defun org-set-font-lock-defaults ()
6294 "Set font lock defaults for the current buffer."
6295 (let* ((em org-fontify-emphasized-text)
6296 (lk org-highlight-links)
6297 (org-font-lock-extra-keywords
6298 (list
6299 ;; Call the hook
6300 '(org-font-lock-hook)
6301 ;; Headlines
6302 `(,(if org-fontify-whole-heading-line
6303 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6304 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6305 (1 (org-get-level-face 1))
6306 (2 (org-get-level-face 2))
6307 (3 (org-get-level-face 3)))
6308 ;; Table lines
6309 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6310 (1 'org-table t))
6311 ;; Table internals
6312 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6313 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6314 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6315 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6316 ;; Drawers
6317 '(org-fontify-drawers)
6318 ;; Properties
6319 (list org-property-re
6320 '(1 'org-special-keyword t)
6321 '(3 'org-property-value t))
6322 ;; Links
6323 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6324 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6325 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6326 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6327 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6328 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6329 (if (memq 'footnote lk) '(org-activate-footnote-links))
6330 ;; Targets.
6331 (list org-any-target-regexp '(0 'org-target t))
6332 ;; Diary sexps.
6333 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6334 ;; Macro
6335 '(org-fontify-macros)
6336 '(org-hide-wide-columns (0 nil append))
6337 ;; TODO keyword
6338 (list (format org-heading-keyword-regexp-format
6339 org-todo-regexp)
6340 '(2 (org-get-todo-face 2) t))
6341 ;; DONE
6342 (if org-fontify-done-headline
6343 (list (format org-heading-keyword-regexp-format
6344 (concat
6345 "\\(?:"
6346 (mapconcat 'regexp-quote org-done-keywords "\\|")
6347 "\\)"))
6348 '(2 'org-headline-done t))
6349 nil)
6350 ;; Priorities
6351 '(org-font-lock-add-priority-faces)
6352 ;; Tags
6353 '(org-font-lock-add-tag-faces)
6354 ;; Tags groups
6355 (if (and org-group-tags org-tag-groups-alist)
6356 (list (concat org-outline-regexp-bol ".+\\(:"
6357 (regexp-opt (mapcar 'car org-tag-groups-alist))
6358 ":\\).*$")
6359 '(1 'org-tag-group prepend)))
6360 ;; Special keywords
6361 (list (concat "\\<" org-comment-string) '(0 'org-special-keyword t))
6362 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6363 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6364 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6365 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6366 ;; Emphasis
6367 (if em
6368 (if (featurep 'xemacs)
6369 '(org-do-emphasis-faces (0 nil append))
6370 '(org-do-emphasis-faces)))
6371 ;; Checkboxes
6372 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6373 1 'org-checkbox prepend)
6374 (if (cdr (assq 'checkbox org-list-automatic-rules))
6375 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6376 (0 (org-get-checkbox-statistics-face) t)))
6377 ;; Description list items
6378 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6379 1 'org-list-dt prepend)
6380 ;; ARCHIVEd headings
6381 (list (concat
6382 org-outline-regexp-bol
6383 "\\(.*:" org-archive-tag ":.*\\)")
6384 '(1 'org-archived prepend))
6385 ;; Specials
6386 '(org-do-latex-and-related)
6387 '(org-fontify-entities)
6388 '(org-raise-scripts)
6389 ;; Code
6390 '(org-activate-code (1 'org-code t))
6391 ;; COMMENT
6392 (list (format
6393 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6394 org-todo-regexp
6395 org-comment-string)
6396 '(9 'org-special-keyword t))
6397 ;; Blocks and meta lines
6398 '(org-fontify-meta-lines-and-blocks))))
6399 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6400 (run-hooks 'org-font-lock-set-keywords-hook)
6401 ;; Now set the full font-lock-keywords
6402 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6403 (org-set-local 'font-lock-defaults
6404 '(org-font-lock-keywords t nil nil backward-paragraph))
6405 (kill-local-variable 'font-lock-keywords) nil))
6407 (defun org-toggle-pretty-entities ()
6408 "Toggle the composition display of entities as UTF8 characters."
6409 (interactive)
6410 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6411 (org-restart-font-lock)
6412 (if org-pretty-entities
6413 (message "Entities are now displayed as UTF8 characters")
6414 (save-restriction
6415 (widen)
6416 (org-decompose-region (point-min) (point-max))
6417 (message "Entities are now displayed as plain text"))))
6419 (defvar org-custom-properties-overlays nil
6420 "List of overlays used for custom properties.")
6421 (make-variable-buffer-local 'org-custom-properties-overlays)
6423 (defun org-toggle-custom-properties-visibility ()
6424 "Display or hide properties in `org-custom-properties'."
6425 (interactive)
6426 (if org-custom-properties-overlays
6427 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6428 (setq org-custom-properties-overlays nil))
6429 (when org-custom-properties
6430 (org-with-wide-buffer
6431 (goto-char (point-min))
6432 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6433 (while (re-search-forward regexp nil t)
6434 (let ((end (cdr (save-match-data (org-get-property-block)))))
6435 (when (and end (< (point) end))
6436 ;; Hide first custom property in current drawer.
6437 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6438 (overlay-put o 'invisible t)
6439 (overlay-put o 'org-custom-property t)
6440 (push o org-custom-properties-overlays))
6441 ;; Hide additional custom properties in the same drawer.
6442 (while (re-search-forward regexp end t)
6443 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6444 (overlay-put o 'invisible t)
6445 (overlay-put o 'org-custom-property t)
6446 (push o org-custom-properties-overlays)))))
6447 ;; Each entry is limited to a single property drawer.
6448 (outline-next-heading)))))))
6450 (defun org-fontify-entities (limit)
6451 "Find an entity to fontify."
6452 (let (ee)
6453 (when org-pretty-entities
6454 (catch 'match
6455 (while (re-search-forward
6456 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6457 limit t)
6458 (if (and (not (org-at-comment-p))
6459 (setq ee (org-entity-get (match-string 1)))
6460 (= (length (nth 6 ee)) 1))
6461 (let*
6462 ((end (if (equal (match-string 2) "{}")
6463 (match-end 2)
6464 (match-end 1))))
6465 (add-text-properties
6466 (match-beginning 0) end
6467 (list 'font-lock-fontified t))
6468 (compose-region (match-beginning 0) end
6469 (nth 6 ee) nil)
6470 (backward-char 1)
6471 (throw 'match t))))
6472 nil))))
6474 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6475 "Fontify string S like in Org-mode."
6476 (with-temp-buffer
6477 (insert s)
6478 (let ((org-odd-levels-only odd-levels))
6479 (org-mode)
6480 (font-lock-ensure)
6481 (buffer-string))))
6483 (defvar org-m nil)
6484 (defvar org-l nil)
6485 (defvar org-f nil)
6486 (defun org-get-level-face (n)
6487 "Get the right face for match N in font-lock matching of headlines."
6488 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6489 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6490 (if org-cycle-level-faces
6491 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6492 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6493 (cond
6494 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6495 ((eq n 2) org-f)
6496 (t (if org-level-color-stars-only nil org-f))))
6499 (defun org-get-todo-face (kwd)
6500 "Get the right face for a TODO keyword KWD.
6501 If KWD is a number, get the corresponding match group."
6502 (if (numberp kwd) (setq kwd (match-string kwd)))
6503 (or (org-face-from-face-or-color
6504 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6505 (and (member kwd org-done-keywords) 'org-done)
6506 'org-todo))
6508 (defun org-face-from-face-or-color (context inherit face-or-color)
6509 "Create a face list that inherits INHERIT, but sets the foreground color.
6510 When FACE-OR-COLOR is not a string, just return it."
6511 (if (stringp face-or-color)
6512 (list :inherit inherit
6513 (cdr (assoc context org-faces-easy-properties))
6514 face-or-color)
6515 face-or-color))
6517 (defun org-font-lock-add-tag-faces (limit)
6518 "Add the special tag faces."
6519 (when (and org-tag-faces org-tags-special-faces-re)
6520 (while (re-search-forward org-tags-special-faces-re limit t)
6521 (add-text-properties (match-beginning 1) (match-end 1)
6522 (list 'face (org-get-tag-face 1)
6523 'font-lock-fontified t))
6524 (backward-char 1))))
6526 (defun org-font-lock-add-priority-faces (limit)
6527 "Add the special priority faces."
6528 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6529 (when (save-match-data (org-at-heading-p))
6530 (add-text-properties
6531 (match-beginning 0) (match-end 0)
6532 (list 'face (or (org-face-from-face-or-color
6533 'priority 'org-priority
6534 (cdr (assoc (char-after (match-beginning 1))
6535 org-priority-faces)))
6536 'org-priority)
6537 'font-lock-fontified t)))))
6539 (defun org-get-tag-face (kwd)
6540 "Get the right face for a TODO keyword KWD.
6541 If KWD is a number, get the corresponding match group."
6542 (if (numberp kwd) (setq kwd (match-string kwd)))
6543 (or (org-face-from-face-or-color
6544 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6545 'org-tag))
6547 (defun org-unfontify-region (beg end &optional maybe_loudly)
6548 "Remove fontification and activation overlays from links."
6549 (font-lock-default-unfontify-region beg end)
6550 (let* ((buffer-undo-list t)
6551 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6552 (inhibit-modification-hooks t)
6553 deactivate-mark buffer-file-name buffer-file-truename)
6554 (org-decompose-region beg end)
6555 (remove-text-properties beg end
6556 '(mouse-face t keymap t org-linked-text t
6557 invisible t intangible t
6558 org-emphasis t))
6559 (org-remove-font-lock-display-properties beg end)))
6561 (defconst org-script-display '(((raise -0.3) (height 0.7))
6562 ((raise 0.3) (height 0.7))
6563 ((raise -0.5))
6564 ((raise 0.5)))
6565 "Display properties for showing superscripts and subscripts.")
6567 (defun org-remove-font-lock-display-properties (beg end)
6568 "Remove specific display properties that have been added by font lock.
6569 The will remove the raise properties that are used to show superscripts
6570 and subscripts."
6571 (let (next prop)
6572 (while (< beg end)
6573 (setq next (next-single-property-change beg 'display nil end)
6574 prop (get-text-property beg 'display))
6575 (if (member prop org-script-display)
6576 (put-text-property beg next 'display nil))
6577 (setq beg next))))
6579 (defun org-raise-scripts (limit)
6580 "Add raise properties to sub/superscripts."
6581 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6582 (if (re-search-forward
6583 (if (eq org-use-sub-superscripts t)
6584 org-match-substring-regexp
6585 org-match-substring-with-braces-regexp)
6586 limit t)
6587 (let* ((pos (point)) table-p comment-p
6588 (mpos (match-beginning 3))
6589 (emph-p (get-text-property mpos 'org-emphasis))
6590 (link-p (get-text-property mpos 'mouse-face))
6591 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6592 (goto-char (point-at-bol))
6593 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6594 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6595 (goto-char pos)
6596 ;; Handle a_b^c
6597 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6598 (if (or comment-p emph-p link-p keyw-p)
6600 (put-text-property (match-beginning 3) (match-end 0)
6601 'display
6602 (if (equal (char-after (match-beginning 2)) ?^)
6603 (nth (if table-p 3 1) org-script-display)
6604 (nth (if table-p 2 0) org-script-display)))
6605 (add-text-properties (match-beginning 2) (match-end 2)
6606 (list 'invisible t
6607 'org-dwidth t 'org-dwidth-n 1))
6608 (if (and (eq (char-after (match-beginning 3)) ?{)
6609 (eq (char-before (match-end 3)) ?}))
6610 (progn
6611 (add-text-properties
6612 (match-beginning 3) (1+ (match-beginning 3))
6613 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6614 (add-text-properties
6615 (1- (match-end 3)) (match-end 3)
6616 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6617 t)))))
6619 ;;;; Visibility cycling, including org-goto and indirect buffer
6621 ;;; Cycling
6623 (defvar org-cycle-global-status nil)
6624 (make-variable-buffer-local 'org-cycle-global-status)
6625 (put 'org-cycle-global-status 'org-state t)
6626 (defvar org-cycle-subtree-status nil)
6627 (make-variable-buffer-local 'org-cycle-subtree-status)
6628 (put 'org-cycle-subtree-status 'org-state t)
6630 (defvar org-inlinetask-min-level)
6632 (defun org-unlogged-message (&rest args)
6633 "Display a message, but avoid logging it in the *Messages* buffer."
6634 (let ((message-log-max nil))
6635 (apply 'message args)))
6637 ;;;###autoload
6638 (defun org-cycle (&optional arg)
6639 "TAB-action and visibility cycling for Org-mode.
6641 This is the command invoked in Org-mode by the TAB key. Its main purpose
6642 is outline visibility cycling, but it also invokes other actions
6643 in special contexts.
6645 - When this function is called with a prefix argument, rotate the entire
6646 buffer through 3 states (global cycling)
6647 1. OVERVIEW: Show only top-level headlines.
6648 2. CONTENTS: Show all headlines of all levels, but no body text.
6649 3. SHOW ALL: Show everything.
6650 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6651 determined by the variable `org-startup-folded', and by any VISIBILITY
6652 properties in the buffer.
6653 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6654 including any drawers.
6656 - When inside a table, re-align the table and move to the next field.
6658 - When point is at the beginning of a headline, rotate the subtree started
6659 by this line through 3 different states (local cycling)
6660 1. FOLDED: Only the main headline is shown.
6661 2. CHILDREN: The main headline and the direct children are shown.
6662 From this state, you can move to one of the children
6663 and zoom in further.
6664 3. SUBTREE: Show the entire subtree, including body text.
6665 If there is no subtree, switch directly from CHILDREN to FOLDED.
6667 - When point is at the beginning of an empty headline and the variable
6668 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6669 of the headline by demoting and promoting it to likely levels. This
6670 speeds up creation document structure by pressing TAB once or several
6671 times right after creating a new headline.
6673 - When there is a numeric prefix, go up to a heading with level ARG, do
6674 a `show-subtree' and return to the previous cursor position. If ARG
6675 is negative, go up that many levels.
6677 - When point is not at the beginning of a headline, execute the global
6678 binding for TAB, which is re-indenting the line. See the option
6679 `org-cycle-emulate-tab' for details.
6681 - Special case: if point is at the beginning of the buffer and there is
6682 no headline in line 1, this function will act as if called with prefix arg
6683 (C-u TAB, same as S-TAB) also when called without prefix arg.
6684 But only if also the variable `org-cycle-global-at-bob' is t."
6685 (interactive "P")
6686 (org-load-modules-maybe)
6687 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6688 (and org-cycle-level-after-item/entry-creation
6689 (or (org-cycle-level)
6690 (org-cycle-item-indentation))))
6691 (let* ((limit-level
6692 (or org-cycle-max-level
6693 (and (boundp 'org-inlinetask-min-level)
6694 org-inlinetask-min-level
6695 (1- org-inlinetask-min-level))))
6696 (nstars (and limit-level
6697 (if org-odd-levels-only
6698 (and limit-level (1- (* limit-level 2)))
6699 limit-level)))
6700 (org-outline-regexp
6701 (if (not (derived-mode-p 'org-mode))
6702 outline-regexp
6703 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6704 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6705 (not (looking-at org-outline-regexp))))
6706 (org-cycle-hook
6707 (if bob-special
6708 (delq 'org-optimize-window-after-visibility-change
6709 (copy-sequence org-cycle-hook))
6710 org-cycle-hook))
6711 (pos (point)))
6713 (if (or bob-special (equal arg '(4)))
6714 ;; special case: use global cycling
6715 (setq arg t))
6717 (cond
6719 ((equal arg '(16))
6720 (setq last-command 'dummy)
6721 (org-set-startup-visibility)
6722 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6724 ((equal arg '(64))
6725 (show-all)
6726 (org-unlogged-message "Entire buffer visible, including drawers"))
6728 ;; Try cdlatex TAB completion
6729 ((org-try-cdlatex-tab))
6731 ;; Table: enter it or move to the next field.
6732 ((org-at-table-p 'any)
6733 (if (org-at-table.el-p)
6734 (message "Use C-c ' to edit table.el tables")
6735 (if arg (org-table-edit-field t)
6736 (org-table-justify-field-maybe)
6737 (call-interactively 'org-table-next-field))))
6739 ((run-hook-with-args-until-success
6740 'org-tab-after-check-for-table-hook))
6742 ;; Global cycling: delegate to `org-cycle-internal-global'.
6743 ((eq arg t) (org-cycle-internal-global))
6745 ;; Drawers: delegate to `org-flag-drawer'.
6746 ((save-excursion
6747 (beginning-of-line 1)
6748 (looking-at org-drawer-regexp))
6749 (org-flag-drawer ; toggle block visibility
6750 (not (get-char-property (match-end 0) 'invisible))))
6752 ;; Show-subtree, ARG levels up from here.
6753 ((integerp arg)
6754 (save-excursion
6755 (org-back-to-heading)
6756 (outline-up-heading (if (< arg 0) (- arg)
6757 (- (funcall outline-level) arg)))
6758 (org-show-subtree)))
6760 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6761 ((and (featurep 'org-inlinetask)
6762 (org-inlinetask-at-task-p)
6763 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6764 (org-inlinetask-toggle-visibility))
6766 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6767 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6768 (save-excursion (beginning-of-line 1)
6769 (looking-at org-outline-regexp)))
6770 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6771 (org-cycle-internal-local))
6773 ;; From there: TAB emulation and template completion.
6774 (buffer-read-only (org-back-to-heading))
6776 ((run-hook-with-args-until-success
6777 'org-tab-after-check-for-cycling-hook))
6779 ((org-try-structure-completion))
6781 ((run-hook-with-args-until-success
6782 'org-tab-before-tab-emulation-hook))
6784 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6785 (or (not (bolp))
6786 (not (looking-at org-outline-regexp))))
6787 (call-interactively (global-key-binding "\t")))
6789 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6790 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6791 (or (and (eq org-cycle-emulate-tab 'white)
6792 (= (match-end 0) (point-at-eol)))
6793 (and (eq org-cycle-emulate-tab 'whitestart)
6794 (>= (match-end 0) pos))))
6796 (eq org-cycle-emulate-tab t))
6797 (call-interactively (global-key-binding "\t")))
6799 (t (save-excursion
6800 (org-back-to-heading)
6801 (org-cycle)))))))
6803 (defun org-cycle-internal-global ()
6804 "Do the global cycling action."
6805 ;; Hack to avoid display of messages for .org attachments in Gnus
6806 (let ((ga (string-match "\\*fontification" (buffer-name))))
6807 (cond
6808 ((and (eq last-command this-command)
6809 (eq org-cycle-global-status 'overview))
6810 ;; We just created the overview - now do table of contents
6811 ;; This can be slow in very large buffers, so indicate action
6812 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6813 (unless ga (org-unlogged-message "CONTENTS..."))
6814 (org-content)
6815 (unless ga (org-unlogged-message "CONTENTS...done"))
6816 (setq org-cycle-global-status 'contents)
6817 (run-hook-with-args 'org-cycle-hook 'contents))
6819 ((and (eq last-command this-command)
6820 (eq org-cycle-global-status 'contents))
6821 ;; We just showed the table of contents - now show everything
6822 (run-hook-with-args 'org-pre-cycle-hook 'all)
6823 (show-all)
6824 (unless ga (org-unlogged-message "SHOW ALL"))
6825 (setq org-cycle-global-status 'all)
6826 (run-hook-with-args 'org-cycle-hook 'all))
6829 ;; Default action: go to overview
6830 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6831 (org-overview)
6832 (unless ga (org-unlogged-message "OVERVIEW"))
6833 (setq org-cycle-global-status 'overview)
6834 (run-hook-with-args 'org-cycle-hook 'overview)))))
6836 (defvar org-called-with-limited-levels nil
6837 "Non-nil when `org-with-limited-levels' is currently active.")
6839 (defun org-cycle-internal-local ()
6840 "Do the local cycling action."
6841 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6842 ;; First, determine end of headline (EOH), end of subtree or item
6843 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6844 (save-excursion
6845 (if (org-at-item-p)
6846 (progn
6847 (beginning-of-line)
6848 (setq struct (org-list-struct))
6849 (setq eoh (point-at-eol))
6850 (setq eos (org-list-get-item-end-before-blank (point) struct))
6851 (setq has-children (org-list-has-child-p (point) struct)))
6852 (org-back-to-heading)
6853 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6854 (setq eos (save-excursion (org-end-of-subtree t t)
6855 (when (bolp) (backward-char)) (point)))
6856 (setq has-children
6857 (or (save-excursion
6858 (let ((level (funcall outline-level)))
6859 (outline-next-heading)
6860 (and (org-at-heading-p t)
6861 (> (funcall outline-level) level))))
6862 (save-excursion
6863 (org-list-search-forward (org-item-beginning-re) eos t)))))
6864 ;; Determine end invisible part of buffer (EOL)
6865 (beginning-of-line 2)
6866 ;; XEmacs doesn't have `next-single-char-property-change'
6867 (if (featurep 'xemacs)
6868 (while (and (not (eobp)) ;; this is like `next-line'
6869 (get-char-property (1- (point)) 'invisible))
6870 (beginning-of-line 2))
6871 (while (and (not (eobp)) ;; this is like `next-line'
6872 (get-char-property (1- (point)) 'invisible))
6873 (goto-char (next-single-char-property-change (point) 'invisible))
6874 (and (eolp) (beginning-of-line 2))))
6875 (setq eol (point)))
6876 ;; Find out what to do next and set `this-command'
6877 (cond
6878 ((= eos eoh)
6879 ;; Nothing is hidden behind this heading
6880 (unless (org-before-first-heading-p)
6881 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6882 (org-unlogged-message "EMPTY ENTRY")
6883 (setq org-cycle-subtree-status nil)
6884 (save-excursion
6885 (goto-char eos)
6886 (outline-next-heading)
6887 (if (outline-invisible-p) (org-flag-heading nil))))
6888 ((and (or (>= eol eos)
6889 (not (string-match "\\S-" (buffer-substring eol eos))))
6890 (or has-children
6891 (not (setq children-skipped
6892 org-cycle-skip-children-state-if-no-children))))
6893 ;; Entire subtree is hidden in one line: children view
6894 (unless (org-before-first-heading-p)
6895 (run-hook-with-args 'org-pre-cycle-hook 'children))
6896 (if (org-at-item-p)
6897 (org-list-set-item-visibility (point-at-bol) struct 'children)
6898 (org-show-entry)
6899 (org-with-limited-levels (show-children))
6900 ;; FIXME: This slows down the func way too much.
6901 ;; How keep drawers hidden in subtree anyway?
6902 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6903 ;; (org-cycle-hide-drawers 'subtree))
6905 ;; Fold every list in subtree to top-level items.
6906 (when (eq org-cycle-include-plain-lists 'integrate)
6907 (save-excursion
6908 (org-back-to-heading)
6909 (while (org-list-search-forward (org-item-beginning-re) eos t)
6910 (beginning-of-line 1)
6911 (let* ((struct (org-list-struct))
6912 (prevs (org-list-prevs-alist struct))
6913 (end (org-list-get-bottom-point struct)))
6914 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6915 (org-list-get-all-items (point) struct prevs))
6916 (goto-char (if (< end eos) end eos)))))))
6917 (org-unlogged-message "CHILDREN")
6918 (save-excursion
6919 (goto-char eos)
6920 (outline-next-heading)
6921 (if (outline-invisible-p) (org-flag-heading nil)))
6922 (setq org-cycle-subtree-status 'children)
6923 (unless (org-before-first-heading-p)
6924 (run-hook-with-args 'org-cycle-hook 'children)))
6925 ((or children-skipped
6926 (and (eq last-command this-command)
6927 (eq org-cycle-subtree-status 'children)))
6928 ;; We just showed the children, or no children are there,
6929 ;; now show everything.
6930 (unless (org-before-first-heading-p)
6931 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6932 (outline-flag-region eoh eos nil)
6933 (org-unlogged-message
6934 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6935 (setq org-cycle-subtree-status 'subtree)
6936 (unless (org-before-first-heading-p)
6937 (run-hook-with-args 'org-cycle-hook 'subtree)))
6939 ;; Default action: hide the subtree.
6940 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6941 (outline-flag-region eoh eos t)
6942 (org-unlogged-message "FOLDED")
6943 (setq org-cycle-subtree-status 'folded)
6944 (unless (org-before-first-heading-p)
6945 (run-hook-with-args 'org-cycle-hook 'folded))))))
6947 ;;;###autoload
6948 (defun org-global-cycle (&optional arg)
6949 "Cycle the global visibility. For details see `org-cycle'.
6950 With \\[universal-argument] prefix arg, switch to startup visibility.
6951 With a numeric prefix, show all headlines up to that level."
6952 (interactive "P")
6953 (let ((org-cycle-include-plain-lists
6954 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6955 (cond
6956 ((integerp arg)
6957 (show-all)
6958 (hide-sublevels arg)
6959 (setq org-cycle-global-status 'contents))
6960 ((equal arg '(4))
6961 (org-set-startup-visibility)
6962 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6964 (org-cycle '(4))))))
6966 (defun org-set-startup-visibility ()
6967 "Set the visibility required by startup options and properties."
6968 (cond
6969 ((eq org-startup-folded t)
6970 (org-overview))
6971 ((eq org-startup-folded 'content)
6972 (org-content))
6973 ((or (eq org-startup-folded 'showeverything)
6974 (eq org-startup-folded nil))
6975 (show-all)))
6976 (unless (eq org-startup-folded 'showeverything)
6977 (if org-hide-block-startup (org-hide-block-all))
6978 (org-set-visibility-according-to-property 'no-cleanup)
6979 (org-cycle-hide-archived-subtrees 'all)
6980 (org-cycle-hide-drawers 'all)
6981 (org-cycle-show-empty-lines t)))
6983 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6984 "Switch subtree visibilities according to :VISIBILITY: property."
6985 (interactive)
6986 (let (org-show-entry-below)
6987 (org-with-wide-buffer
6988 (goto-char (point-min))
6989 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6990 (if (not (org-at-property-p)) (outline-next-heading)
6991 (let ((state (match-string 3)))
6992 (save-excursion
6993 (org-back-to-heading t)
6994 (hide-subtree)
6995 (org-reveal)
6996 (cond
6997 ((equal state "folded")
6998 (hide-subtree))
6999 ((equal state "children")
7000 (org-show-hidden-entry)
7001 (show-children))
7002 ((equal state "content")
7003 (save-excursion
7004 (save-restriction
7005 (org-narrow-to-subtree)
7006 (org-content))))
7007 ((member state '("all" "showall"))
7008 (show-subtree)))))))
7009 (unless no-cleanup
7010 (org-cycle-hide-archived-subtrees 'all)
7011 (org-cycle-hide-drawers 'all)
7012 (org-cycle-show-empty-lines 'all)))))
7014 ;; This function uses outline-regexp instead of the more fundamental
7015 ;; org-outline-regexp so that org-cycle-global works outside of Org
7016 ;; buffers, where outline-regexp is needed.
7017 (defun org-overview ()
7018 "Switch to overview mode, showing only top-level headlines.
7019 This shows all headlines with a level equal or greater than the level
7020 of the first headline in the buffer. This is important, because if the
7021 first headline is not level one, then (hide-sublevels 1) gives confusing
7022 results."
7023 (interactive)
7024 (save-excursion
7025 (let ((level
7026 (save-excursion
7027 (goto-char (point-min))
7028 (if (re-search-forward (concat "^" outline-regexp) nil t)
7029 (progn
7030 (goto-char (match-beginning 0))
7031 (funcall outline-level))))))
7032 (and level (hide-sublevels level)))))
7034 (defun org-content (&optional arg)
7035 "Show all headlines in the buffer, like a table of contents.
7036 With numerical argument N, show content up to level N."
7037 (interactive "P")
7038 (org-overview)
7039 (save-excursion
7040 ;; Visit all headings and show their offspring
7041 (and (integerp arg) (org-overview))
7042 (goto-char (point-max))
7043 (catch 'exit
7044 (while (and (progn (condition-case nil
7045 (outline-previous-visible-heading 1)
7046 (error (goto-char (point-min))))
7048 (looking-at org-outline-regexp))
7049 (if (integerp arg)
7050 (show-children (1- arg))
7051 (show-branches))
7052 (if (bobp) (throw 'exit nil))))))
7054 (defun org-optimize-window-after-visibility-change (state)
7055 "Adjust the window after a change in outline visibility.
7056 This function is the default value of the hook `org-cycle-hook'."
7057 (when (get-buffer-window (current-buffer))
7058 (cond
7059 ((eq state 'content) nil)
7060 ((eq state 'all) nil)
7061 ((eq state 'folded) nil)
7062 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7063 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7065 (defun org-remove-empty-overlays-at (pos)
7066 "Remove outline overlays that do not contain non-white stuff."
7067 (mapc
7068 (lambda (o)
7069 (and (eq 'outline (overlay-get o 'invisible))
7070 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7071 (overlay-end o))))
7072 (delete-overlay o)))
7073 (overlays-at pos)))
7075 (defun org-clean-visibility-after-subtree-move ()
7076 "Fix visibility issues after moving a subtree."
7077 ;; First, find a reasonable region to look at:
7078 ;; Start two siblings above, end three below
7079 (let* ((beg (save-excursion
7080 (and (org-get-last-sibling)
7081 (org-get-last-sibling))
7082 (point)))
7083 (end (save-excursion
7084 (and (org-get-next-sibling)
7085 (org-get-next-sibling)
7086 (org-get-next-sibling))
7087 (if (org-at-heading-p)
7088 (point-at-eol)
7089 (point))))
7090 (level (looking-at "\\*+"))
7091 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7092 (save-excursion
7093 (save-restriction
7094 (narrow-to-region beg end)
7095 (when re
7096 ;; Properly fold already folded siblings
7097 (goto-char (point-min))
7098 (while (re-search-forward re nil t)
7099 (if (and (not (outline-invisible-p))
7100 (save-excursion
7101 (goto-char (point-at-eol)) (outline-invisible-p)))
7102 (hide-entry))))
7103 (org-cycle-show-empty-lines 'overview)
7104 (org-cycle-hide-drawers 'overview)))))
7106 (defun org-cycle-show-empty-lines (state)
7107 "Show empty lines above all visible headlines.
7108 The region to be covered depends on STATE when called through
7109 `org-cycle-hook'. Lisp program can use t for STATE to get the
7110 entire buffer covered. Note that an empty line is only shown if there
7111 are at least `org-cycle-separator-lines' empty lines before the headline."
7112 (when (not (= org-cycle-separator-lines 0))
7113 (save-excursion
7114 (let* ((n (abs org-cycle-separator-lines))
7115 (re (cond
7116 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7117 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7118 (t (let ((ns (number-to-string (- n 2))))
7119 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7120 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7121 beg end b e)
7122 (cond
7123 ((memq state '(overview contents t))
7124 (setq beg (point-min) end (point-max)))
7125 ((memq state '(children folded))
7126 (setq beg (point) end (progn (org-end-of-subtree t t)
7127 (beginning-of-line 2)
7128 (point)))))
7129 (when beg
7130 (goto-char beg)
7131 (while (re-search-forward re end t)
7132 (unless (get-char-property (match-end 1) 'invisible)
7133 (setq e (match-end 1))
7134 (if (< org-cycle-separator-lines 0)
7135 (setq b (save-excursion
7136 (goto-char (match-beginning 0))
7137 (org-back-over-empty-lines)
7138 (if (save-excursion
7139 (goto-char (max (point-min) (1- (point))))
7140 (org-at-heading-p))
7141 (1- (point))
7142 (point))))
7143 (setq b (match-beginning 1)))
7144 (outline-flag-region b e nil)))))))
7145 ;; Never hide empty lines at the end of the file.
7146 (save-excursion
7147 (goto-char (point-max))
7148 (outline-previous-heading)
7149 (outline-end-of-heading)
7150 (if (and (looking-at "[ \t\n]+")
7151 (= (match-end 0) (point-max)))
7152 (outline-flag-region (point) (match-end 0) nil))))
7154 (defun org-show-empty-lines-in-parent ()
7155 "Move to the parent and re-show empty lines before visible headlines."
7156 (save-excursion
7157 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7158 (org-cycle-show-empty-lines context))))
7160 (defun org-files-list ()
7161 "Return `org-agenda-files' list, plus all open org-mode files.
7162 This is useful for operations that need to scan all of a user's
7163 open and agenda-wise Org files."
7164 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7165 (dolist (buf (buffer-list))
7166 (with-current-buffer buf
7167 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7168 (let ((file (expand-file-name (buffer-file-name))))
7169 (unless (member file files)
7170 (push file files))))))
7171 files))
7173 (defsubst org-entry-beginning-position ()
7174 "Return the beginning position of the current entry."
7175 (save-excursion (outline-back-to-heading t) (point)))
7177 (defsubst org-entry-end-position ()
7178 "Return the end position of the current entry."
7179 (save-excursion (outline-next-heading) (point)))
7181 (defun org-cycle-hide-drawers (state &optional exceptions)
7182 "Re-hide all drawers after a visibility state change.
7183 When non-nil, optional argument EXCEPTIONS is a list of strings
7184 specifying which drawers should not be hidden."
7185 (when (and (derived-mode-p 'org-mode)
7186 (not (memq state '(overview folded contents))))
7187 (save-excursion
7188 (let* ((globalp (memq state '(contents all)))
7189 (beg (if globalp (point-min) (point)))
7190 (end (if globalp (point-max)
7191 (if (eq state 'children)
7192 (save-excursion (outline-next-heading) (point))
7193 (org-end-of-subtree t)))))
7194 (goto-char beg)
7195 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7196 (unless (member-ignore-case (match-string 1) exceptions)
7197 (let ((drawer (org-element-at-point)))
7198 (when (memq (org-element-type drawer) '(drawer property-drawer))
7199 (org-flag-drawer t drawer)
7200 ;; Make sure to skip drawer entirely or we might flag
7201 ;; it another time when matching its ending line with
7202 ;; `org-drawer-regexp'.
7203 (goto-char (org-element-property :end drawer))))))))))
7205 (defun org-cycle-hide-inline-tasks (state)
7206 "Re-hide inline tasks when switching to 'contents or 'children
7207 visibility state."
7208 (case state
7209 (contents
7210 (when (org-bound-and-true-p org-inlinetask-min-level)
7211 (hide-sublevels (1- org-inlinetask-min-level))))
7212 (children
7213 (when (featurep 'org-inlinetask)
7214 (save-excursion
7215 (while (and (outline-next-heading)
7216 (org-inlinetask-at-task-p))
7217 (org-inlinetask-toggle-visibility)
7218 (org-inlinetask-goto-end)))))))
7220 (defun org-flag-drawer (flag &optional element)
7221 "When FLAG is non-nil, hide the drawer we are at.
7222 Otherwise make it visible. When optional argument ELEMENT is
7223 a parsed drawer, as returned by `org-element-at-point', hide or
7224 show that drawer instead."
7225 (when (save-excursion
7226 (beginning-of-line)
7227 (org-looking-at-p org-drawer-regexp))
7228 (let ((drawer (or element (org-element-at-point))))
7229 (when (memq (org-element-type drawer) '(drawer property-drawer))
7230 (let ((post (org-element-property :post-affiliated drawer)))
7231 (save-excursion
7232 (outline-flag-region
7233 (progn (goto-char post) (line-end-position))
7234 (progn (goto-char (org-element-property :end drawer))
7235 (skip-chars-backward " \r\t\n")
7236 (line-end-position))
7237 flag))
7238 ;; When the drawer is hidden away, make sure point lies in
7239 ;; a visible part of the buffer.
7240 (when (and flag (> (line-beginning-position) post))
7241 (goto-char post)))))))
7243 (defun org-subtree-end-visible-p ()
7244 "Is the end of the current subtree visible?"
7245 (pos-visible-in-window-p
7246 (save-excursion (org-end-of-subtree t) (point))))
7248 (defun org-first-headline-recenter ()
7249 "Move cursor to the first headline and recenter the headline."
7250 (goto-char (point-min))
7251 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7252 (set-window-start (selected-window) (point-at-bol))))
7254 ;;; Saving and restoring visibility
7256 (defun org-outline-overlay-data (&optional use-markers)
7257 "Return a list of the locations of all outline overlays.
7258 These are overlays with the `invisible' property value `outline'.
7259 The return value is a list of cons cells, with start and stop
7260 positions for each overlay.
7261 If USE-MARKERS is set, return the positions as markers."
7262 (let (beg end)
7263 (save-excursion
7264 (save-restriction
7265 (widen)
7266 (delq nil
7267 (mapcar (lambda (o)
7268 (when (eq (overlay-get o 'invisible) 'outline)
7269 (setq beg (overlay-start o)
7270 end (overlay-end o))
7271 (and beg end (> end beg)
7272 (if use-markers
7273 (cons (copy-marker beg)
7274 (copy-marker end t))
7275 (cons beg end)))))
7276 (overlays-in (point-min) (point-max))))))))
7278 (defun org-set-outline-overlay-data (data)
7279 "Create visibility overlays for all positions in DATA.
7280 DATA should have been made by `org-outline-overlay-data'."
7281 (let (o)
7282 (save-excursion
7283 (save-restriction
7284 (widen)
7285 (show-all)
7286 (mapc (lambda (c)
7287 (outline-flag-region (car c) (cdr c) t))
7288 data)))))
7290 ;;; Folding of blocks
7292 (defvar org-hide-block-overlays nil
7293 "Overlays hiding blocks.")
7294 (make-variable-buffer-local 'org-hide-block-overlays)
7296 (defun org-block-map (function &optional start end)
7297 "Call FUNCTION at the head of all source blocks in the current buffer.
7298 Optional arguments START and END can be used to limit the range."
7299 (let ((start (or start (point-min)))
7300 (end (or end (point-max))))
7301 (save-excursion
7302 (goto-char start)
7303 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7304 (save-excursion
7305 (save-match-data
7306 (goto-char (match-beginning 0))
7307 (funcall function)))))))
7309 (defun org-hide-block-toggle-all ()
7310 "Toggle the visibility of all blocks in the current buffer."
7311 (org-block-map 'org-hide-block-toggle))
7313 (defun org-hide-block-all ()
7314 "Fold all blocks in the current buffer."
7315 (interactive)
7316 (org-show-block-all)
7317 (org-block-map 'org-hide-block-toggle-maybe))
7319 (defun org-show-block-all ()
7320 "Unfold all blocks in the current buffer."
7321 (interactive)
7322 (mapc 'delete-overlay org-hide-block-overlays)
7323 (setq org-hide-block-overlays nil))
7325 (defun org-hide-block-toggle-maybe ()
7326 "Toggle visibility of block at point.
7327 Unlike to `org-hide-block-toggle', this function does not throw
7328 an error. Return a non-nil value when toggling is successful."
7329 (interactive)
7330 (ignore-errors (org-hide-block-toggle)))
7332 (defun org-hide-block-toggle (&optional force)
7333 "Toggle the visibility of the current block.
7334 When optional argument FORCE is `off', make block visible. If it
7335 is non-nil, hide it unconditionally. Throw an error when not at
7336 a block. Return a non-nil value when toggling is successful."
7337 (interactive)
7338 (let ((element (org-element-at-point)))
7339 (unless (memq (org-element-type element)
7340 '(center-block comment-block dynamic-block example-block
7341 export-block quote-block special-block
7342 src-block verse-block))
7343 (user-error "Not at a block"))
7344 (let* ((start (save-excursion
7345 (goto-char (org-element-property :post-affiliated element))
7346 (line-end-position)))
7347 (end (save-excursion
7348 (goto-char (org-element-property :end element))
7349 (skip-chars-backward " \r\t\n")
7350 (line-end-position)))
7351 (overlays (overlays-at start)))
7352 (cond
7353 ;; Do nothing when not before or at the block opening line or
7354 ;; at the block closing line.
7355 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7356 ((and (not (eq force 'off))
7357 (not (memq t (mapcar
7358 (lambda (o)
7359 (eq (overlay-get o 'invisible) 'org-hide-block))
7360 overlays))))
7361 (let ((ov (make-overlay start end)))
7362 (overlay-put ov 'invisible 'org-hide-block)
7363 ;; Make the block accessible to `isearch'.
7364 (overlay-put
7365 ov 'isearch-open-invisible
7366 (lambda (ov)
7367 (when (memq ov org-hide-block-overlays)
7368 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7369 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7370 (delete-overlay ov))))
7371 (push ov org-hide-block-overlays)
7372 ;; When the block is hidden away, make sure point is left in
7373 ;; a visible part of the buffer.
7374 (when (> (line-beginning-position) start)
7375 (goto-char start)
7376 (beginning-of-line))
7377 ;; Signal successful toggling.
7379 ((or (not force) (eq force 'off))
7380 (dolist (ov overlays t)
7381 (when (memq ov org-hide-block-overlays)
7382 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7383 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7384 (delete-overlay ov))))))))
7386 ;; org-tab-after-check-for-cycling-hook
7387 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7388 ;; Remove overlays when changing major mode
7389 (add-hook 'org-mode-hook
7390 (lambda () (org-add-hook 'change-major-mode-hook
7391 'org-show-block-all 'append 'local)))
7393 ;;; Org-goto
7395 (defvar org-goto-window-configuration nil)
7396 (defvar org-goto-marker nil)
7397 (defvar org-goto-map)
7398 (defun org-goto-map ()
7399 "Set the keymap `org-goto'."
7400 (setq org-goto-map
7401 (let ((map (make-sparse-keymap)))
7402 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7403 mouse-drag-region universal-argument org-occur))
7404 cmd)
7405 (while (setq cmd (pop cmds))
7406 (substitute-key-definition cmd cmd map global-map)))
7407 (suppress-keymap map)
7408 (org-defkey map "\C-m" 'org-goto-ret)
7409 (org-defkey map [(return)] 'org-goto-ret)
7410 (org-defkey map [(left)] 'org-goto-left)
7411 (org-defkey map [(right)] 'org-goto-right)
7412 (org-defkey map [(control ?g)] 'org-goto-quit)
7413 (org-defkey map "\C-i" 'org-cycle)
7414 (org-defkey map [(tab)] 'org-cycle)
7415 (org-defkey map [(down)] 'outline-next-visible-heading)
7416 (org-defkey map [(up)] 'outline-previous-visible-heading)
7417 (if org-goto-auto-isearch
7418 (if (fboundp 'define-key-after)
7419 (define-key-after map [t] 'org-goto-local-auto-isearch)
7420 nil)
7421 (org-defkey map "q" 'org-goto-quit)
7422 (org-defkey map "n" 'outline-next-visible-heading)
7423 (org-defkey map "p" 'outline-previous-visible-heading)
7424 (org-defkey map "f" 'outline-forward-same-level)
7425 (org-defkey map "b" 'outline-backward-same-level)
7426 (org-defkey map "u" 'outline-up-heading))
7427 (org-defkey map "/" 'org-occur)
7428 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7429 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7430 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7431 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7432 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7433 map)))
7435 (defconst org-goto-help
7436 "Browse buffer copy, to find location or copy text.%s
7437 RET=jump to location C-g=quit and return to previous location
7438 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7440 (defvar org-goto-start-pos) ; dynamically scoped parameter
7442 (defun org-goto (&optional alternative-interface)
7443 "Look up a different location in the current file, keeping current visibility.
7445 When you want look-up or go to a different location in a
7446 document, the fastest way is often to fold the entire buffer and
7447 then dive into the tree. This method has the disadvantage, that
7448 the previous location will be folded, which may not be what you
7449 want.
7451 This command works around this by showing a copy of the current
7452 buffer in an indirect buffer, in overview mode. You can dive
7453 into the tree in that copy, use org-occur and incremental search
7454 to find a location. When pressing RET or `Q', the command
7455 returns to the original buffer in which the visibility is still
7456 unchanged. After RET it will also jump to the location selected
7457 in the indirect buffer and expose the headline hierarchy above.
7459 With a prefix argument, use the alternative interface: e.g. if
7460 `org-goto-interface' is 'outline use 'outline-path-completion."
7461 (interactive "P")
7462 (org-goto-map)
7463 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7464 (org-refile-use-outline-path t)
7465 (org-refile-target-verify-function nil)
7466 (interface
7467 (if (not alternative-interface)
7468 org-goto-interface
7469 (if (eq org-goto-interface 'outline)
7470 'outline-path-completion
7471 'outline)))
7472 (org-goto-start-pos (point))
7473 (selected-point
7474 (if (eq interface 'outline)
7475 (car (org-get-location (current-buffer) org-goto-help))
7476 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7477 (org-refile-check-position pa)
7478 (nth 3 pa)))))
7479 (if selected-point
7480 (progn
7481 (org-mark-ring-push org-goto-start-pos)
7482 (goto-char selected-point)
7483 (if (or (outline-invisible-p) (org-invisible-p2))
7484 (org-show-context 'org-goto)))
7485 (message "Quit"))))
7487 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7488 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7489 (defvar org-goto-local-auto-isearch-map) ; defined below
7491 (defun org-get-location (buf help)
7492 "Let the user select a location in the Org-mode buffer BUF.
7493 This function uses a recursive edit. It returns the selected position
7494 or nil."
7495 (org-no-popups
7496 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7497 (isearch-hide-immediately nil)
7498 (isearch-search-fun-function
7499 (lambda () 'org-goto-local-search-headings))
7500 (org-goto-selected-point org-goto-exit-command))
7501 (save-excursion
7502 (save-window-excursion
7503 (delete-other-windows)
7504 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7505 (org-pop-to-buffer-same-window
7506 (condition-case nil
7507 (make-indirect-buffer (current-buffer) "*org-goto*")
7508 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7509 (with-output-to-temp-buffer "*Org Help*"
7510 (princ (format help (if org-goto-auto-isearch
7511 " Just type for auto-isearch."
7512 " n/p/f/b/u to navigate, q to quit."))))
7513 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7514 (setq buffer-read-only nil)
7515 (let ((org-startup-truncated t)
7516 (org-startup-folded nil)
7517 (org-startup-align-all-tables nil))
7518 (org-mode)
7519 (org-overview))
7520 (setq buffer-read-only t)
7521 (if (and (boundp 'org-goto-start-pos)
7522 (integer-or-marker-p org-goto-start-pos))
7523 (let ((org-show-hierarchy-above t)
7524 (org-show-siblings t)
7525 (org-show-following-heading t))
7526 (goto-char org-goto-start-pos)
7527 (and (outline-invisible-p) (org-show-context)))
7528 (goto-char (point-min)))
7529 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7530 (message "Select location and press RET")
7531 (use-local-map org-goto-map)
7532 (recursive-edit)))
7533 (kill-buffer "*org-goto*")
7534 (cons org-goto-selected-point org-goto-exit-command))))
7536 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7537 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7538 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7539 (if (fboundp 'isearch-other-control-char)
7540 (progn
7541 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7542 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7543 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7544 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7545 (define-key org-goto-local-auto-isearch-map [return] nil))
7547 (defun org-goto-local-search-headings (string bound noerror)
7548 "Search and make sure that any matches are in headlines."
7549 (catch 'return
7550 (while (if isearch-forward
7551 (search-forward string bound noerror)
7552 (search-backward string bound noerror))
7553 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7554 (and (member :headline context)
7555 (not (member :tags context))))
7556 (throw 'return (point))))))
7558 (defun org-goto-local-auto-isearch ()
7559 "Start isearch."
7560 (interactive)
7561 (goto-char (point-min))
7562 (let ((keys (this-command-keys)))
7563 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7564 (isearch-mode t)
7565 (isearch-process-search-char (string-to-char keys)))))
7567 (defun org-goto-ret (&optional arg)
7568 "Finish `org-goto' by going to the new location."
7569 (interactive "P")
7570 (setq org-goto-selected-point (point)
7571 org-goto-exit-command 'return)
7572 (throw 'exit nil))
7574 (defun org-goto-left ()
7575 "Finish `org-goto' by going to the new location."
7576 (interactive)
7577 (if (org-at-heading-p)
7578 (progn
7579 (beginning-of-line 1)
7580 (setq org-goto-selected-point (point)
7581 org-goto-exit-command 'left)
7582 (throw 'exit nil))
7583 (user-error "Not on a heading")))
7585 (defun org-goto-right ()
7586 "Finish `org-goto' by going to the new location."
7587 (interactive)
7588 (if (org-at-heading-p)
7589 (progn
7590 (setq org-goto-selected-point (point)
7591 org-goto-exit-command 'right)
7592 (throw 'exit nil))
7593 (user-error "Not on a heading")))
7595 (defun org-goto-quit ()
7596 "Finish `org-goto' without cursor motion."
7597 (interactive)
7598 (setq org-goto-selected-point nil)
7599 (setq org-goto-exit-command 'quit)
7600 (throw 'exit nil))
7602 ;;; Indirect buffer display of subtrees
7604 (defvar org-indirect-dedicated-frame nil
7605 "This is the frame being used for indirect tree display.")
7606 (defvar org-last-indirect-buffer nil)
7608 (defun org-tree-to-indirect-buffer (&optional arg)
7609 "Create indirect buffer and narrow it to current subtree.
7610 With a numerical prefix ARG, go up to this level and then take that tree.
7611 If ARG is negative, go up that many levels.
7613 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7614 indirect buffer previously made with this command, to avoid proliferation of
7615 indirect buffers. However, when you call the command with a \
7616 \\[universal-argument] prefix, or
7617 when `org-indirect-buffer-display' is `new-frame', the last buffer
7618 is kept so that you can work with several indirect buffers at the same time.
7619 If `org-indirect-buffer-display' is `dedicated-frame', the \
7620 \\[universal-argument] prefix also
7621 requests that a new frame be made for the new buffer, so that the dedicated
7622 frame is not changed."
7623 (interactive "P")
7624 (let ((cbuf (current-buffer))
7625 (cwin (selected-window))
7626 (pos (point))
7627 beg end level heading ibuf)
7628 (save-excursion
7629 (org-back-to-heading t)
7630 (when (numberp arg)
7631 (setq level (org-outline-level))
7632 (if (< arg 0) (setq arg (+ level arg)))
7633 (while (> (setq level (org-outline-level)) arg)
7634 (org-up-heading-safe)))
7635 (setq beg (point)
7636 heading (org-get-heading))
7637 (org-end-of-subtree t t)
7638 (if (org-at-heading-p) (backward-char 1))
7639 (setq end (point)))
7640 (if (and (buffer-live-p org-last-indirect-buffer)
7641 (not (eq org-indirect-buffer-display 'new-frame))
7642 (not arg))
7643 (kill-buffer org-last-indirect-buffer))
7644 (setq ibuf (org-get-indirect-buffer cbuf heading)
7645 org-last-indirect-buffer ibuf)
7646 (cond
7647 ((or (eq org-indirect-buffer-display 'new-frame)
7648 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7649 (select-frame (make-frame))
7650 (delete-other-windows)
7651 (org-pop-to-buffer-same-window ibuf)
7652 (org-set-frame-title heading))
7653 ((eq org-indirect-buffer-display 'dedicated-frame)
7654 (raise-frame
7655 (select-frame (or (and org-indirect-dedicated-frame
7656 (frame-live-p org-indirect-dedicated-frame)
7657 org-indirect-dedicated-frame)
7658 (setq org-indirect-dedicated-frame (make-frame)))))
7659 (delete-other-windows)
7660 (org-pop-to-buffer-same-window ibuf)
7661 (org-set-frame-title (concat "Indirect: " heading)))
7662 ((eq org-indirect-buffer-display 'current-window)
7663 (org-pop-to-buffer-same-window ibuf))
7664 ((eq org-indirect-buffer-display 'other-window)
7665 (pop-to-buffer ibuf))
7666 (t (error "Invalid value")))
7667 (if (featurep 'xemacs)
7668 (save-excursion (org-mode) (turn-on-font-lock)))
7669 (narrow-to-region beg end)
7670 (show-all)
7671 (goto-char pos)
7672 (run-hook-with-args 'org-cycle-hook 'all)
7673 (and (window-live-p cwin) (select-window cwin))))
7675 (defun org-get-indirect-buffer (&optional buffer heading)
7676 (setq buffer (or buffer (current-buffer)))
7677 (let ((n 1) (base (buffer-name buffer)) bname)
7678 (while (buffer-live-p
7679 (get-buffer
7680 (setq bname
7681 (concat base "-"
7682 (if heading (concat heading "-" (number-to-string n))
7683 (number-to-string n))))))
7684 (setq n (1+ n)))
7685 (condition-case nil
7686 (make-indirect-buffer buffer bname 'clone)
7687 (error (make-indirect-buffer buffer bname)))))
7689 (defun org-set-frame-title (title)
7690 "Set the title of the current frame to the string TITLE."
7691 ;; FIXME: how to name a single frame in XEmacs???
7692 (unless (featurep 'xemacs)
7693 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7695 ;;;; Structure editing
7697 ;;; Inserting headlines
7699 (defun org-previous-line-empty-p (&optional next)
7700 "Is the previous line a blank line?
7701 When NEXT is non-nil, check the next line instead."
7702 (save-excursion
7703 (and (not (bobp))
7704 (or (beginning-of-line (if next 2 0)) t)
7705 (save-match-data
7706 (looking-at "[ \t]*$")))))
7708 (defun org-insert-heading (&optional arg invisible-ok)
7709 "Insert a new heading or an item with the same depth at point.
7711 If point is at the beginning of a heading or a list item, insert
7712 a new heading or a new item above the current one. If point is
7713 at the beginning of a normal line, turn the line into a heading.
7715 If point is in the middle of a headline or a list item, split the
7716 headline or the item and create a new headline/item with the text
7717 in the current line after point \(see `org-M-RET-may-split-line'
7718 on how to modify this behavior).
7720 With one universal prefix argument, set the user option
7721 `org-insert-heading-respect-content' to t for the duration of
7722 the command. This modifies the behavior described above in this
7723 ways: on list items and at the beginning of normal lines, force
7724 the insertion of a heading after the current subtree.
7726 With two universal prefix arguments, insert the heading at the
7727 end of the grandparent subtree. For example, if point is within
7728 a 2nd-level heading, then it will insert a 2nd-level heading at
7729 the end of the 1st-level parent heading.
7731 If point is at the beginning of a headline, insert a sibling
7732 before the current headline. If point is not at the beginning,
7733 split the line and create a new headline with the text in the
7734 current line after point \(see `org-M-RET-may-split-line' on how
7735 to modify this behavior).
7737 If point is at the beginning of a normal line, turn this line
7738 into a heading.
7740 When INVISIBLE-OK is set, stop at invisible headlines when going
7741 back. This is important for non-interactive uses of the
7742 command."
7743 (interactive "P")
7744 (if (org-called-interactively-p 'any) (org-reveal))
7745 (let ((itemp (org-in-item-p))
7746 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7747 (respect-content (or org-insert-heading-respect-content
7748 (equal arg '(4))))
7749 (initial-content "")
7750 (adjust-empty-lines t))
7752 (cond
7754 ((or (= (buffer-size) 0)
7755 (and (not (save-excursion
7756 (and (ignore-errors (org-back-to-heading invisible-ok))
7757 (org-at-heading-p))))
7758 (or arg (not itemp))))
7759 ;; At beginning of buffer or so high up that only a heading
7760 ;; makes sense.
7761 (cond ((and (bolp) (not respect-content)) (insert "* "))
7762 ((not respect-content)
7763 (unless may-split (end-of-line))
7764 (insert "\n* "))
7765 ((re-search-forward org-outline-regexp-bol nil t)
7766 (beginning-of-line)
7767 (insert "* \n")
7768 (backward-char))
7769 (t (goto-char (point-max))
7770 (insert "\n* ")))
7771 (run-hooks 'org-insert-heading-hook))
7773 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7776 ;; Maybe move at the end of the subtree
7777 (when (equal arg '(16))
7778 (org-up-heading-safe)
7779 (org-end-of-subtree t))
7780 ;; Insert a heading
7781 (save-restriction
7782 (widen)
7783 (let* ((level nil)
7784 (on-heading (org-at-heading-p))
7785 (empty-line-p (if on-heading
7786 (org-previous-line-empty-p)
7787 ;; We will decide later
7788 nil))
7789 ;; Get a level string to fall back on
7790 (fix-level
7791 (if (org-before-first-heading-p) "*"
7792 (save-excursion
7793 (org-back-to-heading t)
7794 (if (org-previous-line-empty-p) (setq empty-line-p t))
7795 (looking-at org-outline-regexp)
7796 (make-string (1- (length (match-string 0))) ?*))))
7797 (stars
7798 (save-excursion
7799 (condition-case nil
7800 (progn
7801 (org-back-to-heading invisible-ok)
7802 (when (and (not on-heading)
7803 (featurep 'org-inlinetask)
7804 (integerp org-inlinetask-min-level)
7805 (>= (length (match-string 0))
7806 org-inlinetask-min-level))
7807 ;; Find a heading level before the inline task
7808 (while (and (setq level (org-up-heading-safe))
7809 (>= level org-inlinetask-min-level)))
7810 (if (org-at-heading-p)
7811 (org-back-to-heading invisible-ok)
7812 (error "This should not happen")))
7813 (unless (and (save-excursion
7814 (save-match-data
7815 (org-backward-heading-same-level
7816 1 invisible-ok))
7817 (= (point) (match-beginning 0)))
7818 (not (org-previous-line-empty-p t)))
7819 (setq empty-line-p (or empty-line-p
7820 (org-previous-line-empty-p))))
7821 (match-string 0))
7822 (error (or fix-level "* ")))))
7823 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7824 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7825 pos hide-previous previous-pos)
7827 ;; If we insert after content, move there and clean up whitespace
7828 (when (and respect-content
7829 (not (org-looking-at-p org-outline-regexp-bol)))
7830 (if (not (org-before-first-heading-p))
7831 (org-end-of-subtree nil t)
7832 (re-search-forward org-outline-regexp-bol)
7833 (beginning-of-line 0))
7834 (skip-chars-backward " \r\n")
7835 (and (not (looking-back "^\\*+"))
7836 (looking-at "[ \t]+") (replace-match ""))
7837 (unless (eobp) (forward-char 1))
7838 (when (looking-at "^\\*")
7839 (unless (bobp) (backward-char 1))
7840 (insert "\n")))
7842 ;; If we are splitting, grab the text that should be moved to the new headline
7843 (when may-split
7844 (if (org-on-heading-p)
7845 ;; This is a heading, we split intelligently (keeping tags)
7846 (let ((pos (point)))
7847 (goto-char (point-at-bol))
7848 (unless (looking-at org-complex-heading-regexp)
7849 (error "This should not happen"))
7850 (when (and (match-beginning 4)
7851 (> pos (match-beginning 4))
7852 (< pos (match-end 4)))
7853 (setq initial-content (buffer-substring pos (match-end 4)))
7854 (goto-char pos)
7855 (delete-region (point) (match-end 4))
7856 (if (looking-at "[ \t]*$")
7857 (replace-match "")
7858 (insert (make-string (length initial-content) ?\ )))
7859 (setq initial-content (org-trim initial-content)))
7860 (goto-char pos))
7861 ;; a normal line
7862 (setq initial-content
7863 (org-trim (buffer-substring (point) (point-at-eol))))
7864 (delete-region (point) (point-at-eol))))
7866 ;; If we are at the beginning of the line, insert before it. Else after
7867 (cond
7868 ((and (bolp) (looking-at "[ \t]*$")))
7869 ((and (bolp) (not (looking-at "[ \t]*$")))
7870 (open-line 1))
7872 (goto-char (point-at-eol))
7873 (insert "\n")))
7875 ;; Insert the new heading
7876 (insert stars)
7877 (just-one-space)
7878 (insert initial-content)
7879 (when adjust-empty-lines
7880 (if (or (not blank)
7881 (and blank (not (org-previous-line-empty-p))))
7882 (org-N-empty-lines-before-current (if blank 1 0))))
7883 (run-hooks 'org-insert-heading-hook)))))))
7885 (defun org-N-empty-lines-before-current (N)
7886 "Make the number of empty lines before current exactly N.
7887 So this will delete or add empty lines."
7888 (save-excursion
7889 (beginning-of-line)
7890 (let ((p (point)))
7891 (skip-chars-backward " \r\t\n")
7892 (unless (bolp) (forward-line))
7893 (delete-region (point) p))
7894 (when (> N 0) (insert (make-string N ?\n)))))
7896 (defun org-get-heading (&optional no-tags no-todo)
7897 "Return the heading of the current entry, without the stars.
7898 When NO-TAGS is non-nil, don't include tags.
7899 When NO-TODO is non-nil, don't include TODO keywords."
7900 (save-excursion
7901 (org-back-to-heading t)
7902 (cond
7903 ((and no-tags no-todo)
7904 (looking-at org-complex-heading-regexp)
7905 (match-string 4))
7906 (no-tags
7907 (looking-at (concat org-outline-regexp
7908 "\\(.*?\\)"
7909 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7910 (match-string 1))
7911 (no-todo
7912 (looking-at org-todo-line-regexp)
7913 (match-string 3))
7914 (t (looking-at org-heading-regexp)
7915 (match-string 2)))))
7917 (defvar orgstruct-mode) ; defined below
7919 (defun org-heading-components ()
7920 "Return the components of the current heading.
7921 This is a list with the following elements:
7922 - the level as an integer
7923 - the reduced level, different if `org-odd-levels-only' is set.
7924 - the TODO keyword, or nil
7925 - the priority character, like ?A, or nil if no priority is given
7926 - the headline text itself, or the tags string if no headline text
7927 - the tags string, or nil."
7928 (save-excursion
7929 (org-back-to-heading t)
7930 (if (let (case-fold-search)
7931 (looking-at
7932 (if orgstruct-mode
7933 org-heading-regexp
7934 org-complex-heading-regexp)))
7935 (if orgstruct-mode
7936 (list (length (match-string 1))
7937 (org-reduced-level (length (match-string 1)))
7940 (match-string 2)
7941 nil)
7942 (list (length (match-string 1))
7943 (org-reduced-level (length (match-string 1)))
7944 (org-match-string-no-properties 2)
7945 (and (match-end 3) (aref (match-string 3) 2))
7946 (org-match-string-no-properties 4)
7947 (org-match-string-no-properties 5))))))
7949 (defun org-get-entry ()
7950 "Get the entry text, after heading, entire subtree."
7951 (save-excursion
7952 (org-back-to-heading t)
7953 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7955 (defun org-insert-heading-after-current ()
7956 "Insert a new heading with same level as current, after current subtree."
7957 (interactive)
7958 (org-back-to-heading)
7959 (org-insert-heading)
7960 (org-move-subtree-down)
7961 (end-of-line 1))
7963 (defun org-insert-heading-respect-content (&optional invisible-ok)
7964 "Insert heading with `org-insert-heading-respect-content' set to t."
7965 (interactive)
7966 (org-insert-heading '(4) invisible-ok))
7968 (defun org-insert-todo-heading-respect-content (&optional force-state)
7969 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7970 (interactive)
7971 (org-insert-todo-heading force-state '(4)))
7973 (defun org-insert-todo-heading (arg &optional force-heading)
7974 "Insert a new heading with the same level and TODO state as current heading.
7975 If the heading has no TODO state, or if the state is DONE, use the first
7976 state (TODO by default). Also with one prefix arg, force first state. With
7977 two prefix args, force inserting at the end of the parent subtree."
7978 (interactive "P")
7979 (when (or force-heading (not (org-insert-item 'checkbox)))
7980 (org-insert-heading (or (and (equal arg '(16)) '(16))
7981 force-heading))
7982 (save-excursion
7983 (org-back-to-heading)
7984 (outline-previous-heading)
7985 (looking-at org-todo-line-regexp))
7986 (let*
7987 ((new-mark-x
7988 (if (or (equal arg '(4))
7989 (not (match-beginning 2))
7990 (member (match-string 2) org-done-keywords))
7991 (car org-todo-keywords-1)
7992 (match-string 2)))
7993 (new-mark
7995 (run-hook-with-args-until-success
7996 'org-todo-get-default-hook new-mark-x nil)
7997 new-mark-x)))
7998 (beginning-of-line 1)
7999 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8000 (if org-treat-insert-todo-heading-as-state-change
8001 (org-todo new-mark)
8002 (insert new-mark " "))))
8003 (when org-provide-todo-statistics
8004 (org-update-parent-todo-statistics))))
8006 (defun org-insert-subheading (arg)
8007 "Insert a new subheading and demote it.
8008 Works for outline headings and for plain lists alike."
8009 (interactive "P")
8010 (org-insert-heading arg)
8011 (cond
8012 ((org-at-heading-p) (org-do-demote))
8013 ((org-at-item-p) (org-indent-item))))
8015 (defun org-insert-todo-subheading (arg)
8016 "Insert a new subheading with TODO keyword or checkbox and demote it.
8017 Works for outline headings and for plain lists alike."
8018 (interactive "P")
8019 (org-insert-todo-heading arg)
8020 (cond
8021 ((org-at-heading-p) (org-do-demote))
8022 ((org-at-item-p) (org-indent-item))))
8024 ;;; Promotion and Demotion
8026 (defvar org-after-demote-entry-hook nil
8027 "Hook run after an entry has been demoted.
8028 The cursor will be at the beginning of the entry.
8029 When a subtree is being demoted, the hook will be called for each node.")
8031 (defvar org-after-promote-entry-hook nil
8032 "Hook run after an entry has been promoted.
8033 The cursor will be at the beginning of the entry.
8034 When a subtree is being promoted, the hook will be called for each node.")
8036 (defun org-promote-subtree ()
8037 "Promote the entire subtree.
8038 See also `org-promote'."
8039 (interactive)
8040 (save-excursion
8041 (org-with-limited-levels (org-map-tree 'org-promote)))
8042 (org-fix-position-after-promote))
8044 (defun org-demote-subtree ()
8045 "Demote the entire subtree. See `org-demote'.
8046 See also `org-promote'."
8047 (interactive)
8048 (save-excursion
8049 (org-with-limited-levels (org-map-tree 'org-demote)))
8050 (org-fix-position-after-promote))
8053 (defun org-do-promote ()
8054 "Promote the current heading higher up the tree.
8055 If the region is active in `transient-mark-mode', promote all headings
8056 in the region."
8057 (interactive)
8058 (save-excursion
8059 (if (org-region-active-p)
8060 (org-map-region 'org-promote (region-beginning) (region-end))
8061 (org-promote)))
8062 (org-fix-position-after-promote))
8064 (defun org-do-demote ()
8065 "Demote the current heading lower down the tree.
8066 If the region is active in `transient-mark-mode', demote all headings
8067 in the region."
8068 (interactive)
8069 (save-excursion
8070 (if (org-region-active-p)
8071 (org-map-region 'org-demote (region-beginning) (region-end))
8072 (org-demote)))
8073 (org-fix-position-after-promote))
8075 (defun org-fix-position-after-promote ()
8076 "Make sure that after pro/demotion cursor position is right."
8077 (let ((pos (point)))
8078 (when (save-excursion
8079 (beginning-of-line 1)
8080 (looking-at org-todo-line-regexp)
8081 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8082 (cond ((eobp) (insert " "))
8083 ((eolp) (insert " "))
8084 ((equal (char-after) ?\ ) (forward-char 1))))))
8086 (defun org-current-level ()
8087 "Return the level of the current entry, or nil if before the first headline.
8088 The level is the number of stars at the beginning of the
8089 headline. Use `org-reduced-level' to remove the effect of
8090 `org-odd-levels'. Unlike to `org-outline-level', this function
8091 ignores inlinetasks."
8092 (let ((level (org-with-limited-levels (org-outline-level))))
8093 (and (> level 0) level)))
8095 (defun org-get-previous-line-level ()
8096 "Return the outline depth of the last headline before the current line.
8097 Returns 0 for the first headline in the buffer, and nil if before the
8098 first headline."
8099 (and (org-current-level)
8100 (or (and (/= (line-beginning-position) (point-min))
8101 (save-excursion (beginning-of-line 0) (org-current-level)))
8102 0)))
8104 (defun org-reduced-level (l)
8105 "Compute the effective level of a heading.
8106 This takes into account the setting of `org-odd-levels-only'."
8107 (cond
8108 ((zerop l) 0)
8109 (org-odd-levels-only (1+ (floor (/ l 2))))
8110 (t l)))
8112 (defun org-level-increment ()
8113 "Return the number of stars that will be added or removed at a
8114 time to headlines when structure editing, based on the value of
8115 `org-odd-levels-only'."
8116 (if org-odd-levels-only 2 1))
8118 (defun org-get-valid-level (level &optional change)
8119 "Rectify a level change under the influence of `org-odd-levels-only'
8120 LEVEL is a current level, CHANGE is by how much the level should be
8121 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8122 even level numbers will become the next higher odd number."
8123 (if org-odd-levels-only
8124 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8125 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8126 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8127 (max 1 (+ level (or change 0)))))
8129 (if (boundp 'define-obsolete-function-alias)
8130 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8131 (define-obsolete-function-alias 'org-get-legal-level
8132 'org-get-valid-level)
8133 (define-obsolete-function-alias 'org-get-legal-level
8134 'org-get-valid-level "23.1")))
8136 (defun org-promote ()
8137 "Promote the current heading higher up the tree."
8138 (org-with-wide-buffer
8139 (org-back-to-heading t)
8140 (let* ((after-change-functions (remq 'flyspell-after-change-function
8141 after-change-functions))
8142 (level (save-match-data (funcall outline-level)))
8143 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8144 (diff (abs (- level (length up-head) -1))))
8145 (cond
8146 ((and (= level 1) org-allow-promoting-top-level-subtree)
8147 (replace-match "# " nil t))
8148 ((= level 1)
8149 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8150 (t (replace-match up-head nil t)))
8151 (unless (= level 1)
8152 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8153 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8154 (run-hooks 'org-after-promote-entry-hook))))
8156 (defun org-demote ()
8157 "Demote the current heading lower down the tree."
8158 (org-with-wide-buffer
8159 (org-back-to-heading t)
8160 (let* ((after-change-functions (remq 'flyspell-after-change-function
8161 after-change-functions))
8162 (level (save-match-data (funcall outline-level)))
8163 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8164 (diff (abs (- level (length down-head) -1))))
8165 (replace-match down-head nil t)
8166 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8167 (when org-adapt-indentation (org-fixup-indentation diff))
8168 (run-hooks 'org-after-demote-entry-hook))))
8170 (defun org-cycle-level ()
8171 "Cycle the level of an empty headline through possible states.
8172 This goes first to child, then to parent, level, then up the hierarchy.
8173 After top level, it switches back to sibling level."
8174 (interactive)
8175 (let ((org-adapt-indentation nil))
8176 (when (org-point-at-end-of-empty-headline)
8177 (setq this-command 'org-cycle-level) ; Only needed for caching
8178 (let ((cur-level (org-current-level))
8179 (prev-level (org-get-previous-line-level)))
8180 (cond
8181 ;; If first headline in file, promote to top-level.
8182 ((= prev-level 0)
8183 (loop repeat (/ (- cur-level 1) (org-level-increment))
8184 do (org-do-promote)))
8185 ;; If same level as prev, demote one.
8186 ((= prev-level cur-level)
8187 (org-do-demote))
8188 ;; If parent is top-level, promote to top level if not already.
8189 ((= prev-level 1)
8190 (loop repeat (/ (- cur-level 1) (org-level-increment))
8191 do (org-do-promote)))
8192 ;; If top-level, return to prev-level.
8193 ((= cur-level 1)
8194 (loop repeat (/ (- prev-level 1) (org-level-increment))
8195 do (org-do-demote)))
8196 ;; If less than prev-level, promote one.
8197 ((< cur-level prev-level)
8198 (org-do-promote))
8199 ;; If deeper than prev-level, promote until higher than
8200 ;; prev-level.
8201 ((> cur-level prev-level)
8202 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8203 do (org-do-promote))))
8204 t))))
8206 (defun org-map-tree (fun)
8207 "Call FUN for every heading underneath the current one."
8208 (org-back-to-heading)
8209 (let ((level (funcall outline-level)))
8210 (save-excursion
8211 (funcall fun)
8212 (while (and (progn
8213 (outline-next-heading)
8214 (> (funcall outline-level) level))
8215 (not (eobp)))
8216 (funcall fun)))))
8218 (defun org-map-region (fun beg end)
8219 "Call FUN for every heading between BEG and END."
8220 (let ((org-ignore-region t))
8221 (save-excursion
8222 (setq end (copy-marker end))
8223 (goto-char beg)
8224 (if (and (re-search-forward org-outline-regexp-bol nil t)
8225 (< (point) end))
8226 (funcall fun))
8227 (while (and (progn
8228 (outline-next-heading)
8229 (< (point) end))
8230 (not (eobp)))
8231 (funcall fun)))))
8233 (defun org-fixup-indentation (diff)
8234 "Change the indentation in the current entry by DIFF.
8236 DIFF is an integer. Indentation is done according to the
8237 following rules:
8239 - Planning information and property drawers are always indented
8240 according to the new level of the headline;
8242 - Footnote definitions and their contents are ignored;
8244 - Inlinetasks' boundaries are not shifted;
8246 - Empty lines are ignored;
8248 - Other lines' indentation are shifted by DIFF columns, unless
8249 it would introduce a structural change in the document, in
8250 which case no shifting is done at all.
8252 Assume point is at a heading or an inlinetask beginning."
8253 (org-with-wide-buffer
8254 (narrow-to-region (line-beginning-position)
8255 (save-excursion
8256 (if (org-with-limited-levels (org-at-heading-p))
8257 (org-with-limited-levels (outline-next-heading))
8258 (org-inlinetask-goto-end))
8259 (point)))
8260 (forward-line)
8261 ;; Indent properly planning info and property drawer.
8262 (when (org-looking-at-p org-planning-line-re)
8263 (org-indent-line)
8264 (forward-line))
8265 (when (looking-at org-property-drawer-re)
8266 (goto-char (match-end 0))
8267 (forward-line)
8268 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8269 (catch 'no-shift
8270 (when (zerop diff) (throw 'no-shift nil))
8271 ;; If DIFF is negative, first check if a shift is possible at all
8272 ;; (e.g., it doesn't break structure). This can only happen if
8273 ;; some contents are not properly indented.
8274 (let ((case-fold-search t))
8275 (when (< diff 0)
8276 (let ((diff (- diff))
8277 (forbidden-re (concat org-outline-regexp
8278 "\\|"
8279 (substring org-footnote-definition-re 1))))
8280 (save-excursion
8281 (while (not (eobp))
8282 (cond
8283 ((org-looking-at-p "[ \t]*$") (forward-line))
8284 ((and (org-looking-at-p org-footnote-definition-re)
8285 (let ((e (org-element-at-point)))
8286 (and (eq (org-element-type e) 'footnote-definition)
8287 (goto-char (org-element-property :end e))))))
8288 ((org-looking-at-p org-outline-regexp) (forward-line))
8289 ;; Give up if shifting would move before column 0 or
8290 ;; if it would introduce a headline or a footnote
8291 ;; definition.
8293 (skip-chars-forward " \t")
8294 (let ((ind (current-column)))
8295 (when (or (< ind diff)
8296 (and (= ind diff) (org-looking-at-p forbidden-re)))
8297 (throw 'no-shift nil)))
8298 ;; Ignore contents of example blocks and source
8299 ;; blocks if their indentation is meant to be
8300 ;; preserved. Jump to block's closing line.
8301 (beginning-of-line)
8302 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8303 (let ((e (org-element-at-point)))
8304 (and (memq (org-element-type e)
8305 '(example-block src-block))
8306 (or org-src-preserve-indentation
8307 (org-element-property :preserve-indent e))
8308 (goto-char (org-element-property :end e))
8309 (progn (skip-chars-backward " \r\t\n")
8310 (beginning-of-line)
8311 t))))
8312 (forward-line))))))))
8313 ;; Shift lines but footnote definitions, inlinetasks boundaries
8314 ;; by DIFF. Also skip contents of source or example blocks
8315 ;; when indentation is meant to be preserved.
8316 (while (not (eobp))
8317 (cond
8318 ((and (org-looking-at-p org-footnote-definition-re)
8319 (let ((e (org-element-at-point)))
8320 (and (eq (org-element-type e) 'footnote-definition)
8321 (goto-char (org-element-property :end e))))))
8322 ((org-looking-at-p org-outline-regexp) (forward-line))
8323 ((org-looking-at-p "[ \t]*$") (forward-line))
8325 (org-indent-line-to (+ (org-get-indentation) diff))
8326 (beginning-of-line)
8327 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8328 (let ((e (org-element-at-point)))
8329 (and (memq (org-element-type e)
8330 '(example-block src-block))
8331 (or org-src-preserve-indentation
8332 (org-element-property :preserve-indent e))
8333 (goto-char (org-element-property :end e))
8334 (progn (skip-chars-backward " \r\t\n")
8335 (beginning-of-line)
8336 t))))
8337 (forward-line)))))))))
8339 (defun org-convert-to-odd-levels ()
8340 "Convert an org-mode file with all levels allowed to one with odd levels.
8341 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8342 level 5 etc."
8343 (interactive)
8344 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8345 (let ((outline-level 'org-outline-level)
8346 (org-odd-levels-only nil) n)
8347 (save-excursion
8348 (goto-char (point-min))
8349 (while (re-search-forward "^\\*\\*+ " nil t)
8350 (setq n (- (length (match-string 0)) 2))
8351 (while (>= (setq n (1- n)) 0)
8352 (org-demote))
8353 (end-of-line 1))))))
8355 (defun org-convert-to-oddeven-levels ()
8356 "Convert an org-mode file with only odd levels to one with odd/even levels.
8357 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8358 file contains a section with an even level, conversion would
8359 destroy the structure of the file. An error is signaled in this
8360 case."
8361 (interactive)
8362 (goto-char (point-min))
8363 ;; First check if there are no even levels
8364 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8365 (org-show-context t)
8366 (error "Not all levels are odd in this file. Conversion not possible"))
8367 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8368 (let ((outline-regexp org-outline-regexp)
8369 (outline-level 'org-outline-level)
8370 (org-odd-levels-only nil) n)
8371 (save-excursion
8372 (goto-char (point-min))
8373 (while (re-search-forward "^\\*\\*+ " nil t)
8374 (setq n (/ (1- (length (match-string 0))) 2))
8375 (while (>= (setq n (1- n)) 0)
8376 (org-promote))
8377 (end-of-line 1))))))
8379 (defun org-tr-level (n)
8380 "Make N odd if required."
8381 (if org-odd-levels-only (1+ (/ n 2)) n))
8383 ;;; Vertical tree motion, cutting and pasting of subtrees
8385 (defun org-move-subtree-up (&optional arg)
8386 "Move the current subtree up past ARG headlines of the same level."
8387 (interactive "p")
8388 (org-move-subtree-down (- (prefix-numeric-value arg))))
8390 (defun org-move-subtree-down (&optional arg)
8391 "Move the current subtree down past ARG headlines of the same level."
8392 (interactive "p")
8393 (setq arg (prefix-numeric-value arg))
8394 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8395 'org-get-last-sibling))
8396 (ins-point (make-marker))
8397 (cnt (abs arg))
8398 (col (current-column))
8399 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8400 ;; Select the tree
8401 (org-back-to-heading)
8402 (setq beg0 (point))
8403 (save-excursion
8404 (setq ne-beg (org-back-over-empty-lines))
8405 (setq beg (point)))
8406 (save-match-data
8407 (save-excursion (outline-end-of-heading)
8408 (setq folded (outline-invisible-p)))
8409 (progn (org-end-of-subtree nil t)
8410 (unless (eobp) (backward-char))))
8411 (outline-next-heading)
8412 (setq ne-end (org-back-over-empty-lines))
8413 (setq end (point))
8414 (goto-char beg0)
8415 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8416 ;; include less whitespace
8417 (save-excursion
8418 (goto-char beg)
8419 (forward-line (- ne-beg ne-end))
8420 (setq beg (point))))
8421 ;; Find insertion point, with error handling
8422 (while (> cnt 0)
8423 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8424 (progn (goto-char beg0)
8425 (user-error "Cannot move past superior level or buffer limit")))
8426 (setq cnt (1- cnt)))
8427 (if (> arg 0)
8428 ;; Moving forward - still need to move over subtree
8429 (progn (org-end-of-subtree t t)
8430 (save-excursion
8431 (org-back-over-empty-lines)
8432 (or (bolp) (newline)))))
8433 (setq ne-ins (org-back-over-empty-lines))
8434 (move-marker ins-point (point))
8435 (setq txt (buffer-substring beg end))
8436 (org-save-markers-in-region beg end)
8437 (delete-region beg end)
8438 (org-remove-empty-overlays-at beg)
8439 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8440 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8441 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8442 (let ((bbb (point)))
8443 (insert-before-markers txt)
8444 (org-reinstall-markers-in-region bbb)
8445 (move-marker ins-point bbb))
8446 (or (bolp) (insert "\n"))
8447 (setq ins-end (point))
8448 (goto-char ins-point)
8449 (org-skip-whitespace)
8450 (when (and (< arg 0)
8451 (org-first-sibling-p)
8452 (> ne-ins ne-beg))
8453 ;; Move whitespace back to beginning
8454 (save-excursion
8455 (goto-char ins-end)
8456 (let ((kill-whole-line t))
8457 (kill-line (- ne-ins ne-beg)) (point)))
8458 (insert (make-string (- ne-ins ne-beg) ?\n)))
8459 (move-marker ins-point nil)
8460 (if folded
8461 (hide-subtree)
8462 (org-show-entry)
8463 (show-children)
8464 (org-cycle-hide-drawers 'children))
8465 (org-clean-visibility-after-subtree-move)
8466 ;; move back to the initial column we were at
8467 (move-to-column col)))
8469 (defvar org-subtree-clip ""
8470 "Clipboard for cut and paste of subtrees.
8471 This is actually only a copy of the kill, because we use the normal kill
8472 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8474 (defvar org-subtree-clip-folded nil
8475 "Was the last copied subtree folded?
8476 This is used to fold the tree back after pasting.")
8478 (defun org-cut-subtree (&optional n)
8479 "Cut the current subtree into the clipboard.
8480 With prefix arg N, cut this many sequential subtrees.
8481 This is a short-hand for marking the subtree and then cutting it."
8482 (interactive "p")
8483 (org-copy-subtree n 'cut))
8485 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8486 "Copy the current subtree it in the clipboard.
8487 With prefix arg N, copy this many sequential subtrees.
8488 This is a short-hand for marking the subtree and then copying it.
8489 If CUT is non-nil, actually cut the subtree.
8490 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8491 of some markers in the region, even if CUT is non-nil. This is
8492 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8493 (interactive "p")
8494 (let (beg end folded (beg0 (point)))
8495 (if (org-called-interactively-p 'any)
8496 (org-back-to-heading nil) ; take what looks like a subtree
8497 (org-back-to-heading t)) ; take what is really there
8498 (setq beg (point))
8499 (skip-chars-forward " \t\r\n")
8500 (save-match-data
8501 (if nosubtrees
8502 (outline-next-heading)
8503 (save-excursion (outline-end-of-heading)
8504 (setq folded (outline-invisible-p)))
8505 (ignore-errors (org-forward-heading-same-level (1- n) t))
8506 (org-end-of-subtree t t)))
8507 (setq end (point))
8508 (goto-char beg0)
8509 (when (> end beg)
8510 (setq org-subtree-clip-folded folded)
8511 (when (or cut force-store-markers)
8512 (org-save-markers-in-region beg end))
8513 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8514 (setq org-subtree-clip (current-kill 0))
8515 (message "%s: Subtree(s) with %d characters"
8516 (if cut "Cut" "Copied")
8517 (length org-subtree-clip)))))
8519 (defun org-paste-subtree (&optional level tree for-yank remove)
8520 "Paste the clipboard as a subtree, with modification of headline level.
8521 The entire subtree is promoted or demoted in order to match a new headline
8522 level.
8524 If the cursor is at the beginning of a headline, the same level as
8525 that headline is used to paste the tree.
8527 If not, the new level is derived from the *visible* headings
8528 before and after the insertion point, and taken to be the inferior headline
8529 level of the two. So if the previous visible heading is level 3 and the
8530 next is level 4 (or vice versa), level 4 will be used for insertion.
8531 This makes sure that the subtree remains an independent subtree and does
8532 not swallow low level entries.
8534 You can also force a different level, either by using a numeric prefix
8535 argument, or by inserting the heading marker by hand. For example, if the
8536 cursor is after \"*****\", then the tree will be shifted to level 5.
8538 If optional TREE is given, use this text instead of the kill ring.
8540 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8541 move back over whitespace before inserting, and move point to the end of
8542 the inserted text when done.
8544 When REMOVE is non-nil, remove the subtree from the clipboard."
8545 (interactive "P")
8546 (setq tree (or tree (and kill-ring (current-kill 0))))
8547 (unless (org-kill-is-subtree-p tree)
8548 (user-error "%s"
8549 (substitute-command-keys
8550 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8551 (org-with-limited-levels
8552 (let* ((visp (not (outline-invisible-p)))
8553 (txt tree)
8554 (^re_ "\\(\\*+\\)[ \t]*")
8555 (old-level (if (string-match org-outline-regexp-bol txt)
8556 (- (match-end 0) (match-beginning 0) 1)
8557 -1))
8558 (force-level (cond (level (prefix-numeric-value level))
8559 ((and (looking-at "[ \t]*$")
8560 (string-match
8561 "^\\*+$" (buffer-substring
8562 (point-at-bol) (point))))
8563 (- (match-end 0) (match-beginning 0)))
8564 ((and (bolp)
8565 (looking-at org-outline-regexp))
8566 (- (match-end 0) (point) 1))))
8567 (previous-level (save-excursion
8568 (condition-case nil
8569 (progn
8570 (outline-previous-visible-heading 1)
8571 (if (looking-at ^re_)
8572 (- (match-end 0) (match-beginning 0) 1)
8574 (error 1))))
8575 (next-level (save-excursion
8576 (condition-case nil
8577 (progn
8578 (or (looking-at org-outline-regexp)
8579 (outline-next-visible-heading 1))
8580 (if (looking-at ^re_)
8581 (- (match-end 0) (match-beginning 0) 1)
8583 (error 1))))
8584 (new-level (or force-level (max previous-level next-level)))
8585 (shift (if (or (= old-level -1)
8586 (= new-level -1)
8587 (= old-level new-level))
8589 (- new-level old-level)))
8590 (delta (if (> shift 0) -1 1))
8591 (func (if (> shift 0) 'org-demote 'org-promote))
8592 (org-odd-levels-only nil)
8593 beg end newend)
8594 ;; Remove the forced level indicator
8595 (if force-level
8596 (delete-region (point-at-bol) (point)))
8597 ;; Paste
8598 (beginning-of-line (if (bolp) 1 2))
8599 (setq beg (point))
8600 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8601 (insert-before-markers txt)
8602 (unless (string-match "\n\\'" txt) (insert "\n"))
8603 (setq newend (point))
8604 (org-reinstall-markers-in-region beg)
8605 (setq end (point))
8606 (goto-char beg)
8607 (skip-chars-forward " \t\n\r")
8608 (setq beg (point))
8609 (if (and (outline-invisible-p) visp)
8610 (save-excursion (outline-show-heading)))
8611 ;; Shift if necessary
8612 (unless (= shift 0)
8613 (save-restriction
8614 (narrow-to-region beg end)
8615 (while (not (= shift 0))
8616 (org-map-region func (point-min) (point-max))
8617 (setq shift (+ delta shift)))
8618 (goto-char (point-min))
8619 (setq newend (point-max))))
8620 (when (or (org-called-interactively-p 'interactive) for-yank)
8621 (message "Clipboard pasted as level %d subtree" new-level))
8622 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8623 kill-ring
8624 (eq org-subtree-clip (current-kill 0))
8625 org-subtree-clip-folded)
8626 ;; The tree was folded before it was killed/copied
8627 (hide-subtree))
8628 (and for-yank (goto-char newend))
8629 (and remove (setq kill-ring (cdr kill-ring))))))
8631 (defun org-kill-is-subtree-p (&optional txt)
8632 "Check if the current kill is an outline subtree, or a set of trees.
8633 Returns nil if kill does not start with a headline, or if the first
8634 headline level is not the largest headline level in the tree.
8635 So this will actually accept several entries of equal levels as well,
8636 which is OK for `org-paste-subtree'.
8637 If optional TXT is given, check this string instead of the current kill."
8638 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8639 (re (org-get-limited-outline-regexp))
8640 (^re (concat "^" re))
8641 (start-level (and kill
8642 (string-match
8643 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8644 kill)
8645 (- (match-end 2) (match-beginning 2) 1)))
8646 (start (1+ (or (match-beginning 2) -1))))
8647 (if (not start-level)
8648 (progn
8649 nil) ;; does not even start with a heading
8650 (catch 'exit
8651 (while (setq start (string-match ^re kill (1+ start)))
8652 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8653 (throw 'exit nil)))
8654 t))))
8656 (defvar org-markers-to-move nil
8657 "Markers that should be moved with a cut-and-paste operation.
8658 Those markers are stored together with their positions relative to
8659 the start of the region.")
8661 (defun org-save-markers-in-region (beg end)
8662 "Check markers in region.
8663 If these markers are between BEG and END, record their position relative
8664 to BEG, so that after moving the block of text, we can put the markers back
8665 into place.
8666 This function gets called just before an entry or tree gets cut from the
8667 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8668 called immediately, to move the markers with the entries."
8669 (setq org-markers-to-move nil)
8670 (when (featurep 'org-clock)
8671 (org-clock-save-markers-for-cut-and-paste beg end))
8672 (when (featurep 'org-agenda)
8673 (org-agenda-save-markers-for-cut-and-paste beg end)))
8675 (defun org-check-and-save-marker (marker beg end)
8676 "Check if MARKER is between BEG and END.
8677 If yes, remember the marker and the distance to BEG."
8678 (when (and (marker-buffer marker)
8679 (equal (marker-buffer marker) (current-buffer)))
8680 (if (and (>= marker beg) (< marker end))
8681 (push (cons marker (- marker beg)) org-markers-to-move))))
8683 (defun org-reinstall-markers-in-region (beg)
8684 "Move all remembered markers to their position relative to BEG."
8685 (mapc (lambda (x)
8686 (move-marker (car x) (+ beg (cdr x))))
8687 org-markers-to-move)
8688 (setq org-markers-to-move nil))
8690 (defun org-narrow-to-subtree ()
8691 "Narrow buffer to the current subtree."
8692 (interactive)
8693 (save-excursion
8694 (save-match-data
8695 (org-with-limited-levels
8696 (narrow-to-region
8697 (progn (org-back-to-heading t) (point))
8698 (progn (org-end-of-subtree t t)
8699 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8700 (point)))))))
8702 (defun org-narrow-to-block ()
8703 "Narrow buffer to the current block."
8704 (interactive)
8705 (let* ((case-fold-search t)
8706 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8707 "^[ \t]*#\\+end_.*")))
8708 (if blockp
8709 (narrow-to-region (car blockp) (cdr blockp))
8710 (user-error "Not in a block"))))
8712 (defun org-clone-subtree-with-time-shift (n &optional shift)
8713 "Clone the task (subtree) at point N times.
8714 The clones will be inserted as siblings.
8716 In interactive use, the user will be prompted for the number of
8717 clones to be produced. If the entry has a timestamp, the user
8718 will also be prompted for a time shift, which may be a repeater
8719 as used in time stamps, for example `+3d'. To disable this,
8720 you can call the function with a universal prefix argument.
8722 When a valid repeater is given and the entry contains any time
8723 stamps, the clones will become a sequence in time, with time
8724 stamps in the subtree shifted for each clone produced. If SHIFT
8725 is nil or the empty string, time stamps will be left alone. The
8726 ID property of the original subtree is removed.
8728 If the original subtree did contain time stamps with a repeater,
8729 the following will happen:
8730 - the repeater will be removed in each clone
8731 - an additional clone will be produced, with the current, unshifted
8732 date(s) in the entry.
8733 - the original entry will be placed *after* all the clones, with
8734 repeater intact.
8735 - the start days in the repeater in the original entry will be shifted
8736 to past the last clone.
8737 In this way you can spell out a number of instances of a repeating task,
8738 and still retain the repeater to cover future instances of the task."
8739 (interactive "nNumber of clones to produce: ")
8740 (let ((shift
8741 (or shift
8742 (if (and (not (equal current-prefix-arg '(4)))
8743 (save-excursion
8744 (re-search-forward org-ts-regexp-both
8745 (save-excursion
8746 (org-end-of-subtree t)
8747 (point)) t)))
8748 (read-from-minibuffer
8749 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8750 ""))) ;; No time shift
8751 (n-no-remove -1)
8752 (drawer-re org-drawer-regexp)
8753 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8754 beg end template task idprop
8755 shift-n shift-what doshift nmin nmax)
8756 (if (not (and (integerp n) (> n 0)))
8757 (user-error "Invalid number of replications %s" n))
8758 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8759 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8760 shift)))
8761 (user-error "Invalid shift specification %s" shift))
8762 (when doshift
8763 (setq shift-n (string-to-number (match-string 1 shift))
8764 shift-what (cdr (assoc (match-string 2 shift)
8765 '(("d" . day) ("w" . week)
8766 ("m" . month) ("y" . year))))))
8767 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8768 (setq nmin 1 nmax n)
8769 (org-back-to-heading t)
8770 (setq beg (point))
8771 (setq idprop (org-entry-get nil "ID"))
8772 (org-end-of-subtree t t)
8773 (or (bolp) (insert "\n"))
8774 (setq end (point))
8775 (setq template (buffer-substring beg end))
8776 (when (and doshift
8777 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8778 (delete-region beg end)
8779 (setq end beg)
8780 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8781 (goto-char end)
8782 (loop for n from nmin to nmax do
8783 ;; prepare clone
8784 (with-temp-buffer
8785 (insert template)
8786 (org-mode)
8787 (goto-char (point-min))
8788 (org-show-subtree)
8789 (and idprop (if org-clone-delete-id
8790 (org-entry-delete nil "ID")
8791 (org-id-get-create t)))
8792 (unless (= n 0)
8793 (while (re-search-forward org-clock-re nil t)
8794 (kill-whole-line))
8795 (goto-char (point-min))
8796 (while (re-search-forward drawer-re nil t)
8797 (org-remove-empty-drawer-at (point))))
8798 (goto-char (point-min))
8799 (when doshift
8800 (while (re-search-forward org-ts-regexp-both nil t)
8801 (org-timestamp-change (* n shift-n) shift-what))
8802 (unless (= n n-no-remove)
8803 (goto-char (point-min))
8804 (while (re-search-forward org-ts-regexp nil t)
8805 (save-excursion
8806 (goto-char (match-beginning 0))
8807 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8808 (delete-region (match-beginning 1) (match-end 1)))))))
8809 (setq task (buffer-string)))
8810 (insert task))
8811 (goto-char beg)))
8813 ;;; Outline Sorting
8815 (defun org-sort (with-case)
8816 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8817 Optional argument WITH-CASE means sort case-sensitively."
8818 (interactive "P")
8819 (cond
8820 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8821 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8823 (org-call-with-arg 'org-sort-entries with-case))))
8825 (defun org-sort-remove-invisible (s)
8826 "Remove invisible links from string S."
8827 (remove-text-properties 0 (length s) org-rm-props s)
8828 (while (string-match org-bracket-link-regexp s)
8829 (setq s (replace-match (if (match-end 2)
8830 (match-string 3 s)
8831 (match-string 1 s)) t t s)))
8832 (let ((st (format " %s " s)))
8833 (while (string-match org-emph-re st)
8834 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8835 (setq s (substring st 1 -1)))
8838 (defvar org-priority-regexp) ; defined later in the file
8840 (defvar org-after-sorting-entries-or-items-hook nil
8841 "Hook that is run after a bunch of entries or items have been sorted.
8842 When children are sorted, the cursor is in the parent line when this
8843 hook gets called. When a region or a plain list is sorted, the cursor
8844 will be in the first entry of the sorted region/list.")
8846 (defun org-sort-entries
8847 (&optional with-case sorting-type getkey-func compare-func property)
8848 "Sort entries on a certain level of an outline tree.
8849 If there is an active region, the entries in the region are sorted.
8850 Else, if the cursor is before the first entry, sort the top-level items.
8851 Else, the children of the entry at point are sorted.
8853 Sorting can be alphabetically, numerically, by date/time as given by
8854 a time stamp, by a property, by priority order, or by a custom function.
8856 The command prompts for the sorting type unless it has been given to the
8857 function through the SORTING-TYPE argument, which needs to be a character,
8858 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8859 the precise meaning of each character:
8861 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8862 c By creation time, which is assumed to be the first inactive time stamp
8863 at the beginning of a line.
8864 d By deadline date/time.
8865 k By clocking time.
8866 n Numerically, by converting the beginning of the entry/item to a number.
8867 o By order of TODO keywords.
8868 p By priority according to the cookie.
8869 r By the value of a property.
8870 s By scheduled date/time.
8871 t By date/time, either the first active time stamp in the entry, or, if
8872 none exist, by the first inactive one.
8874 Capital letters will reverse the sort order.
8876 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8877 called with point at the beginning of the record. It must return either
8878 a string or a number that should serve as the sorting key for that record.
8880 Comparing entries ignores case by default. However, with an optional argument
8881 WITH-CASE, the sorting considers case as well.
8883 Sorting is done against the visible part of the headlines, it ignores hidden
8884 links.
8886 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8887 (interactive "P")
8888 (let ((case-func (if with-case 'identity 'downcase))
8889 (cmstr
8890 ;; The clock marker is lost when using `sort-subr', let's
8891 ;; store the clocking string.
8892 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8893 (save-excursion
8894 (goto-char org-clock-marker)
8895 (looking-back "^.*") (match-string-no-properties 0))))
8896 start beg end stars re re2
8897 txt what tmp)
8898 ;; Find beginning and end of region to sort
8899 (cond
8900 ((org-region-active-p)
8901 ;; we will sort the region
8902 (setq end (region-end)
8903 what "region")
8904 (goto-char (region-beginning))
8905 (if (not (org-at-heading-p)) (outline-next-heading))
8906 (setq start (point)))
8907 ((or (org-at-heading-p)
8908 (ignore-errors (progn (org-back-to-heading) t)))
8909 ;; we will sort the children of the current headline
8910 (org-back-to-heading)
8911 (setq start (point)
8912 end (progn (org-end-of-subtree t t)
8913 (or (bolp) (insert "\n"))
8914 (when (>= (org-back-over-empty-lines) 1)
8915 (forward-line 1))
8916 (point))
8917 what "children")
8918 (goto-char start)
8919 (show-subtree)
8920 (outline-next-heading))
8922 ;; we will sort the top-level entries in this file
8923 (goto-char (point-min))
8924 (or (org-at-heading-p) (outline-next-heading))
8925 (setq start (point))
8926 (goto-char (point-max))
8927 (beginning-of-line 1)
8928 (when (looking-at ".*?\\S-")
8929 ;; File ends in a non-white line
8930 (end-of-line 1)
8931 (insert "\n"))
8932 (setq end (point-max))
8933 (setq what "top-level")
8934 (goto-char start)
8935 (show-all)))
8937 (setq beg (point))
8938 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8940 (looking-at "\\(\\*+\\)")
8941 (setq stars (match-string 1)
8942 re (concat "^" (regexp-quote stars) " +")
8943 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8944 txt (buffer-substring beg end))
8945 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8946 (if (and (not (equal stars "*")) (string-match re2 txt))
8947 (user-error "Region to sort contains a level above the first entry"))
8949 (unless sorting-type
8950 (message
8951 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8952 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8953 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8954 what)
8955 (setq sorting-type (read-char-exclusive))
8957 (unless getkey-func
8958 (and (= (downcase sorting-type) ?f)
8959 (setq getkey-func
8960 (org-icompleting-read "Sort using function: "
8961 obarray 'fboundp t nil nil))
8962 (setq getkey-func (intern getkey-func))))
8964 (and (= (downcase sorting-type) ?r)
8965 (not property)
8966 (setq property
8967 (org-icompleting-read "Property: "
8968 (mapcar 'list (org-buffer-property-keys t))
8969 nil t))))
8971 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8972 (message "Sorting entries...")
8974 (save-restriction
8975 (narrow-to-region start end)
8976 (let ((dcst (downcase sorting-type))
8977 (case-fold-search nil)
8978 (now (current-time)))
8979 (sort-subr
8980 (/= dcst sorting-type)
8981 ;; This function moves to the beginning character of the "record" to
8982 ;; be sorted.
8983 (lambda nil
8984 (if (re-search-forward re nil t)
8985 (goto-char (match-beginning 0))
8986 (goto-char (point-max))))
8987 ;; This function moves to the last character of the "record" being
8988 ;; sorted.
8989 (lambda nil
8990 (save-match-data
8991 (condition-case nil
8992 (outline-forward-same-level 1)
8993 (error
8994 (goto-char (point-max))))))
8995 ;; This function returns the value that gets sorted against.
8996 (lambda nil
8997 (cond
8998 ((= dcst ?n)
8999 (if (looking-at org-complex-heading-regexp)
9000 (string-to-number (org-sort-remove-invisible (match-string 4)))
9001 nil))
9002 ((= dcst ?a)
9003 (if (looking-at org-complex-heading-regexp)
9004 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9005 nil))
9006 ((= dcst ?k)
9007 (or (get-text-property (point) :org-clock-minutes) 0))
9008 ((= dcst ?t)
9009 (let ((end (save-excursion (outline-next-heading) (point))))
9010 (if (or (re-search-forward org-ts-regexp end t)
9011 (re-search-forward org-ts-regexp-both end t))
9012 (org-time-string-to-seconds (match-string 0))
9013 (org-float-time now))))
9014 ((= dcst ?c)
9015 (let ((end (save-excursion (outline-next-heading) (point))))
9016 (if (re-search-forward
9017 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9018 end t)
9019 (org-time-string-to-seconds (match-string 0))
9020 (org-float-time now))))
9021 ((= dcst ?s)
9022 (let ((end (save-excursion (outline-next-heading) (point))))
9023 (if (re-search-forward org-scheduled-time-regexp end t)
9024 (org-time-string-to-seconds (match-string 1))
9025 (org-float-time now))))
9026 ((= dcst ?d)
9027 (let ((end (save-excursion (outline-next-heading) (point))))
9028 (if (re-search-forward org-deadline-time-regexp end t)
9029 (org-time-string-to-seconds (match-string 1))
9030 (org-float-time now))))
9031 ((= dcst ?p)
9032 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9033 (string-to-char (match-string 2))
9034 org-default-priority))
9035 ((= dcst ?r)
9036 (or (org-entry-get nil property) ""))
9037 ((= dcst ?o)
9038 (if (looking-at org-complex-heading-regexp)
9039 (let* ((m (match-string 2))
9040 (s (if (member m org-done-keywords) '- '+)))
9041 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9042 ((= dcst ?f)
9043 (if getkey-func
9044 (progn
9045 (setq tmp (funcall getkey-func))
9046 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
9047 tmp)
9048 (error "Invalid key function `%s'" getkey-func)))
9049 (t (error "Invalid sorting type `%c'" sorting-type))))
9051 (cond
9052 ((= dcst ?a) 'string<)
9053 ((= dcst ?f) compare-func)
9054 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9055 (run-hooks 'org-after-sorting-entries-or-items-hook)
9056 ;; Reset the clock marker if needed
9057 (when cmstr
9058 (save-excursion
9059 (goto-char start)
9060 (search-forward cmstr nil t)
9061 (move-marker org-clock-marker (point))))
9062 (message "Sorting entries...done")))
9064 ;;; The orgstruct minor mode
9066 ;; Define a minor mode which can be used in other modes in order to
9067 ;; integrate the org-mode structure editing commands.
9069 ;; This is really a hack, because the org-mode structure commands use
9070 ;; keys which normally belong to the major mode. Here is how it
9071 ;; works: The minor mode defines all the keys necessary to operate the
9072 ;; structure commands, but wraps the commands into a function which
9073 ;; tests if the cursor is currently at a headline or a plain list
9074 ;; item. If that is the case, the structure command is used,
9075 ;; temporarily setting many Org-mode variables like regular
9076 ;; expressions for filling etc. However, when any of those keys is
9077 ;; used at a different location, function uses `key-binding' to look
9078 ;; up if the key has an associated command in another currently active
9079 ;; keymap (minor modes, major mode, global), and executes that
9080 ;; command. There might be problems if any of the keys is otherwise
9081 ;; used as a prefix key.
9083 (defcustom orgstruct-heading-prefix-regexp ""
9084 "Regexp that matches the custom prefix of Org headlines in
9085 orgstruct(++)-mode."
9086 :group 'org
9087 :version "24.4"
9088 :package-version '(Org . "8.3")
9089 :type 'regexp)
9090 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9092 (defcustom orgstruct-setup-hook nil
9093 "Hook run after orgstruct-mode-map is filled."
9094 :group 'org
9095 :version "24.4"
9096 :package-version '(Org . "8.0")
9097 :type 'hook)
9099 (defvar orgstruct-initialized nil)
9101 (defvar org-local-vars nil
9102 "List of local variables, for use by `orgstruct-mode'.")
9104 ;;;###autoload
9105 (define-minor-mode orgstruct-mode
9106 "Toggle the minor mode `orgstruct-mode'.
9107 This mode is for using Org-mode structure commands in other
9108 modes. The following keys behave as if Org-mode were active, if
9109 the cursor is on a headline, or on a plain list item (both as
9110 defined by Org-mode)."
9111 nil " OrgStruct" (make-sparse-keymap)
9112 (funcall (if orgstruct-mode
9113 'add-to-invisibility-spec
9114 'remove-from-invisibility-spec)
9115 '(outline . t))
9116 (when orgstruct-mode
9117 (org-load-modules-maybe)
9118 (unless orgstruct-initialized
9119 (orgstruct-setup)
9120 (setq orgstruct-initialized t))))
9122 ;;;###autoload
9123 (defun turn-on-orgstruct ()
9124 "Unconditionally turn on `orgstruct-mode'."
9125 (orgstruct-mode 1))
9127 (defvar org-fb-vars nil)
9128 (make-variable-buffer-local 'org-fb-vars)
9129 (defun orgstruct++-mode (&optional arg)
9130 "Toggle `orgstruct-mode', the enhanced version of it.
9131 In addition to setting orgstruct-mode, this also exports all
9132 indentation and autofilling variables from org-mode into the
9133 buffer. It will also recognize item context in multiline items."
9134 (interactive "P")
9135 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9136 (if (< arg 1)
9137 (progn (orgstruct-mode -1)
9138 (mapc (lambda(v)
9139 (org-set-local (car v)
9140 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9141 org-fb-vars))
9142 (orgstruct-mode 1)
9143 (setq org-fb-vars nil)
9144 (unless org-local-vars
9145 (setq org-local-vars (org-get-local-variables)))
9146 (let (var val)
9147 (mapc
9148 (lambda (x)
9149 (when (string-match
9150 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9151 (symbol-name (car x)))
9152 (setq var (car x) val (nth 1 x))
9153 (push (list var `(quote ,(eval var))) org-fb-vars)
9154 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9155 org-local-vars)
9156 (org-set-local 'orgstruct-is-++ t))))
9158 (defvar orgstruct-is-++ nil
9159 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9160 (make-variable-buffer-local 'orgstruct-is-++)
9162 ;;;###autoload
9163 (defun turn-on-orgstruct++ ()
9164 "Unconditionally turn on `orgstruct++-mode'."
9165 (orgstruct++-mode 1))
9167 (defun orgstruct-error ()
9168 "Error when there is no default binding for a structure key."
9169 (interactive)
9170 (funcall (if (fboundp 'user-error)
9171 'user-error
9172 'error)
9173 "This key has no function outside structure elements"))
9175 (defun orgstruct-setup ()
9176 "Setup orgstruct keymap."
9177 (dolist (cell '((org-demote . t)
9178 (org-metaleft . t)
9179 (org-metaright . t)
9180 (org-promote . t)
9181 (org-shiftmetaleft . t)
9182 (org-shiftmetaright . t)
9183 org-backward-element
9184 org-backward-heading-same-level
9185 org-ctrl-c-ret
9186 org-ctrl-c-minus
9187 org-ctrl-c-star
9188 org-cycle
9189 org-forward-heading-same-level
9190 org-insert-heading
9191 org-insert-heading-respect-content
9192 org-kill-note-or-show-branches
9193 org-mark-subtree
9194 org-meta-return
9195 org-metadown
9196 org-metaup
9197 org-narrow-to-subtree
9198 org-promote-subtree
9199 org-reveal
9200 org-shiftdown
9201 org-shiftleft
9202 org-shiftmetadown
9203 org-shiftmetaup
9204 org-shiftright
9205 org-shifttab
9206 org-shifttab
9207 org-shiftup
9208 org-show-subtree
9209 org-sort
9210 org-up-element
9211 outline-demote
9212 outline-next-visible-heading
9213 outline-previous-visible-heading
9214 outline-promote
9215 outline-up-heading
9216 show-children))
9217 (let ((f (or (car-safe cell) cell))
9218 (disable-when-heading-prefix (cdr-safe cell)))
9219 (when (fboundp f)
9220 (let ((new-bindings))
9221 (dolist (binding (nconc (where-is-internal f org-mode-map)
9222 (where-is-internal f outline-mode-map)))
9223 (push binding new-bindings)
9224 ;; TODO use local-function-key-map
9225 (dolist (rep '(("<tab>" . "TAB")
9226 ("<return>" . "RET")
9227 ("<escape>" . "ESC")
9228 ("<delete>" . "DEL")))
9229 (setq binding (read-kbd-macro
9230 (let ((case-fold-search))
9231 (replace-regexp-in-string
9232 (regexp-quote (cdr rep))
9233 (car rep)
9234 (key-description binding)))))
9235 (pushnew binding new-bindings :test 'equal)))
9236 (dolist (binding new-bindings)
9237 (let ((key (lookup-key orgstruct-mode-map binding)))
9238 (when (or (not key) (numberp key))
9239 (ignore-errors
9240 (org-defkey orgstruct-mode-map
9241 binding
9242 (orgstruct-make-binding
9243 f binding disable-when-heading-prefix))))))))))
9244 (run-hooks 'orgstruct-setup-hook))
9246 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9247 "Create a function for binding in the structure minor mode.
9248 FUN is the command to call inside a table. KEY is the key that
9249 should be checked in for a command to execute outside of tables.
9250 Non-nil `disable-when-heading-prefix' means to disable the command
9251 if `orgstruct-heading-prefix-regexp' is not empty."
9252 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9253 (let ((nname name)
9254 (i 0))
9255 (while (fboundp (intern nname))
9256 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9257 (setq name (intern nname)))
9258 (eval
9259 (let ((bindings '((org-heading-regexp
9260 (concat "^"
9261 orgstruct-heading-prefix-regexp
9262 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9263 (org-outline-regexp
9264 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9265 (org-outline-regexp-bol
9266 (concat "^" org-outline-regexp))
9267 (outline-regexp org-outline-regexp)
9268 (outline-heading-end-regexp "\n")
9269 (outline-level 'org-outline-level)
9270 (outline-heading-alist))))
9271 `(defun ,name (arg)
9272 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9273 "Outside of structure, run the binding of `"
9274 (key-description key) "'."
9275 (when disable-when-heading-prefix
9276 (concat
9277 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9278 "back to the default binding due to limitations of Org's implementation of\n"
9279 "`" (symbol-name fun) "'.")))
9280 (interactive "p")
9281 (let* ((disable
9282 ,(and disable-when-heading-prefix
9283 '(not (string= orgstruct-heading-prefix-regexp ""))))
9284 (fallback
9285 (or disable
9286 (not
9287 (let* ,bindings
9288 (org-context-p 'headline 'item
9289 ,(when (memq fun
9290 '(org-insert-heading
9291 org-insert-heading-respect-content
9292 org-meta-return))
9293 '(when orgstruct-is-++
9294 'item-body))))))))
9295 (if fallback
9296 (let* ((orgstruct-mode)
9297 (binding
9298 (let ((key ,key))
9299 (catch 'exit
9300 (dolist
9301 (rep
9302 '(nil
9303 ("<\\([^>]*\\)tab>" . "\\1TAB")
9304 ("<\\([^>]*\\)return>" . "\\1RET")
9305 ("<\\([^>]*\\)escape>" . "\\1ESC")
9306 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9307 nil)
9308 (when rep
9309 (setq key (read-kbd-macro
9310 (let ((case-fold-search))
9311 (replace-regexp-in-string
9312 (car rep)
9313 (cdr rep)
9314 (key-description key))))))
9315 (when (key-binding key)
9316 (throw 'exit (key-binding key))))))))
9317 (if (keymapp binding)
9318 (org-set-transient-map binding)
9319 (let ((func (or binding
9320 (unless disable
9321 'orgstruct-error))))
9322 (when func
9323 (call-interactively func)))))
9324 (org-run-like-in-org-mode
9325 (lambda ()
9326 (interactive)
9327 (let* ,bindings
9328 (call-interactively ',fun)))))))))
9329 name))
9331 (defun org-contextualize-keys (alist contexts)
9332 "Return valid elements in ALIST depending on CONTEXTS.
9334 `org-agenda-custom-commands' or `org-capture-templates' are the
9335 values used for ALIST, and `org-agenda-custom-commands-contexts'
9336 or `org-capture-templates-contexts' are the associated contexts
9337 definitions."
9338 (let ((contexts
9339 ;; normalize contexts
9340 (mapcar
9341 (lambda(c) (cond ((listp (cadr c))
9342 (list (car c) (car c) (cadr c)))
9343 ((string= "" (cadr c))
9344 (list (car c) (car c) (caddr c)))
9345 (t c))) contexts))
9346 (a alist) c r s)
9347 ;; loop over all commands or templates
9348 (while (setq c (pop a))
9349 (let (vrules repl)
9350 (cond
9351 ((not (assoc (car c) contexts))
9352 (push c r))
9353 ((and (assoc (car c) contexts)
9354 (setq vrules (org-contextualize-validate-key
9355 (car c) contexts)))
9356 (mapc (lambda (vr)
9357 (when (not (equal (car vr) (cadr vr)))
9358 (setq repl vr))) vrules)
9359 (if (not repl) (push c r)
9360 (push (cadr repl) s)
9361 (push
9362 (cons (car c)
9363 (cdr (or (assoc (cadr repl) alist)
9364 (error "Undefined key `%s' as contextual replacement for `%s'"
9365 (cadr repl) (car c)))))
9366 r))))))
9367 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9368 (delq
9370 (delete-dups
9371 (mapcar (lambda (x)
9372 (let ((tpl (car x)))
9373 (when (not (delq
9375 (mapcar (lambda(y)
9376 (equal y tpl)) s))) x)))
9377 (reverse r))))))
9379 (defun org-contextualize-validate-key (key contexts)
9380 "Check CONTEXTS for agenda or capture KEY."
9381 (let (r rr res)
9382 (while (setq r (pop contexts))
9383 (mapc
9384 (lambda (rr)
9385 (when
9386 (and (equal key (car r))
9387 (if (functionp rr) (funcall rr)
9388 (or (and (eq (car rr) 'in-file)
9389 (buffer-file-name)
9390 (string-match (cdr rr) (buffer-file-name)))
9391 (and (eq (car rr) 'in-mode)
9392 (string-match (cdr rr) (symbol-name major-mode)))
9393 (and (eq (car rr) 'in-buffer)
9394 (string-match (cdr rr) (buffer-name)))
9395 (when (and (eq (car rr) 'not-in-file)
9396 (buffer-file-name))
9397 (not (string-match (cdr rr) (buffer-file-name))))
9398 (when (eq (car rr) 'not-in-mode)
9399 (not (string-match (cdr rr) (symbol-name major-mode))))
9400 (when (eq (car rr) 'not-in-buffer)
9401 (not (string-match (cdr rr) (buffer-name)))))))
9402 (push r res)))
9403 (car (last r))))
9404 (delete-dups (delq nil res))))
9406 (defun org-context-p (&rest contexts)
9407 "Check if local context is any of CONTEXTS.
9408 Possible values in the list of contexts are `table', `headline', and `item'."
9409 (let ((pos (point)))
9410 (goto-char (point-at-bol))
9411 (prog1 (or (and (memq 'table contexts)
9412 (looking-at "[ \t]*|"))
9413 (and (memq 'headline contexts)
9414 (looking-at org-outline-regexp))
9415 (and (memq 'item contexts)
9416 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9417 (and (memq 'item-body contexts)
9418 (org-in-item-p)))
9419 (goto-char pos))))
9421 (defun org-get-local-variables ()
9422 "Return a list of all local variables in an Org mode buffer."
9423 (let (varlist)
9424 (with-current-buffer (get-buffer-create "*Org tmp*")
9425 (erase-buffer)
9426 (org-mode)
9427 (setq varlist (buffer-local-variables)))
9428 (kill-buffer "*Org tmp*")
9429 (delq nil
9430 (mapcar
9431 (lambda (x)
9432 (setq x
9433 (if (symbolp x)
9434 (list x)
9435 (list (car x) (cdr x))))
9436 (if (and (not (get (car x) 'org-state))
9437 (string-match
9438 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9439 (symbol-name (car x))))
9440 x nil))
9441 varlist))))
9443 (defun org-clone-local-variables (from-buffer &optional regexp)
9444 "Clone local variables from FROM-BUFFER.
9445 Optional argument REGEXP selects variables to clone."
9446 (mapc
9447 (lambda (pair)
9448 (and (symbolp (car pair))
9449 (or (null regexp)
9450 (string-match regexp (symbol-name (car pair))))
9451 (set (make-local-variable (car pair))
9452 (cdr pair))))
9453 (buffer-local-variables from-buffer)))
9455 ;;;###autoload
9456 (defun org-run-like-in-org-mode (cmd)
9457 "Run a command, pretending that the current buffer is in Org-mode.
9458 This will temporarily bind local variables that are typically bound in
9459 Org-mode to the values they have in Org-mode, and then interactively
9460 call CMD."
9461 (org-load-modules-maybe)
9462 (unless org-local-vars
9463 (setq org-local-vars (org-get-local-variables)))
9464 (let (binds)
9465 (dolist (var org-local-vars)
9466 (when (or (not (boundp (car var)))
9467 (eq (symbol-value (car var))
9468 (default-value (car var))))
9469 (push (list (car var) `(quote ,(cadr var))) binds)))
9470 (eval `(let ,binds
9471 (call-interactively (quote ,cmd))))))
9473 (defun org-get-category (&optional pos force-refresh)
9474 "Get the category applying to position POS."
9475 (save-match-data
9476 (if force-refresh (org-refresh-category-properties))
9477 (let ((pos (or pos (point))))
9478 (or (get-text-property pos 'org-category)
9479 (progn (org-refresh-category-properties)
9480 (get-text-property pos 'org-category))))))
9482 ;;; Refresh properties
9484 (defun org-refresh-properties (dprop tprop)
9485 "Refresh buffer text properties.
9486 DPROP is the drawer property and TPROP is either the
9487 corresponding text property to set, or an alist with each element
9488 being a text property (as a symbol) and a function to apply to
9489 the value of the drawer property."
9490 (let ((case-fold-search t)
9491 (inhibit-read-only t))
9492 (org-with-silent-modifications
9493 (save-excursion
9494 (save-restriction
9495 (widen)
9496 (goto-char (point-min))
9497 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9498 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9500 (defun org-refresh-property (tprop p)
9501 "Refresh the buffer text property TPROP from the drawer property P.
9502 The refresh happens only for the current tree (not subtree)."
9503 (save-excursion
9504 (org-back-to-heading t)
9505 ;; tprop is a text property symbol
9506 (if (symbolp tprop)
9507 (put-text-property
9508 (point) (or (outline-next-heading) (point-max)) tprop p)
9509 ;; tprop is an alist with (properties . function) elements
9510 (mapc (lambda(al)
9511 (save-excursion
9512 (put-text-property
9513 (point-at-bol) (or (outline-next-heading) (point-max))
9514 (car al)
9515 (funcall (cdr al) p))))
9516 tprop))))
9518 (defun org-refresh-category-properties ()
9519 "Refresh category text properties in the buffer."
9520 (let ((case-fold-search t)
9521 (inhibit-read-only t)
9522 (def-cat (cond
9523 ((null org-category)
9524 (if buffer-file-name
9525 (file-name-sans-extension
9526 (file-name-nondirectory buffer-file-name))
9527 "???"))
9528 ((symbolp org-category) (symbol-name org-category))
9529 (t org-category)))
9530 beg end cat pos optionp)
9531 (org-with-silent-modifications
9532 (save-excursion
9533 (save-restriction
9534 (widen)
9535 (goto-char (point-min))
9536 (put-text-property (point) (point-max) 'org-category def-cat)
9537 (while (re-search-forward
9538 "^[ \t]*\\(\\(?:#\\+\\|:\\)CATEGORY:\\)\\(.*\\)" nil t)
9539 (setq pos (match-end 0)
9540 optionp (equal (char-after (match-beginning 0)) ?#)
9541 cat (org-trim (match-string 2)))
9542 (if optionp
9543 (setq beg (point-at-bol) end (point-max))
9544 (org-back-to-heading t)
9545 (setq beg (point) end (org-end-of-subtree t t)))
9546 (put-text-property beg end 'org-category cat)
9547 (goto-char pos)))))))
9549 (defun org-refresh-stats-properties ()
9550 "Refresh stats text properties in the buffer."
9551 (let (stats)
9552 (org-with-silent-modifications
9553 (save-excursion
9554 (save-restriction
9555 (widen)
9556 (goto-char (point-min))
9557 (while (re-search-forward
9558 (concat org-outline-regexp-bol ".*"
9559 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9560 nil t)
9561 (setq stats (cond ((equal (match-string 3) "0") 0)
9562 ((match-string 2)
9563 (/ (* (string-to-number (match-string 2)) 100)
9564 (string-to-number (match-string 3))))
9565 (t (string-to-number (match-string 1)))))
9566 (org-back-to-heading t)
9567 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9568 'org-stats stats)))))))
9570 (defun org-refresh-effort-properties ()
9571 "Refresh effort properties"
9572 (org-refresh-properties
9573 org-effort-property
9574 '((effort . identity)
9575 (effort-minutes . org-duration-string-to-minutes))))
9577 ;;;; Link Stuff
9579 ;;; Link abbreviations
9581 (defun org-link-expand-abbrev (link)
9582 "Apply replacements as defined in `org-link-abbrev-alist'."
9583 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9584 (let* ((key (match-string 1 link))
9585 (as (or (assoc key org-link-abbrev-alist-local)
9586 (assoc key org-link-abbrev-alist)))
9587 (tag (and (match-end 2) (match-string 3 link)))
9588 rpl)
9589 (if (not as)
9590 link
9591 (setq rpl (cdr as))
9592 (cond
9593 ((symbolp rpl) (funcall rpl tag))
9594 ((string-match "%(\\([^)]+\\))" rpl)
9595 (replace-match
9596 (save-match-data
9597 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9598 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9599 ((string-match "%h" rpl)
9600 (replace-match (url-hexify-string (or tag "")) t t rpl))
9601 (t (concat rpl tag)))))
9602 link))
9604 ;;; Storing and inserting links
9606 (defvar org-insert-link-history nil
9607 "Minibuffer history for links inserted with `org-insert-link'.")
9609 (defvar org-stored-links nil
9610 "Contains the links stored with `org-store-link'.")
9612 (defvar org-store-link-plist nil
9613 "Plist with info about the most recently link created with `org-store-link'.")
9615 (defvar org-link-protocols nil
9616 "Link protocols added to Org-mode using `org-add-link-type'.")
9618 (defvar org-store-link-functions nil
9619 "List of functions that are called to create and store a link.
9620 Each function will be called in turn until one returns a non-nil
9621 value. Each function should check if it is responsible for creating
9622 this link (for example by looking at the major mode).
9623 If not, it must exit and return nil.
9624 If yes, it should return a non-nil value after a calling
9625 `org-store-link-props' with a list of properties and values.
9626 Special properties are:
9628 :type The link prefix, like \"http\". This must be given.
9629 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9630 This is obligatory as well.
9631 :description Optional default description for the second pair
9632 of brackets in an Org-mode link. The user can still change
9633 this when inserting this link into an Org-mode buffer.
9635 In addition to these, any additional properties can be specified
9636 and then used in capture templates.")
9638 (defun org-add-link-type (type &optional follow export)
9639 "Add TYPE to the list of `org-link-types'.
9640 Re-compute all regular expressions depending on `org-link-types'
9642 FOLLOW and EXPORT are two functions.
9644 FOLLOW should take the link path as the single argument and do whatever
9645 is necessary to follow the link, for example find a file or display
9646 a mail message.
9648 EXPORT should format the link path for export to one of the export formats.
9649 It should be a function accepting three arguments:
9651 path the path of the link, the text after the prefix (like \"http:\")
9652 desc the description of the link, if any
9653 format the export format, a symbol like `html' or `latex' or `ascii'.
9655 The function may use the FORMAT information to return different values
9656 depending on the format. The return value will be put literally into
9657 the exported file. If the return value is nil, this means Org should
9658 do what it normally does with links which do not have EXPORT defined.
9660 Org mode has a built-in default for exporting links. If you are happy with
9661 this default, there is no need to define an export function for the link
9662 type. For a simple example of an export function, see `org-bbdb.el'."
9663 (add-to-list 'org-link-types type t)
9664 (org-make-link-regexps)
9665 (org-element-update-syntax)
9666 (if (assoc type org-link-protocols)
9667 (setcdr (assoc type org-link-protocols) (list follow export))
9668 (push (list type follow export) org-link-protocols)))
9670 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9671 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9673 ;;;###autoload
9674 (defun org-store-link (arg)
9675 "\\<org-mode-map>Store an org-link to the current location.
9676 This link is added to `org-stored-links' and can later be inserted
9677 into an org-buffer with \\[org-insert-link].
9679 For some link types, a prefix arg is interpreted.
9680 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9681 For file links, arg negates `org-context-in-file-links'.
9683 A double prefix arg force skipping storing functions that are not
9684 part of Org's core.
9686 A triple prefix arg force storing a link for each line in the
9687 active region."
9688 (interactive "P")
9689 (org-load-modules-maybe)
9690 (if (and (equal arg '(64)) (org-region-active-p))
9691 (save-excursion
9692 (let ((end (region-end)))
9693 (goto-char (region-beginning))
9694 (set-mark (point))
9695 (while (< (point-at-eol) end)
9696 (move-end-of-line 1) (activate-mark)
9697 (let (current-prefix-arg)
9698 (call-interactively 'org-store-link))
9699 (move-beginning-of-line 2)
9700 (set-mark (point)))))
9701 (org-with-limited-levels
9702 (setq org-store-link-plist nil)
9703 (let (link cpltxt desc description search
9704 txt custom-id agenda-link sfuns sfunsn)
9705 (cond
9707 ;; Store a link using an external link type
9708 ((and (not (equal arg '(16)))
9709 (setq sfuns
9710 (delq
9711 nil (mapcar (lambda (f)
9712 (let (fs) (if (funcall f) (push f fs))))
9713 org-store-link-functions))
9714 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9715 (or (and (cdr sfuns)
9716 (funcall (intern
9717 (completing-read
9718 "Which function for creating the link? "
9719 sfunsn nil t (car sfunsn)))))
9720 (funcall (caar sfuns)))
9721 (setq link (plist-get org-store-link-plist :link)
9722 desc (or (plist-get org-store-link-plist
9723 :description) link))))
9725 ;; Store a link from a source code buffer
9726 ((org-src-edit-buffer-p)
9727 (let (label gc)
9728 (while (or (not label)
9729 (save-excursion
9730 (save-restriction
9731 (widen)
9732 (goto-char (point-min))
9733 (re-search-forward
9734 (regexp-quote (format org-coderef-label-format label))
9735 nil t))))
9736 (when label (message "Label exists already") (sit-for 2))
9737 (setq label (read-string "Code line label: " label)))
9738 (end-of-line 1)
9739 (setq link (format org-coderef-label-format label))
9740 (setq gc (- 79 (length link)))
9741 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9742 (insert link)
9743 (setq link (concat "(" label ")") desc nil)))
9745 ;; We are in the agenda, link to referenced location
9746 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9747 (let ((m (or (get-text-property (point) 'org-hd-marker)
9748 (get-text-property (point) 'org-marker))))
9749 (when m
9750 (org-with-point-at m
9751 (setq agenda-link
9752 (if (org-called-interactively-p 'any)
9753 (call-interactively 'org-store-link)
9754 (org-store-link nil)))))))
9756 ((eq major-mode 'calendar-mode)
9757 (let ((cd (calendar-cursor-to-date)))
9758 (setq link
9759 (format-time-string
9760 (car org-time-stamp-formats)
9761 (apply 'encode-time
9762 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9763 nil nil nil))))
9764 (org-store-link-props :type "calendar" :date cd)))
9766 ((eq major-mode 'help-mode)
9767 (setq link (concat "help:" (save-excursion
9768 (goto-char (point-min))
9769 (looking-at "^[^ ]+")
9770 (match-string 0))))
9771 (org-store-link-props :type "help"))
9773 ((eq major-mode 'w3-mode)
9774 (setq cpltxt (if (and (buffer-name)
9775 (not (string-match "Untitled" (buffer-name))))
9776 (buffer-name)
9777 (url-view-url t))
9778 link (url-view-url t))
9779 (org-store-link-props :type "w3" :url (url-view-url t)))
9781 ((eq major-mode 'image-mode)
9782 (setq cpltxt (concat "file:"
9783 (abbreviate-file-name buffer-file-name))
9784 link cpltxt)
9785 (org-store-link-props :type "image" :file buffer-file-name))
9787 ;; In dired, store a link to the file of the current line
9788 ((derived-mode-p 'dired-mode)
9789 (let ((file (dired-get-filename nil t)))
9790 (setq file (if file
9791 (abbreviate-file-name
9792 (expand-file-name (dired-get-filename nil t)))
9793 ;; otherwise, no file so use current directory.
9794 default-directory))
9795 (setq cpltxt (concat "file:" file)
9796 link cpltxt)))
9798 ((setq search (run-hook-with-args-until-success
9799 'org-create-file-search-functions))
9800 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9801 "::" search))
9802 (setq cpltxt (or description link)))
9804 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9805 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9806 (cond
9807 ;; Store a link using the target at point
9808 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9809 (setq cpltxt
9810 (concat "file:"
9811 (abbreviate-file-name
9812 (buffer-file-name (buffer-base-buffer)))
9813 "::" (match-string 1))
9814 link cpltxt))
9815 ((and (featurep 'org-id)
9816 (or (eq org-id-link-to-org-use-id t)
9817 (and (org-called-interactively-p 'any)
9818 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9819 (and (eq org-id-link-to-org-use-id
9820 'create-if-interactive-and-no-custom-id)
9821 (not custom-id))))
9822 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9823 ;; Store a link using the ID at point
9824 (setq link (condition-case nil
9825 (prog1 (org-id-store-link)
9826 (setq desc (or (plist-get org-store-link-plist
9827 :description)
9828 "")))
9829 (error
9830 ;; Probably before first headline, link only to file
9831 (concat "file:"
9832 (abbreviate-file-name
9833 (buffer-file-name (buffer-base-buffer))))))))
9835 ;; Just link to current headline
9836 (setq cpltxt (concat "file:"
9837 (abbreviate-file-name
9838 (buffer-file-name (buffer-base-buffer)))))
9839 ;; Add a context search string
9840 (when (org-xor org-context-in-file-links arg)
9841 (let* ((ee (org-element-at-point))
9842 (et (org-element-type ee))
9843 (ev (plist-get (cadr ee) :value))
9844 (ek (plist-get (cadr ee) :key))
9845 (eok (and (stringp ek) (string-match "name" ek))))
9846 (setq txt (cond
9847 ((org-at-heading-p) nil)
9848 ((and (eq et 'keyword) eok) ev)
9849 ((org-region-active-p)
9850 (buffer-substring (region-beginning) (region-end)))))
9851 (when (or (null txt) (string-match "\\S-" txt))
9852 (setq cpltxt
9853 (concat cpltxt "::"
9854 (condition-case nil
9855 (org-make-org-heading-search-string txt)
9856 (error "")))
9857 desc (or (and (eq et 'keyword) eok ev)
9858 (nth 4 (ignore-errors (org-heading-components)))
9859 "NONE")))))
9860 (if (string-match "::\\'" cpltxt)
9861 (setq cpltxt (substring cpltxt 0 -2)))
9862 (setq link cpltxt))))
9864 ((buffer-file-name (buffer-base-buffer))
9865 ;; Just link to this file here.
9866 (setq cpltxt (concat "file:"
9867 (abbreviate-file-name
9868 (buffer-file-name (buffer-base-buffer)))))
9869 ;; Add a context string.
9870 (when (org-xor org-context-in-file-links arg)
9871 (setq txt (if (org-region-active-p)
9872 (buffer-substring (region-beginning) (region-end))
9873 (buffer-substring (point-at-bol) (point-at-eol))))
9874 ;; Only use search option if there is some text.
9875 (when (string-match "\\S-" txt)
9876 (setq cpltxt
9877 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9878 desc "NONE")))
9879 (setq link cpltxt))
9881 ((org-called-interactively-p 'interactive)
9882 (user-error "No method for storing a link from this buffer"))
9884 (t (setq link nil)))
9886 ;; We're done setting link and desc, clean up
9887 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9888 (setq link (or link cpltxt)
9889 desc (or desc cpltxt))
9890 (cond ((equal desc "NONE") (setq desc nil))
9891 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9892 (let ((d0 (match-string 3 desc))
9893 (p0 (match-string 5 desc)))
9894 (setq desc
9895 (replace-regexp-in-string
9896 org-bracket-link-regexp
9897 (concat (or p0 d0)
9898 (if (equal (length (match-string 0 desc))
9899 (length desc)) "*" "")) desc)))))
9901 ;; Return the link
9902 (if (not (and (or (org-called-interactively-p 'any)
9903 executing-kbd-macro) link))
9904 (or agenda-link (and link (org-make-link-string link desc)))
9905 (push (list link desc) org-stored-links)
9906 (message "Stored: %s" (or desc link))
9907 (when custom-id
9908 (setq link (concat "file:" (abbreviate-file-name
9909 (buffer-file-name)) "::#" custom-id))
9910 (push (list link desc) org-stored-links))
9911 (car org-stored-links))))))
9913 (defun org-store-link-props (&rest plist)
9914 "Store link properties, extract names and addresses."
9915 (let (x adr)
9916 (when (setq x (plist-get plist :from))
9917 (setq adr (mail-extract-address-components x))
9918 (setq plist (plist-put plist :fromname (car adr)))
9919 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9920 (when (setq x (plist-get plist :to))
9921 (setq adr (mail-extract-address-components x))
9922 (setq plist (plist-put plist :toname (car adr)))
9923 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9924 (let ((from (plist-get plist :from))
9925 (to (plist-get plist :to)))
9926 (when (and from to org-from-is-user-regexp)
9927 (setq plist
9928 (plist-put plist :fromto
9929 (if (string-match org-from-is-user-regexp from)
9930 (concat "to %t")
9931 (concat "from %f"))))))
9932 (setq org-store-link-plist plist))
9934 (defun org-add-link-props (&rest plist)
9935 "Add these properties to the link property list."
9936 (let (key value)
9937 (while plist
9938 (setq key (pop plist) value (pop plist))
9939 (setq org-store-link-plist
9940 (plist-put org-store-link-plist key value)))))
9942 (defun org-email-link-description (&optional fmt)
9943 "Return the description part of an email link.
9944 This takes information from `org-store-link-plist' and formats it
9945 according to FMT (default from `org-email-link-description-format')."
9946 (setq fmt (or fmt org-email-link-description-format))
9947 (let* ((p org-store-link-plist)
9948 (to (plist-get p :toaddress))
9949 (from (plist-get p :fromaddress))
9950 (table
9951 (list
9952 (cons "%c" (plist-get p :fromto))
9953 (cons "%F" (plist-get p :from))
9954 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9955 (cons "%T" (plist-get p :to))
9956 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9957 (cons "%s" (plist-get p :subject))
9958 (cons "%d" (plist-get p :date))
9959 (cons "%m" (plist-get p :message-id)))))
9960 (when (string-match "%c" fmt)
9961 ;; Check if the user wrote this message
9962 (if (and org-from-is-user-regexp from to
9963 (save-match-data (string-match org-from-is-user-regexp from)))
9964 (setq fmt (replace-match "to %t" t t fmt))
9965 (setq fmt (replace-match "from %f" t t fmt))))
9966 (org-replace-escapes fmt table)))
9968 (defun org-make-org-heading-search-string (&optional string)
9969 "Make search string for the current headline or STRING."
9970 (let ((s (or string
9971 (and (derived-mode-p 'org-mode)
9972 (save-excursion
9973 (org-back-to-heading t)
9974 (org-element-property :raw-value (org-element-at-point))))))
9975 (lines org-context-in-file-links))
9976 (or string (setq s (concat "*" s))) ; Add * for headlines
9977 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9978 (when (and string (integerp lines) (> lines 0))
9979 (let ((slines (org-split-string s "\n")))
9980 (when (< lines (length slines))
9981 (setq s (mapconcat
9982 'identity
9983 (reverse (nthcdr (- (length slines) lines)
9984 (reverse slines))) "\n")))))
9985 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9987 (defun org-make-link-string (link &optional description)
9988 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9989 (unless (string-match "\\S-" link)
9990 (error "Empty link"))
9991 (when (and description
9992 (stringp description)
9993 (not (string-match "\\S-" description)))
9994 (setq description nil))
9995 (when (stringp description)
9996 ;; Remove brackets from the description, they are fatal.
9997 (while (string-match "\\[" description)
9998 (setq description (replace-match "{" t t description)))
9999 (while (string-match "\\]" description)
10000 (setq description (replace-match "}" t t description))))
10001 (when (equal link description)
10002 ;; No description needed, it is identical
10003 (setq description nil))
10004 (when (and (not description)
10005 (not (string-match (org-image-file-name-regexp) link))
10006 (not (equal link (org-link-escape link))))
10007 (setq description (org-extract-attributes link)))
10008 (setq link
10009 (cond ((string-match (org-image-file-name-regexp) link) link)
10010 ((string-match org-link-types-re link)
10011 (concat (match-string 1 link)
10012 (org-link-escape (substring link (match-end 1)))))
10013 (t (org-link-escape link))))
10014 (concat "[[" link "]"
10015 (if description (concat "[" description "]") "")
10016 "]"))
10018 (defconst org-link-escape-chars
10019 ;;%20 %5B %5D
10020 '(?\ ?\[ ?\])
10021 "List of characters that should be escaped in a link when stored to Org.
10022 This is the list that is used for internal purposes.")
10024 (defconst org-link-escape-chars-browser
10025 ;;%20 %22
10026 '(?\ ?\")
10027 "List of characters to be escaped before handing over to the browser.
10028 If you consider using this constant then you probably want to use
10029 the function `org-link-escape-browser' instead. See there why
10030 this constant is a candidate to be removed once Org drops support
10031 for Emacs 24.1 and 24.2.")
10033 (defun org-link-escape (text &optional table merge)
10034 "Return percent escaped representation of TEXT.
10035 TEXT is a string with the text to escape.
10036 Optional argument TABLE is a list with characters that should be
10037 escaped. When nil, `org-link-escape-chars' is used.
10038 If optional argument MERGE is set, merge TABLE into
10039 `org-link-escape-chars'."
10040 ;; Don't escape chars in internal links
10041 (if (string-match "^\\*[[:alnum:]]+" text)
10042 text
10043 (cond
10044 ((and table merge)
10045 (mapc (lambda (defchr)
10046 (unless (member defchr table)
10047 (setq table (cons defchr table))))
10048 org-link-escape-chars))
10049 ((null table)
10050 (setq table org-link-escape-chars)))
10051 (mapconcat
10052 (lambda (char)
10053 (if (or (member char table)
10054 (and (or (< char 32) (= char ?\%) (> char 126))
10055 org-url-hexify-p))
10056 (mapconcat (lambda (sequence-element)
10057 (format "%%%.2X" sequence-element))
10058 (or (encode-coding-char char 'utf-8)
10059 (error "Unable to percent escape character: %s"
10060 (char-to-string char))) "")
10061 (char-to-string char))) text "")))
10063 (defun org-link-escape-browser (text)
10064 "Escape some characters before handing over to the browser.
10065 This function is a candidate to be removed together with the
10066 constant `org-link-escape-chars-browser' once Org drops support
10067 for Emacs 24.1 and 24.2. All calls to this function will have to
10068 be replaced with `url-encode-url' which is available since Emacs
10069 24.3.1."
10070 ;; Example with the Org link
10071 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10072 ;; to open the browser with +subject:"Release 8.2" filled into the
10073 ;; query field: In this case the variable TEXT contains the
10074 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10075 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10076 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10077 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10078 (if (fboundp 'url-encode-url)
10079 (url-encode-url text)
10080 (if (org-string-match-p
10081 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10082 text)
10083 (org-link-escape text org-link-escape-chars-browser)
10084 text)))
10086 (defun org-link-unescape (str)
10087 "Unhex hexified Unicode strings as returned from the JavaScript function
10088 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10089 (unless (and (null str) (string= "" str))
10090 (let ((pos 0) (case-fold-search t) unhexed)
10091 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10092 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10093 (setq str (replace-match unhexed t t str))
10094 (setq pos (+ pos (length unhexed))))))
10095 str)
10097 (defun org-link-unescape-compound (hex)
10098 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10099 Note: this function also decodes single byte encodings like
10100 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10101 (save-match-data
10102 (let* ((bytes (cdr (split-string hex "%")))
10103 (ret "")
10104 (eat 0)
10105 (sum 0))
10106 (while bytes
10107 (let* ((val (string-to-number (pop bytes) 16))
10108 (shift-xor
10109 (if (= 0 eat)
10110 (cond
10111 ((>= val 252) (cons 6 252))
10112 ((>= val 248) (cons 5 248))
10113 ((>= val 240) (cons 4 240))
10114 ((>= val 224) (cons 3 224))
10115 ((>= val 192) (cons 2 192))
10116 (t (cons 0 0)))
10117 (cons 6 128))))
10118 (if (>= val 192) (setq eat (car shift-xor)))
10119 (setq val (logxor val (cdr shift-xor)))
10120 (setq sum (+ (lsh sum (car shift-xor)) val))
10121 (if (> eat 0) (setq eat (- eat 1)))
10122 (cond
10123 ((= 0 eat) ;multi byte
10124 (setq ret (concat ret (org-char-to-string sum)))
10125 (setq sum 0))
10126 ((not bytes) ; single byte(s)
10127 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10128 ret)))
10130 (defun org-link-unescape-single-byte-sequence (hex)
10131 "Unhexify hex-encoded single byte character sequences."
10132 (mapconcat (lambda (byte)
10133 (char-to-string (string-to-number byte 16)))
10134 (cdr (split-string hex "%")) ""))
10136 (defun org-xor (a b)
10137 "Exclusive or."
10138 (if a (not b) b))
10140 (defun org-fixup-message-id-for-http (s)
10141 "Replace special characters in a message id, so it can be used in an http query."
10142 (when (string-match "%" s)
10143 (setq s (mapconcat (lambda (c)
10144 (if (eq c ?%)
10145 "%25"
10146 (char-to-string c)))
10147 s "")))
10148 (while (string-match "<" s)
10149 (setq s (replace-match "%3C" t t s)))
10150 (while (string-match ">" s)
10151 (setq s (replace-match "%3E" t t s)))
10152 (while (string-match "@" s)
10153 (setq s (replace-match "%40" t t s)))
10156 (defun org-link-prettify (link)
10157 "Return a human-readable representation of LINK.
10158 The car of LINK must be a raw link.
10159 The cdr of LINK must be either a link description or nil."
10160 (let ((desc (or (cadr link) "<no description>")))
10161 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10162 "<" (car link) ">")))
10164 ;;;###autoload
10165 (defun org-insert-link-global ()
10166 "Insert a link like Org-mode does.
10167 This command can be called in any mode to insert a link in Org-mode syntax."
10168 (interactive)
10169 (org-load-modules-maybe)
10170 (org-run-like-in-org-mode 'org-insert-link))
10172 (defun org-insert-all-links (arg &optional pre post)
10173 "Insert all links in `org-stored-links'.
10174 When a universal prefix, do not delete the links from `org-stored-links'.
10175 When `ARG' is a number, insert the last N link(s).
10176 `PRE' and `POST' are optional arguments to define a string to
10177 prepend or to append."
10178 (interactive "P")
10179 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10180 (links (copy-seq org-stored-links))
10181 (pr (or pre "- "))
10182 (po (or post "\n"))
10183 (cnt 1) l)
10184 (if (null org-stored-links)
10185 (message "No link to insert")
10186 (while (and (or (listp arg) (>= arg cnt))
10187 (setq l (if (listp arg)
10188 (pop links)
10189 (pop org-stored-links))))
10190 (setq cnt (1+ cnt))
10191 (insert pr)
10192 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10193 (insert po)))))
10195 (defun org-insert-last-stored-link (arg)
10196 "Insert the last link stored in `org-stored-links'."
10197 (interactive "p")
10198 (org-insert-all-links arg "" "\n"))
10200 (defun org-link-fontify-links-to-this-file ()
10201 "Fontify links to the current file in `org-stored-links'."
10202 (let ((f (buffer-file-name)) a b)
10203 (setq a (mapcar (lambda(l)
10204 (let ((ll (car l)))
10205 (when (and (string-match "^file:\\(.+\\)::" ll)
10206 (equal f (expand-file-name (match-string 1 ll))))
10207 ll)))
10208 org-stored-links))
10209 (when (featurep 'org-id)
10210 (setq b (mapcar (lambda(l)
10211 (let ((ll (car l)))
10212 (when (and (string-match "^id:\\(.+\\)$" ll)
10213 (equal f (expand-file-name
10214 (or (org-id-find-id-file
10215 (match-string 1 ll)) ""))))
10216 ll)))
10217 org-stored-links)))
10218 (mapcar (lambda(l)
10219 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10220 (delq nil (append a b)))))
10222 (defvar org-link-links-in-this-file nil)
10223 (defun org-insert-link (&optional complete-file link-location default-description)
10224 "Insert a link. At the prompt, enter the link.
10226 Completion can be used to insert any of the link protocol prefixes like
10227 http or ftp in use.
10229 The history can be used to select a link previously stored with
10230 `org-store-link'. When the empty string is entered (i.e. if you just
10231 press RET at the prompt), the link defaults to the most recently
10232 stored link. As SPC triggers completion in the minibuffer, you need to
10233 use M-SPC or C-q SPC to force the insertion of a space character.
10235 You will also be prompted for a description, and if one is given, it will
10236 be displayed in the buffer instead of the link.
10238 If there is already a link at point, this command will allow you to edit link
10239 and description parts.
10241 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10242 be selected using completion. The path to the file will be relative to the
10243 current directory if the file is in the current directory or a subdirectory.
10244 Otherwise, the link will be the absolute path as completed in the minibuffer
10245 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10246 option `org-link-file-path-type'.
10248 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10249 the current directory or below.
10251 With three \\[universal-argument] prefixes, negate the meaning of
10252 `org-keep-stored-link-after-insertion'.
10254 If `org-make-link-description-function' is non-nil, this function will be
10255 called with the link target, and the result will be the default
10256 link description.
10258 If the LINK-LOCATION parameter is non-nil, this value will be
10259 used as the link location instead of reading one interactively.
10261 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10262 be used as the default description."
10263 (interactive "P")
10264 (let* ((wcf (current-window-configuration))
10265 (origbuf (current-buffer))
10266 (region (if (org-region-active-p)
10267 (buffer-substring (region-beginning) (region-end))))
10268 (remove (and region (list (region-beginning) (region-end))))
10269 (desc region)
10270 tmphist ; byte-compile incorrectly complains about this
10271 (link link-location)
10272 (abbrevs org-link-abbrev-alist-local)
10273 entry file all-prefixes auto-desc)
10274 (cond
10275 (link-location) ; specified by arg, just use it.
10276 ((org-in-regexp org-bracket-link-regexp 1)
10277 ;; We do have a link at point, and we are going to edit it.
10278 (setq remove (list (match-beginning 0) (match-end 0)))
10279 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10280 (setq link (read-string "Link: "
10281 (org-link-unescape
10282 (org-match-string-no-properties 1)))))
10283 ((or (org-in-regexp org-angle-link-re)
10284 (org-in-regexp org-plain-link-re))
10285 ;; Convert to bracket link
10286 (setq remove (list (match-beginning 0) (match-end 0))
10287 link (read-string "Link: "
10288 (org-remove-angle-brackets (match-string 0)))))
10289 ((member complete-file '((4) (16)))
10290 ;; Completing read for file names.
10291 (setq link (org-file-complete-link complete-file)))
10293 ;; Read link, with completion for stored links.
10294 (org-link-fontify-links-to-this-file)
10295 (org-switch-to-buffer-other-window "*Org Links*")
10296 (with-current-buffer "*Org Links*"
10297 (erase-buffer)
10298 (insert "Insert a link.
10299 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10300 (when org-stored-links
10301 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10302 (insert (mapconcat 'org-link-prettify
10303 (reverse org-stored-links) "\n")))
10304 (goto-char (point-min)))
10305 (let ((cw (selected-window)))
10306 (select-window (get-buffer-window "*Org Links*" 'visible))
10307 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10308 (unless (pos-visible-in-window-p (point-max))
10309 (org-fit-window-to-buffer))
10310 (and (window-live-p cw) (select-window cw)))
10311 ;; Fake a link history, containing the stored links.
10312 (setq tmphist (append (mapcar 'car org-stored-links)
10313 org-insert-link-history))
10314 (setq all-prefixes (append (mapcar 'car abbrevs)
10315 (mapcar 'car org-link-abbrev-alist)
10316 org-link-types))
10317 (unwind-protect
10318 (progn
10319 (setq link
10320 (org-completing-read
10321 "Link: "
10322 (append
10323 (mapcar (lambda (x) (concat x ":"))
10324 all-prefixes)
10325 (mapcar 'car org-stored-links))
10326 nil nil nil
10327 'tmphist
10328 (caar org-stored-links)))
10329 (if (not (string-match "\\S-" link))
10330 (user-error "No link selected"))
10331 (mapc (lambda(l)
10332 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10333 org-stored-links)
10334 (if (or (member link all-prefixes)
10335 (and (equal ":" (substring link -1))
10336 (member (substring link 0 -1) all-prefixes)
10337 (setq link (substring link 0 -1))))
10338 (setq link (with-current-buffer origbuf
10339 (org-link-try-special-completion link)))))
10340 (set-window-configuration wcf)
10341 (kill-buffer "*Org Links*"))
10342 (setq entry (assoc link org-stored-links))
10343 (or entry (push link org-insert-link-history))
10344 (setq desc (or desc (nth 1 entry)))))
10346 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10347 (not org-keep-stored-link-after-insertion))
10348 (setq org-stored-links (delq (assoc link org-stored-links)
10349 org-stored-links)))
10351 (if (and (string-match org-plain-link-re link)
10352 (not (string-match org-ts-regexp link)))
10353 ;; URL-like link, normalize the use of angular brackets.
10354 (setq link (org-remove-angle-brackets link)))
10356 ;; Check if we are linking to the current file with a search
10357 ;; option If yes, simplify the link by using only the search
10358 ;; option.
10359 (when (and buffer-file-name
10360 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10361 (let* ((path (match-string 1 link))
10362 (case-fold-search nil)
10363 (search (match-string 2 link)))
10364 (save-match-data
10365 (if (equal (file-truename buffer-file-name) (file-truename path))
10366 ;; We are linking to this same file, with a search option
10367 (setq link search)))))
10369 ;; Check if we can/should use a relative path. If yes, simplify the link
10370 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10371 (let* ((type (match-string 1 link))
10372 (path (match-string 2 link))
10373 (origpath path)
10374 (case-fold-search nil))
10375 (cond
10376 ((or (eq org-link-file-path-type 'absolute)
10377 (equal complete-file '(16)))
10378 (setq path (abbreviate-file-name (expand-file-name path))))
10379 ((eq org-link-file-path-type 'noabbrev)
10380 (setq path (expand-file-name path)))
10381 ((eq org-link-file-path-type 'relative)
10382 (setq path (file-relative-name path)))
10384 (save-match-data
10385 (if (string-match (concat "^" (regexp-quote
10386 (expand-file-name
10387 (file-name-as-directory
10388 default-directory))))
10389 (expand-file-name path))
10390 ;; We are linking a file with relative path name.
10391 (setq path (substring (expand-file-name path)
10392 (match-end 0)))
10393 (setq path (abbreviate-file-name (expand-file-name path)))))))
10394 (setq link (concat type path))
10395 (if (equal desc origpath)
10396 (setq desc path))))
10398 (if org-make-link-description-function
10399 (setq desc
10400 (or (condition-case nil
10401 (funcall org-make-link-description-function link desc)
10402 (error (progn (message "Can't get link description from `%s'"
10403 (symbol-name org-make-link-description-function))
10404 (sit-for 2) nil)))
10405 (read-string "Description: " default-description)))
10406 (if default-description (setq desc default-description)
10407 (setq desc (or (and auto-desc desc)
10408 (read-string "Description: " desc)))))
10410 (unless (string-match "\\S-" desc) (setq desc nil))
10411 (if remove (apply 'delete-region remove))
10412 (insert (org-make-link-string link desc))))
10414 (defun org-link-try-special-completion (type)
10415 "If there is completion support for link type TYPE, offer it."
10416 (let ((fun (intern (concat "org-" type "-complete-link"))))
10417 (if (functionp fun)
10418 (funcall fun)
10419 (read-string "Link (no completion support): " (concat type ":")))))
10421 (defun org-file-complete-link (&optional arg)
10422 "Create a file link using completion."
10423 (let (file link)
10424 (setq file (org-iread-file-name "File: "))
10425 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10426 (pwd1 (file-name-as-directory (abbreviate-file-name
10427 (expand-file-name ".")))))
10428 (cond
10429 ((equal arg '(16))
10430 (setq link (concat
10431 "file:"
10432 (abbreviate-file-name (expand-file-name file)))))
10433 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10434 (setq link (concat "file:" (match-string 1 file))))
10435 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10436 (expand-file-name file))
10437 (setq link (concat
10438 "file:" (match-string 1 (expand-file-name file)))))
10439 (t (setq link (concat "file:" file)))))
10440 link))
10442 (defun org-iread-file-name (&rest args)
10443 "Read-file-name using `ido-mode' speedup if available.
10444 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10445 See `read-file-name' for a description of parameters."
10446 (org-without-partial-completion
10447 (if (and org-completion-use-ido
10448 (fboundp 'ido-read-file-name)
10449 (boundp 'ido-mode) ido-mode
10450 (listp (second args)))
10451 (let ((ido-enter-matching-directory nil))
10452 (apply 'ido-read-file-name args))
10453 (apply 'read-file-name args))))
10455 (defun org-completing-read (&rest args)
10456 "Completing-read with SPACE being a normal character."
10457 (let ((enable-recursive-minibuffers t)
10458 (minibuffer-local-completion-map
10459 (copy-keymap minibuffer-local-completion-map)))
10460 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10461 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10462 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10463 (apply 'org-icompleting-read args)))
10465 (defun org-completing-read-no-i (&rest args)
10466 (let (org-completion-use-ido org-completion-use-iswitchb)
10467 (apply 'org-completing-read args)))
10469 (defun org-iswitchb-completing-read (prompt choices &rest args)
10470 "Use iswitch as a completing-read replacement to choose from choices.
10471 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10472 from."
10473 (let* ((iswitchb-use-virtual-buffers nil)
10474 (iswitchb-make-buflist-hook
10475 (lambda ()
10476 (setq iswitchb-temp-buflist choices))))
10477 (iswitchb-read-buffer prompt)))
10479 (defun org-icompleting-read (&rest args)
10480 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10481 (org-without-partial-completion
10482 (if (and org-completion-use-ido
10483 (fboundp 'ido-completing-read)
10484 (boundp 'ido-mode) ido-mode
10485 (listp (second args)))
10486 (let ((ido-enter-matching-directory nil))
10487 (apply 'ido-completing-read (concat (car args))
10488 (if (consp (car (nth 1 args)))
10489 (mapcar 'car (nth 1 args))
10490 (nth 1 args))
10491 (cddr args)))
10492 (if (and org-completion-use-iswitchb
10493 (boundp 'iswitchb-mode) iswitchb-mode
10494 (listp (second args)))
10495 (apply 'org-iswitchb-completing-read (concat (car args))
10496 (if (consp (car (nth 1 args)))
10497 (mapcar 'car (nth 1 args))
10498 (nth 1 args))
10499 (cddr args))
10500 (apply 'completing-read args)))))
10502 (defun org-extract-attributes (s)
10503 "Extract the attributes cookie from a string and set as text property."
10504 (let (a attr (start 0) key value)
10505 (save-match-data
10506 (when (string-match "{{\\([^}]+\\)}}$" s)
10507 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10508 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10509 (setq key (match-string 1 a) value (match-string 2 a)
10510 start (match-end 0)
10511 attr (plist-put attr (intern key) value))))
10512 (org-add-props s nil 'org-attr attr))
10515 ;;; Opening/following a link
10517 (defvar org-link-search-failed nil)
10519 (defvar org-open-link-functions nil
10520 "Hook for functions finding a plain text link.
10521 These functions must take a single argument, the link content.
10522 They will be called for links that look like [[link text][description]]
10523 when LINK TEXT does not have a protocol like \"http:\" and does not look
10524 like a filename (e.g. \"./blue.png\").
10526 These functions will be called *before* Org attempts to resolve the
10527 link by doing text searches in the current buffer - so if you want a
10528 link \"[[target]]\" to still find \"<<target>>\", your function should
10529 handle this as a special case.
10531 When the function does handle the link, it must return a non-nil value.
10532 If it decides that it is not responsible for this link, it must return
10533 nil to indicate that that Org-mode can continue with other options
10534 like exact and fuzzy text search.")
10536 (defun org-next-link (&optional search-backward)
10537 "Move forward to the next link.
10538 If the link is in hidden text, expose it."
10539 (interactive "P")
10540 (when (and org-link-search-failed (eq this-command last-command))
10541 (goto-char (point-min))
10542 (message "Link search wrapped back to beginning of buffer"))
10543 (setq org-link-search-failed nil)
10544 (let* ((pos (point))
10545 (ct (org-context))
10546 (a (assoc :link ct))
10547 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10548 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10549 ((looking-at org-any-link-re)
10550 ;; Don't stay stuck at link without an org-link face
10551 (forward-char (if search-backward -1 1))))
10552 (if (funcall srch-fun org-any-link-re nil t)
10553 (progn
10554 (goto-char (match-beginning 0))
10555 (if (outline-invisible-p) (org-show-context)))
10556 (goto-char pos)
10557 (setq org-link-search-failed t)
10558 (message "No further link found"))))
10560 (defun org-previous-link ()
10561 "Move backward to the previous link.
10562 If the link is in hidden text, expose it."
10563 (interactive)
10564 (funcall 'org-next-link t))
10566 (defun org-translate-link (s)
10567 "Translate a link string if a translation function has been defined."
10568 (if (and org-link-translation-function
10569 (fboundp org-link-translation-function)
10570 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10571 (progn
10572 (setq s (funcall org-link-translation-function
10573 (match-string 1 s) (match-string 2 s)))
10574 (concat (car s) ":" (cdr s)))
10577 (defun org-translate-link-from-planner (type path)
10578 "Translate a link from Emacs Planner syntax so that Org can follow it.
10579 This is still an experimental function, your mileage may vary."
10580 (cond
10581 ((member type '("http" "https" "news" "ftp"))
10582 ;; standard Internet links are the same.
10583 nil)
10584 ((and (equal type "irc") (string-match "^//" path))
10585 ;; Planner has two / at the beginning of an irc link, we have 1.
10586 ;; We should have zero, actually....
10587 (setq path (substring path 1)))
10588 ((and (equal type "lisp") (string-match "^/" path))
10589 ;; Planner has a slash, we do not.
10590 (setq type "elisp" path (substring path 1)))
10591 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10592 ;; A typical message link. Planner has the id after the final slash,
10593 ;; we separate it with a hash mark
10594 (setq path (concat (match-string 1 path) "#"
10595 (org-remove-angle-brackets (match-string 2 path))))))
10596 (cons type path))
10598 (defun org-find-file-at-mouse (ev)
10599 "Open file link or URL at mouse."
10600 (interactive "e")
10601 (mouse-set-point ev)
10602 (org-open-at-point 'in-emacs))
10604 (defun org-open-at-mouse (ev)
10605 "Open file link or URL at mouse.
10606 See the docstring of `org-open-file' for details."
10607 (interactive "e")
10608 (mouse-set-point ev)
10609 (if (eq major-mode 'org-agenda-mode)
10610 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10611 (org-open-at-point))
10613 (defvar org-window-config-before-follow-link nil
10614 "The window configuration before following a link.
10615 This is saved in case the need arises to restore it.")
10617 (defvar org-open-link-marker (make-marker)
10618 "Marker pointing to the location where `org-open-at-point' was called.")
10620 ;;;###autoload
10621 (defun org-open-at-point-global ()
10622 "Follow a link like Org-mode does.
10623 This command can be called in any mode to follow a link that has
10624 Org-mode syntax."
10625 (interactive)
10626 (org-run-like-in-org-mode 'org-open-at-point))
10628 ;;;###autoload
10629 (defun org-open-link-from-string (s &optional arg reference-buffer)
10630 "Open a link in the string S, as if it was in Org-mode."
10631 (interactive "sLink: \nP")
10632 (let ((reference-buffer (or reference-buffer (current-buffer))))
10633 (with-temp-buffer
10634 (let ((org-inhibit-startup (not reference-buffer)))
10635 (org-mode)
10636 (insert s)
10637 (goto-char (point-min))
10638 (when reference-buffer
10639 (setq org-link-abbrev-alist-local
10640 (with-current-buffer reference-buffer
10641 org-link-abbrev-alist-local)))
10642 (org-open-at-point arg reference-buffer)))))
10644 (defvar org-open-at-point-functions nil
10645 "Hook that is run when following a link at point.
10647 Functions in this hook must return t if they identify and follow
10648 a link at point. If they don't find anything interesting at point,
10649 they must return nil.")
10651 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10652 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10653 (defun org-open-at-point (&optional arg reference-buffer)
10654 "Open link, timestamp, footnote or tags at point.
10656 When point is on a link, follow it. Normally, files will be
10657 opened by an appropriate application. If the optional prefix
10658 argument ARG is non-nil, Emacs will visit the file. With
10659 a double prefix argument, try to open outside of Emacs, in the
10660 application the system uses for this file type.
10662 When point is on a timestamp, open the agenda at the day
10663 specified.
10665 When point is a footnote definition, move to the first reference
10666 found. If it is on a reference, move to the associated
10667 definition.
10669 When point is on a headline, display a list of every link in the
10670 entry, so it is possible to pick one, or all, of them. If point
10671 is on a tag, call `org-tags-view' instead.
10673 When optional argument REFERENCE-BUFFER is non-nil, it should
10674 specify a buffer from where the link search should happen. This
10675 is used internally by `org-open-link-from-string'.
10677 On top of syntactically correct links, this function will open
10678 the link at point in comments or comment blocks and the first
10679 link in a property drawer line."
10680 (interactive "P")
10681 ;; On a code block, open block's results.
10682 (unless (call-interactively 'org-babel-open-src-block-result)
10683 (org-load-modules-maybe)
10684 (move-marker org-open-link-marker (point))
10685 (setq org-window-config-before-follow-link (current-window-configuration))
10686 (org-remove-occur-highlights nil nil t)
10687 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10688 (let* ((context (org-element-context)) type value)
10689 ;; On an unsupported type, check if point is contained within
10690 ;; a support one.
10691 (while (and (not (memq (setq type (org-element-type context))
10692 '(comment comment-block
10693 headline inlinetask link
10694 footnote-definition footnote-reference
10695 node-property timestamp)))
10696 (setq context (org-element-property :parent context))))
10697 (setq value (org-element-property :value context))
10698 (cond
10699 ;; Blank lines at the beginning of buffer: bail out.
10700 ((not context) (user-error "No link found"))
10701 ;; Exception n°1: links in property drawers
10702 ((eq type 'node-property)
10703 (org-open-link-from-string
10704 (and (string-match org-any-link-re value)
10705 (match-string-no-properties 0 value))))
10706 ;; Exception n°2: links in comments.
10707 ((memq type '(comment comment-block))
10708 (save-excursion
10709 (skip-chars-forward "\\S-" (point-at-eol))
10710 (let ((string-rear (replace-regexp-in-string
10711 "^[ \t]*# [ \t]*" ""
10712 (buffer-substring (point) (line-beginning-position))))
10713 (string-front (buffer-substring (point) (line-end-position))))
10714 (with-temp-buffer
10715 (let ((org-inhibit-startup t)) (org-mode))
10716 (insert value)
10717 (goto-char (point-min))
10718 (when (and (search-forward string-rear nil t)
10719 (search-forward string-front (line-end-position) t))
10720 (goto-char (match-beginning 0))
10721 (org-open-at-point)
10722 (when (string= string-rear "") (forward-char)))))))
10723 ;; On a headline or an inlinetask, but not on a timestamp,
10724 ;; a link, a footnote reference or on tags.
10725 ((and (memq type '(headline inlinetask))
10726 ;; Not on tags.
10727 (progn (save-excursion (beginning-of-line)
10728 (looking-at org-complex-heading-regexp))
10729 (or (not (match-beginning 5))
10730 (< (point) (match-beginning 5)))))
10731 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10732 (links (car data))
10733 (links-end (cdr data)))
10734 (if links
10735 (dolist (link (if (stringp links) (list links) links))
10736 (search-forward link nil links-end)
10737 (goto-char (match-beginning 0))
10738 (org-open-at-point))
10739 (require 'org-attach)
10740 (org-attach-reveal 'if-exists))))
10741 ;; Do nothing on white spaces after an object, unless point
10742 ;; is right after it.
10743 ((> (point)
10744 (save-excursion
10745 (goto-char (org-element-property :end context))
10746 (skip-chars-backward " \t")
10747 (point)))
10748 (user-error "No link found"))
10749 ((eq type 'timestamp) (org-follow-timestamp-link))
10750 ;; On tags within a headline or an inlinetask.
10751 ((and (memq type '(headline inlinetask))
10752 (progn (save-excursion (beginning-of-line)
10753 (looking-at org-complex-heading-regexp))
10754 (and (match-beginning 5)
10755 (>= (point) (match-beginning 5)))))
10756 (org-tags-view arg (substring (match-string 5) 0 -1)))
10757 ((eq type 'link)
10758 ;; When link is located within the description of another
10759 ;; link (e.g., an inline image), always open the parent
10760 ;; link.
10761 (let*((link (let ((up (org-element-property :parent context)))
10762 (if (eq (org-element-type up) 'link) up context)))
10763 (type (org-element-property :type link))
10764 (path (org-link-unescape (org-element-property :path link))))
10765 ;; Switch back to REFERENCE-BUFFER needed when called in
10766 ;; a temporary buffer through `org-open-link-from-string'.
10767 (with-current-buffer (or reference-buffer (current-buffer))
10768 (cond
10769 ((equal type "file")
10770 (if (string-match "[*?{]" (file-name-nondirectory path))
10771 (dired path)
10772 ;; Look into `org-link-protocols' in order to find
10773 ;; a DEDICATED-FUNCTION to open file. The function
10774 ;; will be applied on raw link instead of parsed
10775 ;; link due to the limitation in `org-add-link-type'
10776 ;; ("open" function called with a single argument).
10777 ;; If no such function is found, fallback to
10778 ;; `org-open-file'.
10780 ;; Note : "file+emacs" and "file+sys" types are
10781 ;; hard-coded in order to escape the previous
10782 ;; limitation.
10783 (let* ((option (org-element-property :search-option link))
10784 (app (org-element-property :application link))
10785 (dedicated-function
10786 (nth 1 (assoc app org-link-protocols))))
10787 (if dedicated-function
10788 (funcall dedicated-function
10789 (concat path
10790 (and option (concat "::" option))))
10791 (apply 'org-open-file
10792 path
10793 (cond (arg)
10794 ((equal app "emacs") 'emacs)
10795 ((equal app "sys") 'system))
10796 (cond ((not option) nil)
10797 ((org-string-match-p "\\`[0-9]+\\'" option)
10798 (list (string-to-number option)))
10799 (t (list nil
10800 (org-link-unescape option)))))))))
10801 ((assoc type org-link-protocols)
10802 (funcall (nth 1 (assoc type org-link-protocols)) path))
10803 ((equal type "help")
10804 (let ((f-or-v (intern path)))
10805 (cond ((fboundp f-or-v) (describe-function f-or-v))
10806 ((boundp f-or-v) (describe-variable f-or-v))
10807 (t (error "Not a known function or variable")))))
10808 ((member type '("http" "https" "ftp" "mailto" "news"))
10809 (browse-url (org-link-escape-browser (concat type ":" path))))
10810 ((equal type "doi")
10811 (browse-url
10812 (org-link-escape-browser (concat org-doi-server-url path))))
10813 ((equal type "message") (browse-url (concat type ":" path)))
10814 ((equal type "shell")
10815 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10816 (cmd path))
10817 (if (or (and (org-string-nw-p
10818 org-confirm-shell-link-not-regexp)
10819 (string-match
10820 org-confirm-shell-link-not-regexp cmd))
10821 (not org-confirm-shell-link-function)
10822 (funcall org-confirm-shell-link-function
10823 (format "Execute \"%s\" in shell? "
10824 (org-add-props cmd nil
10825 'face 'org-warning))))
10826 (progn
10827 (message "Executing %s" cmd)
10828 (shell-command cmd buf)
10829 (when (featurep 'midnight)
10830 (setq clean-buffer-list-kill-buffer-names
10831 (cons buf
10832 clean-buffer-list-kill-buffer-names))))
10833 (user-error "Abort"))))
10834 ((equal type "elisp")
10835 (let ((cmd path))
10836 (if (or (and (org-string-nw-p
10837 org-confirm-elisp-link-not-regexp)
10838 (org-string-match-p
10839 org-confirm-elisp-link-not-regexp cmd))
10840 (not org-confirm-elisp-link-function)
10841 (funcall org-confirm-elisp-link-function
10842 (format "Execute \"%s\" as elisp? "
10843 (org-add-props cmd nil
10844 'face 'org-warning))))
10845 (message "%s => %s" cmd
10846 (if (eq (string-to-char cmd) ?\()
10847 (eval (read cmd))
10848 (call-interactively (read cmd))))
10849 (user-error "Abort"))))
10850 ((equal type "id")
10851 (require 'ord-id)
10852 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10853 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10854 (unless (run-hook-with-args-until-success
10855 'org-open-link-functions path)
10856 (if (not arg) (org-mark-ring-push)
10857 (switch-to-buffer-other-window
10858 (org-get-buffer-for-internal-link (current-buffer))))
10859 (let ((cmd `(org-link-search
10860 ,(if (member type '("custom-id" "coderef"))
10861 (org-element-property :raw-link link)
10862 path)
10863 ,(cond ((equal arg '(4)) 'occur)
10864 ((equal arg '(16)) 'org-occur))
10865 ,(org-element-property :begin link))))
10866 (condition-case nil
10867 (let ((org-link-search-inhibit-query t))
10868 (eval cmd))
10869 (error (progn (widen) (eval cmd)))))))
10870 (t (browse-url-at-point))))))
10871 ;; On a footnote reference or at a footnote definition's label.
10872 ((or (eq type 'footnote-reference)
10873 (and (eq type 'footnote-definition)
10874 (save-excursion
10875 ;; Do not validate action when point is on the
10876 ;; spaces right after the footnote label, in
10877 ;; order to be on par with behaviour on links.
10878 (skip-chars-forward " \t")
10879 (let ((begin
10880 (org-element-property :contents-begin context)))
10881 (if begin (< (point) begin)
10882 (= (org-element-property :post-affiliated context)
10883 (line-beginning-position)))))))
10884 (org-footnote-action))
10885 (t (user-error "No link found")))))
10886 (move-marker org-open-link-marker nil)
10887 (run-hook-with-args 'org-follow-link-hook)))
10889 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10890 "Offer links in the current entry and return the selected link.
10891 If there is only one link, return it.
10892 If NTH is an integer, return the NTH link found.
10893 If ZERO is a string, check also this string for a link, and if
10894 there is one, return it."
10895 (with-current-buffer buffer
10896 (save-excursion
10897 (save-restriction
10898 (widen)
10899 (goto-char marker)
10900 (let ((cnt ?0)
10901 (in-emacs (if (integerp nth) nil nth))
10902 have-zero end links link c)
10903 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10904 (push (match-string 0 zero) links)
10905 (setq cnt (1- cnt) have-zero t))
10906 (save-excursion
10907 (org-back-to-heading t)
10908 (setq end (save-excursion (outline-next-heading) (point)))
10909 (while (re-search-forward org-any-link-re end t)
10910 (push (match-string 0) links))
10911 (setq links (org-uniquify (reverse links))))
10912 (cond
10913 ((null links)
10914 (message "No links"))
10915 ((equal (length links) 1)
10916 (setq link (car links)))
10917 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10918 (setq link (nth (if have-zero nth (1- nth)) links)))
10919 (t ; we have to select a link
10920 (save-excursion
10921 (save-window-excursion
10922 (delete-other-windows)
10923 (with-output-to-temp-buffer "*Select Link*"
10924 (mapc (lambda (l)
10925 (if (not (string-match org-bracket-link-regexp l))
10926 (princ (format "[%c] %s\n" (incf cnt)
10927 (org-remove-angle-brackets l)))
10928 (if (match-end 3)
10929 (princ (format "[%c] %s (%s)\n" (incf cnt)
10930 (match-string 3 l) (match-string 1 l)))
10931 (princ (format "[%c] %s\n" (incf cnt)
10932 (match-string 1 l))))))
10933 links))
10934 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10935 (message "Select link to open, RET to open all:")
10936 (setq c (read-char-exclusive))
10937 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10938 (when (equal c ?q) (user-error "Abort"))
10939 (if (equal c ?\C-m)
10940 (setq link links)
10941 (setq nth (- c ?0))
10942 (if have-zero (setq nth (1+ nth)))
10943 (unless (and (integerp nth) (>= (length links) nth))
10944 (user-error "Invalid link selection"))
10945 (setq link (nth (1- nth) links)))))
10946 (cons link end))))))
10948 ;; TODO: These functions are deprecated since `org-open-at-point'
10949 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10950 (defun org-open-file-with-system (path)
10951 "Open file at PATH using the system way of opening it."
10952 (org-open-file path 'system))
10953 (defun org-open-file-with-emacs (path)
10954 "Open file at PATH in Emacs."
10955 (org-open-file path 'emacs))
10958 ;;; File search
10960 (defvar org-create-file-search-functions nil
10961 "List of functions to construct the right search string for a file link.
10962 These functions are called in turn with point at the location to
10963 which the link should point.
10965 A function in the hook should first test if it would like to
10966 handle this file type, for example by checking the `major-mode'
10967 or the file extension. If it decides not to handle this file, it
10968 should just return nil to give other functions a chance. If it
10969 does handle the file, it must return the search string to be used
10970 when following the link. The search string will be part of the
10971 file link, given after a double colon, and `org-open-at-point'
10972 will automatically search for it. If special measures must be
10973 taken to make the search successful, another function should be
10974 added to the companion hook `org-execute-file-search-functions',
10975 which see.
10977 A function in this hook may also use `setq' to set the variable
10978 `description' to provide a suggestion for the descriptive text to
10979 be used for this link when it gets inserted into an Org-mode
10980 buffer with \\[org-insert-link].")
10982 (defvar org-execute-file-search-functions nil
10983 "List of functions to execute a file search triggered by a link.
10985 Functions added to this hook must accept a single argument, the
10986 search string that was part of the file link, the part after the
10987 double colon. The function must first check if it would like to
10988 handle this search, for example by checking the `major-mode' or
10989 the file extension. If it decides not to handle this search, it
10990 should just return nil to give other functions a chance. If it
10991 does handle the search, it must return a non-nil value to keep
10992 other functions from trying.
10994 Each function can access the current prefix argument through the
10995 variable `current-prefix-arg'. Note that a single prefix is used
10996 to force opening a link in Emacs, so it may be good to only use a
10997 numeric or double prefix to guide the search function.
10999 In case this is needed, a function in this hook can also restore
11000 the window configuration before `org-open-at-point' was called using:
11002 (set-window-configuration org-window-config-before-follow-link)")
11004 (defun org-link-search (s &optional type avoid-pos stealth)
11005 "Search for a link search option.
11006 If S is surrounded by forward slashes, it is interpreted as a
11007 regular expression. In org-mode files, this will create an `org-occur'
11008 sparse tree. In ordinary files, `occur' will be used to list matches.
11009 If the current buffer is in `dired-mode', grep will be used to search
11010 in all files. If AVOID-POS is given, ignore matches near that position.
11012 When optional argument STEALTH is non-nil, do not modify
11013 visibility around point, thus ignoring
11014 `org-show-hierarchy-above', `org-show-following-heading' and
11015 `org-show-siblings' variables."
11016 (let ((case-fold-search t)
11017 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
11018 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
11019 (append '(("") (" ") ("\t") ("\n"))
11020 org-emphasis-alist)
11021 "\\|") "\\)"))
11022 (pos (point))
11023 (pre nil) (post nil)
11024 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
11025 (cond
11026 ;; First check if there are any special search functions
11027 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11028 ;; Now try the builtin stuff
11029 ((and (equal (string-to-char s0) ?#)
11030 (> (length s0) 1)
11031 (save-excursion
11032 (goto-char (point-min))
11033 (and
11034 (re-search-forward
11035 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
11036 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
11037 (setq type 'dedicated
11038 pos (match-beginning 0))))
11039 ;; There is an exact target for this
11040 (goto-char pos)
11041 (org-back-to-heading t)))
11042 ((save-excursion
11043 (goto-char (point-min))
11044 (and
11045 (re-search-forward
11046 (concat "<<" (regexp-quote s0) ">>") nil t)
11047 (setq type 'dedicated
11048 pos (match-beginning 0))))
11049 ;; There is an exact target for this
11050 (goto-char pos))
11051 ((save-excursion
11052 (goto-char (point-min))
11053 (and
11054 (re-search-forward
11055 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
11056 (setq type 'dedicated pos (match-beginning 0))))
11057 ;; Found an element with a matching #+name affiliated keyword.
11058 (goto-char pos))
11059 ((and (string-match "^(\\(.*\\))$" s0)
11060 (save-excursion
11061 (goto-char (point-min))
11062 (and
11063 (re-search-forward
11064 (concat "[^[]" (regexp-quote
11065 (format org-coderef-label-format
11066 (match-string 1 s0))))
11067 nil t)
11068 (setq type 'dedicated
11069 pos (1+ (match-beginning 0))))))
11070 ;; There is a coderef target for this
11071 (goto-char pos))
11072 ((string-match "^/\\(.*\\)/$" s)
11073 ;; A regular expression
11074 (cond
11075 ((derived-mode-p 'org-mode)
11076 (org-occur (match-string 1 s)))
11077 (t (org-do-occur (match-string 1 s)))))
11078 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11079 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11080 (goto-char (point-min))
11081 (cond
11082 ((let (case-fold-search)
11083 (re-search-forward (format org-complex-heading-regexp-format
11084 (regexp-quote s))
11085 nil t))
11086 ;; OK, found a match
11087 (setq type 'dedicated)
11088 (goto-char (match-beginning 0)))
11089 ((and (not org-link-search-inhibit-query)
11090 (eq org-link-search-must-match-exact-headline 'query-to-create)
11091 (y-or-n-p "No match - create this as a new heading? "))
11092 (goto-char (point-max))
11093 (or (bolp) (newline))
11094 (insert "* " s "\n")
11095 (beginning-of-line 0))
11097 (goto-char pos)
11098 (error "No match"))))
11100 ;; A normal search string
11101 (when (equal (string-to-char s) ?*)
11102 ;; Anchor on headlines, post may include tags.
11103 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11104 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11105 s (substring s 1)))
11106 (remove-text-properties
11107 0 (length s)
11108 '(face nil mouse-face nil keymap nil fontified nil) s)
11109 ;; Make a series of regular expressions to find a match
11110 (setq words (org-split-string s "[ \n\r\t]+")
11112 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11113 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11114 "\\)" markers)
11115 re2a_ (concat "\\(" (mapconcat 'downcase words
11116 "[ \t\r\n]+") "\\)[ \t\r\n]")
11117 re2a (concat "[ \t\r\n]" re2a_)
11118 re4_ (concat "\\(" (mapconcat 'downcase words
11119 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11120 re4 (concat "[^a-zA-Z_]" re4_)
11122 re1 (concat pre re2 post)
11123 re3 (concat pre (if pre re4_ re4) post)
11124 re5 (concat pre ".*" re4)
11125 re2 (concat pre re2)
11126 re2a (concat pre (if pre re2a_ re2a))
11127 re4 (concat pre (if pre re4_ re4))
11128 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11129 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11130 re5 "\\)"))
11131 (cond
11132 ((eq type 'org-occur) (org-occur reall))
11133 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11134 (t (goto-char (point-min))
11135 (setq type 'fuzzy)
11136 (if (or (and (org-search-not-self 1 re0 nil t)
11137 (setq type 'dedicated))
11138 (org-search-not-self 1 re1 nil t)
11139 (org-search-not-self 1 re2 nil t)
11140 (org-search-not-self 1 re2a nil t)
11141 (org-search-not-self 1 re3 nil t)
11142 (org-search-not-self 1 re4 nil t)
11143 (org-search-not-self 1 re5 nil t))
11144 (goto-char (match-beginning 1))
11145 (goto-char pos)
11146 (error "No match"))))))
11147 (and (derived-mode-p 'org-mode)
11148 (not stealth)
11149 (org-show-context 'link-search))
11150 type))
11152 (defun org-search-not-self (group &rest args)
11153 "Execute `re-search-forward', but only accept matches that do not
11154 enclose the position of `org-open-link-marker'."
11155 (let ((m org-open-link-marker))
11156 (catch 'exit
11157 (while (apply 're-search-forward args)
11158 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11159 (goto-char (match-end group))
11160 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11161 (> (match-beginning 0) (marker-position m))
11162 (< (match-end 0) (marker-position m)))
11163 (save-match-data
11164 (or (not (org-in-regexp
11165 org-bracket-link-analytic-regexp 1))
11166 (not (match-end 4)) ; no description
11167 (and (<= (match-beginning 4) (point))
11168 (>= (match-end 4) (point))))))
11169 (throw 'exit (point))))))))
11171 (defun org-get-buffer-for-internal-link (buffer)
11172 "Return a buffer to be used for displaying the link target of internal links."
11173 (cond
11174 ((not org-display-internal-link-with-indirect-buffer)
11175 buffer)
11176 ((string-match "(Clone)$" (buffer-name buffer))
11177 (message "Buffer is already a clone, not making another one")
11178 ;; we also do not modify visibility in this case
11179 buffer)
11180 (t ; make a new indirect buffer for displaying the link
11181 (let* ((bn (buffer-name buffer))
11182 (ibn (concat bn "(Clone)"))
11183 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11184 (with-current-buffer ib (org-overview))
11185 ib))))
11187 (defun org-do-occur (regexp &optional cleanup)
11188 "Call the Emacs command `occur'.
11189 If CLEANUP is non-nil, remove the printout of the regular expression
11190 in the *Occur* buffer. This is useful if the regex is long and not useful
11191 to read."
11192 (occur regexp)
11193 (when cleanup
11194 (let ((cwin (selected-window)) win beg end)
11195 (when (setq win (get-buffer-window "*Occur*"))
11196 (select-window win))
11197 (goto-char (point-min))
11198 (when (re-search-forward "match[a-z]+" nil t)
11199 (setq beg (match-end 0))
11200 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11201 (setq end (1- (match-beginning 0)))))
11202 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11203 (goto-char (point-min))
11204 (select-window cwin))))
11206 ;;; The mark ring for links jumps
11208 (defvar org-mark-ring nil
11209 "Mark ring for positions before jumps in Org-mode.")
11210 (defvar org-mark-ring-last-goto nil
11211 "Last position in the mark ring used to go back.")
11212 ;; Fill and close the ring
11213 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11214 (loop for i from 1 to org-mark-ring-length do
11215 (push (make-marker) org-mark-ring))
11216 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11217 org-mark-ring)
11219 (defun org-mark-ring-push (&optional pos buffer)
11220 "Put the current position or POS into the mark ring and rotate it."
11221 (interactive)
11222 (setq pos (or pos (point)))
11223 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11224 (move-marker (car org-mark-ring)
11225 (or pos (point))
11226 (or buffer (current-buffer)))
11227 (message "%s"
11228 (substitute-command-keys
11229 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11231 (defun org-mark-ring-goto (&optional n)
11232 "Jump to the previous position in the mark ring.
11233 With prefix arg N, jump back that many stored positions. When
11234 called several times in succession, walk through the entire ring.
11235 Org-mode commands jumping to a different position in the current file,
11236 or to another Org-mode file, automatically push the old position
11237 onto the ring."
11238 (interactive "p")
11239 (let (p m)
11240 (if (eq last-command this-command)
11241 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11242 (setq p org-mark-ring))
11243 (setq org-mark-ring-last-goto p)
11244 (setq m (car p))
11245 (org-pop-to-buffer-same-window (marker-buffer m))
11246 (goto-char m)
11247 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11249 (defun org-remove-angle-brackets (s)
11250 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11251 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11253 (defun org-add-angle-brackets (s)
11254 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11255 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11257 (defun org-remove-double-quotes (s)
11258 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11259 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11262 ;;; Following specific links
11264 (defun org-follow-timestamp-link ()
11265 "Open an agenda view for the time-stamp date/range at point."
11266 (cond
11267 ((org-at-date-range-p t)
11268 (let ((org-agenda-start-on-weekday)
11269 (t1 (match-string 1))
11270 (t2 (match-string 2)) tt1 tt2)
11271 (setq tt1 (time-to-days (org-time-string-to-time t1))
11272 tt2 (time-to-days (org-time-string-to-time t2)))
11273 (let ((org-agenda-buffer-tmp-name
11274 (format "*Org Agenda(a:%s)"
11275 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11276 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11277 ((org-at-timestamp-p t)
11278 (let ((org-agenda-buffer-tmp-name
11279 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11280 (org-agenda-list nil (time-to-days (org-time-string-to-time
11281 (substring (match-string 1) 0 10)))
11282 1)))
11283 (t (error "This should not happen"))))
11286 ;;; Following file links
11287 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11288 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11289 (declare-function mailcap-mime-info
11290 "mailcap" (string &optional request no-decode))
11291 (defvar org-wait nil)
11292 (defun org-open-file (path &optional in-emacs line search)
11293 "Open the file at PATH.
11294 First, this expands any special file name abbreviations. Then the
11295 configuration variable `org-file-apps' is checked if it contains an
11296 entry for this file type, and if yes, the corresponding command is launched.
11298 If no application is found, Emacs simply visits the file.
11300 With optional prefix argument IN-EMACS, Emacs will visit the file.
11301 With a double \\[universal-argument] \\[universal-argument] \
11302 prefix arg, Org tries to avoid opening in Emacs
11303 and to use an external application to visit the file.
11305 Optional LINE specifies a line to go to, optional SEARCH a string
11306 to search for. If LINE or SEARCH is given, the file will be
11307 opened in Emacs, unless an entry from org-file-apps that makes
11308 use of groups in a regexp matches.
11310 If you want to change the way frames are used when following a
11311 link, please customize `org-link-frame-setup'.
11313 If the file does not exist, an error is thrown."
11314 (let* ((file (if (equal path "")
11315 buffer-file-name
11316 (substitute-in-file-name (expand-file-name path))))
11317 (file-apps (append org-file-apps (org-default-apps)))
11318 (apps (org-remove-if
11319 'org-file-apps-entry-match-against-dlink-p file-apps))
11320 (apps-dlink (org-remove-if-not
11321 'org-file-apps-entry-match-against-dlink-p file-apps))
11322 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11323 (dirp (if remp nil (file-directory-p file)))
11324 (file (if (and dirp org-open-directory-means-index-dot-org)
11325 (concat (file-name-as-directory file) "index.org")
11326 file))
11327 (a-m-a-p (assq 'auto-mode apps))
11328 (dfile (downcase file))
11329 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11330 (link (cond ((and (eq line nil)
11331 (eq search nil))
11332 file)
11333 (line
11334 (concat file "::" (number-to-string line)))
11335 (search
11336 (concat file "::" search))))
11337 (dlink (downcase link))
11338 (old-buffer (current-buffer))
11339 (old-pos (point))
11340 (old-mode major-mode)
11341 ext cmd link-match-data)
11342 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11343 (setq ext (match-string 1 dfile))
11344 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11345 (setq ext (match-string 1 dfile))))
11346 (cond
11347 ((member in-emacs '((16) system))
11348 (setq cmd (cdr (assoc 'system apps))))
11349 (in-emacs (setq cmd 'emacs))
11351 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11352 (and dirp (cdr (assoc 'directory apps)))
11353 ; first, try matching against apps-dlink
11354 ; if we get a match here, store the match data for later
11355 (let ((match (assoc-default dlink apps-dlink
11356 'string-match)))
11357 (if match
11358 (progn (setq link-match-data (match-data))
11359 match)
11360 (progn (setq in-emacs (or in-emacs line search))
11361 nil))) ; if we have no match in apps-dlink,
11362 ; always open the file in emacs if line or search
11363 ; is given (for backwards compatibility)
11364 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11365 'string-match)
11366 (cdr (assoc ext apps))
11367 (cdr (assoc t apps))))))
11368 (when (eq cmd 'system)
11369 (setq cmd (cdr (assoc 'system apps))))
11370 (when (eq cmd 'default)
11371 (setq cmd (cdr (assoc t apps))))
11372 (when (eq cmd 'mailcap)
11373 (require 'mailcap)
11374 (mailcap-parse-mailcaps)
11375 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11376 (command (mailcap-mime-info mime-type)))
11377 (if (stringp command)
11378 (setq cmd command)
11379 (setq cmd 'emacs))))
11380 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11381 (not (file-exists-p file))
11382 (not org-open-non-existing-files))
11383 (user-error "No such file: %s" file))
11384 (cond
11385 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11386 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11387 (while (string-match "['\"]%s['\"]" cmd)
11388 (setq cmd (replace-match "%s" t t cmd)))
11389 (while (string-match "%s" cmd)
11390 (setq cmd (replace-match
11391 (save-match-data
11392 (shell-quote-argument
11393 (convert-standard-filename file)))
11394 t t cmd)))
11396 ;; Replace "%1", "%2" etc. in command with group matches from regex
11397 (save-match-data
11398 (let ((match-index 1)
11399 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11400 (set-match-data link-match-data)
11401 (while (<= match-index number-of-groups)
11402 (let ((regex (concat "%" (number-to-string match-index)))
11403 (replace-with (match-string match-index dlink)))
11404 (while (string-match regex cmd)
11405 (setq cmd (replace-match replace-with t t cmd))))
11406 (setq match-index (+ match-index 1)))))
11408 (save-window-excursion
11409 (message "Running %s...done" cmd)
11410 (start-process-shell-command cmd nil cmd)
11411 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11412 ((or (stringp cmd)
11413 (eq cmd 'emacs))
11414 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11415 (widen)
11416 (if line (progn (org-goto-line line)
11417 (if (derived-mode-p 'org-mode)
11418 (org-reveal)))
11419 (if search (org-link-search search))))
11420 ((consp cmd)
11421 (let ((file (convert-standard-filename file)))
11422 (save-match-data
11423 (set-match-data link-match-data)
11424 (eval cmd))))
11425 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11426 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11427 (or (not (equal old-buffer (current-buffer)))
11428 (not (equal old-pos (point))))
11429 (org-mark-ring-push old-pos old-buffer))))
11431 (defun org-file-apps-entry-match-against-dlink-p (entry)
11432 "This function returns non-nil if `entry' uses a regular
11433 expression which should be matched against the whole link by
11434 org-open-file.
11436 It assumes that is the case when the entry uses a regular
11437 expression which has at least one grouping construct and the
11438 action is either a lisp form or a command string containing
11439 '%1', i.e. using at least one subexpression match as a
11440 parameter."
11441 (let ((selector (car entry))
11442 (action (cdr entry)))
11443 (if (stringp selector)
11444 (and (> (regexp-opt-depth selector) 0)
11445 (or (and (stringp action)
11446 (string-match "%[0-9]" action))
11447 (consp action)))
11448 nil)))
11450 (defun org-default-apps ()
11451 "Return the default applications for this operating system."
11452 (cond
11453 ((eq system-type 'darwin)
11454 org-file-apps-defaults-macosx)
11455 ((eq system-type 'windows-nt)
11456 org-file-apps-defaults-windowsnt)
11457 (t org-file-apps-defaults-gnu)))
11459 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11460 "Convert extensions to regular expressions in the cars of LIST.
11461 Also, weed out any non-string entries, because the return value is used
11462 only for regexp matching.
11463 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11464 point to the symbol `emacs', indicating that the file should
11465 be opened in Emacs."
11466 (append
11467 (delq nil
11468 (mapcar (lambda (x)
11469 (if (not (stringp (car x)))
11471 (if (string-match "\\W" (car x))
11473 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11474 list))
11475 (if add-auto-mode
11476 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11478 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11479 (defun org-file-remote-p (file)
11480 "Test whether FILE specifies a location on a remote system.
11481 Return non-nil if the location is indeed remote.
11483 For example, the filename \"/user@host:/foo\" specifies a location
11484 on the system \"/user@host:\"."
11485 (cond ((fboundp 'file-remote-p)
11486 (file-remote-p file))
11487 ((fboundp 'tramp-handle-file-remote-p)
11488 (tramp-handle-file-remote-p file))
11489 ((and (boundp 'ange-ftp-name-format)
11490 (string-match (car ange-ftp-name-format) file))
11491 t)))
11494 ;;;; Refiling
11496 (defun org-get-org-file ()
11497 "Read a filename, with default directory `org-directory'."
11498 (let ((default (or org-default-notes-file remember-data-file)))
11499 (read-file-name (format "File name [%s]: " default)
11500 (file-name-as-directory org-directory)
11501 default)))
11503 (defun org-notes-order-reversed-p ()
11504 "Check if the current file should receive notes in reversed order."
11505 (cond
11506 ((not org-reverse-note-order) nil)
11507 ((eq t org-reverse-note-order) t)
11508 ((not (listp org-reverse-note-order)) nil)
11509 (t (catch 'exit
11510 (let ((all org-reverse-note-order)
11511 entry)
11512 (while (setq entry (pop all))
11513 (if (string-match (car entry) buffer-file-name)
11514 (throw 'exit (cdr entry))))
11515 nil)))))
11517 (defvar org-refile-target-table nil
11518 "The list of refile targets, created by `org-refile'.")
11520 (defvar org-agenda-new-buffers nil
11521 "Buffers created to visit agenda files.")
11523 (defvar org-refile-cache nil
11524 "Cache for refile targets.")
11526 (defvar org-refile-markers nil
11527 "All the markers used for caching refile locations.")
11529 (defun org-refile-marker (pos)
11530 "Get a new refile marker, but only if caching is in use."
11531 (if (not org-refile-use-cache)
11533 (let ((m (make-marker)))
11534 (move-marker m pos)
11535 (push m org-refile-markers)
11536 m)))
11538 (defun org-refile-cache-clear ()
11539 "Clear the refile cache and disable all the markers."
11540 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11541 (setq org-refile-markers nil)
11542 (setq org-refile-cache nil)
11543 (message "Refile cache has been cleared"))
11545 (defun org-refile-cache-check-set (set)
11546 "Check if all the markers in the cache still have live buffers."
11547 (let (marker)
11548 (catch 'exit
11549 (while (and set (setq marker (nth 3 (pop set))))
11550 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11551 (when (and marker (null (marker-buffer marker)))
11552 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11553 (sit-for 3)
11554 (throw 'exit nil)))
11555 t)))
11557 (defun org-refile-cache-put (set &rest identifiers)
11558 "Push the refile targets SET into the cache, under IDENTIFIERS."
11559 (let* ((key (sha1 (prin1-to-string identifiers)))
11560 (entry (assoc key org-refile-cache)))
11561 (if entry
11562 (setcdr entry set)
11563 (push (cons key set) org-refile-cache))))
11565 (defun org-refile-cache-get (&rest identifiers)
11566 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11567 (cond
11568 ((not org-refile-cache) nil)
11569 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11571 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11572 org-refile-cache))))
11573 (and set (org-refile-cache-check-set set) set)))))
11575 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11576 "Produce a table with refile targets."
11577 (let ((case-fold-search nil)
11578 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11579 (entries (or org-refile-targets '((nil . (:level . 1)))))
11580 targets tgs txt re files f desc descre fast-path-p level pos0)
11581 (message "Getting targets...")
11582 (with-current-buffer (or default-buffer (current-buffer))
11583 (while (setq entry (pop entries))
11584 (setq files (car entry) desc (cdr entry))
11585 (setq fast-path-p nil)
11586 (cond
11587 ((null files) (setq files (list (current-buffer))))
11588 ((eq files 'org-agenda-files)
11589 (setq files (org-agenda-files 'unrestricted)))
11590 ((and (symbolp files) (fboundp files))
11591 (setq files (funcall files)))
11592 ((and (symbolp files) (boundp files))
11593 (setq files (symbol-value files))))
11594 (if (stringp files) (setq files (list files)))
11595 (cond
11596 ((eq (car desc) :tag)
11597 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11598 ((eq (car desc) :todo)
11599 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11600 ((eq (car desc) :regexp)
11601 (setq descre (cdr desc)))
11602 ((eq (car desc) :level)
11603 (setq descre (concat "^\\*\\{" (number-to-string
11604 (if org-odd-levels-only
11605 (1- (* 2 (cdr desc)))
11606 (cdr desc)))
11607 "\\}[ \t]")))
11608 ((eq (car desc) :maxlevel)
11609 (setq fast-path-p t)
11610 (setq descre (concat "^\\*\\{1," (number-to-string
11611 (if org-odd-levels-only
11612 (1- (* 2 (cdr desc)))
11613 (cdr desc)))
11614 "\\}[ \t]")))
11615 (t (error "Bad refiling target description %s" desc)))
11616 (while (setq f (pop files))
11617 (with-current-buffer
11618 (if (bufferp f) f (org-get-agenda-file-buffer f))
11620 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11621 (progn
11622 (if (bufferp f) (setq f (buffer-file-name
11623 (buffer-base-buffer f))))
11624 (setq f (and f (expand-file-name f)))
11625 (if (eq org-refile-use-outline-path 'file)
11626 (push (list (file-name-nondirectory f) f nil nil) tgs))
11627 (save-excursion
11628 (save-restriction
11629 (widen)
11630 (goto-char (point-min))
11631 (while (re-search-forward descre nil t)
11632 (goto-char (setq pos0 (point-at-bol)))
11633 (catch 'next
11634 (when org-refile-target-verify-function
11635 (save-match-data
11636 (or (funcall org-refile-target-verify-function)
11637 (throw 'next t))))
11638 (when (and (looking-at org-complex-heading-regexp)
11639 (not (member (match-string 4) excluded-entries))
11640 (match-string 4))
11641 (setq level (org-reduced-level
11642 (- (match-end 1) (match-beginning 1)))
11643 txt (org-link-display-format (match-string 4))
11644 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11645 re (format org-complex-heading-regexp-format
11646 (regexp-quote (match-string 4))))
11647 (when org-refile-use-outline-path
11648 (setq txt (mapconcat
11649 'org-protect-slash
11650 (append
11651 (if (eq org-refile-use-outline-path
11652 'file)
11653 (list (file-name-nondirectory
11654 (buffer-file-name
11655 (buffer-base-buffer))))
11656 (if (eq org-refile-use-outline-path
11657 'full-file-path)
11658 (list (buffer-file-name
11659 (buffer-base-buffer)))))
11660 (org-get-outline-path fast-path-p
11661 level txt)
11662 (list txt))
11663 "/")))
11664 (push (list txt f re (org-refile-marker (point)))
11665 tgs)))
11666 (when (= (point) pos0)
11667 ;; verification function has not moved point
11668 (goto-char (point-at-eol))))))))
11669 (when org-refile-use-cache
11670 (org-refile-cache-put tgs (buffer-file-name) descre))
11671 (setq targets (append tgs targets))))))
11672 (message "Getting targets...done")
11673 (nreverse targets)))
11675 (defun org-protect-slash (s)
11676 (while (string-match "/" s)
11677 (setq s (replace-match "\\" t t s)))
11680 (defvar org-olpa (make-vector 20 nil))
11682 (defun org-get-outline-path (&optional fastp level heading)
11683 "Return the outline path to the current entry, as a list.
11685 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11686 routine which makes outline path derivations for an entire file,
11687 avoiding backtracing. Refile target collection makes use of that."
11688 (if fastp
11689 (progn
11690 (if (> level 19)
11691 (error "Outline path failure, more than 19 levels"))
11692 (loop for i from level upto 19 do
11693 (aset org-olpa i nil))
11694 (prog1
11695 (delq nil (append org-olpa nil))
11696 (aset org-olpa level heading)))
11697 (let (rtn case-fold-search)
11698 (save-excursion
11699 (save-restriction
11700 (widen)
11701 (while (org-up-heading-safe)
11702 (when (looking-at org-complex-heading-regexp)
11703 (push (org-trim
11704 (replace-regexp-in-string
11705 ;; Remove statistical/checkboxes cookies
11706 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11707 (org-match-string-no-properties 4)))
11708 rtn)))
11709 rtn)))))
11711 (defun org-format-outline-path (path &optional width prefix separator)
11712 "Format the outline path PATH for display.
11713 WIDTH is the maximum number of characters that is available.
11714 PREFIX is a prefix to be included in the returned string,
11715 such as the file name.
11716 SEPARATOR is inserted between the different parts of the path,
11717 the default is \"/\"."
11718 (setq width (or width 79))
11719 (if prefix (setq width (- width (length prefix))))
11720 (if (not path)
11721 (or prefix "")
11722 (let* ((nsteps (length path))
11723 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11724 (maxwidth (if (<= total-width width)
11725 10000 ;; everything fits
11726 ;; we need to shorten the level headings
11727 (/ (- width nsteps) nsteps)))
11728 (org-odd-levels-only nil)
11729 (n 0)
11730 (total (1+ (length prefix))))
11731 (setq maxwidth (max maxwidth 10))
11732 (concat prefix
11733 (if prefix (or separator "/"))
11734 (mapconcat
11735 (lambda (h)
11736 (setq n (1+ n))
11737 (if (and (= n nsteps) (< maxwidth 10000))
11738 (setq maxwidth (- total-width total)))
11739 (if (< (length h) maxwidth)
11740 (progn (setq total (+ total (length h) 1)) h)
11741 (setq h (substring h 0 (- maxwidth 2))
11742 total (+ total maxwidth 1))
11743 (if (string-match "[ \t]+\\'" h)
11744 (setq h (substring h 0 (match-beginning 0))))
11745 (setq h (concat h "..")))
11746 (org-add-props h nil 'face
11747 (nth (% (1- n) org-n-level-faces)
11748 org-level-faces))
11750 path (or separator "/"))))))
11752 (defun org-display-outline-path (&optional file current separator just-return-string)
11753 "Display the current outline path in the echo area.
11755 If FILE is non-nil, prepend the output with the file name.
11756 If CURRENT is non-nil, append the current heading to the output.
11757 SEPARATOR is passed through to `org-format-outline-path'. It separates
11758 the different parts of the path and defaults to \"/\".
11759 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11760 (interactive "P")
11761 (let* (case-fold-search
11762 (bfn (buffer-file-name (buffer-base-buffer)))
11763 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11764 res)
11765 (if current (setq path (append path
11766 (save-excursion
11767 (org-back-to-heading t)
11768 (if (looking-at org-complex-heading-regexp)
11769 (list (match-string 4)))))))
11770 (setq res
11771 (org-format-outline-path
11772 path
11773 (1- (frame-width))
11774 (and file bfn (concat (file-name-nondirectory bfn) separator))
11775 separator))
11776 (if just-return-string
11777 (org-no-properties res)
11778 (org-unlogged-message "%s" res))))
11780 (defvar org-refile-history nil
11781 "History for refiling operations.")
11783 (defvar org-after-refile-insert-hook nil
11784 "Hook run after `org-refile' has inserted its stuff at the new location.
11785 Note that this is still *before* the stuff will be removed from
11786 the *old* location.")
11788 (defvar org-capture-last-stored-marker)
11789 (defvar org-refile-keep nil
11790 "Non-nil means `org-refile' will copy instead of refile.")
11792 (defun org-copy ()
11793 "Like `org-refile', but copy."
11794 (interactive)
11795 (let ((org-refile-keep t))
11796 (funcall 'org-refile nil nil nil "Copy")))
11798 (defun org-refile (&optional arg default-buffer rfloc msg)
11799 "Move the entry or entries at point to another heading.
11800 The list of target headings is compiled using the information in
11801 `org-refile-targets', which see.
11803 At the target location, the entry is filed as a subitem of the
11804 target heading. Depending on `org-reverse-note-order', the new
11805 subitem will either be the first or the last subitem.
11807 If there is an active region, all entries in that region will be
11808 refiled. However, the region must fulfill the requirement that
11809 the first heading sets the top-level of the moved text.
11811 With prefix arg ARG, the command will only visit the target
11812 location and not actually move anything.
11814 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11815 refiling operation has put the subtree.
11817 With a numeric prefix argument of `2', refile to the running clock.
11819 With a numeric prefix argument of `3', emulate `org-refile-keep'
11820 being set to `t' and copy to the target location, don't move it.
11821 Beware that keeping refiled entries may result in duplicated ID
11822 properties.
11824 RFLOC can be a refile location obtained in a different way.
11826 MSG is a string to replace \"Refile\" in the default prompt with
11827 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11829 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11831 If you are using target caching (see `org-refile-use-cache'), you
11832 have to clear the target cache in order to find new targets.
11833 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11834 prefix argument (`C-u C-u C-u C-c C-w')."
11835 (interactive "P")
11836 (if (member arg '(0 (64)))
11837 (org-refile-cache-clear)
11838 (let* ((actionmsg (cond (msg msg)
11839 ((equal arg 3) "Refile (and keep)")
11840 (t "Refile")))
11841 (cbuf (current-buffer))
11842 (regionp (org-region-active-p))
11843 (region-start (and regionp (region-beginning)))
11844 (region-end (and regionp (region-end)))
11845 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11846 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11847 pos it nbuf file re level reversed)
11848 (setq last-command nil)
11849 (when regionp
11850 (goto-char region-start)
11851 (or (bolp) (goto-char (point-at-bol)))
11852 (setq region-start (point))
11853 (unless (or (org-kill-is-subtree-p
11854 (buffer-substring region-start region-end))
11855 (prog1 org-refile-active-region-within-subtree
11856 (let ((s (point-at-eol)))
11857 (org-toggle-heading)
11858 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11859 (user-error "The region is not a (sequence of) subtree(s)")))
11860 (if (equal arg '(16))
11861 (org-refile-goto-last-stored)
11862 (when (or
11863 (and (equal arg 2)
11864 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11865 (prog1
11866 (setq it (list (or org-clock-heading "running clock")
11867 (buffer-file-name
11868 (marker-buffer org-clock-hd-marker))
11870 (marker-position org-clock-hd-marker)))
11871 (setq arg nil)))
11872 (setq it (or rfloc
11873 (let (heading-text)
11874 (save-excursion
11875 (unless (and arg (listp arg))
11876 (org-back-to-heading t)
11877 (setq heading-text
11878 (replace-regexp-in-string
11879 org-bracket-link-regexp
11880 "\\3"
11881 (nth 4 (org-heading-components)))))
11882 (org-refile-get-location
11883 (cond ((and arg (listp arg)) "Goto")
11884 (regionp (concat actionmsg " region to"))
11885 (t (concat actionmsg " subtree \""
11886 heading-text "\" to")))
11887 default-buffer
11888 (and (not (equal '(4) arg))
11889 org-refile-allow-creating-parent-nodes)
11890 arg))))))
11891 (setq file (nth 1 it)
11892 re (nth 2 it)
11893 pos (nth 3 it))
11894 (if (and (not arg)
11896 (equal (buffer-file-name) file)
11897 (if regionp
11898 (and (>= pos region-start)
11899 (<= pos region-end))
11900 (and (>= pos (point))
11901 (< pos (save-excursion
11902 (org-end-of-subtree t t))))))
11903 (error "Cannot refile to position inside the tree or region"))
11904 (setq nbuf (or (find-buffer-visiting file)
11905 (find-file-noselect file)))
11906 (if (and arg (not (equal arg 3)))
11907 (progn
11908 (org-pop-to-buffer-same-window nbuf)
11909 (goto-char pos)
11910 (org-show-context 'org-goto))
11911 (if regionp
11912 (progn
11913 (org-kill-new (buffer-substring region-start region-end))
11914 (org-save-markers-in-region region-start region-end))
11915 (org-copy-subtree 1 nil t))
11916 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11917 (find-file-noselect file)))
11918 (setq reversed (org-notes-order-reversed-p))
11919 (save-excursion
11920 (save-restriction
11921 (widen)
11922 (if pos
11923 (progn
11924 (goto-char pos)
11925 (looking-at org-outline-regexp)
11926 (setq level (org-get-valid-level (funcall outline-level) 1))
11927 (goto-char
11928 (if reversed
11929 (or (outline-next-heading) (point-max))
11930 (or (save-excursion (org-get-next-sibling))
11931 (org-end-of-subtree t t)
11932 (point-max)))))
11933 (setq level 1)
11934 (if (not reversed)
11935 (goto-char (point-max))
11936 (goto-char (point-min))
11937 (or (outline-next-heading) (goto-char (point-max)))))
11938 (if (not (bolp)) (newline))
11939 (org-paste-subtree level nil nil t)
11940 (when org-log-refile
11941 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11942 (unless (eq org-log-refile 'note)
11943 (save-excursion (org-add-log-note))))
11944 (and org-auto-align-tags
11945 (let ((org-loop-over-headlines-in-active-region nil))
11946 (org-set-tags nil t)))
11947 (let ((bookmark-name (plist-get org-bookmark-names-plist
11948 :last-refile)))
11949 (when bookmark-name
11950 (with-demoted-errors
11951 (bookmark-set bookmark-name))))
11952 ;; If we are refiling for capture, make sure that the
11953 ;; last-capture pointers point here
11954 (when (org-bound-and-true-p org-refile-for-capture)
11955 (let ((bookmark-name (plist-get org-bookmark-names-plist
11956 :last-capture-marker)))
11957 (when bookmark-name
11958 (with-demoted-errors
11959 (bookmark-set bookmark-name))))
11960 (move-marker org-capture-last-stored-marker (point)))
11961 (if (fboundp 'deactivate-mark) (deactivate-mark))
11962 (run-hooks 'org-after-refile-insert-hook))))
11963 (unless org-refile-keep
11964 (if regionp
11965 (delete-region (point) (+ (point) (- region-end region-start)))
11966 (delete-region
11967 (and (org-back-to-heading t) (point))
11968 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11969 (when (featurep 'org-inlinetask)
11970 (org-inlinetask-remove-END-maybe))
11971 (setq org-markers-to-move nil)
11972 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11974 (defun org-refile-goto-last-stored ()
11975 "Go to the location where the last refile was stored."
11976 (interactive)
11977 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11978 (message "This is the location of the last refile"))
11980 (defun org-refile--get-location (refloc tbl)
11981 "When user refile to REFLOC, find the associated target in TBL.
11982 Also check `org-refile-target-table'."
11983 (car (delq
11985 (mapcar
11986 (lambda (r) (or (assoc r tbl)
11987 (assoc r org-refile-target-table)))
11988 (list (replace-regexp-in-string "/$" "" refloc)
11989 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11991 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11992 no-exclude)
11993 "Prompt the user for a refile location, using PROMPT.
11994 PROMPT should not be suffixed with a colon and a space, because
11995 this function appends the default value from
11996 `org-refile-history' automatically, if that is not empty.
11997 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11998 this is used for the GOTO interface."
11999 (let ((org-refile-targets org-refile-targets)
12000 (org-refile-use-outline-path org-refile-use-outline-path)
12001 excluded-entries)
12002 (when (and (derived-mode-p 'org-mode)
12003 (not org-refile-use-cache)
12004 (not no-exclude))
12005 (org-map-tree
12006 (lambda()
12007 (setq excluded-entries
12008 (append excluded-entries (list (org-get-heading t t)))))))
12009 (setq org-refile-target-table
12010 (org-refile-get-targets default-buffer excluded-entries)))
12011 (unless org-refile-target-table
12012 (user-error "No refile targets"))
12013 (let* ((cbuf (current-buffer))
12014 (partial-completion-mode nil)
12015 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12016 (cfunc (if (and org-refile-use-outline-path
12017 org-outline-path-complete-in-steps)
12018 'org-olpath-completing-read
12019 'org-icompleting-read))
12020 (extra (if org-refile-use-outline-path "/" ""))
12021 (cbnex (concat (buffer-name) extra))
12022 (filename (and cfn (expand-file-name cfn)))
12023 (tbl (mapcar
12024 (lambda (x)
12025 (if (and (not (member org-refile-use-outline-path
12026 '(file full-file-path)))
12027 (not (equal filename (nth 1 x))))
12028 (cons (concat (car x) extra " ("
12029 (file-name-nondirectory (nth 1 x)) ")")
12030 (cdr x))
12031 (cons (concat (car x) extra) (cdr x))))
12032 org-refile-target-table))
12033 (completion-ignore-case t)
12034 cdef
12035 (prompt (concat prompt
12036 (or (and (car org-refile-history)
12037 (concat " (default " (car org-refile-history) ")"))
12038 (and (assoc cbnex tbl) (setq cdef cbnex)
12039 (concat " (default " cbnex ")"))) ": "))
12040 pa answ parent-target child parent old-hist)
12041 (setq old-hist org-refile-history)
12042 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12043 nil 'org-refile-history (or cdef (car org-refile-history))))
12044 (if (setq pa (org-refile--get-location answ tbl))
12045 (progn
12046 (org-refile-check-position pa)
12047 (when (or (not org-refile-history)
12048 (not (eq old-hist org-refile-history))
12049 (not (equal (car pa) (car org-refile-history))))
12050 (setq org-refile-history
12051 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12052 org-refile-history
12053 (cdr org-refile-history))))
12054 (if (equal (car org-refile-history) (nth 1 org-refile-history))
12055 (pop org-refile-history)))
12057 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12058 (progn
12059 (setq parent (match-string 1 answ)
12060 child (match-string 2 answ))
12061 (setq parent-target (org-refile--get-location parent tbl))
12062 (when (and parent-target
12063 (or (eq new-nodes t)
12064 (and (eq new-nodes 'confirm)
12065 (y-or-n-p (format "Create new node \"%s\"? "
12066 child)))))
12067 (org-refile-new-child parent-target child)))
12068 (user-error "Invalid target location")))))
12070 (declare-function org-string-nw-p "org-macs" (s))
12071 (defun org-refile-check-position (refile-pointer)
12072 "Check if the refile pointer matches the headline to which it points."
12073 (let* ((file (nth 1 refile-pointer))
12074 (re (nth 2 refile-pointer))
12075 (pos (nth 3 refile-pointer))
12076 buffer)
12077 (if (and (not (markerp pos)) (not file))
12078 (user-error "Please indicate a target file in the refile path")
12079 (when (org-string-nw-p re)
12080 (setq buffer (if (markerp pos)
12081 (marker-buffer pos)
12082 (or (find-buffer-visiting file)
12083 (find-file-noselect file))))
12084 (with-current-buffer buffer
12085 (save-excursion
12086 (save-restriction
12087 (widen)
12088 (goto-char pos)
12089 (beginning-of-line 1)
12090 (unless (org-looking-at-p re)
12091 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12093 (defun org-refile-new-child (parent-target child)
12094 "Use refile target PARENT-TARGET to add new CHILD below it."
12095 (unless parent-target
12096 (error "Cannot find parent for new node"))
12097 (let ((file (nth 1 parent-target))
12098 (pos (nth 3 parent-target))
12099 level)
12100 (with-current-buffer (or (find-buffer-visiting file)
12101 (find-file-noselect file))
12102 (save-excursion
12103 (save-restriction
12104 (widen)
12105 (if pos
12106 (goto-char pos)
12107 (goto-char (point-max))
12108 (if (not (bolp)) (newline)))
12109 (when (looking-at org-outline-regexp)
12110 (setq level (funcall outline-level))
12111 (org-end-of-subtree t t))
12112 (org-back-over-empty-lines)
12113 (insert "\n" (make-string
12114 (if pos (org-get-valid-level level 1) 1) ?*)
12115 " " child "\n")
12116 (beginning-of-line 0)
12117 (list (concat (car parent-target) "/" child) file "" (point)))))))
12119 (defun org-olpath-completing-read (prompt collection &rest args)
12120 "Read an outline path like a file name."
12121 (let ((thetable collection)
12122 (org-completion-use-ido nil) ; does not work with ido.
12123 (org-completion-use-iswitchb nil)) ; or iswitchb
12124 (apply
12125 'org-icompleting-read prompt
12126 (lambda (string predicate &optional flag)
12127 (let (rtn r f (l (length string)))
12128 (cond
12129 ((eq flag nil)
12130 ;; try completion
12131 (try-completion string thetable))
12132 ((eq flag t)
12133 ;; all-completions
12134 (setq rtn (all-completions string thetable predicate))
12135 (mapcar
12136 (lambda (x)
12137 (setq r (substring x l))
12138 (if (string-match " ([^)]*)$" x)
12139 (setq f (match-string 0 x))
12140 (setq f ""))
12141 (if (string-match "/" r)
12142 (concat string (substring r 0 (match-end 0)) f)
12144 rtn))
12145 ((eq flag 'lambda)
12146 ;; exact match?
12147 (assoc string thetable)))))
12148 args)))
12150 ;;;; Dynamic blocks
12152 (defun org-find-dblock (name)
12153 "Find the first dynamic block with name NAME in the buffer.
12154 If not found, stay at current position and return nil."
12155 (let ((case-fold-search t) pos)
12156 (save-excursion
12157 (goto-char (point-min))
12158 (setq pos (and (re-search-forward
12159 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12160 (match-beginning 0))))
12161 (if pos (goto-char pos))
12162 pos))
12164 (defun org-create-dblock (plist)
12165 "Create a dynamic block section, with parameters taken from PLIST.
12166 PLIST must contain a :name entry which is used as the name of the block."
12167 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12168 (end-of-line 1)
12169 (newline))
12170 (let ((col (current-column))
12171 (name (plist-get plist :name)))
12172 (insert "#+BEGIN: " name)
12173 (while plist
12174 (if (eq (car plist) :name)
12175 (setq plist (cddr plist))
12176 (insert " " (prin1-to-string (pop plist)))))
12177 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12178 (beginning-of-line -2)))
12180 (defun org-prepare-dblock ()
12181 "Prepare dynamic block for refresh.
12182 This empties the block, puts the cursor at the insert position and returns
12183 the property list including an extra property :name with the block name."
12184 (unless (looking-at org-dblock-start-re)
12185 (user-error "Not at a dynamic block"))
12186 (let* ((begdel (1+ (match-end 0)))
12187 (name (org-no-properties (match-string 1)))
12188 (params (append (list :name name)
12189 (read (concat "(" (match-string 3) ")")))))
12190 (save-excursion
12191 (beginning-of-line 1)
12192 (skip-chars-forward " \t")
12193 (setq params (plist-put params :indentation-column (current-column))))
12194 (unless (re-search-forward org-dblock-end-re nil t)
12195 (error "Dynamic block not terminated"))
12196 (setq params
12197 (append params
12198 (list :content (buffer-substring
12199 begdel (match-beginning 0)))))
12200 (delete-region begdel (match-beginning 0))
12201 (goto-char begdel)
12202 (open-line 1)
12203 params))
12205 (defun org-map-dblocks (&optional command)
12206 "Apply COMMAND to all dynamic blocks in the current buffer.
12207 If COMMAND is not given, use `org-update-dblock'."
12208 (let ((cmd (or command 'org-update-dblock)))
12209 (save-excursion
12210 (goto-char (point-min))
12211 (while (re-search-forward org-dblock-start-re nil t)
12212 (goto-char (match-beginning 0))
12213 (save-excursion
12214 (condition-case nil
12215 (funcall cmd)
12216 (error (message "Error during update of dynamic block"))))
12217 (unless (re-search-forward org-dblock-end-re nil t)
12218 (error "Dynamic block not terminated"))))))
12220 (defun org-dblock-update (&optional arg)
12221 "User command for updating dynamic blocks.
12222 Update the dynamic block at point. With prefix ARG, update all dynamic
12223 blocks in the buffer."
12224 (interactive "P")
12225 (if arg
12226 (org-update-all-dblocks)
12227 (or (looking-at org-dblock-start-re)
12228 (org-beginning-of-dblock))
12229 (org-update-dblock)))
12231 (defun org-update-dblock ()
12232 "Update the dynamic block at point.
12233 This means to empty the block, parse for parameters and then call
12234 the correct writing function."
12235 (interactive)
12236 (save-excursion
12237 (let* ((win (selected-window))
12238 (pos (point))
12239 (line (org-current-line))
12240 (params (org-prepare-dblock))
12241 (name (plist-get params :name))
12242 (indent (plist-get params :indentation-column))
12243 (cmd (intern (concat "org-dblock-write:" name))))
12244 (message "Updating dynamic block `%s' at line %d..." name line)
12245 (funcall cmd params)
12246 (message "Updating dynamic block `%s' at line %d...done" name line)
12247 (goto-char pos)
12248 (when (and indent (> indent 0))
12249 (setq indent (make-string indent ?\ ))
12250 (save-excursion
12251 (select-window win)
12252 (org-beginning-of-dblock)
12253 (forward-line 1)
12254 (while (not (looking-at org-dblock-end-re))
12255 (insert indent)
12256 (beginning-of-line 2))
12257 (when (looking-at org-dblock-end-re)
12258 (and (looking-at "[ \t]+")
12259 (replace-match ""))
12260 (insert indent)))))))
12262 (defun org-beginning-of-dblock ()
12263 "Find the beginning of the dynamic block at point.
12264 Error if there is no such block at point."
12265 (let ((pos (point))
12266 beg)
12267 (end-of-line 1)
12268 (if (and (re-search-backward org-dblock-start-re nil t)
12269 (setq beg (match-beginning 0))
12270 (re-search-forward org-dblock-end-re nil t)
12271 (> (match-end 0) pos))
12272 (goto-char beg)
12273 (goto-char pos)
12274 (error "Not in a dynamic block"))))
12276 (defun org-update-all-dblocks ()
12277 "Update all dynamic blocks in the buffer.
12278 This function can be used in a hook."
12279 (interactive)
12280 (when (derived-mode-p 'org-mode)
12281 (org-map-dblocks 'org-update-dblock)))
12284 ;;;; Completion
12286 (declare-function org-export-backend-name "org-export" (cl-x))
12287 (declare-function org-export-backend-options "org-export" (cl-x))
12288 (defun org-get-export-keywords ()
12289 "Return a list of all currently understood export keywords.
12290 Export keywords include options, block names, attributes and
12291 keywords relative to each registered export back-end."
12292 (let (keywords)
12293 (dolist (backend
12294 (org-bound-and-true-p org-export--registered-backends)
12295 (delq nil keywords))
12296 ;; Back-end name (for keywords, like #+LATEX:)
12297 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12298 (dolist (option-entry (org-export-backend-options backend))
12299 ;; Back-end options.
12300 (push (nth 1 option-entry) keywords)))))
12302 (defconst org-options-keywords
12303 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12304 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12305 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12306 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12307 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12309 (defcustom org-structure-template-alist
12310 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12311 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12312 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12313 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12314 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12315 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12316 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12317 ("L" "#+LaTeX: ")
12318 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12319 ("H" "#+HTML: ")
12320 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12321 ("A" "#+ASCII: ")
12322 ("i" "#+INDEX: ?")
12323 ("I" "#+INCLUDE: %file ?"))
12324 "Structure completion elements.
12325 This is a list of abbreviation keys and values. The value gets inserted
12326 if you type `<' followed by the key and then press the completion key,
12327 usually `TAB'. %file will be replaced by a file name after prompting
12328 for the file using completion. The cursor will be placed at the position
12329 of the `?` in the template.
12330 There are two templates for each key, the first uses the original Org syntax,
12331 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12332 the default when the /org-mtags.el/ module has been loaded. See also the
12333 variable `org-mtags-prefer-muse-templates'."
12334 :group 'org-completion
12335 :type '(repeat
12336 (list
12337 (string :tag "Key")
12338 (string :tag "Template")))
12339 :version "25.1"
12340 :package-version '(Org . "8.3"))
12342 (defun org-try-structure-completion ()
12343 "Try to complete a structure template before point.
12344 This looks for strings like \"<e\" on an otherwise empty line and
12345 expands them."
12346 (let ((l (buffer-substring (point-at-bol) (point)))
12348 (when (and (looking-at "[ \t]*$")
12349 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12350 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12351 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12352 (match-beginning 1)) a)
12353 t)))
12355 (defun org-complete-expand-structure-template (start cell)
12356 "Expand a structure template."
12357 (let ((rpl (nth 1 cell))
12358 (ind ""))
12359 (delete-region start (point))
12360 (when (string-match "\\`[ \t]*#\\+" rpl)
12361 (cond
12362 ((bolp))
12363 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12364 (setq ind (buffer-substring (point-at-bol) (point))))
12365 (t (newline))))
12366 (setq start (point))
12367 (if (string-match "%file" rpl)
12368 (setq rpl (replace-match
12369 (concat
12370 "\""
12371 (save-match-data
12372 (abbreviate-file-name (read-file-name "Include file: ")))
12373 "\"")
12374 t t rpl)))
12375 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12376 (concat "\n" ind)))
12377 (insert rpl)
12378 (if (re-search-backward "\\?" start t) (delete-char 1))))
12380 ;;;; TODO, DEADLINE, Comments
12382 (defun org-toggle-comment ()
12383 "Change the COMMENT state of an entry."
12384 (interactive)
12385 (save-excursion
12386 (org-back-to-heading)
12387 (looking-at org-complex-heading-regexp)
12388 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12389 (skip-chars-forward " \t")
12390 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12391 (if (org-in-commented-heading-p t)
12392 (delete-region (point)
12393 (progn (search-forward " " (line-end-position) 'move)
12394 (skip-chars-forward " \t")
12395 (point)))
12396 (insert org-comment-string)
12397 (unless (eolp) (insert " ")))))
12399 (defvar org-last-todo-state-is-todo nil
12400 "This is non-nil when the last TODO state change led to a TODO state.
12401 If the last change removed the TODO tag or switched to DONE, then
12402 this is nil.")
12404 (defvar org-setting-tags nil) ; dynamically skipped
12406 (defvar org-todo-setup-filter-hook nil
12407 "Hook for functions that pre-filter todo specs.
12408 Each function takes a todo spec and returns either nil or the spec
12409 transformed into canonical form." )
12411 (defvar org-todo-get-default-hook nil
12412 "Hook for functions that get a default item for todo.
12413 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12414 nil or a string to be used for the todo mark." )
12416 (defvar org-agenda-headline-snapshot-before-repeat)
12418 (defun org-current-effective-time ()
12419 "Return current time adjusted for `org-extend-today-until' variable."
12420 (let* ((ct (org-current-time))
12421 (dct (decode-time ct))
12422 (ct1
12423 (cond
12424 (org-use-last-clock-out-time-as-effective-time
12425 (or (org-clock-get-last-clock-out-time) ct))
12426 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12427 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12428 (t ct))))
12429 ct1))
12431 (defun org-todo-yesterday (&optional arg)
12432 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12433 (interactive "P")
12434 (if (eq major-mode 'org-agenda-mode)
12435 (apply 'org-agenda-todo-yesterday arg)
12436 (let* ((org-use-effective-time t)
12437 (hour (third (decode-time
12438 (org-current-time))))
12439 (org-extend-today-until (1+ hour)))
12440 (org-todo arg))))
12442 (defvar org-block-entry-blocking ""
12443 "First entry preventing the TODO state change.")
12445 (defun org-cancel-repeater ()
12446 "Cancel a repeater by setting its numeric value to zero."
12447 (interactive)
12448 (save-excursion
12449 (org-back-to-heading t)
12450 (let ((bound1 (point))
12451 (bound0 (save-excursion (outline-next-heading) (point))))
12452 (when (re-search-forward
12453 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12454 org-deadline-time-regexp "\\)\\|\\("
12455 org-ts-regexp "\\)")
12456 bound0 t)
12457 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12458 (replace-match "0" t nil nil 1))))))
12460 (defun org-todo (&optional arg)
12461 "Change the TODO state of an item.
12462 The state of an item is given by a keyword at the start of the heading,
12463 like
12464 *** TODO Write paper
12465 *** DONE Call mom
12467 The different keywords are specified in the variable `org-todo-keywords'.
12468 By default the available states are \"TODO\" and \"DONE\".
12469 So for this example: when the item starts with TODO, it is changed to DONE.
12470 When it starts with DONE, the DONE is removed. And when neither TODO nor
12471 DONE are present, add TODO at the beginning of the heading.
12473 With \\[universal-argument] prefix arg, use completion to determine the new \
12474 state.
12475 With numeric prefix arg, switch to that state.
12476 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12477 keywords (nextset).
12478 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12479 With a numeric prefix arg of 0, inhibit note taking for the change.
12480 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12482 When called through ELisp, arg is also interpreted in the following way:
12483 'none -> empty state
12484 \"\"(empty string) -> switch to empty state
12485 'done -> switch to DONE
12486 'nextset -> switch to the next set of keywords
12487 'previousset -> switch to the previous set of keywords
12488 \"WAITING\" -> switch to the specified keyword, but only if it
12489 really is a member of `org-todo-keywords'."
12490 (interactive "P")
12491 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12492 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12493 'region-start-level 'region))
12494 org-loop-over-headlines-in-active-region)
12495 (org-map-entries
12496 `(org-todo ,arg)
12497 org-loop-over-headlines-in-active-region
12498 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12499 (if (equal arg '(16)) (setq arg 'nextset))
12500 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12501 (let ((org-blocker-hook org-blocker-hook)
12502 commentp
12503 case-fold-search)
12504 (when (equal arg '(64))
12505 (setq arg nil org-blocker-hook nil))
12506 (when (and org-blocker-hook
12507 (or org-inhibit-blocking
12508 (org-entry-get nil "NOBLOCKING")))
12509 (setq org-blocker-hook nil))
12510 (save-excursion
12511 (catch 'exit
12512 (org-back-to-heading t)
12513 (when (org-in-commented-heading-p t)
12514 (org-toggle-comment)
12515 (setq commentp t))
12516 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12517 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12518 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12519 (let* ((match-data (match-data))
12520 (startpos (point-at-bol))
12521 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12522 (org-log-done org-log-done)
12523 (org-log-repeat org-log-repeat)
12524 (org-todo-log-states org-todo-log-states)
12525 (org-inhibit-logging
12526 (if (equal arg 0)
12527 (progn (setq arg nil) 'note) org-inhibit-logging))
12528 (this (match-string 1))
12529 (hl-pos (match-beginning 0))
12530 (head (org-get-todo-sequence-head this))
12531 (ass (assoc head org-todo-kwd-alist))
12532 (interpret (nth 1 ass))
12533 (done-word (nth 3 ass))
12534 (final-done-word (nth 4 ass))
12535 (org-last-state (or this ""))
12536 (completion-ignore-case t)
12537 (member (member this org-todo-keywords-1))
12538 (tail (cdr member))
12539 (org-state (cond
12540 ((and org-todo-key-trigger
12541 (or (and (equal arg '(4))
12542 (eq org-use-fast-todo-selection 'prefix))
12543 (and (not arg) org-use-fast-todo-selection
12544 (not (eq org-use-fast-todo-selection
12545 'prefix)))))
12546 ;; Use fast selection
12547 (org-fast-todo-selection))
12548 ((and (equal arg '(4))
12549 (or (not org-use-fast-todo-selection)
12550 (not org-todo-key-trigger)))
12551 ;; Read a state with completion
12552 (org-icompleting-read
12553 "State: " (mapcar 'list org-todo-keywords-1)
12554 nil t))
12555 ((eq arg 'right)
12556 (if this
12557 (if tail (car tail) nil)
12558 (car org-todo-keywords-1)))
12559 ((eq arg 'left)
12560 (if (equal member org-todo-keywords-1)
12562 (if this
12563 (nth (- (length org-todo-keywords-1)
12564 (length tail) 2)
12565 org-todo-keywords-1)
12566 (org-last org-todo-keywords-1))))
12567 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12568 (setq arg nil))) ; hack to fall back to cycling
12569 (arg
12570 ;; user or caller requests a specific state
12571 (cond
12572 ((equal arg "") nil)
12573 ((eq arg 'none) nil)
12574 ((eq arg 'done) (or done-word (car org-done-keywords)))
12575 ((eq arg 'nextset)
12576 (or (car (cdr (member head org-todo-heads)))
12577 (car org-todo-heads)))
12578 ((eq arg 'previousset)
12579 (let ((org-todo-heads (reverse org-todo-heads)))
12580 (or (car (cdr (member head org-todo-heads)))
12581 (car org-todo-heads))))
12582 ((car (member arg org-todo-keywords-1)))
12583 ((stringp arg)
12584 (user-error "State `%s' not valid in this file" arg))
12585 ((nth (1- (prefix-numeric-value arg))
12586 org-todo-keywords-1))))
12587 ((null member) (or head (car org-todo-keywords-1)))
12588 ((equal this final-done-word) nil) ;; -> make empty
12589 ((null tail) nil) ;; -> first entry
12590 ((memq interpret '(type priority))
12591 (if (eq this-command last-command)
12592 (car tail)
12593 (if (> (length tail) 0)
12594 (or done-word (car org-done-keywords))
12595 nil)))
12597 (car tail))))
12598 (org-state (or
12599 (run-hook-with-args-until-success
12600 'org-todo-get-default-hook org-state org-last-state)
12601 org-state))
12602 (next (if org-state (concat " " org-state " ") " "))
12603 (change-plist (list :type 'todo-state-change :from this :to org-state
12604 :position startpos))
12605 dolog now-done-p)
12606 (when org-blocker-hook
12607 (setq org-last-todo-state-is-todo
12608 (not (member this org-done-keywords)))
12609 (unless (save-excursion
12610 (save-match-data
12611 (org-with-wide-buffer
12612 (run-hook-with-args-until-failure
12613 'org-blocker-hook change-plist))))
12614 (if (org-called-interactively-p 'interactive)
12615 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12616 this org-state org-block-entry-blocking)
12617 ;; fail silently
12618 (message "TODO state change from %s to %s blocked (by \"%s\")"
12619 this org-state org-block-entry-blocking)
12620 (throw 'exit nil))))
12621 (store-match-data match-data)
12622 (replace-match next t t)
12623 (cond ((equal this org-state)
12624 (message "TODO state was already %s" (org-trim next)))
12625 ((pos-visible-in-window-p hl-pos)
12626 (message "TODO state changed to %s" (org-trim next))))
12627 (unless head
12628 (setq head (org-get-todo-sequence-head org-state)
12629 ass (assoc head org-todo-kwd-alist)
12630 interpret (nth 1 ass)
12631 done-word (nth 3 ass)
12632 final-done-word (nth 4 ass)))
12633 (when (memq arg '(nextset previousset))
12634 (message "Keyword-Set %d/%d: %s"
12635 (- (length org-todo-sets) -1
12636 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12637 (length org-todo-sets)
12638 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12639 (setq org-last-todo-state-is-todo
12640 (not (member org-state org-done-keywords)))
12641 (setq now-done-p (and (member org-state org-done-keywords)
12642 (not (member this org-done-keywords))))
12643 (and logging (org-local-logging logging))
12644 (when (and (or org-todo-log-states org-log-done)
12645 (not (eq org-inhibit-logging t))
12646 (not (memq arg '(nextset previousset))))
12647 ;; we need to look at recording a time and note
12648 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12649 (nth 2 (assoc this org-todo-log-states))))
12650 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12651 (setq dolog 'time))
12652 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12653 (and org-state
12654 (member org-state org-not-done-keywords)
12655 (not (member this org-not-done-keywords))))
12656 ;; This is now a todo state and was not one before
12657 ;; If there was a CLOSED time stamp, get rid of it.
12658 (org-add-planning-info nil nil 'closed))
12659 (when (and now-done-p org-log-done)
12660 ;; It is now done, and it was not done before
12661 (org-add-planning-info 'closed (org-current-effective-time))
12662 (if (and (not dolog) (eq 'note org-log-done))
12663 (org-add-log-setup 'done org-state this 'findpos 'note)))
12664 (when (and org-state dolog)
12665 ;; This is a non-nil state, and we need to log it
12666 (org-add-log-setup 'state org-state this 'findpos dolog)))
12667 ;; Fixup tag positioning
12668 (org-todo-trigger-tag-changes org-state)
12669 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12670 (when org-provide-todo-statistics
12671 (org-update-parent-todo-statistics))
12672 (run-hooks 'org-after-todo-state-change-hook)
12673 (if (and arg (not (member org-state org-done-keywords)))
12674 (setq head (org-get-todo-sequence-head org-state)))
12675 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12676 ;; Do we need to trigger a repeat?
12677 (when now-done-p
12678 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12679 ;; This is for the agenda, take a snapshot of the headline.
12680 (save-match-data
12681 (setq org-agenda-headline-snapshot-before-repeat
12682 (org-get-heading))))
12683 (org-auto-repeat-maybe org-state))
12684 ;; Fixup cursor location if close to the keyword
12685 (if (and (outline-on-heading-p)
12686 (not (bolp))
12687 (save-excursion (beginning-of-line 1)
12688 (looking-at org-todo-line-regexp))
12689 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12690 (progn
12691 (goto-char (or (match-end 2) (match-end 1)))
12692 (and (looking-at " ") (just-one-space))))
12693 (when org-trigger-hook
12694 (save-excursion
12695 (run-hook-with-args 'org-trigger-hook change-plist)))
12696 (when commentp (org-toggle-comment))))))))
12698 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12699 "Block turning an entry into a TODO, using the hierarchy.
12700 This checks whether the current task should be blocked from state
12701 changes. Such blocking occurs when:
12703 1. The task has children which are not all in a completed state.
12705 2. A task has a parent with the property :ORDERED:, and there
12706 are siblings prior to the current task with incomplete
12707 status.
12709 3. The parent of the task is blocked because it has siblings that should
12710 be done first, or is child of a block grandparent TODO entry."
12712 (if (not org-enforce-todo-dependencies)
12713 t ; if locally turned off don't block
12714 (catch 'dont-block
12715 ;; If this is not a todo state change, or if this entry is already DONE,
12716 ;; do not block
12717 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12718 (member (plist-get change-plist :from)
12719 (cons 'done org-done-keywords))
12720 (member (plist-get change-plist :to)
12721 (cons 'todo org-not-done-keywords))
12722 (not (plist-get change-plist :to)))
12723 (throw 'dont-block t))
12724 ;; If this task has children, and any are undone, it's blocked
12725 (save-excursion
12726 (org-back-to-heading t)
12727 (let ((this-level (funcall outline-level)))
12728 (outline-next-heading)
12729 (let ((child-level (funcall outline-level)))
12730 (while (and (not (eobp))
12731 (> child-level this-level))
12732 ;; this todo has children, check whether they are all
12733 ;; completed
12734 (if (and (not (org-entry-is-done-p))
12735 (org-entry-is-todo-p))
12736 (progn (setq org-block-entry-blocking (org-get-heading))
12737 (throw 'dont-block nil)))
12738 (outline-next-heading)
12739 (setq child-level (funcall outline-level))))))
12740 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12741 ;; any previous siblings are undone, it's blocked
12742 (save-excursion
12743 (org-back-to-heading t)
12744 (let* ((pos (point))
12745 (parent-pos (and (org-up-heading-safe) (point))))
12746 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12747 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12748 (forward-line 1)
12749 (re-search-forward org-not-done-heading-regexp pos t))
12750 (setq org-block-entry-blocking (match-string 0))
12751 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12752 ;; Search further up the hierarchy, to see if an ancestor is blocked
12753 (while t
12754 (goto-char parent-pos)
12755 (if (not (looking-at org-not-done-heading-regexp))
12756 (throw 'dont-block t)) ; do not block, parent is not a TODO
12757 (setq pos (point))
12758 (setq parent-pos (and (org-up-heading-safe) (point)))
12759 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12760 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12761 (forward-line 1)
12762 (re-search-forward org-not-done-heading-regexp pos t)
12763 (setq org-block-entry-blocking (org-get-heading)))
12764 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12766 (defcustom org-track-ordered-property-with-tag nil
12767 "Should the ORDERED property also be shown as a tag?
12768 The ORDERED property decides if an entry should require subtasks to be
12769 completed in sequence. Since a property is not very visible, setting
12770 this option means that toggling the ORDERED property with the command
12771 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12772 not relevant for the behavior, but it makes things more visible.
12774 Note that toggling the tag with tags commands will not change the property
12775 and therefore not influence behavior!
12777 This can be t, meaning the tag ORDERED should be used, It can also be a
12778 string to select a different tag for this task."
12779 :group 'org-todo
12780 :type '(choice
12781 (const :tag "No tracking" nil)
12782 (const :tag "Track with ORDERED tag" t)
12783 (string :tag "Use other tag")))
12785 (defun org-toggle-ordered-property ()
12786 "Toggle the ORDERED property of the current entry.
12787 For better visibility, you can track the value of this property with a tag.
12788 See variable `org-track-ordered-property-with-tag'."
12789 (interactive)
12790 (let* ((t1 org-track-ordered-property-with-tag)
12791 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12792 (save-excursion
12793 (org-back-to-heading)
12794 (if (org-entry-get nil "ORDERED")
12795 (progn
12796 (org-delete-property "ORDERED")
12797 (and tag (org-toggle-tag tag 'off))
12798 (message "Subtasks can be completed in arbitrary order"))
12799 (org-entry-put nil "ORDERED" "t")
12800 (and tag (org-toggle-tag tag 'on))
12801 (message "Subtasks must be completed in sequence")))))
12803 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12804 (defun org-block-todo-from-checkboxes (change-plist)
12805 "Block turning an entry into a TODO, using checkboxes.
12806 This checks whether the current task should be blocked from state
12807 changes because there are unchecked boxes in this entry."
12808 (if (not org-enforce-todo-checkbox-dependencies)
12809 t ; if locally turned off don't block
12810 (catch 'dont-block
12811 ;; If this is not a todo state change, or if this entry is already DONE,
12812 ;; do not block
12813 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12814 (member (plist-get change-plist :from)
12815 (cons 'done org-done-keywords))
12816 (member (plist-get change-plist :to)
12817 (cons 'todo org-not-done-keywords))
12818 (not (plist-get change-plist :to)))
12819 (throw 'dont-block t))
12820 ;; If this task has checkboxes that are not checked, it's blocked
12821 (save-excursion
12822 (org-back-to-heading t)
12823 (let ((beg (point)) end)
12824 (outline-next-heading)
12825 (setq end (point))
12826 (goto-char beg)
12827 (if (org-list-search-forward
12828 (concat (org-item-beginning-re)
12829 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12830 "\\[[- ]\\]")
12831 end t)
12832 (progn
12833 (if (boundp 'org-blocked-by-checkboxes)
12834 (setq org-blocked-by-checkboxes t))
12835 (throw 'dont-block nil)))))
12836 t))) ; do not block
12838 (defun org-entry-blocked-p ()
12839 "Is the current entry blocked?"
12840 (org-with-silent-modifications
12841 (if (org-entry-get nil "NOBLOCKING")
12842 nil ;; Never block this entry
12843 (not (run-hook-with-args-until-failure
12844 'org-blocker-hook
12845 (list :type 'todo-state-change
12846 :position (point)
12847 :from 'todo
12848 :to 'done))))))
12850 (defun org-update-statistics-cookies (all)
12851 "Update the statistics cookie, either from TODO or from checkboxes.
12852 This should be called with the cursor in a line with a statistics cookie."
12853 (interactive "P")
12854 (if all
12855 (progn
12856 (org-update-checkbox-count 'all)
12857 (org-map-entries 'org-update-parent-todo-statistics))
12858 (if (not (org-at-heading-p))
12859 (org-update-checkbox-count)
12860 (let ((pos (point-marker))
12861 end l1 l2)
12862 (ignore-errors (org-back-to-heading t))
12863 (if (not (org-at-heading-p))
12864 (org-update-checkbox-count)
12865 (setq l1 (org-outline-level))
12866 (setq end (save-excursion
12867 (outline-next-heading)
12868 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12869 (point)))
12870 (if (and (save-excursion
12871 (re-search-forward
12872 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12873 (not (save-excursion (re-search-forward
12874 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12875 (org-update-checkbox-count)
12876 (if (and l2 (> l2 l1))
12877 (progn
12878 (goto-char end)
12879 (org-update-parent-todo-statistics))
12880 (goto-char pos)
12881 (beginning-of-line 1)
12882 (while (re-search-forward
12883 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12884 (point-at-eol) t)
12885 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12886 (goto-char pos)
12887 (move-marker pos nil)))))
12889 (defvar org-entry-property-inherited-from) ;; defined below
12890 (defun org-update-parent-todo-statistics ()
12891 "Update any statistics cookie in the parent of the current headline.
12892 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12893 the entire subtree and this will travel up the hierarchy and update
12894 statistics everywhere."
12895 (let* ((prop (save-excursion (org-up-heading-safe)
12896 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12897 (recursive (or (not org-hierarchical-todo-statistics)
12898 (and prop (string-match "\\<recursive\\>" prop))))
12899 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12901 (first t)
12902 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12903 level ltoggle l1 new ndel
12904 (cnt-all 0) (cnt-done 0) is-percent kwd
12905 checkbox-beg ov ovs ove cookie-present)
12906 (catch 'exit
12907 (save-excursion
12908 (beginning-of-line 1)
12909 (setq ltoggle (funcall outline-level))
12910 ;; Three situations are to consider:
12912 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12913 ;; to the top-level ancestor on the headline;
12915 ;; 2. If parent has "recursive" property, repeat up to the
12916 ;; headline setting that property, taking inheritance into
12917 ;; account;
12919 ;; 3. Else, move up to direct parent and proceed only once.
12920 (while (and (setq level (org-up-heading-safe))
12921 (or recursive first)
12922 (>= (point) lim))
12923 (setq first nil cookie-present nil)
12924 (unless (and level
12925 (not (string-match
12926 "\\<checkbox\\>"
12927 (downcase (or (org-entry-get nil "COOKIE_DATA")
12928 "")))))
12929 (throw 'exit nil))
12930 (while (re-search-forward box-re (point-at-eol) t)
12931 (setq cnt-all 0 cnt-done 0 cookie-present t)
12932 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12933 (save-match-data
12934 (unless (outline-next-heading) (throw 'exit nil))
12935 (while (and (looking-at org-complex-heading-regexp)
12936 (> (setq l1 (length (match-string 1))) level))
12937 (setq kwd (and (or recursive (= l1 ltoggle))
12938 (match-string 2)))
12939 (if (or (eq org-provide-todo-statistics 'all-headlines)
12940 (and (eq org-provide-todo-statistics t)
12941 (or (member kwd org-done-keywords)))
12942 (and (listp org-provide-todo-statistics)
12943 (stringp (car org-provide-todo-statistics))
12944 (or (member kwd org-provide-todo-statistics)
12945 (member kwd org-done-keywords)))
12946 (and (listp org-provide-todo-statistics)
12947 (listp (car org-provide-todo-statistics))
12948 (or (member kwd (car org-provide-todo-statistics))
12949 (and (member kwd org-done-keywords)
12950 (member kwd (cadr org-provide-todo-statistics))))))
12951 (setq cnt-all (1+ cnt-all))
12952 (if (eq org-provide-todo-statistics t)
12953 (and kwd (setq cnt-all (1+ cnt-all)))))
12954 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12955 (member kwd org-done-keywords))
12956 (and (listp org-provide-todo-statistics)
12957 (listp (car org-provide-todo-statistics))
12958 (member kwd org-done-keywords)
12959 (member kwd (cadr org-provide-todo-statistics)))
12960 (and (listp org-provide-todo-statistics)
12961 (stringp (car org-provide-todo-statistics))
12962 (member kwd org-done-keywords)))
12963 (setq cnt-done (1+ cnt-done)))
12964 (outline-next-heading)))
12965 (setq new
12966 (if is-percent
12967 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12968 (format "[%d/%d]" cnt-done cnt-all))
12969 ndel (- (match-end 0) checkbox-beg))
12970 ;; handle overlays when updating cookie from column view
12971 (when (setq ov (car (overlays-at checkbox-beg)))
12972 (setq ovs (overlay-start ov) ove (overlay-end ov))
12973 (delete-overlay ov))
12974 (goto-char checkbox-beg)
12975 (insert new)
12976 (delete-region (point) (+ (point) ndel))
12977 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12978 (when ov (move-overlay ov ovs ove)))
12979 (when cookie-present
12980 (run-hook-with-args 'org-after-todo-statistics-hook
12981 cnt-done (- cnt-all cnt-done))))))
12982 (run-hooks 'org-todo-statistics-hook)))
12984 (defvar org-after-todo-statistics-hook nil
12985 "Hook that is called after a TODO statistics cookie has been updated.
12986 Each function is called with two arguments: the number of not-done entries
12987 and the number of done entries.
12989 For example, the following function, when added to this hook, will switch
12990 an entry to DONE when all children are done, and back to TODO when new
12991 entries are set to a TODO status. Note that this hook is only called
12992 when there is a statistics cookie in the headline!
12994 (defun org-summary-todo (n-done n-not-done)
12995 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12996 (let (org-log-done org-log-states) ; turn off logging
12997 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13000 (defvar org-todo-statistics-hook nil
13001 "Hook that is run whenever Org thinks TODO statistics should be updated.
13002 This hook runs even if there is no statistics cookie present, in which case
13003 `org-after-todo-statistics-hook' would not run.")
13005 (defun org-todo-trigger-tag-changes (state)
13006 "Apply the changes defined in `org-todo-state-tags-triggers'."
13007 (let ((l org-todo-state-tags-triggers)
13008 changes)
13009 (when (or (not state) (equal state ""))
13010 (setq changes (append changes (cdr (assoc "" l)))))
13011 (when (and (stringp state) (> (length state) 0))
13012 (setq changes (append changes (cdr (assoc state l)))))
13013 (when (member state org-not-done-keywords)
13014 (setq changes (append changes (cdr (assoc 'todo l)))))
13015 (when (member state org-done-keywords)
13016 (setq changes (append changes (cdr (assoc 'done l)))))
13017 (dolist (c changes)
13018 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13020 (defun org-local-logging (value)
13021 "Get logging settings from a property VALUE."
13022 (let* (words w a)
13023 ;; directly set the variables, they are already local.
13024 (setq org-log-done nil
13025 org-log-repeat nil
13026 org-todo-log-states nil)
13027 (setq words (org-split-string value))
13028 (while (setq w (pop words))
13029 (cond
13030 ((setq a (assoc w org-startup-options))
13031 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13032 (set (nth 1 a) (nth 2 a))))
13033 ((setq a (org-extract-log-state-settings w))
13034 (and (member (car a) org-todo-keywords-1)
13035 (push a org-todo-log-states)))))))
13037 (defun org-get-todo-sequence-head (kwd)
13038 "Return the head of the TODO sequence to which KWD belongs.
13039 If KWD is not set, check if there is a text property remembering the
13040 right sequence."
13041 (let (p)
13042 (cond
13043 ((not kwd)
13044 (or (get-text-property (point-at-bol) 'org-todo-head)
13045 (progn
13046 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13047 nil (point-at-eol)))
13048 (get-text-property p 'org-todo-head))))
13049 ((not (member kwd org-todo-keywords-1))
13050 (car org-todo-keywords-1))
13051 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13053 (defun org-fast-todo-selection ()
13054 "Fast TODO keyword selection with single keys.
13055 Returns the new TODO keyword, or nil if no state change should occur."
13056 (let* ((fulltable org-todo-key-alist)
13057 (done-keywords org-done-keywords) ;; needed for the faces.
13058 (maxlen (apply 'max (mapcar
13059 (lambda (x)
13060 (if (stringp (car x)) (string-width (car x)) 0))
13061 fulltable)))
13062 (expert nil)
13063 (fwidth (+ maxlen 3 1 3))
13064 (ncol (/ (- (window-width) 4) fwidth))
13065 tg cnt e c tbl
13066 groups ingroup)
13067 (save-excursion
13068 (save-window-excursion
13069 (if expert
13070 (set-buffer (get-buffer-create " *Org todo*"))
13071 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13072 (erase-buffer)
13073 (org-set-local 'org-done-keywords done-keywords)
13074 (setq tbl fulltable cnt 0)
13075 (while (setq e (pop tbl))
13076 (cond
13077 ((equal e '(:startgroup))
13078 (push '() groups) (setq ingroup t)
13079 (when (not (= cnt 0))
13080 (setq cnt 0)
13081 (insert "\n"))
13082 (insert "{ "))
13083 ((equal e '(:endgroup))
13084 (setq ingroup nil cnt 0)
13085 (insert "}\n"))
13086 ((equal e '(:newline))
13087 (when (not (= cnt 0))
13088 (setq cnt 0)
13089 (insert "\n")
13090 (setq e (car tbl))
13091 (while (equal (car tbl) '(:newline))
13092 (insert "\n")
13093 (setq tbl (cdr tbl)))))
13095 (setq tg (car e) c (cdr e))
13096 (if ingroup (push tg (car groups)))
13097 (setq tg (org-add-props tg nil 'face
13098 (org-get-todo-face tg)))
13099 (if (and (= cnt 0) (not ingroup)) (insert " "))
13100 (insert "[" c "] " tg (make-string
13101 (- fwidth 4 (length tg)) ?\ ))
13102 (when (= (setq cnt (1+ cnt)) ncol)
13103 (insert "\n")
13104 (if ingroup (insert " "))
13105 (setq cnt 0)))))
13106 (insert "\n")
13107 (goto-char (point-min))
13108 (if (not expert) (org-fit-window-to-buffer))
13109 (message "[a-z..]:Set [SPC]:clear")
13110 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13111 (cond
13112 ((or (= c ?\C-g)
13113 (and (= c ?q) (not (rassoc c fulltable))))
13114 (setq quit-flag t))
13115 ((= c ?\ ) nil)
13116 ((setq e (rassoc c fulltable) tg (car e))
13118 (t (setq quit-flag t)))))))
13120 (defun org-entry-is-todo-p ()
13121 (member (org-get-todo-state) org-not-done-keywords))
13123 (defun org-entry-is-done-p ()
13124 (member (org-get-todo-state) org-done-keywords))
13126 (defun org-get-todo-state ()
13127 "Return the TODO keyword of the current subtree."
13128 (save-excursion
13129 (org-back-to-heading t)
13130 (and (looking-at org-todo-line-regexp)
13131 (match-end 2)
13132 (match-string 2))))
13134 (defun org-at-date-range-p (&optional inactive-ok)
13135 "Is the cursor inside a date range?"
13136 (interactive)
13137 (save-excursion
13138 (catch 'exit
13139 (let ((pos (point)))
13140 (skip-chars-backward "^[<\r\n")
13141 (skip-chars-backward "<[")
13142 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13143 (>= (match-end 0) pos)
13144 (throw 'exit t))
13145 (skip-chars-backward "^<[\r\n")
13146 (skip-chars-backward "<[")
13147 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13148 (>= (match-end 0) pos)
13149 (throw 'exit t)))
13150 nil)))
13152 (defun org-get-repeat (&optional tagline)
13153 "Check if there is a deadline/schedule with repeater in this entry."
13154 (save-match-data
13155 (save-excursion
13156 (org-back-to-heading t)
13157 (and (re-search-forward (if tagline
13158 (concat tagline "\\s-*" org-repeat-re)
13159 org-repeat-re)
13160 (org-entry-end-position) t)
13161 (match-string-no-properties 1)))))
13163 (defvar org-last-changed-timestamp)
13164 (defvar org-last-inserted-timestamp)
13165 (defvar org-log-post-message)
13166 (defvar org-log-note-purpose)
13167 (defvar org-log-note-how nil)
13168 (defvar org-log-note-extra)
13169 (defun org-auto-repeat-maybe (done-word)
13170 "Check if the current headline contains a repeated deadline/schedule.
13171 If yes, set TODO state back to what it was and change the base date
13172 of repeating deadline/scheduled time stamps to new date.
13173 This function is run automatically after each state change to a DONE state."
13174 ;; last-state is dynamically scoped into this function
13175 (let* ((repeat (org-get-repeat))
13176 (aa (assoc org-last-state org-todo-kwd-alist))
13177 (interpret (nth 1 aa))
13178 (head (nth 2 aa))
13179 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13180 (msg "Entry repeats: ")
13181 (org-log-done nil)
13182 (org-todo-log-states nil)
13183 re type n what ts time to-state)
13184 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13185 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13186 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13187 org-todo-repeat-to-state))
13188 (unless (and to-state (member to-state org-todo-keywords-1))
13189 (setq to-state (if (eq interpret 'type) org-last-state head)))
13190 (org-todo to-state)
13191 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13192 (org-entry-put nil "LAST_REPEAT" (format-time-string
13193 (org-time-stamp-format t t))))
13194 (when org-log-repeat
13195 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13196 (memq 'org-add-log-note post-command-hook))
13197 ;; OK, we are already setup for some record
13198 (if (eq org-log-repeat 'note)
13199 ;; make sure we take a note, not only a time stamp
13200 (setq org-log-note-how 'note))
13201 ;; Set up for taking a record
13202 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13203 org-last-state
13204 'findpos org-log-repeat)))
13205 (org-back-to-heading t)
13206 (org-add-planning-info nil nil 'closed)
13207 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13208 org-deadline-time-regexp "\\)\\|\\("
13209 org-ts-regexp "\\)"))
13210 (while (re-search-forward
13211 re (save-excursion (outline-next-heading) (point)) t)
13212 (setq type (if (match-end 1) org-scheduled-string
13213 (if (match-end 3) org-deadline-string "Plain:"))
13214 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13215 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13216 (setq n (string-to-number (match-string 2 ts))
13217 what (match-string 3 ts))
13218 (if (equal what "w") (setq n (* n 7) what "d"))
13219 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13220 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13221 ;; Preparation, see if we need to modify the start date for the change
13222 (when (match-end 1)
13223 (setq time (save-match-data (org-time-string-to-time ts)))
13224 (cond
13225 ((equal (match-string 1 ts) ".")
13226 ;; Shift starting date to today
13227 (org-timestamp-change
13228 (- (org-today) (time-to-days time))
13229 'day))
13230 ((equal (match-string 1 ts) "+")
13231 (let ((nshiftmax 10) (nshift 0))
13232 (while (or (= nshift 0)
13233 (<= (time-to-days time)
13234 (time-to-days (current-time))))
13235 (when (= (incf nshift) nshiftmax)
13236 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13237 (user-error "Abort")))
13238 (org-timestamp-change n (cdr (assoc what whata)))
13239 (org-at-timestamp-p t)
13240 (setq ts (match-string 1))
13241 (setq time (save-match-data (org-time-string-to-time ts)))))
13242 (org-timestamp-change (- n) (cdr (assoc what whata)))
13243 ;; rematch, so that we have everything in place for the real shift
13244 (org-at-timestamp-p t)
13245 (setq ts (match-string 1))
13246 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13247 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13248 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13249 (setq org-log-post-message msg)
13250 (message "%s" msg))))
13252 (defun org-show-todo-tree (arg)
13253 "Make a compact tree which shows all headlines marked with TODO.
13254 The tree will show the lines where the regexp matches, and all higher
13255 headlines above the match.
13256 With a \\[universal-argument] prefix, prompt for a regexp to match.
13257 With a numeric prefix N, construct a sparse tree for the Nth element
13258 of `org-todo-keywords-1'."
13259 (interactive "P")
13260 (let ((case-fold-search nil)
13261 (kwd-re
13262 (cond ((null arg) org-not-done-regexp)
13263 ((equal arg '(4))
13264 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13265 (mapcar 'list org-todo-keywords-1))))
13266 (concat "\\("
13267 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13268 "\\)\\>")))
13269 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13270 (regexp-quote (nth (1- (prefix-numeric-value arg))
13271 org-todo-keywords-1)))
13272 (t (user-error "Invalid prefix argument: %s" arg)))))
13273 (message "%d TODO entries found"
13274 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13276 (defun org-deadline (arg &optional time)
13277 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13278 With one universal prefix argument, remove any deadline from the item.
13279 With two universal prefix arguments, prompt for a warning delay.
13280 With argument TIME, set the deadline at the corresponding date. TIME
13281 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13282 (interactive "P")
13283 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13284 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13285 'region-start-level 'region))
13286 org-loop-over-headlines-in-active-region)
13287 (org-map-entries
13288 `(org-deadline ',arg ,time)
13289 org-loop-over-headlines-in-active-region
13290 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13291 (let* ((old-date (org-entry-get nil "DEADLINE"))
13292 (old-date-time (if old-date (org-time-string-to-time old-date)))
13293 (repeater (and old-date
13294 (string-match
13295 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13296 old-date)
13297 (match-string 1 old-date))))
13298 (cond
13299 ((equal arg '(4))
13300 (when (and old-date org-log-redeadline)
13301 (org-add-log-setup 'deldeadline nil old-date 'findpos
13302 org-log-redeadline))
13303 (org-remove-timestamp-with-keyword org-deadline-string)
13304 (message "Item no longer has a deadline."))
13305 ((equal arg '(16))
13306 (save-excursion
13307 (org-back-to-heading t)
13308 (if (re-search-forward
13309 org-deadline-time-regexp
13310 (save-excursion (outline-next-heading) (point)) t)
13311 (let* ((rpl0 (match-string 1))
13312 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13313 (replace-match
13314 (concat org-deadline-string
13315 " <" rpl
13316 (format " -%dd"
13317 (abs
13318 (- (time-to-days
13319 (save-match-data
13320 (org-read-date nil t nil "Warn starting from" old-date-time)))
13321 (time-to-days old-date-time))))
13322 ">") t t))
13323 (user-error "No deadline information to update"))))
13325 (org-add-planning-info 'deadline time 'closed)
13326 (when (and old-date org-log-redeadline
13327 (not (equal old-date
13328 (substring org-last-inserted-timestamp 1 -1))))
13329 (org-add-log-setup 'redeadline nil old-date 'findpos
13330 org-log-redeadline))
13331 (when repeater
13332 (save-excursion
13333 (org-back-to-heading t)
13334 (when (re-search-forward (concat org-deadline-string " "
13335 org-last-inserted-timestamp)
13336 (save-excursion
13337 (outline-next-heading) (point)) t)
13338 (goto-char (1- (match-end 0)))
13339 (insert " " repeater)
13340 (setq org-last-inserted-timestamp
13341 (concat (substring org-last-inserted-timestamp 0 -1)
13342 " " repeater
13343 (substring org-last-inserted-timestamp -1))))))
13344 (message "Deadline on %s" org-last-inserted-timestamp))))))
13346 (defun org-schedule (arg &optional time)
13347 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13348 With one universal prefix argument, remove any scheduling date from the item.
13349 With two universal prefix arguments, prompt for a delay cookie.
13350 With argument TIME, scheduled at the corresponding date. TIME can
13351 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13352 (interactive "P")
13353 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13354 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13355 'region-start-level 'region))
13356 org-loop-over-headlines-in-active-region)
13357 (org-map-entries
13358 `(org-schedule ',arg ,time)
13359 org-loop-over-headlines-in-active-region
13360 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13361 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13362 (old-date-time (if old-date (org-time-string-to-time old-date)))
13363 (repeater (and old-date
13364 (string-match
13365 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13366 old-date)
13367 (match-string 1 old-date))))
13368 (cond
13369 ((equal arg '(4))
13370 (progn
13371 (when (and old-date org-log-reschedule)
13372 (org-add-log-setup 'delschedule nil old-date 'findpos
13373 org-log-reschedule))
13374 (org-remove-timestamp-with-keyword org-scheduled-string)
13375 (message "Item is no longer scheduled.")))
13376 ((equal arg '(16))
13377 (save-excursion
13378 (org-back-to-heading t)
13379 (if (re-search-forward
13380 org-scheduled-time-regexp
13381 (save-excursion (outline-next-heading) (point)) t)
13382 (let* ((rpl0 (match-string 1))
13383 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13384 (replace-match
13385 (concat org-scheduled-string
13386 " <" rpl
13387 (format " -%dd"
13388 (abs
13389 (- (time-to-days
13390 (save-match-data
13391 (org-read-date nil t nil "Delay until" old-date-time)))
13392 (time-to-days old-date-time))))
13393 ">") t t))
13394 (user-error "No scheduled information to update"))))
13396 (org-add-planning-info 'scheduled time 'closed)
13397 (when (and old-date org-log-reschedule
13398 (not (equal old-date
13399 (substring org-last-inserted-timestamp 1 -1))))
13400 (org-add-log-setup 'reschedule nil old-date 'findpos
13401 org-log-reschedule))
13402 (when repeater
13403 (save-excursion
13404 (org-back-to-heading t)
13405 (when (re-search-forward (concat org-scheduled-string " "
13406 org-last-inserted-timestamp)
13407 (save-excursion
13408 (outline-next-heading) (point)) t)
13409 (goto-char (1- (match-end 0)))
13410 (insert " " repeater)
13411 (setq org-last-inserted-timestamp
13412 (concat (substring org-last-inserted-timestamp 0 -1)
13413 " " repeater
13414 (substring org-last-inserted-timestamp -1))))))
13415 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13417 (defun org-get-scheduled-time (pom &optional inherit)
13418 "Get the scheduled time as a time tuple, of a format suitable
13419 for calling org-schedule with, or if there is no scheduling,
13420 returns nil."
13421 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13422 (when time
13423 (apply 'encode-time (org-parse-time-string time)))))
13425 (defun org-get-deadline-time (pom &optional inherit)
13426 "Get the deadline as a time tuple, of a format suitable for
13427 calling org-deadline with, or if there is no scheduling, returns
13428 nil."
13429 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13430 (when time
13431 (apply 'encode-time (org-parse-time-string time)))))
13433 (defun org-remove-timestamp-with-keyword (keyword)
13434 "Remove all time stamps with KEYWORD in the current entry."
13435 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13436 beg)
13437 (save-excursion
13438 (org-back-to-heading t)
13439 (setq beg (point))
13440 (outline-next-heading)
13441 (while (re-search-backward re beg t)
13442 (replace-match "")
13443 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13444 (equal (char-before) ?\ ))
13445 (backward-delete-char 1)
13446 (if (string-match "^[ \t]*$" (buffer-substring
13447 (point-at-bol) (point-at-eol)))
13448 (delete-region (point-at-bol)
13449 (min (point-max) (1+ (point-at-eol))))))))))
13451 (defvar org-time-was-given) ; dynamically scoped parameter
13452 (defvar org-end-time-was-given) ; dynamically scoped parameter
13454 (defun org-at-planning-p ()
13455 "Non-nil when point is on a planning info line."
13456 ;; This is as accurate and faster than `org-element-at-point' since
13457 ;; planning info location is fixed in the section.
13458 (org-with-wide-buffer
13459 (beginning-of-line)
13460 (and (org-looking-at-p org-planning-line-re)
13461 (eq (point)
13462 (ignore-errors
13463 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13464 (org-back-to-heading t)
13465 (org-with-limited-levels (org-back-to-heading t)))
13466 (line-beginning-position 2))))))
13468 (defun org-add-planning-info (what &optional time &rest remove)
13469 "Insert new timestamp with keyword in the planning line.
13470 WHAT indicates what kind of time stamp to add. It is a symbol
13471 among `closed', `deadline', `scheduled' and nil. TIME indicates
13472 the time to use. If none is given, the user is prompted for
13473 a date. REMOVE indicates what kind of entries to remove. An old
13474 WHAT entry will also be removed."
13475 (let (org-time-was-given org-end-time-was-given default-time default-input)
13476 (catch 'exit
13477 (when (and (memq what '(scheduled deadline))
13478 (or (not time)
13479 (and (stringp time)
13480 (string-match "^[-+]+[0-9]" time))))
13481 ;; Try to get a default date/time from existing timestamp
13482 (save-excursion
13483 (org-back-to-heading t)
13484 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13485 (when (re-search-forward (if (eq what 'scheduled)
13486 org-scheduled-time-regexp
13487 org-deadline-time-regexp)
13488 end t)
13489 (setq ts (match-string 1)
13490 default-time (apply 'encode-time (org-parse-time-string ts))
13491 default-input (and ts (org-get-compact-tod ts)))))))
13492 (when what
13493 (setq time
13494 (if (stringp time)
13495 ;; This is a string (relative or absolute), set
13496 ;; proper date.
13497 (apply #'encode-time
13498 (org-read-date-analyze
13499 time default-time (decode-time default-time)))
13500 ;; If necessary, get the time from the user
13501 (or time (org-read-date nil 'to-time nil nil
13502 default-time default-input)))))
13504 (org-with-wide-buffer
13505 (org-back-to-heading t)
13506 (forward-line)
13507 (unless (bolp) (insert "\n"))
13508 (cond ((org-looking-at-p org-planning-line-re)
13509 ;; Move to current indentation.
13510 (skip-chars-forward " \t")
13511 ;; Check if we have to remove something.
13512 (dolist (type (if what (cons what remove) remove))
13513 (when (save-excursion
13514 (re-search-forward
13515 (case type
13516 (closed org-closed-time-regexp)
13517 (deadline org-deadline-time-regexp)
13518 (scheduled org-scheduled-time-regexp)
13519 (otherwise (error "Invalid planning type: %s" type)))
13520 (line-end-position) t))
13521 (replace-match "")
13522 (when (looking-at "--+<[^>]+>") (replace-match ""))
13523 (when (and (not what) (eq type 'closed))
13524 (save-excursion
13525 (beginning-of-line)
13526 (if (looking-at "[ \t]*$")
13527 (delete-region (point) (1+ (point-at-eol)))))))
13528 ;; Remove leading white spaces.
13529 (when (and (not (bolp)) (looking-at "[ \t]+")) (replace-match ""))))
13530 ((not what) (throw 'exit nil)) ; Nothing to do.
13531 (t (insert-before-markers "\n")
13532 (backward-char 1)
13533 (when org-adapt-indentation
13534 (org-indent-to-column (1+ (org-outline-level))))))
13535 (when what
13536 ;; Insert planning keyword.
13537 (insert (case what
13538 (closed org-closed-string)
13539 (deadline org-deadline-string)
13540 (scheduled org-scheduled-string)
13541 (otherwise (error "Invalid planning type: %s" what)))
13542 " ")
13543 ;; Insert associated timestamp.
13544 (let ((ts (org-insert-time-stamp
13545 time
13546 (or org-time-was-given
13547 (and (eq what 'closed) org-log-done-with-time))
13548 (eq what 'closed)
13549 nil nil (list org-end-time-was-given))))
13550 (unless (eolp) (insert " "))
13551 ts))))))
13553 (defvar org-log-note-marker (make-marker))
13554 (defvar org-log-note-purpose nil)
13555 (defvar org-log-note-state nil)
13556 (defvar org-log-note-previous-state nil)
13557 (defvar org-log-note-extra nil)
13558 (defvar org-log-note-window-configuration nil)
13559 (defvar org-log-note-return-to (make-marker))
13560 (defvar org-log-note-effective-time nil
13561 "Remembered current time so that dynamically scoped
13562 `org-extend-today-until' affects tha timestamps in state change
13563 log")
13565 (defvar org-log-post-message nil
13566 "Message to be displayed after a log note has been stored.
13567 The auto-repeater uses this.")
13569 (defun org-add-note ()
13570 "Add a note to the current entry.
13571 This is done in the same way as adding a state change note."
13572 (interactive)
13573 (org-add-log-setup 'note nil nil 'findpos nil))
13575 (defun org-log-beginning (&optional create)
13576 "Return expected start of log notes in current entry.
13577 When optional argument CREATE is non-nil, the function creates
13578 a drawer to store notes, if necessary. Returned position ignores
13579 narrowing."
13580 (org-with-wide-buffer
13581 (org-back-to-heading t)
13582 ;; Skip planning info and property drawer.
13583 (forward-line)
13584 (when (org-looking-at-p org-planning-line-re) (forward-line))
13585 (when (looking-at org-property-drawer-re)
13586 (goto-char (match-end 0))
13587 (forward-line))
13588 (let ((end (if (org-at-heading-p) (point)
13589 (save-excursion (outline-next-heading) (point))))
13590 (drawer (org-log-into-drawer)))
13591 (cond
13592 (drawer
13593 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13594 (case-fold-search t))
13595 (catch 'exit
13596 ;; Try to find existing drawer.
13597 (while (re-search-forward regexp end t)
13598 (let ((element (org-element-at-point)))
13599 (when (eq (org-element-type element) 'drawer)
13600 (let ((cend (org-element-property :contents-end element)))
13601 (when (and (not org-log-states-order-reversed) cend)
13602 (goto-char cend)))
13603 (throw 'exit nil))))
13604 ;; No drawer found. Create one, if permitted.
13605 (when create
13606 (unless (bolp) (insert "\n"))
13607 (let ((beg (point)))
13608 (insert ":" drawer ":\n:END:\n")
13609 (org-indent-region beg (point)))
13610 (end-of-line -1)))))
13611 (org-log-state-notes-insert-after-drawers
13612 (while (and (looking-at org-drawer-regexp)
13613 (progn (goto-char (match-end 0))
13614 (re-search-forward org-property-end-re end t)))
13615 (forward-line)))))
13616 (if (bolp) (point) (line-beginning-position 2))))
13618 (defun org-add-log-setup (&optional purpose state prev-state findpos how extra)
13619 "Set up the post command hook to take a note.
13620 If this is about to TODO state change, the new state is expected in STATE.
13621 When FINDPOS is non-nil, find the correct position for the note in
13622 the current entry. If not, assume that it can be inserted at point.
13623 HOW is an indicator what kind of note should be created.
13624 EXTRA is additional text that will be inserted into the notes buffer."
13625 (org-with-wide-buffer
13626 (when findpos
13627 (goto-char (org-log-beginning t))
13628 (unless org-log-states-order-reversed
13629 (org-skip-over-state-notes)
13630 (skip-chars-backward " \t\n\r")
13631 (forward-line)))
13632 (move-marker org-log-note-marker (point))
13633 ;; Preserve position even if a property drawer is inserted in the
13634 ;; process.
13635 (set-marker-insertion-type org-log-note-marker t)
13636 (setq org-log-note-purpose purpose
13637 org-log-note-state state
13638 org-log-note-previous-state prev-state
13639 org-log-note-how how
13640 org-log-note-extra extra
13641 org-log-note-effective-time (org-current-effective-time))
13642 (add-hook 'post-command-hook 'org-add-log-note 'append)))
13644 (defun org-skip-over-state-notes ()
13645 "Skip past the list of State notes in an entry."
13646 (when (ignore-errors (goto-char (org-in-item-p)))
13647 (let* ((struct (org-list-struct))
13648 (prevs (org-list-prevs-alist struct))
13649 (regexp
13650 (concat "[ \t]*- +"
13651 (replace-regexp-in-string
13652 " +" " +"
13653 (org-replace-escapes
13654 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13655 `(("%d" . ,org-ts-regexp-inactive)
13656 ("%D" . ,org-ts-regexp)
13657 ("%s" . "\"\\S-+\"")
13658 ("%S" . "\"\\S-+\"")
13659 ("%t" . ,org-ts-regexp-inactive)
13660 ("%T" . ,org-ts-regexp)
13661 ("%u" . ".*?")
13662 ("%U" . ".*?")))))))
13663 (while (org-looking-at-p regexp)
13664 (goto-char (or (org-list-get-next-item (point) struct prevs)
13665 (org-list-get-item-end (point) struct)))))))
13667 (defun org-add-log-note (&optional purpose)
13668 "Pop up a window for taking a note, and add this note later at point."
13669 (remove-hook 'post-command-hook 'org-add-log-note)
13670 (setq org-log-note-window-configuration (current-window-configuration))
13671 (delete-other-windows)
13672 (move-marker org-log-note-return-to (point))
13673 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13674 (goto-char org-log-note-marker)
13675 (org-switch-to-buffer-other-window "*Org Note*")
13676 (erase-buffer)
13677 (if (memq org-log-note-how '(time state))
13678 (let (current-prefix-arg) (org-store-log-note))
13679 (let ((org-inhibit-startup t)) (org-mode))
13680 (insert (format "# Insert note for %s.
13681 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13682 (cond
13683 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13684 ((eq org-log-note-purpose 'done) "closed todo item")
13685 ((eq org-log-note-purpose 'state)
13686 (format "state change from \"%s\" to \"%s\""
13687 (or org-log-note-previous-state "")
13688 (or org-log-note-state "")))
13689 ((eq org-log-note-purpose 'reschedule)
13690 "rescheduling")
13691 ((eq org-log-note-purpose 'delschedule)
13692 "no longer scheduled")
13693 ((eq org-log-note-purpose 'redeadline)
13694 "changing deadline")
13695 ((eq org-log-note-purpose 'deldeadline)
13696 "removing deadline")
13697 ((eq org-log-note-purpose 'refile)
13698 "refiling")
13699 ((eq org-log-note-purpose 'note)
13700 "this entry")
13701 (t (error "This should not happen")))))
13702 (if org-log-note-extra (insert org-log-note-extra))
13703 (org-set-local 'org-finish-function 'org-store-log-note)
13704 (run-hooks 'org-log-buffer-setup-hook)))
13706 (defvar org-note-abort nil) ; dynamically scoped
13707 (defun org-store-log-note ()
13708 "Finish taking a log note, and insert it to where it belongs."
13709 (let ((txt (buffer-string)))
13710 (kill-buffer (current-buffer))
13711 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings))) lines)
13712 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13713 (setq txt (replace-match "" t t txt)))
13714 (if (string-match "\\s-+\\'" txt)
13715 (setq txt (replace-match "" t t txt)))
13716 (setq lines (org-split-string txt "\n"))
13717 (when (and note (string-match "\\S-" note))
13718 (setq note
13719 (org-replace-escapes
13720 note
13721 (list (cons "%u" (user-login-name))
13722 (cons "%U" user-full-name)
13723 (cons "%t" (format-time-string
13724 (org-time-stamp-format 'long 'inactive)
13725 org-log-note-effective-time))
13726 (cons "%T" (format-time-string
13727 (org-time-stamp-format 'long nil)
13728 org-log-note-effective-time))
13729 (cons "%d" (format-time-string
13730 (org-time-stamp-format nil 'inactive)
13731 org-log-note-effective-time))
13732 (cons "%D" (format-time-string
13733 (org-time-stamp-format nil nil)
13734 org-log-note-effective-time))
13735 (cons "%s" (if org-log-note-state
13736 (concat "\"" org-log-note-state "\"")
13737 ""))
13738 (cons "%S" (if org-log-note-previous-state
13739 (concat "\"" org-log-note-previous-state "\"")
13740 "\"\"")))))
13741 (when lines (setq note (concat note " \\\\")))
13742 (push note lines))
13743 (when (or current-prefix-arg org-note-abort)
13744 (when (org-log-into-drawer)
13745 (org-remove-empty-drawer-at org-log-note-marker))
13746 (setq lines nil))
13747 (when lines
13748 (with-current-buffer (marker-buffer org-log-note-marker)
13749 (save-excursion
13750 (goto-char org-log-note-marker)
13751 (move-marker org-log-note-marker nil)
13752 ;; Make sure point is at the beginning of an empty line.
13753 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13754 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13755 ;; In an existing list, add a new item at the top level.
13756 ;; Otherwise, indent line like a regular one.
13757 (let ((itemp (org-in-item-p)))
13758 (if itemp
13759 (org-indent-line-to
13760 (let ((struct (save-excursion
13761 (goto-char itemp) (org-list-struct))))
13762 (org-list-get-ind (org-list-get-top-point struct) struct)))
13763 (org-indent-line)))
13764 (insert (org-list-bullet-string "-") (pop lines))
13765 (let ((ind (org-list-item-body-column (line-beginning-position))))
13766 (dolist (line lines)
13767 (insert "\n")
13768 (org-indent-line-to ind)
13769 (insert line)))
13770 (message "Note stored")
13771 (org-back-to-heading t)
13772 (org-cycle-hide-drawers 'children))
13773 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13774 ;; from within `org-add-log-note' because `buffer-undo-list'
13775 ;; is then modified outside of `org-with-remote-undo'.
13776 (when (eq this-command 'org-agenda-todo)
13777 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13778 ;; Don't add undo information when called from `org-agenda-todo'
13779 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13780 (set-window-configuration org-log-note-window-configuration)
13781 (with-current-buffer (marker-buffer org-log-note-return-to)
13782 (goto-char org-log-note-return-to))
13783 (move-marker org-log-note-return-to nil)
13784 (and org-log-post-message (message "%s" org-log-post-message))))
13786 (defun org-remove-empty-drawer-at (pos)
13787 "Remove an empty drawer at position POS.
13788 POS may also be a marker."
13789 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13790 (org-with-wide-buffer
13791 (goto-char pos)
13792 (let ((drawer (org-element-at-point)))
13793 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13794 (not (org-element-property :contents-begin drawer)))
13795 (delete-region (org-element-property :begin drawer)
13796 (progn (goto-char (org-element-property :end drawer))
13797 (skip-chars-backward " \r\t\n")
13798 (forward-line)
13799 (point))))))))
13801 (defvar org-ts-type nil)
13802 (defun org-sparse-tree (&optional arg type)
13803 "Create a sparse tree, prompt for the details.
13804 This command can create sparse trees. You first need to select the type
13805 of match used to create the tree:
13807 t Show all TODO entries.
13808 T Show entries with a specific TODO keyword.
13809 m Show entries selected by a tags/property match.
13810 p Enter a property name and its value (both with completion on existing
13811 names/values) and show entries with that property.
13812 r Show entries matching a regular expression (`/' can be used as well).
13813 b Show deadlines and scheduled items before a date.
13814 a Show deadlines and scheduled items after a date.
13815 d Show deadlines due within `org-deadline-warning-days'.
13816 D Show deadlines and scheduled items between a date range."
13817 (interactive "P")
13818 (setq type (or type org-sparse-tree-default-date-type))
13819 (setq org-ts-type type)
13820 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13821 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13822 [c]ycle through date types: %s"
13823 (case type
13824 (all "all timestamps")
13825 (scheduled "only scheduled")
13826 (deadline "only deadline")
13827 (active "only active timestamps")
13828 (inactive "only inactive timestamps")
13829 (closed "with a closed time-stamp")
13830 (otherwise "scheduled/deadline")))
13831 (let ((answer (read-char-exclusive)))
13832 (case answer
13834 (org-sparse-tree
13836 (cadr
13837 (memq type '(nil all scheduled deadline active inactive closed)))))
13838 (?d (call-interactively 'org-check-deadlines))
13839 (?b (call-interactively 'org-check-before-date))
13840 (?a (call-interactively 'org-check-after-date))
13841 (?D (call-interactively 'org-check-dates-range))
13842 (?t (call-interactively 'org-show-todo-tree))
13843 (?T (org-show-todo-tree '(4)))
13844 (?m (call-interactively 'org-match-sparse-tree))
13845 ((?p ?P)
13846 (let* ((kwd (org-icompleting-read
13847 "Property: " (mapcar 'list (org-buffer-property-keys))))
13848 (value (org-icompleting-read
13849 "Value: " (mapcar 'list (org-property-values kwd)))))
13850 (unless (string-match "\\`{.*}\\'" value)
13851 (setq value (concat "\"" value "\"")))
13852 (org-match-sparse-tree arg (concat kwd "=" value))))
13853 ((?r ?R ?/) (call-interactively 'org-occur))
13854 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13856 (defvar org-occur-highlights nil
13857 "List of overlays used for occur matches.")
13858 (make-variable-buffer-local 'org-occur-highlights)
13859 (defvar org-occur-parameters nil
13860 "Parameters of the active org-occur calls.
13861 This is a list, each call to org-occur pushes as cons cell,
13862 containing the regular expression and the callback, onto the list.
13863 The list can contain several entries if `org-occur' has been called
13864 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13865 will only contain one set of parameters. When the highlights are
13866 removed (for example with `C-c C-c', or with the next edit (depending
13867 on `org-remove-highlights-with-change'), this variable is emptied
13868 as well.")
13869 (make-variable-buffer-local 'org-occur-parameters)
13871 (defun org-occur (regexp &optional keep-previous callback)
13872 "Make a compact tree which shows all matches of REGEXP.
13873 The tree will show the lines where the regexp matches, and all higher
13874 headlines above the match. It will also show the heading after the match,
13875 to make sure editing the matching entry is easy.
13876 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13877 call to `org-occur' will be kept, to allow stacking of calls to this
13878 command.
13879 If CALLBACK is non-nil, it is a function which is called to confirm
13880 that the match should indeed be shown."
13881 (interactive "sRegexp: \nP")
13882 (when (equal regexp "")
13883 (user-error "Regexp cannot be empty"))
13884 (unless keep-previous
13885 (org-remove-occur-highlights nil nil t))
13886 (push (cons regexp callback) org-occur-parameters)
13887 (let ((cnt 0))
13888 (save-excursion
13889 (goto-char (point-min))
13890 (if (or (not keep-previous) ; do not want to keep
13891 (not org-occur-highlights)) ; no previous matches
13892 ;; hide everything
13893 (org-overview))
13894 (while (re-search-forward regexp nil t)
13895 (when (or (not callback)
13896 (save-match-data (funcall callback)))
13897 (setq cnt (1+ cnt))
13898 (when org-highlight-sparse-tree-matches
13899 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13900 (org-show-context 'occur-tree))))
13901 (when org-remove-highlights-with-change
13902 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13903 nil 'local))
13904 (unless org-sparse-tree-open-archived-trees
13905 (org-hide-archived-subtrees (point-min) (point-max)))
13906 (run-hooks 'org-occur-hook)
13907 (if (org-called-interactively-p 'interactive)
13908 (message "%d match(es) for regexp %s" cnt regexp))
13909 cnt))
13911 (defun org-occur-next-match (&optional n reset)
13912 "Function for `next-error-function' to find sparse tree matches.
13913 N is the number of matches to move, when negative move backwards.
13914 RESET is entirely ignored - this function always goes back to the
13915 starting point when no match is found."
13916 (let* ((limit (if (< n 0) (point-min) (point-max)))
13917 (search-func (if (< n 0)
13918 'previous-single-char-property-change
13919 'next-single-char-property-change))
13920 (n (abs n))
13921 (pos (point))
13923 (catch 'exit
13924 (while (setq p1 (funcall search-func (point) 'org-type))
13925 (when (equal p1 limit)
13926 (goto-char pos)
13927 (user-error "No more matches"))
13928 (when (equal (get-char-property p1 'org-type) 'org-occur)
13929 (setq n (1- n))
13930 (when (= n 0)
13931 (goto-char p1)
13932 (throw 'exit (point))))
13933 (goto-char p1))
13934 (goto-char p1)
13935 (user-error "No more matches"))))
13937 (defun org-show-context (&optional key)
13938 "Make sure point and context are visible.
13939 How much context is shown depends upon the variables
13940 `org-show-hierarchy-above', `org-show-following-heading',
13941 `org-show-entry-below' and `org-show-siblings'."
13942 (let ((heading-p (org-at-heading-p t))
13943 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13944 (following-p (org-get-alist-option org-show-following-heading key))
13945 (entry-p (org-get-alist-option org-show-entry-below key))
13946 (siblings-p (org-get-alist-option org-show-siblings key)))
13947 ;; Show heading or entry text
13948 (if (and heading-p (not entry-p))
13949 (org-flag-heading nil) ; only show the heading
13950 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13951 (org-show-hidden-entry))) ; show entire entry
13952 (when following-p
13953 ;; Show next sibling, or heading below text
13954 (save-excursion
13955 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13956 (org-flag-heading nil))))
13957 (when siblings-p (org-show-siblings))
13958 (when hierarchy-p
13959 ;; show all higher headings, possibly with siblings
13960 (save-excursion
13961 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13962 (not (bobp)))
13963 (org-flag-heading nil)
13964 (when siblings-p (org-show-siblings)))))))
13966 (defvar org-reveal-start-hook nil
13967 "Hook run before revealing a location.")
13969 (defun org-reveal (&optional siblings)
13970 "Show current entry, hierarchy above it, and the following headline.
13971 This can be used to show a consistent set of context around locations
13972 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13973 not t for the search context.
13975 With optional argument SIBLINGS, on each level of the hierarchy all
13976 siblings are shown. This repairs the tree structure to what it would
13977 look like when opened with hierarchical calls to `org-cycle'.
13978 With double optional argument \\[universal-argument] \\[universal-argument], \
13979 go to the parent and show the
13980 entire tree."
13981 (interactive "P")
13982 (run-hooks 'org-reveal-start-hook)
13983 (let ((org-show-hierarchy-above t)
13984 (org-show-following-heading t)
13985 (org-show-siblings (if siblings t org-show-siblings)))
13986 (org-show-context nil))
13987 (when (equal siblings '(16))
13988 (save-excursion
13989 (when (org-up-heading-safe)
13990 (org-show-subtree)
13991 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13993 (defun org-highlight-new-match (beg end)
13994 "Highlight from BEG to END and mark the highlight is an occur headline."
13995 (let ((ov (make-overlay beg end)))
13996 (overlay-put ov 'face 'secondary-selection)
13997 (overlay-put ov 'org-type 'org-occur)
13998 (push ov org-occur-highlights)))
14000 (defun org-remove-occur-highlights (&optional beg end noremove)
14001 "Remove the occur highlights from the buffer.
14002 BEG and END are ignored. If NOREMOVE is nil, remove this function
14003 from the `before-change-functions' in the current buffer."
14004 (interactive)
14005 (unless org-inhibit-highlight-removal
14006 (mapc 'delete-overlay org-occur-highlights)
14007 (setq org-occur-highlights nil)
14008 (setq org-occur-parameters nil)
14009 (unless noremove
14010 (remove-hook 'before-change-functions
14011 'org-remove-occur-highlights 'local))))
14013 ;;;; Priorities
14015 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14016 "Regular expression matching the priority indicator.")
14018 (defvar org-remove-priority-next-time nil)
14020 (defun org-priority-up ()
14021 "Increase the priority of the current item."
14022 (interactive)
14023 (org-priority 'up))
14025 (defun org-priority-down ()
14026 "Decrease the priority of the current item."
14027 (interactive)
14028 (org-priority 'down))
14030 (defun org-priority (&optional action show)
14031 "Change the priority of an item.
14032 ACTION can be `set', `up', `down', or a character."
14033 (interactive "P")
14034 (if (equal action '(4))
14035 (org-show-priority)
14036 (unless org-enable-priority-commands
14037 (user-error "Priority commands are disabled"))
14038 (setq action (or action 'set))
14039 (let (current new news have remove)
14040 (save-excursion
14041 (org-back-to-heading t)
14042 (if (looking-at org-priority-regexp)
14043 (setq current (string-to-char (match-string 2))
14044 have t))
14045 (cond
14046 ((eq action 'remove)
14047 (setq remove t new ?\ ))
14048 ((or (eq action 'set)
14049 (if (featurep 'xemacs) (characterp action) (integerp action)))
14050 (if (not (eq action 'set))
14051 (setq new action)
14052 (message "Priority %c-%c, SPC to remove: "
14053 org-highest-priority org-lowest-priority)
14054 (save-match-data
14055 (setq new (read-char-exclusive))))
14056 (if (and (= (upcase org-highest-priority) org-highest-priority)
14057 (= (upcase org-lowest-priority) org-lowest-priority))
14058 (setq new (upcase new)))
14059 (cond ((equal new ?\ ) (setq remove t))
14060 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14061 (user-error "Priority must be between `%c' and `%c'"
14062 org-highest-priority org-lowest-priority))))
14063 ((eq action 'up)
14064 (setq new (if have
14065 (1- current) ; normal cycling
14066 ;; last priority was empty
14067 (if (eq last-command this-command)
14068 org-lowest-priority ; wrap around empty to lowest
14069 ;; default
14070 (if org-priority-start-cycle-with-default
14071 org-default-priority
14072 (1- org-default-priority))))))
14073 ((eq action 'down)
14074 (setq new (if have
14075 (1+ current) ; normal cycling
14076 ;; last priority was empty
14077 (if (eq last-command this-command)
14078 org-highest-priority ; wrap around empty to highest
14079 ;; default
14080 (if org-priority-start-cycle-with-default
14081 org-default-priority
14082 (1+ org-default-priority))))))
14083 (t (user-error "Invalid action")))
14084 (if (or (< (upcase new) org-highest-priority)
14085 (> (upcase new) org-lowest-priority))
14086 (if (and (memq action '(up down))
14087 (not have) (not (eq last-command this-command)))
14088 ;; `new' is from default priority
14089 (error
14090 "The default can not be set, see `org-default-priority' why")
14091 ;; normal cycling: `new' is beyond highest/lowest priority
14092 ;; and is wrapped around to the empty priority
14093 (setq remove t)))
14094 (setq news (format "%c" new))
14095 (if have
14096 (if remove
14097 (replace-match "" t t nil 1)
14098 (replace-match news t t nil 2))
14099 (if remove
14100 (user-error "No priority cookie found in line")
14101 (let ((case-fold-search nil))
14102 (looking-at org-todo-line-regexp))
14103 (if (match-end 2)
14104 (progn
14105 (goto-char (match-end 2))
14106 (insert " [#" news "]"))
14107 (goto-char (match-beginning 3))
14108 (insert "[#" news "] "))))
14109 (org-set-tags nil 'align))
14110 (if remove
14111 (message "Priority removed")
14112 (message "Priority of current item set to %s" news)))))
14114 (defun org-show-priority ()
14115 "Show the priority of the current item.
14116 This priority is composed of the main priority given with the [#A] cookies,
14117 and by additional input from the age of a schedules or deadline entry."
14118 (interactive)
14119 (let ((pri (if (eq major-mode 'org-agenda-mode)
14120 (org-get-at-bol 'priority)
14121 (save-excursion
14122 (save-match-data
14123 (beginning-of-line)
14124 (and (looking-at org-heading-regexp)
14125 (org-get-priority (match-string 0))))))))
14126 (message "Priority is %d" (if pri pri -1000))))
14128 (defun org-get-priority (s)
14129 "Find priority cookie and return priority."
14130 (save-match-data
14131 (if (functionp org-get-priority-function)
14132 (funcall org-get-priority-function)
14133 (if (not (string-match org-priority-regexp s))
14134 (* 1000 (- org-lowest-priority org-default-priority))
14135 (* 1000 (- org-lowest-priority
14136 (string-to-char (match-string 2 s))))))))
14138 ;;;; Tags
14140 (defvar org-agenda-archives-mode)
14141 (defvar org-map-continue-from nil
14142 "Position from where mapping should continue.
14143 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14145 (defvar org-scanner-tags nil
14146 "The current tag list while the tags scanner is running.")
14147 (defvar org-trust-scanner-tags nil
14148 "Should `org-get-tags-at' use the tags for the scanner.
14149 This is for internal dynamical scoping only.
14150 When this is non-nil, the function `org-get-tags-at' will return the value
14151 of `org-scanner-tags' instead of building the list by itself. This
14152 can lead to large speed-ups when the tags scanner is used in a file with
14153 many entries, and when the list of tags is retrieved, for example to
14154 obtain a list of properties. Building the tags list for each entry in such
14155 a file becomes an N^2 operation - but with this variable set, it scales
14156 as N.")
14158 (defun org-scan-tags (action matcher todo-only &optional start-level)
14159 "Scan headline tags with inheritance and produce output ACTION.
14161 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14162 or `agenda' to produce an entry list for an agenda view. It can also be
14163 a Lisp form or a function that should be called at each matched headline, in
14164 this case the return value is a list of all return values from these calls.
14166 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14167 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14168 only lines with a not-done TODO keyword are included in the output.
14169 This should be the same variable that was scoped into
14170 and set by `org-make-tags-matcher' when it constructed MATCHER.
14172 START-LEVEL can be a string with asterisks, reducing the scope to
14173 headlines matching this string."
14174 (require 'org-agenda)
14175 (let* ((re (concat "^"
14176 (if start-level
14177 ;; Get the correct level to match
14178 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14179 org-outline-regexp)
14180 " *\\(\\<\\("
14181 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14182 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14183 (props (list 'face 'default
14184 'done-face 'org-agenda-done
14185 'undone-face 'default
14186 'mouse-face 'highlight
14187 'org-not-done-regexp org-not-done-regexp
14188 'org-todo-regexp org-todo-regexp
14189 'org-complex-heading-regexp org-complex-heading-regexp
14190 'help-echo
14191 (format "mouse-2 or RET jump to org file %s"
14192 (abbreviate-file-name
14193 (or (buffer-file-name (buffer-base-buffer))
14194 (buffer-name (buffer-base-buffer)))))))
14195 (org-map-continue-from nil)
14196 lspos tags tags-list
14197 (tags-alist (list (cons 0 org-file-tags)))
14198 (llast 0) rtn rtn1 level category i txt
14199 todo marker entry priority)
14200 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14201 (setq action (list 'lambda nil action)))
14202 (save-excursion
14203 (goto-char (point-min))
14204 (when (eq action 'sparse-tree)
14205 (org-overview)
14206 (org-remove-occur-highlights))
14207 (while (let (case-fold-search)
14208 (re-search-forward re nil t))
14209 (setq org-map-continue-from nil)
14210 (catch :skip
14211 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14212 tags (if (match-end 4) (org-match-string-no-properties 4)))
14213 (goto-char (setq lspos (match-beginning 0)))
14214 (setq level (org-reduced-level (org-outline-level))
14215 category (org-get-category))
14216 (setq i llast llast level)
14217 ;; remove tag lists from same and sublevels
14218 (while (>= i level)
14219 (when (setq entry (assoc i tags-alist))
14220 (setq tags-alist (delete entry tags-alist)))
14221 (setq i (1- i)))
14222 ;; add the next tags
14223 (when tags
14224 (setq tags (org-split-string tags ":")
14225 tags-alist
14226 (cons (cons level tags) tags-alist)))
14227 ;; compile tags for current headline
14228 (setq tags-list
14229 (if org-use-tag-inheritance
14230 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14231 tags)
14232 org-scanner-tags tags-list)
14233 (when org-use-tag-inheritance
14234 (setcdr (car tags-alist)
14235 (mapcar (lambda (x)
14236 (setq x (copy-sequence x))
14237 (org-add-prop-inherited x))
14238 (cdar tags-alist))))
14239 (when (and tags org-use-tag-inheritance
14240 (or (not (eq t org-use-tag-inheritance))
14241 org-tags-exclude-from-inheritance))
14242 ;; selective inheritance, remove uninherited ones
14243 (setcdr (car tags-alist)
14244 (org-remove-uninherited-tags (cdar tags-alist))))
14245 (when (and
14247 ;; eval matcher only when the todo condition is OK
14248 (and (or (not todo-only) (member todo org-not-done-keywords))
14249 (let ((case-fold-search t) (org-trust-scanner-tags t))
14250 (eval matcher)))
14252 ;; Call the skipper, but return t if it does not skip,
14253 ;; so that the `and' form continues evaluating
14254 (progn
14255 (unless (eq action 'sparse-tree) (org-agenda-skip))
14258 ;; Check if timestamps are deselecting this entry
14259 (or (not todo-only)
14260 (and (member todo org-not-done-keywords)
14261 (or (not org-agenda-tags-todo-honor-ignore-options)
14262 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14264 ;; select this headline
14265 (cond
14266 ((eq action 'sparse-tree)
14267 (and org-highlight-sparse-tree-matches
14268 (org-get-heading) (match-end 0)
14269 (org-highlight-new-match
14270 (match-beginning 1) (match-end 1)))
14271 (org-show-context 'tags-tree))
14272 ((eq action 'agenda)
14273 (setq txt (org-agenda-format-item
14275 (concat
14276 (if (eq org-tags-match-list-sublevels 'indented)
14277 (make-string (1- level) ?.) "")
14278 (org-get-heading))
14279 level category
14280 tags-list)
14281 priority (org-get-priority txt))
14282 (goto-char lspos)
14283 (setq marker (org-agenda-new-marker))
14284 (org-add-props txt props
14285 'org-marker marker 'org-hd-marker marker 'org-category category
14286 'todo-state todo
14287 'priority priority 'type "tagsmatch")
14288 (push txt rtn))
14289 ((functionp action)
14290 (setq org-map-continue-from nil)
14291 (save-excursion
14292 (setq rtn1 (funcall action))
14293 (push rtn1 rtn)))
14294 (t (user-error "Invalid action")))
14296 ;; if we are to skip sublevels, jump to end of subtree
14297 (unless org-tags-match-list-sublevels
14298 (org-end-of-subtree t)
14299 (backward-char 1))))
14300 ;; Get the correct position from where to continue
14301 (if org-map-continue-from
14302 (goto-char org-map-continue-from)
14303 (and (= (point) lspos) (end-of-line 1)))))
14304 (when (and (eq action 'sparse-tree)
14305 (not org-sparse-tree-open-archived-trees))
14306 (org-hide-archived-subtrees (point-min) (point-max)))
14307 (nreverse rtn)))
14309 (defun org-remove-uninherited-tags (tags)
14310 "Remove all tags that are not inherited from the list TAGS."
14311 (cond
14312 ((eq org-use-tag-inheritance t)
14313 (if org-tags-exclude-from-inheritance
14314 (org-delete-all org-tags-exclude-from-inheritance tags)
14315 tags))
14316 ((not org-use-tag-inheritance) nil)
14317 ((stringp org-use-tag-inheritance)
14318 (delq nil (mapcar
14319 (lambda (x)
14320 (if (and (string-match org-use-tag-inheritance x)
14321 (not (member x org-tags-exclude-from-inheritance)))
14322 x nil))
14323 tags)))
14324 ((listp org-use-tag-inheritance)
14325 (delq nil (mapcar
14326 (lambda (x)
14327 (if (member x org-use-tag-inheritance) x nil))
14328 tags)))))
14330 (defun org-match-sparse-tree (&optional todo-only match)
14331 "Create a sparse tree according to tags string MATCH.
14332 MATCH can contain positive and negative selection of tags, like
14333 \"+WORK+URGENT-WITHBOSS\".
14334 If optional argument TODO-ONLY is non-nil, only select lines that are
14335 also TODO lines."
14336 (interactive "P")
14337 (org-agenda-prepare-buffers (list (current-buffer)))
14338 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14340 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14342 (defvar org-cached-props nil)
14343 (defun org-cached-entry-get (pom property)
14344 (if (or (eq t org-use-property-inheritance)
14345 (and (stringp org-use-property-inheritance)
14346 (let ((case-fold-search t))
14347 (org-string-match-p org-use-property-inheritance property)))
14348 (and (listp org-use-property-inheritance)
14349 (member-ignore-case property org-use-property-inheritance)))
14350 ;; Caching is not possible, check it directly.
14351 (org-entry-get pom property 'inherit)
14352 ;; Get all properties, so we can do complicated checks easily.
14353 (cdr (assoc-string property
14354 (or org-cached-props
14355 (setq org-cached-props (org-entry-properties pom)))
14356 t))))
14358 (defun org-global-tags-completion-table (&optional files)
14359 "Return the list of all tags in all agenda buffer/files.
14360 Optional FILES argument is a list of files which can be used
14361 instead of the agenda files."
14362 (save-excursion
14363 (org-uniquify
14364 (delq nil
14365 (apply 'append
14366 (mapcar
14367 (lambda (file)
14368 (set-buffer (find-file-noselect file))
14369 (append (org-get-buffer-tags)
14370 (mapcar (lambda (x) (if (stringp (car-safe x))
14371 (list (car-safe x)) nil))
14372 org-tag-alist)))
14373 (if (and files (car files))
14374 files
14375 (org-agenda-files))))))))
14377 (defun org-make-tags-matcher (match)
14378 "Create the TAGS/TODO matcher form for the selection string MATCH.
14380 The variable `todo-only' is scoped dynamically into this function.
14381 It will be set to t if the matcher restricts matching to TODO entries,
14382 otherwise will not be touched.
14384 Returns a cons of the selection string MATCH and the constructed
14385 lisp form implementing the matcher. The matcher is to be evaluated
14386 at an Org entry, with point on the headline, and returns t if the
14387 entry matches the selection string MATCH. The returned lisp form
14388 references two variables with information about the entry, which
14389 must be bound around the form's evaluation: todo, the TODO keyword
14390 at the entry (or nil of none); and tags-list, the list of all tags
14391 at the entry including inherited ones. Additionally, the category
14392 of the entry (if any) must be specified as the text property
14393 'org-category on the headline.
14395 See also `org-scan-tags'.
14397 (declare (special todo-only))
14398 (unless (boundp 'todo-only)
14399 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14400 (unless match
14401 ;; Get a new match request, with completion against the global
14402 ;; tags table and the local tags in current buffer
14403 (let ((org-last-tags-completion-table
14404 (org-uniquify
14405 (delq nil (append (org-get-buffer-tags)
14406 (org-global-tags-completion-table))))))
14407 (setq match (org-completing-read-no-i
14408 "Match: " 'org-tags-completion-function nil nil nil
14409 'org-tags-history))))
14411 ;; Parse the string and create a lisp form
14412 (let ((match0 match)
14413 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14414 minus tag mm
14415 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14416 orterms term orlist re-p str-p level-p level-op time-p
14417 prop-p pn pv po gv rest (start 0) (ss 0))
14418 ;; Expand group tags
14419 (setq match (org-tags-expand match))
14421 ;; Check if there is a TODO part of this match, which would be the
14422 ;; part after a "/". TO make sure that this slash is not part of
14423 ;; a property value to be matched against, we also check that there
14424 ;; is no " after that slash.
14425 ;; First, find the last slash
14426 (while (string-match "/+" match ss)
14427 (setq start (match-beginning 0) ss (match-end 0)))
14428 (if (and (string-match "/+" match start)
14429 (not (save-match-data (string-match "\"" match start))))
14430 ;; match contains also a todo-matching request
14431 (progn
14432 (setq tagsmatch (substring match 0 (match-beginning 0))
14433 todomatch (substring match (match-end 0)))
14434 (if (string-match "^!" todomatch)
14435 (setq todo-only t todomatch (substring todomatch 1)))
14436 (if (string-match "^\\s-*$" todomatch)
14437 (setq todomatch nil)))
14438 ;; only matching tags
14439 (setq tagsmatch match todomatch nil))
14441 ;; Make the tags matcher
14442 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14443 (setq tagsmatcher t)
14444 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14445 (while (setq term (pop orterms))
14446 (while (and (equal (substring term -1) "\\") orterms)
14447 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14448 (while (string-match re term)
14449 (setq rest (substring term (match-end 0))
14450 minus (and (match-end 1)
14451 (equal (match-string 1 term) "-"))
14452 tag (save-match-data (replace-regexp-in-string
14453 "\\\\-" "-"
14454 (match-string 2 term)))
14455 re-p (equal (string-to-char tag) ?{)
14456 level-p (match-end 4)
14457 prop-p (match-end 5)
14458 mm (cond
14459 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14460 (level-p
14461 (setq level-op (org-op-to-function (match-string 3 term)))
14462 `(,level-op level ,(string-to-number
14463 (match-string 4 term))))
14464 (prop-p
14465 (setq pn (match-string 5 term)
14466 po (match-string 6 term)
14467 pv (match-string 7 term)
14468 re-p (equal (string-to-char pv) ?{)
14469 str-p (equal (string-to-char pv) ?\")
14470 time-p (save-match-data
14471 (string-match "^\"[[<].*[]>]\"$" pv))
14472 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14473 (if time-p (setq pv (org-matcher-time pv)))
14474 (setq po (org-op-to-function po (if time-p 'time str-p)))
14475 (cond
14476 ((equal pn "CATEGORY")
14477 (setq gv '(get-text-property (point) 'org-category)))
14478 ((equal pn "TODO")
14479 (setq gv 'todo))
14481 (setq gv `(org-cached-entry-get nil ,pn))))
14482 (if re-p
14483 (if (eq po 'org<>)
14484 `(not (string-match ,pv (or ,gv "")))
14485 `(string-match ,pv (or ,gv "")))
14486 (if str-p
14487 `(,po (or ,gv "") ,pv)
14488 `(,po (string-to-number (or ,gv ""))
14489 ,(string-to-number pv) ))))
14490 (t `(member ,tag tags-list)))
14491 mm (if minus (list 'not mm) mm)
14492 term rest)
14493 (push mm tagsmatcher))
14494 (push (if (> (length tagsmatcher) 1)
14495 (cons 'and tagsmatcher)
14496 (car tagsmatcher))
14497 orlist)
14498 (setq tagsmatcher nil))
14499 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14500 (setq tagsmatcher
14501 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14502 ;; Make the todo matcher
14503 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14504 (setq todomatcher t)
14505 (setq orterms (org-split-string todomatch "|") orlist nil)
14506 (while (setq term (pop orterms))
14507 (while (string-match re term)
14508 (setq minus (and (match-end 1)
14509 (equal (match-string 1 term) "-"))
14510 kwd (match-string 2 term)
14511 re-p (equal (string-to-char kwd) ?{)
14512 term (substring term (match-end 0))
14513 mm (if re-p
14514 `(string-match ,(substring kwd 1 -1) todo)
14515 (list 'equal 'todo kwd))
14516 mm (if minus (list 'not mm) mm))
14517 (push mm todomatcher))
14518 (push (if (> (length todomatcher) 1)
14519 (cons 'and todomatcher)
14520 (car todomatcher))
14521 orlist)
14522 (setq todomatcher nil))
14523 (setq todomatcher (if (> (length orlist) 1)
14524 (cons 'or orlist) (car orlist))))
14526 ;; Return the string and lisp forms of the matcher
14527 (setq matcher (if todomatcher
14528 (list 'and tagsmatcher todomatcher)
14529 tagsmatcher))
14530 (when todo-only
14531 (setq matcher (list 'and '(member todo org-not-done-keywords)
14532 matcher)))
14533 (cons match0 matcher)))
14535 (defun org-tags-expand (match &optional single-as-list downcased)
14536 "Expand group tags in MATCH.
14538 This replaces every group tag in MATCH with a regexp tag search.
14539 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14540 will be replaced like this:
14542 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14543 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14544 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14546 Replacing by a regexp preserves the structure of the match.
14547 E.g., this expansion
14549 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14551 will match anything tagged with \"Lab\" and \"Home\", or tagged
14552 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14554 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14555 assumed to be a single group tag, and the function will return
14556 the list of tags in this group.
14558 When DOWNCASE is non-nil, expand downcased TAGS."
14559 (if org-group-tags
14560 (let* ((case-fold-search t)
14561 (stable org-mode-syntax-table)
14562 (tal (or org-tag-groups-alist-for-agenda
14563 org-tag-groups-alist))
14564 (tal (if downcased
14565 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14566 (tml (mapcar 'car tal))
14567 (rtnmatch match) rpl)
14568 ;; @ and _ are allowed as word-components in tags
14569 (modify-syntax-entry ?@ "w" stable)
14570 (modify-syntax-entry ?_ "w" stable)
14571 (while (and tml
14572 (with-syntax-table stable
14573 (string-match
14574 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14575 (regexp-opt tml) "\\>\\)") rtnmatch)))
14576 (let* ((dir (match-string 1 rtnmatch))
14577 (tag (match-string 2 rtnmatch))
14578 (tag (if downcased (downcase tag) tag)))
14579 (setq tml (delete tag tml))
14580 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14581 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14582 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14583 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14584 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14585 (if single-as-list
14586 (or (reverse rpl) (list rtnmatch))
14587 rtnmatch))
14588 (if single-as-list (list (if downcased (downcase match) match))
14589 match)))
14591 (defun org-op-to-function (op &optional stringp)
14592 "Turn an operator into the appropriate function."
14593 (setq op
14594 (cond
14595 ((equal op "<" ) '(< string< org-time<))
14596 ((equal op ">" ) '(> org-string> org-time>))
14597 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14598 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14599 ((member op '("=" "==")) '(= string= org-time=))
14600 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14601 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14603 (defun org<> (a b) (not (= a b)))
14604 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14605 (defun org-string>= (a b) (not (string< a b)))
14606 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14607 (defun org-string<> (a b) (not (string= a b)))
14608 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14609 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14610 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14611 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14612 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14613 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14614 (defun org-2ft (s)
14615 "Convert S to a floating point time.
14616 If S is already a number, just return it. If it is a string, parse
14617 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14618 (cond
14619 ((numberp s) s)
14620 ((stringp s)
14621 (condition-case nil
14622 (float-time (apply 'encode-time (org-parse-time-string s)))
14623 (error 0.)))
14624 (t 0.)))
14626 (defun org-time-today ()
14627 "Time in seconds today at 0:00.
14628 Returns the float number of seconds since the beginning of the
14629 epoch to the beginning of today (00:00)."
14630 (float-time (apply 'encode-time
14631 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14633 (defun org-matcher-time (s)
14634 "Interpret a time comparison value."
14635 (save-match-data
14636 (cond
14637 ((string= s "<now>") (float-time))
14638 ((string= s "<today>") (org-time-today))
14639 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14640 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14641 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14642 (+ (org-time-today)
14643 (* (string-to-number (match-string 1 s))
14644 (cdr (assoc (match-string 2 s)
14645 '(("d" . 86400.0) ("w" . 604800.0)
14646 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14647 (t (org-2ft s)))))
14649 (defun org-match-any-p (re list)
14650 "Does re match any element of list?"
14651 (setq list (mapcar (lambda (x) (string-match re x)) list))
14652 (delq nil list))
14654 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14655 (defvar org-tags-overlay (make-overlay 1 1))
14656 (org-detach-overlay org-tags-overlay)
14658 (defun org-get-local-tags-at (&optional pos)
14659 "Get a list of tags defined in the current headline."
14660 (org-get-tags-at pos 'local))
14662 (defun org-get-local-tags ()
14663 "Get a list of tags defined in the current headline."
14664 (org-get-tags-at nil 'local))
14666 (defun org-get-tags-at (&optional pos local)
14667 "Get a list of all headline tags applicable at POS.
14668 POS defaults to point. If tags are inherited, the list contains
14669 the targets in the same sequence as the headlines appear, i.e.
14670 the tags of the current headline come last.
14671 When LOCAL is non-nil, only return tags from the current headline,
14672 ignore inherited ones."
14673 (interactive)
14674 (if (and org-trust-scanner-tags
14675 (or (not pos) (equal pos (point)))
14676 (not local))
14677 org-scanner-tags
14678 (let (tags ltags lastpos parent)
14679 (save-excursion
14680 (save-restriction
14681 (widen)
14682 (goto-char (or pos (point)))
14683 (save-match-data
14684 (catch 'done
14685 (condition-case nil
14686 (progn
14687 (org-back-to-heading t)
14688 (while (not (equal lastpos (point)))
14689 (setq lastpos (point))
14690 (when (looking-at
14691 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14692 (setq ltags (org-split-string
14693 (org-match-string-no-properties 1) ":"))
14694 (when parent
14695 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14696 (setq tags (append
14697 (if parent
14698 (org-remove-uninherited-tags ltags)
14699 ltags)
14700 tags)))
14701 (or org-use-tag-inheritance (throw 'done t))
14702 (if local (throw 'done t))
14703 (or (org-up-heading-safe) (error nil))
14704 (setq parent t)))
14705 (error nil)))))
14706 (if local
14707 tags
14708 (reverse (delete-dups
14709 (reverse (append
14710 (org-remove-uninherited-tags
14711 org-file-tags) tags)))))))))
14713 (defun org-add-prop-inherited (s)
14714 (add-text-properties 0 (length s) '(inherited t) s)
14717 (defun org-toggle-tag (tag &optional onoff)
14718 "Toggle the tag TAG for the current line.
14719 If ONOFF is `on' or `off', don't toggle but set to this state."
14720 (let (res current)
14721 (save-excursion
14722 (org-back-to-heading t)
14723 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14724 (point-at-eol) t)
14725 (progn
14726 (setq current (match-string 1))
14727 (replace-match ""))
14728 (setq current ""))
14729 (setq current (nreverse (org-split-string current ":")))
14730 (cond
14731 ((eq onoff 'on)
14732 (setq res t)
14733 (or (member tag current) (push tag current)))
14734 ((eq onoff 'off)
14735 (or (not (member tag current)) (setq current (delete tag current))))
14736 (t (if (member tag current)
14737 (setq current (delete tag current))
14738 (setq res t)
14739 (push tag current))))
14740 (end-of-line 1)
14741 (if current
14742 (progn
14743 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14744 (org-set-tags nil t))
14745 (delete-horizontal-space))
14746 (run-hooks 'org-after-tags-change-hook))
14747 res))
14749 (defun org-align-tags-here (to-col)
14750 ;; Assumes that this is a headline
14751 "Align tags on the current headline to TO-COL."
14752 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14753 (beginning-of-line 1)
14754 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14755 (< pos (match-beginning 2)))
14756 (progn
14757 (setq tags-l (- (match-end 2) (match-beginning 2)))
14758 (goto-char (match-beginning 1))
14759 (insert " ")
14760 (delete-region (point) (1+ (match-beginning 2)))
14761 (setq ncol (max (current-column)
14762 (1+ col)
14763 (if (> to-col 0)
14764 to-col
14765 (- (abs to-col) tags-l))))
14766 (setq p (point))
14767 (insert (make-string (- ncol (current-column)) ?\ ))
14768 (setq ncol (current-column))
14769 (when indent-tabs-mode (tabify p (point-at-eol)))
14770 (org-move-to-column (min ncol col)))
14771 (goto-char pos))))
14773 (defun org-set-tags-command (&optional arg just-align)
14774 "Call the set-tags command for the current entry."
14775 (interactive "P")
14776 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14777 (org-set-tags arg just-align)
14778 (save-excursion
14779 (unless (and (org-region-active-p)
14780 org-loop-over-headlines-in-active-region)
14781 (org-back-to-heading t))
14782 (org-set-tags arg just-align))))
14784 (defun org-set-tags-to (data)
14785 "Set the tags of the current entry to DATA, replacing the current tags.
14786 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14787 If DATA is nil or the empty string, any tags will be removed."
14788 (interactive "sTags: ")
14789 (setq data
14790 (cond
14791 ((eq data nil) "")
14792 ((equal data "") "")
14793 ((stringp data)
14794 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14795 ":"))
14796 ((listp data)
14797 (concat ":" (mapconcat 'identity data ":") ":"))))
14798 (when data
14799 (save-excursion
14800 (org-back-to-heading t)
14801 (when (looking-at org-complex-heading-regexp)
14802 (if (match-end 5)
14803 (progn
14804 (goto-char (match-beginning 5))
14805 (insert data)
14806 (delete-region (point) (point-at-eol))
14807 (org-set-tags nil 'align))
14808 (goto-char (point-at-eol))
14809 (insert " " data)
14810 (org-set-tags nil 'align)))
14811 (beginning-of-line 1)
14812 (if (looking-at ".*?\\([ \t]+\\)$")
14813 (delete-region (match-beginning 1) (match-end 1))))))
14815 (defun org-align-all-tags ()
14816 "Align the tags i all headings."
14817 (interactive)
14818 (save-excursion
14819 (or (ignore-errors (org-back-to-heading t))
14820 (outline-next-heading))
14821 (if (org-at-heading-p)
14822 (org-set-tags t)
14823 (message "No headings"))))
14825 (defvar org-indent-indentation-per-level)
14826 (defun org-set-tags (&optional arg just-align)
14827 "Set the tags for the current headline.
14828 With prefix ARG, realign all tags in headings in the current buffer.
14829 When JUST-ALIGN is non-nil, only align tags."
14830 (interactive "P")
14831 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14832 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14833 'region-start-level 'region))
14834 org-loop-over-headlines-in-active-region)
14835 (org-map-entries
14836 ;; We don't use ARG and JUST-ALIGN here because these args
14837 ;; are not useful when looping over headlines.
14838 `(org-set-tags)
14839 org-loop-over-headlines-in-active-region
14840 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14841 (let* ((re org-outline-regexp-bol)
14842 (current (unless arg (org-get-tags-string)))
14843 (col (current-column))
14844 (org-setting-tags t)
14845 table current-tags inherited-tags ; computed below when needed
14846 tags p0 c0 c1 rpl di tc level)
14847 (if arg
14848 (save-excursion
14849 (goto-char (point-min))
14850 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14851 (while (re-search-forward re nil t)
14852 (org-set-tags nil t)
14853 (end-of-line 1)))
14854 (message "All tags realigned to column %d" org-tags-column))
14855 (if just-align
14856 (setq tags current)
14857 ;; Get a new set of tags from the user
14858 (save-excursion
14859 (setq table (append org-tag-persistent-alist
14860 (or org-tag-alist (org-get-buffer-tags))
14861 (and
14862 org-complete-tags-always-offer-all-agenda-tags
14863 (org-global-tags-completion-table
14864 (org-agenda-files))))
14865 org-last-tags-completion-table table
14866 current-tags (org-split-string current ":")
14867 inherited-tags (nreverse
14868 (nthcdr (length current-tags)
14869 (nreverse (org-get-tags-at))))
14870 tags
14871 (if (or (eq t org-use-fast-tag-selection)
14872 (and org-use-fast-tag-selection
14873 (delq nil (mapcar 'cdr table))))
14874 (org-fast-tag-selection
14875 current-tags inherited-tags table
14876 (if org-fast-tag-selection-include-todo
14877 org-todo-key-alist))
14878 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14879 (org-trim
14880 (org-icompleting-read "Tags: "
14881 'org-tags-completion-function
14882 nil nil current 'org-tags-history))))))
14883 (while (string-match "[-+&]+" tags)
14884 ;; No boolean logic, just a list
14885 (setq tags (replace-match ":" t t tags))))
14887 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14889 (if org-tags-sort-function
14890 (setq tags (mapconcat 'identity
14891 (sort (org-split-string
14892 tags (org-re "[^[:alnum:]_@#%]+"))
14893 org-tags-sort-function) ":")))
14895 (if (string-match "\\`[\t ]*\\'" tags)
14896 (setq tags "")
14897 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14898 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14900 ;; Insert new tags at the correct column
14901 (beginning-of-line 1)
14902 (setq level (or (and (looking-at org-outline-regexp)
14903 (- (match-end 0) (point) 1))
14905 (cond
14906 ((and (equal current "") (equal tags "")))
14907 ((re-search-forward
14908 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14909 (point-at-eol) t)
14910 (if (equal tags "")
14911 (setq rpl "")
14912 (goto-char (match-beginning 0))
14913 (setq c0 (current-column)
14914 ;; compute offset for the case of org-indent-mode active
14915 di (if (org-bound-and-true-p org-indent-mode)
14916 (* (1- org-indent-indentation-per-level) (1- level))
14918 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14919 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14920 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14921 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14922 (replace-match rpl t t)
14923 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14924 tags)
14925 (t (error "Tags alignment failed")))
14926 (org-move-to-column col)
14927 (unless just-align
14928 (run-hooks 'org-after-tags-change-hook))))))
14930 (defun org-change-tag-in-region (beg end tag off)
14931 "Add or remove TAG for each entry in the region.
14932 This works in the agenda, and also in an org-mode buffer."
14933 (interactive
14934 (list (region-beginning) (region-end)
14935 (let ((org-last-tags-completion-table
14936 (if (derived-mode-p 'org-mode)
14937 (org-uniquify
14938 (delq nil (append (org-get-buffer-tags)
14939 (org-global-tags-completion-table))))
14940 (org-global-tags-completion-table))))
14941 (org-icompleting-read
14942 "Tag: " 'org-tags-completion-function nil nil nil
14943 'org-tags-history))
14944 (progn
14945 (message "[s]et or [r]emove? ")
14946 (equal (read-char-exclusive) ?r))))
14947 (if (fboundp 'deactivate-mark) (deactivate-mark))
14948 (let ((agendap (equal major-mode 'org-agenda-mode))
14949 l1 l2 m buf pos newhead (cnt 0))
14950 (goto-char end)
14951 (setq l2 (1- (org-current-line)))
14952 (goto-char beg)
14953 (setq l1 (org-current-line))
14954 (loop for l from l1 to l2 do
14955 (org-goto-line l)
14956 (setq m (get-text-property (point) 'org-hd-marker))
14957 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14958 (and agendap m))
14959 (setq buf (if agendap (marker-buffer m) (current-buffer))
14960 pos (if agendap m (point)))
14961 (with-current-buffer buf
14962 (save-excursion
14963 (save-restriction
14964 (goto-char pos)
14965 (setq cnt (1+ cnt))
14966 (org-toggle-tag tag (if off 'off 'on))
14967 (setq newhead (org-get-heading)))))
14968 (and agendap (org-agenda-change-all-lines newhead m))))
14969 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14971 (defun org-tags-completion-function (string predicate &optional flag)
14972 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14973 (confirm (lambda (x) (stringp (car x)))))
14974 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14975 (setq s1 (match-string 1 string)
14976 s2 (match-string 2 string))
14977 (setq s1 "" s2 string))
14978 (cond
14979 ((eq flag nil)
14980 ;; try completion
14981 (setq rtn (try-completion s2 ctable confirm))
14982 (if (stringp rtn)
14983 (setq rtn
14984 (concat s1 s2 (substring rtn (length s2))
14985 (if (and org-add-colon-after-tag-completion
14986 (assoc rtn ctable))
14987 ":" ""))))
14988 rtn)
14989 ((eq flag t)
14990 ;; all-completions
14991 (all-completions s2 ctable confirm))
14992 ((eq flag 'lambda)
14993 ;; exact match?
14994 (assoc s2 ctable)))))
14996 (defun org-fast-tag-insert (kwd tags face &optional end)
14997 "Insert KDW, and the TAGS, the latter with face FACE.
14998 Also insert END."
14999 (insert (format "%-12s" (concat kwd ":"))
15000 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15001 (or end "")))
15003 (defun org-fast-tag-show-exit (flag)
15004 (save-excursion
15005 (org-goto-line 3)
15006 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15007 (replace-match ""))
15008 (when flag
15009 (end-of-line 1)
15010 (org-move-to-column (- (window-width) 19) t)
15011 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15013 (defun org-set-current-tags-overlay (current prefix)
15014 "Add an overlay to CURRENT tag with PREFIX."
15015 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15016 (if (featurep 'xemacs)
15017 (org-overlay-display org-tags-overlay (concat prefix s)
15018 'secondary-selection)
15019 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15020 (org-overlay-display org-tags-overlay (concat prefix s)))))
15022 (defvar org-last-tag-selection-key nil)
15023 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15024 "Fast tag selection with single keys.
15025 CURRENT is the current list of tags in the headline, INHERITED is the
15026 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15027 possibly with grouping information. TODO-TABLE is a similar table with
15028 TODO keywords, should these have keys assigned to them.
15029 If the keys are nil, a-z are automatically assigned.
15030 Returns the new tags string, or nil to not change the current settings."
15031 (let* ((fulltable (append table todo-table))
15032 (maxlen (apply 'max (mapcar
15033 (lambda (x)
15034 (if (stringp (car x)) (string-width (car x)) 0))
15035 fulltable)))
15036 (buf (current-buffer))
15037 (expert (eq org-fast-tag-selection-single-key 'expert))
15038 (buffer-tags nil)
15039 (fwidth (+ maxlen 3 1 3))
15040 (ncol (/ (- (window-width) 4) fwidth))
15041 (i-face 'org-done)
15042 (c-face 'org-todo)
15043 tg cnt e c char c1 c2 ntable tbl rtn
15044 ov-start ov-end ov-prefix
15045 (exit-after-next org-fast-tag-selection-single-key)
15046 (done-keywords org-done-keywords)
15047 groups ingroup)
15048 (save-excursion
15049 (beginning-of-line 1)
15050 (if (looking-at
15051 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15052 (setq ov-start (match-beginning 1)
15053 ov-end (match-end 1)
15054 ov-prefix "")
15055 (setq ov-start (1- (point-at-eol))
15056 ov-end (1+ ov-start))
15057 (skip-chars-forward "^\n\r")
15058 (setq ov-prefix
15059 (concat
15060 (buffer-substring (1- (point)) (point))
15061 (if (> (current-column) org-tags-column)
15063 (make-string (- org-tags-column (current-column)) ?\ ))))))
15064 (move-overlay org-tags-overlay ov-start ov-end)
15065 (save-window-excursion
15066 (if expert
15067 (set-buffer (get-buffer-create " *Org tags*"))
15068 (delete-other-windows)
15069 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15070 (org-switch-to-buffer-other-window " *Org tags*"))
15071 (erase-buffer)
15072 (org-set-local 'org-done-keywords done-keywords)
15073 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15074 (org-fast-tag-insert "Current" current c-face "\n\n")
15075 (org-fast-tag-show-exit exit-after-next)
15076 (org-set-current-tags-overlay current ov-prefix)
15077 (setq tbl fulltable char ?a cnt 0)
15078 (while (setq e (pop tbl))
15079 (cond
15080 ((equal (car e) :startgroup)
15081 (push '() groups) (setq ingroup t)
15082 (when (not (= cnt 0))
15083 (setq cnt 0)
15084 (insert "\n"))
15085 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15086 ((equal (car e) :endgroup)
15087 (setq ingroup nil cnt 0)
15088 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15089 ((equal e '(:newline))
15090 (when (not (= cnt 0))
15091 (setq cnt 0)
15092 (insert "\n")
15093 (setq e (car tbl))
15094 (while (equal (car tbl) '(:newline))
15095 (insert "\n")
15096 (setq tbl (cdr tbl)))))
15097 ((equal e '(:grouptags)) nil)
15099 (setq tg (copy-sequence (car e)) c2 nil)
15100 (if (cdr e)
15101 (setq c (cdr e))
15102 ;; automatically assign a character.
15103 (setq c1 (string-to-char
15104 (downcase (substring
15105 tg (if (= (string-to-char tg) ?@) 1 0)))))
15106 (if (or (rassoc c1 ntable) (rassoc c1 table))
15107 (while (or (rassoc char ntable) (rassoc char table))
15108 (setq char (1+ char)))
15109 (setq c2 c1))
15110 (setq c (or c2 char)))
15111 (if ingroup (push tg (car groups)))
15112 (setq tg (org-add-props tg nil 'face
15113 (cond
15114 ((not (assoc tg table))
15115 (org-get-todo-face tg))
15116 ((member tg current) c-face)
15117 ((member tg inherited) i-face))))
15118 (if (equal (caar tbl) :grouptags)
15119 (org-add-props tg nil 'face 'org-tag-group))
15120 (if (and (= cnt 0) (not ingroup)) (insert " "))
15121 (insert "[" c "] " tg (make-string
15122 (- fwidth 4 (length tg)) ?\ ))
15123 (push (cons tg c) ntable)
15124 (when (= (setq cnt (1+ cnt)) ncol)
15125 (insert "\n")
15126 (if ingroup (insert " "))
15127 (setq cnt 0)))))
15128 (setq ntable (nreverse ntable))
15129 (insert "\n")
15130 (goto-char (point-min))
15131 (if (not expert) (org-fit-window-to-buffer))
15132 (setq rtn
15133 (catch 'exit
15134 (while t
15135 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15136 (if (not groups) "no " "")
15137 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15138 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15139 (setq org-last-tag-selection-key c)
15140 (cond
15141 ((= c ?\r) (throw 'exit t))
15142 ((= c ?!)
15143 (setq groups (not groups))
15144 (goto-char (point-min))
15145 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15146 ((= c ?\C-c)
15147 (if (not expert)
15148 (org-fast-tag-show-exit
15149 (setq exit-after-next (not exit-after-next)))
15150 (setq expert nil)
15151 (delete-other-windows)
15152 (set-window-buffer (split-window-vertically) " *Org tags*")
15153 (org-switch-to-buffer-other-window " *Org tags*")
15154 (org-fit-window-to-buffer)))
15155 ((or (= c ?\C-g)
15156 (and (= c ?q) (not (rassoc c ntable))))
15157 (org-detach-overlay org-tags-overlay)
15158 (setq quit-flag t))
15159 ((= c ?\ )
15160 (setq current nil)
15161 (if exit-after-next (setq exit-after-next 'now)))
15162 ((= c ?\t)
15163 (condition-case nil
15164 (setq tg (org-icompleting-read
15165 "Tag: "
15166 (or buffer-tags
15167 (with-current-buffer buf
15168 (org-get-buffer-tags)))))
15169 (quit (setq tg "")))
15170 (when (string-match "\\S-" tg)
15171 (add-to-list 'buffer-tags (list tg))
15172 (if (member tg current)
15173 (setq current (delete tg current))
15174 (push tg current)))
15175 (if exit-after-next (setq exit-after-next 'now)))
15176 ((setq e (rassoc c todo-table) tg (car e))
15177 (with-current-buffer buf
15178 (save-excursion (org-todo tg)))
15179 (if exit-after-next (setq exit-after-next 'now)))
15180 ((setq e (rassoc c ntable) tg (car e))
15181 (if (member tg current)
15182 (setq current (delete tg current))
15183 (loop for g in groups do
15184 (if (member tg g)
15185 (mapc (lambda (x)
15186 (setq current (delete x current)))
15187 g)))
15188 (push tg current))
15189 (if exit-after-next (setq exit-after-next 'now))))
15191 ;; Create a sorted list
15192 (setq current
15193 (sort current
15194 (lambda (a b)
15195 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15196 (if (eq exit-after-next 'now) (throw 'exit t))
15197 (goto-char (point-min))
15198 (beginning-of-line 2)
15199 (delete-region (point) (point-at-eol))
15200 (org-fast-tag-insert "Current" current c-face)
15201 (org-set-current-tags-overlay current ov-prefix)
15202 (while (re-search-forward
15203 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15204 (setq tg (match-string 1))
15205 (add-text-properties
15206 (match-beginning 1) (match-end 1)
15207 (list 'face
15208 (cond
15209 ((member tg current) c-face)
15210 ((member tg inherited) i-face)
15211 (t (get-text-property (match-beginning 1) 'face))))))
15212 (goto-char (point-min)))))
15213 (org-detach-overlay org-tags-overlay)
15214 (if rtn
15215 (mapconcat 'identity current ":")
15216 nil))))
15218 (defun org-get-tags-string ()
15219 "Get the TAGS string in the current headline."
15220 (unless (org-at-heading-p t)
15221 (user-error "Not on a heading"))
15222 (save-excursion
15223 (beginning-of-line 1)
15224 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15225 (org-match-string-no-properties 1)
15226 "")))
15228 (defun org-get-tags ()
15229 "Get the list of tags specified in the current headline."
15230 (org-split-string (org-get-tags-string) ":"))
15232 (defun org-get-buffer-tags ()
15233 "Get a table of all tags used in the buffer, for completion."
15234 (org-with-wide-buffer
15235 (goto-char (point-min))
15236 (let ((tag-re (concat org-outline-regexp-bol
15237 "\\(?:.*?[ \t]\\)?"
15238 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15239 tags)
15240 (while (re-search-forward tag-re nil t)
15241 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15242 (push tag tags)))
15243 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15245 ;;;; The mapping API
15247 (defun org-map-entries (func &optional match scope &rest skip)
15248 "Call FUNC at each headline selected by MATCH in SCOPE.
15250 FUNC is a function or a lisp form. The function will be called without
15251 arguments, with the cursor positioned at the beginning of the headline.
15252 The return values of all calls to the function will be collected and
15253 returned as a list.
15255 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15256 does not need to preserve point. After evaluation, the cursor will be
15257 moved to the end of the line (presumably of the headline of the
15258 processed entry) and search continues from there. Under some
15259 circumstances, this may not produce the wanted results. For example,
15260 if you have removed (e.g. archived) the current (sub)tree it could
15261 mean that the next entry will be skipped entirely. In such cases, you
15262 can specify the position from where search should continue by making
15263 FUNC set the variable `org-map-continue-from' to the desired buffer
15264 position.
15266 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15267 Only headlines that are matched by this query will be considered during
15268 the iteration. When MATCH is nil or t, all headlines will be
15269 visited by the iteration.
15271 SCOPE determines the scope of this command. It can be any of:
15273 nil The current buffer, respecting the restriction if any
15274 tree The subtree started with the entry at point
15275 region The entries within the active region, if any
15276 region-start-level
15277 The entries within the active region, but only those at
15278 the same level than the first one.
15279 file The current buffer, without restriction
15280 file-with-archives
15281 The current buffer, and any archives associated with it
15282 agenda All agenda files
15283 agenda-with-archives
15284 All agenda files with any archive files associated with them
15285 \(file1 file2 ...)
15286 If this is a list, all files in the list will be scanned
15288 The remaining args are treated as settings for the skipping facilities of
15289 the scanner. The following items can be given here:
15291 archive skip trees with the archive tag
15292 comment skip trees with the COMMENT keyword
15293 function or Emacs Lisp form:
15294 will be used as value for `org-agenda-skip-function', so
15295 whenever the function returns a position, FUNC will not be
15296 called for that entry and search will continue from the
15297 position returned
15299 If your function needs to retrieve the tags including inherited tags
15300 at the *current* entry, you can use the value of the variable
15301 `org-scanner-tags' which will be much faster than getting the value
15302 with `org-get-tags-at'. If your function gets properties with
15303 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15304 to t around the call to `org-entry-properties' to get the same speedup.
15305 Note that if your function moves around to retrieve tags and properties at
15306 a *different* entry, you cannot use these techniques."
15307 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15308 (not (org-region-active-p)))
15309 (let* ((org-agenda-archives-mode nil) ; just to make sure
15310 (org-agenda-skip-archived-trees (memq 'archive skip))
15311 (org-agenda-skip-comment-trees (memq 'comment skip))
15312 (org-agenda-skip-function
15313 (car (org-delete-all '(comment archive) skip)))
15314 (org-tags-match-list-sublevels t)
15315 (start-level (eq scope 'region-start-level))
15316 matcher file res
15317 org-todo-keywords-for-agenda
15318 org-done-keywords-for-agenda
15319 org-todo-keyword-alist-for-agenda
15320 org-tag-alist-for-agenda
15321 todo-only)
15323 (cond
15324 ((eq match t) (setq matcher t))
15325 ((eq match nil) (setq matcher t))
15326 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15328 (save-excursion
15329 (save-restriction
15330 (cond ((eq scope 'tree)
15331 (org-back-to-heading t)
15332 (org-narrow-to-subtree)
15333 (setq scope nil))
15334 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15335 (org-region-active-p))
15336 ;; If needed, set start-level to a string like "2"
15337 (when start-level
15338 (save-excursion
15339 (goto-char (region-beginning))
15340 (unless (org-at-heading-p) (outline-next-heading))
15341 (setq start-level (org-current-level))))
15342 (narrow-to-region (region-beginning)
15343 (save-excursion
15344 (goto-char (region-end))
15345 (unless (and (bolp) (org-at-heading-p))
15346 (outline-next-heading))
15347 (point)))
15348 (setq scope nil)))
15350 (if (not scope)
15351 (progn
15352 (org-agenda-prepare-buffers
15353 (list (buffer-file-name (current-buffer))))
15354 (setq res (org-scan-tags func matcher todo-only start-level)))
15355 ;; Get the right scope
15356 (cond
15357 ((and scope (listp scope) (symbolp (car scope)))
15358 (setq scope (eval scope)))
15359 ((eq scope 'agenda)
15360 (setq scope (org-agenda-files t)))
15361 ((eq scope 'agenda-with-archives)
15362 (setq scope (org-agenda-files t))
15363 (setq scope (org-add-archive-files scope)))
15364 ((eq scope 'file)
15365 (setq scope (list (buffer-file-name))))
15366 ((eq scope 'file-with-archives)
15367 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15368 (org-agenda-prepare-buffers scope)
15369 (while (setq file (pop scope))
15370 (with-current-buffer (org-find-base-buffer-visiting file)
15371 (save-excursion
15372 (save-restriction
15373 (widen)
15374 (goto-char (point-min))
15375 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15376 res)))
15378 ;;; Properties API
15380 (defconst org-special-properties
15381 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15382 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15383 "The special properties valid in Org mode.
15384 These are properties that are not defined in the property drawer,
15385 but in some other way.")
15387 (defconst org-default-properties
15388 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15389 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15390 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15391 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15392 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15393 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15394 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15395 "Some properties that are used by Org mode for various purposes.
15396 Being in this list makes sure that they are offered for completion.")
15398 (defun org--update-property-plist (key val props)
15399 "Associate KEY to VAL in alist PROPS.
15400 Modifications are made by side-effect. Return new alist."
15401 (let* ((appending (string= (substring key -1) "+"))
15402 (key (if appending (substring key 0 -1) key))
15403 (old (assoc-string key props t)))
15404 (if (not old) (cons (cons key val) props)
15405 (setcdr old (if appending (concat (cdr old) " " val) val))
15406 props)))
15408 (defun org-get-property-block (&optional beg force)
15409 "Return the (beg . end) range of the body of the property drawer.
15410 BEG is the beginning of the current subtree, or of the part
15411 before the first headline. If it is not given, it will be found.
15412 If the drawer does not exist, create it if FORCE is non-nil, or
15413 return nil."
15414 (org-with-wide-buffer
15415 (when beg (goto-char beg))
15416 (unless (org-before-first-heading-p)
15417 (let ((beg (cond (beg)
15418 ((or (not (featurep 'org-inlinetask))
15419 (org-inlinetask-in-task-p))
15420 (org-back-to-heading t))
15421 (t (org-with-limited-levels (org-back-to-heading t))))))
15422 (forward-line)
15423 (when (org-looking-at-p org-planning-line-re) (forward-line))
15424 (cond ((looking-at org-property-drawer-re)
15425 (forward-line)
15426 (cons (point) (progn (goto-char (match-end 0))
15427 (line-beginning-position))))
15428 (force
15429 (goto-char beg)
15430 (org-insert-property-drawer)
15431 (let ((pos (save-excursion (search-forward ":END:")
15432 (line-beginning-position))))
15433 (cons pos pos))))))))
15435 (defun org-at-property-p ()
15436 "Non-nil when point is inside a property drawer.
15437 See `org-property-re' for match data, if applicable."
15438 (save-excursion
15439 (beginning-of-line)
15440 (and (looking-at org-property-re)
15441 (let ((property-drawer (save-match-data (org-get-property-block))))
15442 (and property-drawer (< (point) (cdr property-drawer)))))))
15444 (defun org-property-action ()
15445 "Do an action on properties."
15446 (interactive)
15447 (unless (org-at-property-p) (user-error "Not at a property"))
15448 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15449 (let ((c (read-char-exclusive)))
15450 (case c
15451 (?s (call-interactively #'org-set-property))
15452 (?d (call-interactively #'org-delete-property))
15453 (?D (call-interactively #'org-delete-property-globally))
15454 (?c (call-interactively #'org-compute-property-at-point))
15455 (otherwise (user-error "No such property action %c" c)))))
15457 (defun org-inc-effort ()
15458 "Increment the value of the effort property in the current entry."
15459 (interactive)
15460 (org-set-effort nil t))
15462 (defvar org-clock-effort) ; Defined in org-clock.el.
15463 (defvar org-clock-current-task) ; Defined in org-clock.el.
15464 (defun org-set-effort (&optional value increment)
15465 "Set the effort property of the current entry.
15466 With numerical prefix arg, use the nth allowed value, 0 stands for the
15467 10th allowed value.
15469 When INCREMENT is non-nil, set the property to the next allowed value."
15470 (interactive "P")
15471 (if (equal value 0) (setq value 10))
15472 (let* ((completion-ignore-case t)
15473 (prop org-effort-property)
15474 (cur (org-entry-get nil prop))
15475 (allowed (org-property-get-allowed-values nil prop 'table))
15476 (existing (mapcar 'list (org-property-values prop)))
15477 (heading (nth 4 (org-heading-components)))
15479 (val (cond
15480 ((stringp value) value)
15481 ((and allowed (integerp value))
15482 (or (car (nth (1- value) allowed))
15483 (car (org-last allowed))))
15484 ((and allowed increment)
15485 (or (caadr (member (list cur) allowed))
15486 (user-error "Allowed effort values are not set")))
15487 (allowed
15488 (message "Select 1-9,0, [RET%s]: %s"
15489 (if cur (concat "=" cur) "")
15490 (mapconcat 'car allowed " "))
15491 (setq rpl (read-char-exclusive))
15492 (if (equal rpl ?\r)
15494 (setq rpl (- rpl ?0))
15495 (if (equal rpl 0) (setq rpl 10))
15496 (if (and (> rpl 0) (<= rpl (length allowed)))
15497 (car (nth (1- rpl) allowed))
15498 (org-completing-read "Effort: " allowed nil))))
15500 (let (org-completion-use-ido org-completion-use-iswitchb)
15501 (org-completing-read
15502 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15503 (concat "[" cur "]") "")
15504 ": ")
15505 existing nil nil "" nil cur))))))
15506 (unless (equal (org-entry-get nil prop) val)
15507 (org-entry-put nil prop val))
15508 (org-refresh-property
15509 '((effort . identity)
15510 (effort-minutes . org-duration-string-to-minutes))
15511 val)
15512 (when (string= heading org-clock-current-task)
15513 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15514 (org-clock-update-mode-line))
15515 (message "%s is now %s" prop val)))
15517 (defun org-entry-properties (&optional pom which)
15518 "Get all properties of the current entry.
15520 When POM is a buffer position, get all properties from the entry
15521 there instead.
15523 This includes the TODO keyword, the tags, time strings for
15524 deadline, scheduled, and clocking, and any additional properties
15525 defined in the entry.
15527 If WHICH is nil or `all', get all properties. If WHICH is
15528 `special' or `standard', only get that subclass. If WHICH is
15529 a string, only get that property.
15531 Return value is an alist. Keys are properties, as upcased
15532 strings."
15533 (org-with-point-at pom
15534 (when (and (derived-mode-p 'org-mode)
15535 (ignore-errors (org-back-to-heading t)))
15536 (catch 'exit
15537 (let* ((beg (point))
15538 (specific (and (stringp which) (upcase which)))
15539 (which (cond ((not specific) which)
15540 ((member specific org-special-properties) 'special)
15541 (t 'standard)))
15542 props)
15543 ;; Get the special properties, like TODO and TAGS.
15544 (when (memq which '(nil all special))
15545 (when (or (not specific) (string= specific "CLOCKSUM"))
15546 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15547 (when clocksum
15548 (push (cons "CLOCKSUM"
15549 (org-columns-number-to-string
15550 (/ (float clocksum) 60.) 'add_times))
15551 props)))
15552 (when specific (throw 'exit props)))
15553 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15554 (let ((clocksumt (get-text-property (point)
15555 :org-clock-minutes-today)))
15556 (when clocksumt
15557 (push (cons "CLOCKSUM_T"
15558 (org-columns-number-to-string
15559 (/ (float clocksumt) 60.) 'add_times))
15560 props)))
15561 (when specific (throw 'exit props)))
15562 (when (or (not specific) (string= specific "ITEM"))
15563 (when (looking-at org-complex-heading-regexp)
15564 (push (cons "ITEM"
15565 (concat
15566 (org-match-string-no-properties 1)
15567 (let ((title (org-match-string-no-properties 4)))
15568 (when (org-string-nw-p title)
15569 (concat " " (org-remove-tabs title))))))
15570 props))
15571 (when specific (throw 'exit props)))
15572 (when (or (not specific) (string= specific "TODO"))
15573 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15574 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15575 (when specific (throw 'exit props)))
15576 (when (or (not specific) (string= specific "PRIORITY"))
15577 (when (looking-at org-priority-regexp)
15578 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15579 (when specific (throw 'exit props)))
15580 (when (or (not specific) (string= specific "FILE"))
15581 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15582 props)
15583 (when specific (throw 'exit props)))
15584 (when (or (not specific) (string= specific "TAGS"))
15585 (let ((value (org-string-nw-p (org-get-tags-string))))
15586 (when value (push (cons "TAGS" value) props)))
15587 (when specific (throw 'exit props)))
15588 (when (or (not specific) (string= specific "ALLTAGS"))
15589 (let ((value (org-get-tags-at)))
15590 (when value
15591 (push (cons "ALLTAGS"
15592 (format ":%s:" (mapconcat #'identity value ":")))
15593 props)))
15594 (when specific (throw 'exit props)))
15595 (when (or (not specific) (string= specific "BLOCKED"))
15596 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15597 (when specific (throw 'exit props)))
15598 (when (or (not specific)
15599 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15600 (forward-line)
15601 (when (org-looking-at-p org-planning-line-re)
15602 (end-of-line)
15603 (let ((bol (line-beginning-position))
15604 ;; Backward compatibility: time keywords used to
15605 ;; be configurable (before 8.3). Make sure we
15606 ;; get the correct keyword.
15607 (key-assoc `(("CLOSED" . ,org-closed-string)
15608 ("DEADLINE" . ,org-deadline-string)
15609 ("SCHEDULED" . ,org-scheduled-string))))
15610 (dolist (pair (if specific (list (assoc specific key-assoc))
15611 key-assoc))
15612 (save-excursion
15613 (when (search-backward (cdr pair) bol t)
15614 (goto-char (match-end 0))
15615 (skip-chars-forward " \t")
15616 (and (looking-at org-ts-regexp-both)
15617 (push (cons (car pair)
15618 (org-match-string-no-properties 0))
15619 props)))))))
15620 (when specific (throw 'exit props)))
15621 (when (or (not specific)
15622 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15623 (let ((find-ts
15624 (lambda (end ts)
15625 (let ((regexp (if (or (string= specific "TIMESTAMP")
15626 (assoc "TIMESTAMP_IA" ts))
15627 org-ts-regexp
15628 org-ts-regexp-both)))
15629 (catch 'next
15630 (while (re-search-forward regexp end t)
15631 (backward-char)
15632 (let ((object (org-element-context)))
15633 ;; Accept to match timestamps in node
15634 ;; properties, too.
15635 (when (memq (org-element-type object)
15636 '(node-property timestamp))
15637 (let ((type
15638 (org-element-property :type object)))
15639 (cond
15640 ((and (memq type '(active active-range))
15641 (not (equal specific "TIMESTAMP_IA")))
15642 (unless (assoc "TIMESTAMP" ts)
15643 (push (cons "TIMESTAMP"
15644 (org-element-property
15645 :raw-value object))
15647 (when specific (throw 'exit ts))))
15648 ((and (memq type '(inactive inactive-range))
15649 (not (string= specific "TIMESTAMP")))
15650 (unless (assoc "TIMESTAMP_IA" ts)
15651 (push (cons "TIMESTAMP_IA"
15652 (org-element-property
15653 :raw-value object))
15655 (when specific (throw 'exit ts))))))
15656 ;; Both timestamp types are found,
15657 ;; move to next part.
15658 (when (= (length ts) 2) (throw 'next ts)))))
15659 ts)))))
15660 (goto-char beg)
15661 ;; First look for timestamps within headline.
15662 (let ((ts (funcall find-ts (line-end-position) nil)))
15663 (if (= (length ts) 2) (setq props (nconc ts props))
15664 (forward-line)
15665 ;; Then find timestamps in the section, skipping
15666 ;; planning line.
15667 (when (org-looking-at-p org-planning-line-re)
15668 (forward-line))
15669 (let ((end (save-excursion (outline-next-heading))))
15670 (setq props (nconc (funcall find-ts end ts) props))))))))
15671 ;; Get the standard properties, like :PROP:.
15672 (when (memq which '(nil all standard))
15673 ;; If we are looking after a specific property, delegate
15674 ;; to `org-entry-get', which is faster. However, make an
15675 ;; exception for "CATEGORY", since it can be also set
15676 ;; through keywords (i.e. #+CATEGORY).
15677 (if (and specific (not (equal specific "CATEGORY")))
15678 (let ((value (org-entry-get beg specific nil t)))
15679 (throw 'exit (and value (list (cons specific value)))))
15680 (let ((range (org-get-property-block beg)))
15681 (when range
15682 (let ((end (cdr range)) seen-base)
15683 (goto-char (car range))
15684 ;; Unlike to `org--update-property-plist', we
15685 ;; handle the case where base values is found
15686 ;; after its extension. We also forbid standard
15687 ;; properties to be named as special properties.
15688 (while (re-search-forward org-property-re end t)
15689 (let* ((key (upcase (org-match-string-no-properties 2)))
15690 (extendp (org-string-match-p "\\+\\'" key))
15691 (key-base (if extendp (substring key 0 -1) key))
15692 (value (org-match-string-no-properties 3)))
15693 (cond
15694 ((member-ignore-case key-base org-special-properties))
15695 (extendp
15696 (setq props
15697 (org--update-property-plist key value props)))
15698 ((member key seen-base))
15699 (t (push key seen-base)
15700 (let ((p (assoc-string key props t)))
15701 (if p (setcdr p (concat value " " (cdr p)))
15702 (push (cons key value) props))))))))))))
15703 (unless (assoc "CATEGORY" props)
15704 (push (cons "CATEGORY" (org-get-category beg)) props)
15705 (when (string= specific "CATEGORY") (throw 'exit props)))
15706 ;; Return value.
15707 (append (get-text-property beg 'org-summaries) props))))))
15709 (defun org-entry-get (pom property &optional inherit literal-nil)
15710 "Get value of PROPERTY for entry or content at point-or-marker POM.
15712 If INHERIT is non-nil and the entry does not have the property,
15713 then also check higher levels of the hierarchy. If INHERIT is
15714 the symbol `selective', use inheritance only if the setting in
15715 `org-use-property-inheritance' selects PROPERTY for inheritance.
15717 If the property is present but empty, the return value is the
15718 empty string. If the property is not present at all, nil is
15719 returned. In any other case, return the value as a string.
15720 Search is case-insensitive.
15722 If LITERAL-NIL is set, return the string value \"nil\" as
15723 a string, do not interpret it as the list atom nil. This is used
15724 for inheritance when a \"nil\" value can supersede a non-nil
15725 value higher up the hierarchy."
15726 (org-with-point-at pom
15727 (cond
15728 ((and inherit
15729 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15730 (org-entry-get-with-inheritance property literal-nil))
15731 ((member-ignore-case property org-special-properties)
15732 ;; We need a special property. Use `org-entry-properties' to
15733 ;; retrieve it, but specify the wanted property.
15734 (cdr (assoc-string property (org-entry-properties nil property))))
15736 (let ((range (org-get-property-block)))
15737 (when range
15738 (let* ((case-fold-search t)
15739 (end (cdr range))
15740 (props
15741 (let ((global
15742 (or (assoc-string property org-file-properties t)
15743 (assoc-string property org-global-properties t)
15744 (assoc-string
15745 property org-global-properties-fixed t))))
15746 ;; Make sure to not re-use GLOBAL as
15747 ;; `org--update-property-plist' would alter it by
15748 ;; side-effect.
15749 (and global (list (cons property (cdr global))))))
15750 (find-value
15751 (lambda (key)
15752 (when (re-search-forward (org-re-property key nil t) end t)
15753 (setq props
15754 (org--update-property-plist
15755 key (org-match-string-no-properties 3) props))))))
15756 (goto-char (car range))
15757 ;; Find base value.
15758 (save-excursion (funcall find-value property))
15759 ;; Find additional values.
15760 (let ((property+ (concat property "+")))
15761 (while (funcall find-value property+)))
15762 ;; Return final value.
15763 (let ((val (cdr (assoc-string property props t))))
15764 (if literal-nil val (org-not-nil val))))))))))
15766 (defun org-property-or-variable-value (var &optional inherit)
15767 "Check if there is a property fixing the value of VAR.
15768 If yes, return this value. If not, return the current value of the variable."
15769 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15770 (if (and prop (stringp prop) (string-match "\\S-" prop))
15771 (read prop)
15772 (symbol-value var))))
15774 (defun org-entry-delete (pom property)
15775 "Delete the property PROPERTY from entry at point-or-marker POM."
15776 (unless (member property org-special-properties)
15777 (org-with-point-at pom
15778 (let ((range (org-get-property-block)))
15779 (when range
15780 (let ((begin (car range))
15781 (end (copy-marker (cdr range))))
15782 (goto-char begin)
15783 (when (re-search-forward (org-re-property property nil t) end t)
15784 (delete-region (match-beginning 0) (line-beginning-position 2))
15785 ;; If drawer is empty, remove it altogether.
15786 (when (= begin end)
15787 (delete-region (line-beginning-position 0)
15788 (line-beginning-position 2)))
15789 (set-marker end nil))))))))
15791 ;; Multi-values properties are properties that contain multiple values
15792 ;; These values are assumed to be single words, separated by whitespace.
15793 (defun org-entry-add-to-multivalued-property (pom property value)
15794 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15795 (let* ((old (org-entry-get pom property))
15796 (values (and old (org-split-string old "[ \t]"))))
15797 (setq value (org-entry-protect-space value))
15798 (unless (member value values)
15799 (setq values (append values (list value)))
15800 (org-entry-put pom property
15801 (mapconcat 'identity values " ")))))
15803 (defun org-entry-remove-from-multivalued-property (pom property value)
15804 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15805 (let* ((old (org-entry-get pom property))
15806 (values (and old (org-split-string old "[ \t]"))))
15807 (setq value (org-entry-protect-space value))
15808 (when (member value values)
15809 (setq values (delete value values))
15810 (org-entry-put pom property
15811 (mapconcat 'identity values " ")))))
15813 (defun org-entry-member-in-multivalued-property (pom property value)
15814 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15815 (let* ((old (org-entry-get pom property))
15816 (values (and old (org-split-string old "[ \t]"))))
15817 (setq value (org-entry-protect-space value))
15818 (member value values)))
15820 (defun org-entry-get-multivalued-property (pom property)
15821 "Return a list of values in a multivalued property."
15822 (let* ((value (org-entry-get pom property))
15823 (values (and value (org-split-string value "[ \t]"))))
15824 (mapcar 'org-entry-restore-space values)))
15826 (defun org-entry-put-multivalued-property (pom property &rest values)
15827 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15828 VALUES should be a list of strings. Spaces will be protected."
15829 (org-entry-put pom property
15830 (mapconcat 'org-entry-protect-space values " "))
15831 (let* ((value (org-entry-get pom property))
15832 (values (and value (org-split-string value "[ \t]"))))
15833 (mapcar 'org-entry-restore-space values)))
15835 (defun org-entry-protect-space (s)
15836 "Protect spaces and newline in string S."
15837 (while (string-match " " s)
15838 (setq s (replace-match "%20" t t s)))
15839 (while (string-match "\n" s)
15840 (setq s (replace-match "%0A" t t s)))
15843 (defun org-entry-restore-space (s)
15844 "Restore spaces and newline in string S."
15845 (while (string-match "%20" s)
15846 (setq s (replace-match " " t t s)))
15847 (while (string-match "%0A" s)
15848 (setq s (replace-match "\n" t t s)))
15851 (defvar org-entry-property-inherited-from (make-marker)
15852 "Marker pointing to the entry from where a property was inherited.
15853 Each call to `org-entry-get-with-inheritance' will set this marker to the
15854 location of the entry where the inheritance search matched. If there was
15855 no match, the marker will point nowhere.
15856 Note that also `org-entry-get' calls this function, if the INHERIT flag
15857 is set.")
15859 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15860 "Get PROPERTY of entry or content at point, search higher levels if needed.
15861 The search will stop at the first ancestor which has the property defined.
15862 If the value found is \"nil\", return nil to show that the property
15863 should be considered as undefined (this is the meaning of nil here).
15864 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15865 (move-marker org-entry-property-inherited-from nil)
15866 (let (value)
15867 (org-with-wide-buffer
15868 (catch 'exit
15869 (while t
15870 (when (setq value (org-entry-get nil property nil literal-nil))
15871 (org-back-to-heading t)
15872 (move-marker org-entry-property-inherited-from (point))
15873 (throw 'exit nil))
15874 (or (org-up-heading-safe) (throw 'exit nil)))))
15875 (unless value
15876 (setq value
15877 (cdr (or (assoc-string property org-file-properties t)
15878 (assoc-string property org-global-properties t)
15879 (assoc-string property org-global-properties-fixed t)))))
15880 (if literal-nil value (org-not-nil value))))
15882 (defvar org-property-changed-functions nil
15883 "Hook called when the value of a property has changed.
15884 Each hook function should accept two arguments, the name of the property
15885 and the new value.")
15887 (defun org-entry-put (pom property value)
15888 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15890 If the value is `nil', it is converted to the empty string. If
15891 it is not a string, an error is raised.
15893 PROPERTY can be any regular property (see
15894 `org-special-properties'). It can also be \"TODO\",
15895 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15897 For the last two properties, VALUE may have any of the special
15898 values \"earlier\" and \"later\". The function then increases or
15899 decreases scheduled or deadline date by one day."
15900 (cond ((null value) (setq value ""))
15901 ((not (stringp value)) (error "Properties values should be strings")))
15902 (org-with-point-at pom
15903 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15904 (org-back-to-heading t)
15905 (org-with-limited-levels (org-back-to-heading t)))
15906 (let ((beg (point)))
15907 (cond
15908 ((equal property "TODO")
15909 (cond ((not (org-string-nw-p value)) (setq value 'none))
15910 ((not (member value org-todo-keywords-1))
15911 (user-error "\"%s\" is not a valid TODO state" value)))
15912 (org-todo value)
15913 (org-set-tags nil 'align))
15914 ((equal property "PRIORITY")
15915 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15916 (org-set-tags nil 'align))
15917 ((equal property "SCHEDULED")
15918 (forward-line)
15919 (if (and (org-looking-at-p org-planning-line-re)
15920 (re-search-forward
15921 org-scheduled-time-regexp (line-end-position) t))
15922 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15923 ((string= value "later") (org-timestamp-change 1 'day))
15924 ((string= value "") (org-schedule '(4)))
15925 (t (org-schedule nil value)))
15926 (if (member value '("earlier" "later" ""))
15927 (call-interactively #'org-schedule)
15928 (org-schedule nil value))))
15929 ((equal property "DEADLINE")
15930 (forward-line)
15931 (if (and (org-looking-at-p org-planning-line-re)
15932 (re-search-forward
15933 org-deadline-time-regexp (line-end-position) t))
15934 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15935 ((string= value "later") (org-timestamp-change 1 'day))
15936 ((string= value "") (org-deadline '(4)))
15937 (t (org-deadline nil value)))
15938 (if (member value '("earlier" "later" ""))
15939 (call-interactively #'org-deadline)
15940 (org-deadline nil value))))
15941 ((member property org-special-properties)
15942 (error "The %s property cannot be set with `org-entry-put'" property))
15944 (let* ((range (org-get-property-block beg 'force))
15945 (end (cdr range))
15946 (case-fold-search t))
15947 (goto-char (car range))
15948 (if (re-search-forward (org-re-property property nil t) end t)
15949 (progn (delete-region (match-beginning 0) (match-end 0))
15950 (goto-char (match-beginning 0)))
15951 (goto-char end)
15952 (insert "\n")
15953 (backward-char))
15954 (insert ":" property ":")
15955 (when value (insert " " value))
15956 (org-indent-line)))))
15957 (run-hook-with-args 'org-property-changed-functions property value)))
15959 (defun org-buffer-property-keys (&optional specials defaults columns)
15960 "Get all property keys in the current buffer.
15962 When SPECIALS is non-nil, also list the special properties that
15963 reflect things like tags and TODO state.
15965 When DEFAULTS is non-nil, also include properties that has
15966 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15967 DESCRIPTION, LOCATION, and LOGGING and others.
15969 When COLUMNS in non-nil, also include property names given in
15970 COLUMN formats in the current buffer."
15971 (let ((case-fold-search t)
15972 (props (append
15973 (and specials org-special-properties)
15974 (and defaults (cons org-effort-property org-default-properties))
15975 nil)))
15976 (org-with-wide-buffer
15977 (goto-char (point-min))
15978 (while (re-search-forward org-property-start-re nil t)
15979 (let ((range (org-get-property-block)))
15980 (catch 'skip
15981 (unless range
15982 (when (and (not (org-before-first-heading-p))
15983 (y-or-n-p (format "Malformed drawer at %d, repair?"
15984 (line-beginning-position))))
15985 (org-get-property-block nil t))
15986 (throw 'skip nil))
15987 (goto-char (car range))
15988 (let ((begin (car range))
15989 (end (cdr range)))
15990 ;; Make sure that found property block is not located
15991 ;; before current point, as it would generate an infloop.
15992 ;; It can happen, for example, in the following
15993 ;; situation:
15995 ;; * Headline
15996 ;; :PROPERTIES:
15997 ;; ...
15998 ;; :END:
15999 ;; *************** Inlinetask
16000 ;; #+BEGIN_EXAMPLE
16001 ;; :PROPERTIES:
16002 ;; #+END_EXAMPLE
16004 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16005 (while (< (point) end)
16006 (let ((p (progn (looking-at org-property-re)
16007 (org-match-string-no-properties 2))))
16008 ;; Only add true property name, not extension symbol.
16009 (add-to-list 'props
16010 (if (not (org-string-match-p "\\+\\'" p)) p
16011 (substring p 0 -1))))
16012 (forward-line))))
16013 (outline-next-heading)))
16014 (when columns
16015 (goto-char (point-min))
16016 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16017 (let ((element (org-element-at-point)))
16018 (when (memq (org-element-type element) '(keyword node-property))
16019 (let ((value (org-element-property :value element))
16020 (start 0))
16021 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16022 (setq start (match-end 0))
16023 (let ((p (org-match-string-no-properties 1 value)))
16024 (unless (member-ignore-case p org-special-properties)
16025 (add-to-list 'props p))))))))))
16026 (sort props (lambda (a b) (string< (upcase a) (upcase b))))))
16028 (defun org-property-values (key)
16029 "List all non-nil values of property KEY in current buffer."
16030 (org-with-wide-buffer
16031 (goto-char (point-min))
16032 (let ((case-fold-search t)
16033 (re (org-re-property key))
16034 values)
16035 (while (re-search-forward re nil t)
16036 (add-to-list 'values (org-entry-get (point) key)))
16037 values)))
16039 (defun org-insert-property-drawer ()
16040 "Insert a property drawer into the current entry."
16041 (org-with-wide-buffer
16042 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16043 (org-back-to-heading t)
16044 (org-with-limited-levels (org-back-to-heading t)))
16045 (forward-line)
16046 (when (org-looking-at-p org-planning-line-re) (forward-line))
16047 (unless (org-looking-at-p org-property-drawer-re)
16048 (let ((inhibit-read-only t))
16049 (unless (bolp) (insert "\n"))
16050 (let ((begin (point)))
16051 (insert ":PROPERTIES:\n:END:\n")
16052 (org-indent-region begin (point)))))))
16054 (defun org-insert-drawer (&optional arg drawer)
16055 "Insert a drawer at point.
16057 When optional argument ARG is non-nil, insert a property drawer.
16059 Optional argument DRAWER, when non-nil, is a string representing
16060 drawer's name. Otherwise, the user is prompted for a name.
16062 If a region is active, insert the drawer around that region
16063 instead.
16065 Point is left between drawer's boundaries."
16066 (interactive "P")
16067 (let* ((drawer (if arg "PROPERTIES"
16068 (or drawer (read-from-minibuffer "Drawer: ")))))
16069 (cond
16070 ;; With C-u, fall back on `org-insert-property-drawer'
16071 (arg (org-insert-property-drawer))
16072 ;; Check validity of suggested drawer's name.
16073 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16074 (user-error "Invalid drawer name"))
16075 ;; With an active region, insert a drawer at point.
16076 ((not (org-region-active-p))
16077 (progn
16078 (unless (bolp) (insert "\n"))
16079 (insert (format ":%s:\n\n:END:\n" drawer))
16080 (forward-line -2)))
16081 ;; Otherwise, insert the drawer at point
16083 (let ((rbeg (region-beginning))
16084 (rend (copy-marker (region-end))))
16085 (unwind-protect
16086 (progn
16087 (goto-char rbeg)
16088 (beginning-of-line)
16089 (when (save-excursion
16090 (re-search-forward org-outline-regexp-bol rend t))
16091 (user-error "Drawers cannot contain headlines"))
16092 ;; Position point at the beginning of the first
16093 ;; non-blank line in region. Insert drawer's opening
16094 ;; there, then indent it.
16095 (org-skip-whitespace)
16096 (beginning-of-line)
16097 (insert ":" drawer ":\n")
16098 (forward-line -1)
16099 (indent-for-tab-command)
16100 ;; Move point to the beginning of the first blank line
16101 ;; after the last non-blank line in region. Insert
16102 ;; drawer's closing, then indent it.
16103 (goto-char rend)
16104 (skip-chars-backward " \r\t\n")
16105 (insert "\n:END:")
16106 (deactivate-mark t)
16107 (indent-for-tab-command)
16108 (unless (eolp) (insert "\n")))
16109 ;; Clear marker, whatever the outcome of insertion is.
16110 (set-marker rend nil)))))))
16112 (defvar org-property-set-functions-alist nil
16113 "Property set function alist.
16114 Each entry should have the following format:
16116 (PROPERTY . READ-FUNCTION)
16118 The read function will be called with the same argument as
16119 `org-completing-read'.")
16121 (defun org-set-property-function (property)
16122 "Get the function that should be used to set PROPERTY.
16123 This is computed according to `org-property-set-functions-alist'."
16124 (or (cdr (assoc property org-property-set-functions-alist))
16125 'org-completing-read))
16127 (defun org-read-property-value (property)
16128 "Read PROPERTY value from user."
16129 (let* ((completion-ignore-case t)
16130 (allowed (org-property-get-allowed-values nil property 'table))
16131 (cur (org-entry-get nil property))
16132 (prompt (concat property " value"
16133 (if (and cur (string-match "\\S-" cur))
16134 (concat " [" cur "]") "") ": "))
16135 (set-function (org-set-property-function property))
16136 (val (if allowed
16137 (funcall set-function prompt allowed nil
16138 (not (get-text-property 0 'org-unrestricted
16139 (caar allowed))))
16140 (let (org-completion-use-ido org-completion-use-iswitchb)
16141 (funcall set-function prompt
16142 (mapcar 'list (org-property-values property))
16143 nil nil "" nil cur)))))
16144 (org-trim val)))
16146 (defvar org-last-set-property nil)
16147 (defvar org-last-set-property-value nil)
16148 (defun org-read-property-name ()
16149 "Read a property name."
16150 (let* ((completion-ignore-case t)
16151 (keys (org-buffer-property-keys nil t t))
16152 (default-prop (or (save-excursion
16153 (save-match-data
16154 (beginning-of-line)
16155 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16156 (null (string= (match-string 1) "END"))
16157 (match-string 1))))
16158 org-last-set-property))
16159 (property (org-icompleting-read
16160 (concat "Property"
16161 (if default-prop (concat " [" default-prop "]") "")
16162 ": ")
16163 (mapcar 'list keys)
16164 nil nil nil nil
16165 default-prop)))
16166 (if (member property keys)
16167 property
16168 (or (cdr (assoc (downcase property)
16169 (mapcar (lambda (x) (cons (downcase x) x))
16170 keys)))
16171 property))))
16173 (defun org-set-property-and-value (use-last)
16174 "Allow to set [PROPERTY]: [value] direction from prompt.
16175 When use-default, don't even ask, just use the last
16176 \"[PROPERTY]: [value]\" string from the history."
16177 (interactive "P")
16178 (let* ((completion-ignore-case t)
16179 (pv (or (and use-last org-last-set-property-value)
16180 (org-completing-read
16181 "Enter a \"[Property]: [value]\" pair: "
16182 nil nil nil nil nil
16183 org-last-set-property-value)))
16184 prop val)
16185 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16186 (setq prop (match-string 1 pv)
16187 val (match-string 2 pv))
16188 (org-set-property prop val))))
16190 (defun org-set-property (property value)
16191 "In the current entry, set PROPERTY to VALUE.
16192 When called interactively, this will prompt for a property name, offering
16193 completion on existing and default properties. And then it will prompt
16194 for a value, offering completion either on allowed values (via an inherited
16195 xxx_ALL property) or on existing values in other instances of this property
16196 in the current file."
16197 (interactive (list nil nil))
16198 (let* ((property (or property (org-read-property-name)))
16199 (value (or value (org-read-property-value property)))
16200 (fn (cdr (assoc property org-properties-postprocess-alist))))
16201 (setq org-last-set-property property)
16202 (setq org-last-set-property-value (concat property ": " value))
16203 ;; Possibly postprocess the inserted value:
16204 (when fn (setq value (funcall fn value)))
16205 (unless (equal (org-entry-get nil property) value)
16206 (org-entry-put nil property value))))
16208 (defun org-delete-property (property)
16209 "In the current entry, delete PROPERTY."
16210 (interactive
16211 (let* ((completion-ignore-case t)
16212 (cat (org-entry-get (point) "CATEGORY"))
16213 (props0 (org-entry-properties nil 'standard))
16214 (props (if cat props0
16215 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16216 (prop (if (< 1 (length props))
16217 (org-icompleting-read "Property: " props nil t)
16218 (caar props))))
16219 (list prop)))
16220 (if (not property)
16221 (message "No property to delete in this entry")
16222 (org-entry-delete nil property)
16223 (message "Property \"%s\" deleted" property)))
16225 (defun org-delete-property-globally (property)
16226 "Remove PROPERTY globally, from all entries."
16227 (interactive
16228 (let* ((completion-ignore-case t)
16229 (prop (org-icompleting-read
16230 "Globally remove property: "
16231 (mapcar 'list (org-buffer-property-keys)))))
16232 (list prop)))
16233 (save-excursion
16234 (save-restriction
16235 (widen)
16236 (goto-char (point-min))
16237 (let ((cnt 0))
16238 (while (re-search-forward
16239 (org-re-property property)
16240 nil t)
16241 (setq cnt (1+ cnt))
16242 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16243 (message "Property \"%s\" removed from %d entries" property cnt)))))
16245 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16247 (defun org-compute-property-at-point ()
16248 "Compute the property at point.
16249 This looks for an enclosing column format, extracts the operator and
16250 then applies it to the property in the column format's scope."
16251 (interactive)
16252 (unless (org-at-property-p)
16253 (user-error "Not at a property"))
16254 (let ((prop (org-match-string-no-properties 2)))
16255 (org-columns-get-format-and-top-level)
16256 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16257 (user-error "No operator defined for property %s" prop))
16258 (org-columns-compute prop)))
16260 (defvar org-property-allowed-value-functions nil
16261 "Hook for functions supplying allowed values for a specific property.
16262 The functions must take a single argument, the name of the property, and
16263 return a flat list of allowed values. If \":ETC\" is one of
16264 the values, this means that these values are intended as defaults for
16265 completion, but that other values should be allowed too.
16266 The functions must return nil if they are not responsible for this
16267 property.")
16269 (defun org-property-get-allowed-values (pom property &optional table)
16270 "Get allowed values for the property PROPERTY.
16271 When TABLE is non-nil, return an alist that can directly be used for
16272 completion."
16273 (let (vals)
16274 (cond
16275 ((equal property "TODO")
16276 (setq vals (org-with-point-at pom
16277 (append org-todo-keywords-1 '("")))))
16278 ((equal property "PRIORITY")
16279 (let ((n org-lowest-priority))
16280 (while (>= n org-highest-priority)
16281 (push (char-to-string n) vals)
16282 (setq n (1- n)))))
16283 ((member property org-special-properties))
16284 ((setq vals (run-hook-with-args-until-success
16285 'org-property-allowed-value-functions property)))
16287 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16288 (when (and vals (string-match "\\S-" vals))
16289 (setq vals (car (read-from-string (concat "(" vals ")"))))
16290 (setq vals (mapcar (lambda (x)
16291 (cond ((stringp x) x)
16292 ((numberp x) (number-to-string x))
16293 ((symbolp x) (symbol-name x))
16294 (t "???")))
16295 vals)))))
16296 (when (member ":ETC" vals)
16297 (setq vals (remove ":ETC" vals))
16298 (org-add-props (car vals) '(org-unrestricted t)))
16299 (if table (mapcar 'list vals) vals)))
16301 (defun org-property-previous-allowed-value (&optional previous)
16302 "Switch to the next allowed value for this property."
16303 (interactive)
16304 (org-property-next-allowed-value t))
16306 (defun org-property-next-allowed-value (&optional previous)
16307 "Switch to the next allowed value for this property."
16308 (interactive)
16309 (unless (org-at-property-p)
16310 (user-error "Not at a property"))
16311 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16312 (key (match-string 2))
16313 (value (match-string 3))
16314 (allowed (or (org-property-get-allowed-values (point) key)
16315 (and (member value '("[ ]" "[-]" "[X]"))
16316 '("[ ]" "[X]"))))
16317 (heading (save-match-data (nth 4 (org-heading-components))))
16318 nval)
16319 (unless allowed
16320 (user-error "Allowed values for this property have not been defined"))
16321 (if previous (setq allowed (reverse allowed)))
16322 (if (member value allowed)
16323 (setq nval (car (cdr (member value allowed)))))
16324 (setq nval (or nval (car allowed)))
16325 (if (equal nval value)
16326 (user-error "Only one allowed value for this property"))
16327 (org-at-property-p)
16328 (replace-match (concat " :" key ": " nval) t t)
16329 (org-indent-line)
16330 (beginning-of-line 1)
16331 (skip-chars-forward " \t")
16332 (when (equal prop org-effort-property)
16333 (org-refresh-property
16334 '((effort . identity)
16335 (effort-minutes . org-duration-string-to-minutes))
16336 nval)
16337 (when (string= org-clock-current-task heading)
16338 (setq org-clock-effort nval)
16339 (org-clock-update-mode-line)))
16340 (run-hook-with-args 'org-property-changed-functions key nval)))
16342 (defun org-find-olp (path &optional this-buffer)
16343 "Return a marker pointing to the entry at outline path OLP.
16344 If anything goes wrong, throw an error.
16345 You can wrap this call to catch the error like this:
16347 (condition-case msg
16348 (org-mobile-locate-entry (match-string 4))
16349 (error (nth 1 msg)))
16351 The return value will then be either a string with the error message,
16352 or a marker if everything is OK.
16354 If THIS-BUFFER is set, the outline path does not contain a file,
16355 only headings."
16356 (let* ((file (if this-buffer buffer-file-name (pop path)))
16357 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16358 (level 1)
16359 (lmin 1)
16360 (lmax 1)
16361 limit re end found pos heading cnt flevel)
16362 (unless buffer (error "File not found :%s" file))
16363 (with-current-buffer buffer
16364 (save-excursion
16365 (save-restriction
16366 (widen)
16367 (setq limit (point-max))
16368 (goto-char (point-min))
16369 (while (setq heading (pop path))
16370 (setq re (format org-complex-heading-regexp-format
16371 (regexp-quote heading)))
16372 (setq cnt 0 pos (point))
16373 (while (re-search-forward re end t)
16374 (setq level (- (match-end 1) (match-beginning 1)))
16375 (if (and (>= level lmin) (<= level lmax))
16376 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16377 (when (= cnt 0) (error "Heading not found on level %d: %s"
16378 lmax heading))
16379 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16380 lmax heading))
16381 (goto-char found)
16382 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16383 (setq end (save-excursion (org-end-of-subtree t t))))
16384 (when (org-at-heading-p)
16385 (point-marker)))))))
16387 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16388 "Find node HEADING in BUFFER.
16389 Return a marker to the heading if it was found, or nil if not.
16390 If POS-ONLY is set, return just the position instead of a marker.
16392 The heading text must match exact, but it may have a TODO keyword,
16393 a priority cookie and tags in the standard locations."
16394 (with-current-buffer (or buffer (current-buffer))
16395 (save-excursion
16396 (save-restriction
16397 (widen)
16398 (goto-char (point-min))
16399 (let (case-fold-search)
16400 (if (re-search-forward
16401 (format org-complex-heading-regexp-format
16402 (regexp-quote heading)) nil t)
16403 (if pos-only
16404 (match-beginning 0)
16405 (move-marker (make-marker) (match-beginning 0)))))))))
16407 (defun org-find-exact-heading-in-directory (heading &optional dir)
16408 "Find Org node headline HEADING in all .org files in directory DIR.
16409 When the target headline is found, return a marker to this location."
16410 (let ((files (directory-files (or dir default-directory)
16411 t "\\`[^.#].*\\.org\\'"))
16412 file visiting m buffer)
16413 (catch 'found
16414 (while (setq file (pop files))
16415 (message "trying %s" file)
16416 (setq visiting (org-find-base-buffer-visiting file))
16417 (setq buffer (or visiting (find-file-noselect file)))
16418 (setq m (org-find-exact-headline-in-buffer
16419 heading buffer))
16420 (when (and (not m) (not visiting)) (kill-buffer buffer))
16421 (and m (throw 'found m))))))
16423 (defun org-find-entry-with-id (ident)
16424 "Locate the entry that contains the ID property with exact value IDENT.
16425 IDENT can be a string, a symbol or a number, this function will search for
16426 the string representation of it.
16427 Return the position where this entry starts, or nil if there is no such entry."
16428 (interactive "sID: ")
16429 (let ((id (cond
16430 ((stringp ident) ident)
16431 ((symbol-name ident) (symbol-name ident))
16432 ((numberp ident) (number-to-string ident))
16433 (t (error "IDENT %s must be a string, symbol or number" ident))))
16434 (case-fold-search nil))
16435 (save-excursion
16436 (save-restriction
16437 (widen)
16438 (goto-char (point-min))
16439 (when (re-search-forward
16440 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16441 nil t)
16442 (org-back-to-heading t)
16443 (point))))))
16445 ;;;; Timestamps
16447 (defvar org-last-changed-timestamp nil)
16448 (defvar org-last-inserted-timestamp nil
16449 "The last time stamp inserted with `org-insert-time-stamp'.")
16450 (defvar org-ts-what) ; dynamically scoped parameter
16452 (defun org-time-stamp (arg &optional inactive)
16453 "Prompt for a date/time and insert a time stamp.
16454 If the user specifies a time like HH:MM or if this command is
16455 called with at least one prefix argument, the time stamp contains
16456 the date and the time. Otherwise, only the date is be included.
16458 All parts of a date not specified by the user is filled in from
16459 the current date/time. So if you just press return without
16460 typing anything, the time stamp will represent the current
16461 date/time.
16463 If there is already a timestamp at the cursor, it will be
16464 modified.
16466 With two universal prefix arguments, insert an active timestamp
16467 with the current time without prompting the user.
16469 When called from lisp, the timestamp is inactive if INACTIVE is
16470 non-nil."
16471 (interactive "P")
16472 (let* ((ts nil)
16473 (default-time
16474 ;; Default time is either today, or, when entering a range,
16475 ;; the range start.
16476 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16477 (save-excursion
16478 (re-search-backward
16479 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16480 (- (point) 20) t)))
16481 (apply 'encode-time (org-parse-time-string (match-string 1)))
16482 (current-time)))
16483 (default-input (and ts (org-get-compact-tod ts)))
16484 (repeater (save-excursion
16485 (save-match-data
16486 (beginning-of-line)
16487 (when (re-search-forward
16488 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16489 (save-excursion (progn (end-of-line) (point))) t)
16490 (match-string 0)))))
16491 org-time-was-given org-end-time-was-given time)
16492 (cond
16493 ((and (org-at-timestamp-p t)
16494 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16495 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16496 (insert "--")
16497 (setq time (let ((this-command this-command))
16498 (org-read-date arg 'totime nil nil
16499 default-time default-input inactive)))
16500 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16501 ((org-at-timestamp-p t)
16502 (setq time (let ((this-command this-command))
16503 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16504 (when (org-at-timestamp-p t) ; just to get the match data
16505 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16506 (replace-match "")
16507 (setq org-last-changed-timestamp
16508 (org-insert-time-stamp
16509 time (or org-time-was-given arg)
16510 inactive nil nil (list org-end-time-was-given)))
16511 (when repeater (goto-char (1- (point))) (insert " " repeater)
16512 (setq org-last-changed-timestamp
16513 (concat (substring org-last-inserted-timestamp 0 -1)
16514 " " repeater ">"))))
16515 (message "Timestamp updated"))
16516 ((equal arg '(16))
16517 (org-insert-time-stamp (current-time) t inactive))
16519 (setq time (let ((this-command this-command))
16520 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16521 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16522 nil nil (list org-end-time-was-given))))))
16524 ;; FIXME: can we use this for something else, like computing time differences?
16525 (defun org-get-compact-tod (s)
16526 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16527 (let* ((t1 (match-string 1 s))
16528 (h1 (string-to-number (match-string 2 s)))
16529 (m1 (string-to-number (match-string 3 s)))
16530 (t2 (and (match-end 4) (match-string 5 s)))
16531 (h2 (and t2 (string-to-number (match-string 6 s))))
16532 (m2 (and t2 (string-to-number (match-string 7 s))))
16533 dh dm)
16534 (if (not t2)
16536 (setq dh (- h2 h1) dm (- m2 m1))
16537 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16538 (concat t1 "+" (number-to-string dh)
16539 (and (/= 0 dm) (format ":%02d" dm)))))))
16541 (defun org-time-stamp-inactive (&optional arg)
16542 "Insert an inactive time stamp.
16543 An inactive time stamp is enclosed in square brackets instead of angle
16544 brackets. It is inactive in the sense that it does not trigger agenda entries,
16545 does not link to the calendar and cannot be changed with the S-cursor keys.
16546 So these are more for recording a certain time/date."
16547 (interactive "P")
16548 (org-time-stamp arg 'inactive))
16550 (defvar org-date-ovl (make-overlay 1 1))
16551 (overlay-put org-date-ovl 'face 'org-date-selected)
16552 (org-detach-overlay org-date-ovl)
16554 (defvar org-ans1) ; dynamically scoped parameter
16555 (defvar org-ans2) ; dynamically scoped parameter
16557 (defvar org-plain-time-of-day-regexp) ; defined below
16559 (defvar org-overriding-default-time nil) ; dynamically scoped
16560 (defvar org-read-date-overlay nil)
16561 (defvar org-dcst nil) ; dynamically scoped
16562 (defvar org-read-date-history nil)
16563 (defvar org-read-date-final-answer nil)
16564 (defvar org-read-date-analyze-futurep nil)
16565 (defvar org-read-date-analyze-forced-year nil)
16566 (defvar org-read-date-inactive)
16568 (defvar org-read-date-minibuffer-local-map
16569 (let* ((map (make-sparse-keymap)))
16570 (set-keymap-parent map minibuffer-local-map)
16571 (org-defkey map (kbd ".")
16572 (lambda () (interactive)
16573 ;; Are we at the beginning of the prompt?
16574 (if (looking-back "^[^:]+: ")
16575 (org-eval-in-calendar '(calendar-goto-today))
16576 (insert "."))))
16577 (org-defkey map (kbd "C-.")
16578 (lambda () (interactive)
16579 (org-eval-in-calendar '(calendar-goto-today))))
16580 (org-defkey map [(meta shift left)]
16581 (lambda () (interactive)
16582 (org-eval-in-calendar '(calendar-backward-month 1))))
16583 (org-defkey map [(meta shift right)]
16584 (lambda () (interactive)
16585 (org-eval-in-calendar '(calendar-forward-month 1))))
16586 (org-defkey map [(meta shift up)]
16587 (lambda () (interactive)
16588 (org-eval-in-calendar '(calendar-backward-year 1))))
16589 (org-defkey map [(meta shift down)]
16590 (lambda () (interactive)
16591 (org-eval-in-calendar '(calendar-forward-year 1))))
16592 (org-defkey map [?\e (shift left)]
16593 (lambda () (interactive)
16594 (org-eval-in-calendar '(calendar-backward-month 1))))
16595 (org-defkey map [?\e (shift right)]
16596 (lambda () (interactive)
16597 (org-eval-in-calendar '(calendar-forward-month 1))))
16598 (org-defkey map [?\e (shift up)]
16599 (lambda () (interactive)
16600 (org-eval-in-calendar '(calendar-backward-year 1))))
16601 (org-defkey map [?\e (shift down)]
16602 (lambda () (interactive)
16603 (org-eval-in-calendar '(calendar-forward-year 1))))
16604 (org-defkey map [(shift up)]
16605 (lambda () (interactive)
16606 (org-eval-in-calendar '(calendar-backward-week 1))))
16607 (org-defkey map [(shift down)]
16608 (lambda () (interactive)
16609 (org-eval-in-calendar '(calendar-forward-week 1))))
16610 (org-defkey map [(shift left)]
16611 (lambda () (interactive)
16612 (org-eval-in-calendar '(calendar-backward-day 1))))
16613 (org-defkey map [(shift right)]
16614 (lambda () (interactive)
16615 (org-eval-in-calendar '(calendar-forward-day 1))))
16616 (org-defkey map "!"
16617 (lambda () (interactive)
16618 (org-eval-in-calendar '(diary-view-entries))
16619 (message "")))
16620 (org-defkey map ">"
16621 (lambda () (interactive)
16622 (org-eval-in-calendar '(calendar-scroll-left 1))))
16623 (org-defkey map "<"
16624 (lambda () (interactive)
16625 (org-eval-in-calendar '(calendar-scroll-right 1))))
16626 (org-defkey map "\C-v"
16627 (lambda () (interactive)
16628 (org-eval-in-calendar
16629 '(calendar-scroll-left-three-months 1))))
16630 (org-defkey map "\M-v"
16631 (lambda () (interactive)
16632 (org-eval-in-calendar
16633 '(calendar-scroll-right-three-months 1))))
16634 map)
16635 "Keymap for minibuffer commands when using `org-read-date'.")
16637 (defvar org-def)
16638 (defvar org-defdecode)
16639 (defvar org-with-time)
16641 (defun org-read-date (&optional org-with-time to-time from-string prompt
16642 default-time default-input inactive)
16643 "Read a date, possibly a time, and make things smooth for the user.
16644 The prompt will suggest to enter an ISO date, but you can also enter anything
16645 which will at least partially be understood by `parse-time-string'.
16646 Unrecognized parts of the date will default to the current day, month, year,
16647 hour and minute. If this command is called to replace a timestamp at point,
16648 or to enter the second timestamp of a range, the default time is taken
16649 from the existing stamp. Furthermore, the command prefers the future,
16650 so if you are giving a date where the year is not given, and the day-month
16651 combination is already past in the current year, it will assume you
16652 mean next year. For details, see the manual. A few examples:
16654 3-2-5 --> 2003-02-05
16655 feb 15 --> currentyear-02-15
16656 2/15 --> currentyear-02-15
16657 sep 12 9 --> 2009-09-12
16658 12:45 --> today 12:45
16659 22 sept 0:34 --> currentyear-09-22 0:34
16660 12 --> currentyear-currentmonth-12
16661 Fri --> nearest Friday after today
16662 -Tue --> last Tuesday
16663 etc.
16665 Furthermore you can specify a relative date by giving, as the *first* thing
16666 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16667 change in days weeks, months, years.
16668 With a single plus or minus, the date is relative to today. With a double
16669 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16670 +4d --> four days from today
16671 +4 --> same as above
16672 +2w --> two weeks from today
16673 ++5 --> five days from default date
16675 The function understands only English month and weekday abbreviations.
16677 While prompting, a calendar is popped up - you can also select the
16678 date with the mouse (button 1). The calendar shows a period of three
16679 months. To scroll it to other months, use the keys `>' and `<'.
16680 If you don't like the calendar, turn it off with
16681 \(setq org-read-date-popup-calendar nil)
16683 With optional argument TO-TIME, the date will immediately be converted
16684 to an internal time.
16685 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16686 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16687 still enter a time, and this function will inform the calling routine
16688 about this change. The calling routine may then choose to change the
16689 format used to insert the time stamp into the buffer to include the time.
16690 With optional argument FROM-STRING, read from this string instead from
16691 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16692 the time/date that is used for everything that is not specified by the
16693 user."
16694 (require 'parse-time)
16695 (let* ((org-time-stamp-rounding-minutes
16696 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16697 (org-dcst org-display-custom-times)
16698 (ct (org-current-time))
16699 (org-def (or org-overriding-default-time default-time ct))
16700 (org-defdecode (decode-time org-def))
16701 (dummy (progn
16702 (when (< (nth 2 org-defdecode) org-extend-today-until)
16703 (setcar (nthcdr 2 org-defdecode) -1)
16704 (setcar (nthcdr 1 org-defdecode) 59)
16705 (setq org-def (apply 'encode-time org-defdecode)
16706 org-defdecode (decode-time org-def)))))
16707 (cur-frame (selected-frame))
16708 (mouse-autoselect-window nil) ; Don't let the mouse jump
16709 (calendar-frame-setup nil)
16710 (calendar-setup (when (eq calendar-setup 'calendar-only) 'calendar-only))
16711 (calendar-move-hook nil)
16712 (calendar-view-diary-initially-flag nil)
16713 (calendar-view-holidays-initially-flag nil)
16714 (timestr (format-time-string
16715 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16716 (prompt (concat (if prompt (concat prompt " ") "")
16717 (format "Date+time [%s]: " timestr)))
16718 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16720 (cond
16721 (from-string (setq ans from-string))
16722 (org-read-date-popup-calendar
16723 (save-excursion
16724 (save-window-excursion
16725 (calendar)
16726 (when (eq calendar-setup 'calendar-only)
16727 (setq cal-frame
16728 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16729 (select-frame cal-frame))
16730 (org-eval-in-calendar '(setq cursor-type nil) t)
16731 (unwind-protect
16732 (progn
16733 (calendar-forward-day (- (time-to-days org-def)
16734 (calendar-absolute-from-gregorian
16735 (calendar-current-date))))
16736 (org-eval-in-calendar nil t)
16737 (let* ((old-map (current-local-map))
16738 (map (copy-keymap calendar-mode-map))
16739 (minibuffer-local-map
16740 (copy-keymap org-read-date-minibuffer-local-map)))
16741 (org-defkey map (kbd "RET") 'org-calendar-select)
16742 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16743 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16744 (unwind-protect
16745 (progn
16746 (use-local-map map)
16747 (setq org-read-date-inactive inactive)
16748 (add-hook 'post-command-hook 'org-read-date-display)
16749 (setq org-ans0 (read-string prompt default-input
16750 'org-read-date-history nil))
16751 ;; org-ans0: from prompt
16752 ;; org-ans1: from mouse click
16753 ;; org-ans2: from calendar motion
16754 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16755 (remove-hook 'post-command-hook 'org-read-date-display)
16756 (use-local-map old-map)
16757 (when org-read-date-overlay
16758 (delete-overlay org-read-date-overlay)
16759 (setq org-read-date-overlay nil)))))
16760 (bury-buffer "*Calendar*")
16761 (when cal-frame
16762 (delete-frame cal-frame)
16763 (select-frame-set-input-focus cur-frame))))))
16765 (t ; Naked prompt only
16766 (unwind-protect
16767 (setq ans (read-string prompt default-input
16768 'org-read-date-history timestr))
16769 (when org-read-date-overlay
16770 (delete-overlay org-read-date-overlay)
16771 (setq org-read-date-overlay nil)))))
16773 (setq final (org-read-date-analyze ans org-def org-defdecode))
16775 (when org-read-date-analyze-forced-year
16776 (message "Year was forced into %s"
16777 (if org-read-date-force-compatible-dates
16778 "compatible range (1970-2037)"
16779 "range representable on this machine"))
16780 (ding))
16782 ;; One round trip to get rid of 34th of August and stuff like that....
16783 (setq final (decode-time (apply 'encode-time final)))
16785 (setq org-read-date-final-answer ans)
16787 (if to-time
16788 (apply 'encode-time final)
16789 (if (and (boundp 'org-time-was-given) org-time-was-given)
16790 (format "%04d-%02d-%02d %02d:%02d"
16791 (nth 5 final) (nth 4 final) (nth 3 final)
16792 (nth 2 final) (nth 1 final))
16793 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16795 (defun org-read-date-display ()
16796 "Display the current date prompt interpretation in the minibuffer."
16797 (when org-read-date-display-live
16798 (when org-read-date-overlay
16799 (delete-overlay org-read-date-overlay))
16800 (when (minibufferp (current-buffer))
16801 (save-excursion
16802 (end-of-line 1)
16803 (while (not (equal (buffer-substring
16804 (max (point-min) (- (point) 4)) (point))
16805 " "))
16806 (insert " ")))
16807 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16808 " " (or org-ans1 org-ans2)))
16809 (org-end-time-was-given nil)
16810 (f (org-read-date-analyze ans org-def org-defdecode))
16811 (fmts (if org-dcst
16812 org-time-stamp-custom-formats
16813 org-time-stamp-formats))
16814 (fmt (if (or org-with-time
16815 (and (boundp 'org-time-was-given) org-time-was-given))
16816 (cdr fmts)
16817 (car fmts)))
16818 (txt (format-time-string fmt (apply 'encode-time f)))
16819 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16820 (txt (concat "=> " txt)))
16821 (when (and org-end-time-was-given
16822 (string-match org-plain-time-of-day-regexp txt))
16823 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16824 org-end-time-was-given
16825 (substring txt (match-end 0)))))
16826 (when org-read-date-analyze-futurep
16827 (setq txt (concat txt " (=>F)")))
16828 (setq org-read-date-overlay
16829 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16830 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16832 (defun org-read-date-analyze (ans org-def org-defdecode)
16833 "Analyze the combined answer of the date prompt."
16834 ;; FIXME: cleanup and comment
16835 (let ((nowdecode (decode-time (current-time)))
16836 delta deltan deltaw deltadef year month day
16837 hour minute second wday pm h2 m2 tl wday1
16838 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16839 (setq org-read-date-analyze-futurep nil
16840 org-read-date-analyze-forced-year nil)
16841 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16842 (setq ans "+0"))
16844 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16845 (setq ans (replace-match "" t t ans)
16846 deltan (car delta)
16847 deltaw (nth 1 delta)
16848 deltadef (nth 2 delta)))
16850 ;; Check if there is an iso week date in there. If yes, store the
16851 ;; info and postpone interpreting it until the rest of the parsing
16852 ;; is done.
16853 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16854 (setq iso-year (if (match-end 1)
16855 (org-small-year-to-year
16856 (string-to-number (match-string 1 ans))))
16857 iso-weekday (if (match-end 3)
16858 (string-to-number (match-string 3 ans)))
16859 iso-week (string-to-number (match-string 2 ans)))
16860 (setq ans (replace-match "" t t ans)))
16862 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16863 (when (string-match
16864 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16865 (setq year (if (match-end 2)
16866 (string-to-number (match-string 2 ans))
16867 (progn (setq kill-year t)
16868 (string-to-number (format-time-string "%Y"))))
16869 month (string-to-number (match-string 3 ans))
16870 day (string-to-number (match-string 4 ans)))
16871 (if (< year 100) (setq year (+ 2000 year)))
16872 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16873 t nil ans)))
16875 ;; Help matching dotted european dates
16876 (when (string-match
16877 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16878 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16879 (setq kill-year t)
16880 (string-to-number (format-time-string "%Y")))
16881 day (string-to-number (match-string 1 ans))
16882 month (string-to-number (match-string 2 ans))
16883 ans (replace-match (format "%04d-%02d-%02d" year month day)
16884 t nil ans)))
16886 ;; Help matching american dates, like 5/30 or 5/30/7
16887 (when (string-match
16888 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16889 (setq year (if (match-end 4)
16890 (string-to-number (match-string 4 ans))
16891 (progn (setq kill-year t)
16892 (string-to-number (format-time-string "%Y"))))
16893 month (string-to-number (match-string 1 ans))
16894 day (string-to-number (match-string 2 ans)))
16895 (if (< year 100) (setq year (+ 2000 year)))
16896 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16897 t nil ans)))
16898 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16899 ;; If there is a time with am/pm, and *no* time without it, we convert
16900 ;; so that matching will be successful.
16901 (loop for i from 1 to 2 do ; twice, for end time as well
16902 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16903 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16904 (setq hour (string-to-number (match-string 1 ans))
16905 minute (if (match-end 3)
16906 (string-to-number (match-string 3 ans))
16908 pm (equal ?p
16909 (string-to-char (downcase (match-string 4 ans)))))
16910 (if (and (= hour 12) (not pm))
16911 (setq hour 0)
16912 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16913 (setq ans (replace-match (format "%02d:%02d" hour minute)
16914 t t ans))))
16916 ;; Check if a time range is given as a duration
16917 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16918 (setq hour (string-to-number (match-string 1 ans))
16919 h2 (+ hour (string-to-number (match-string 3 ans)))
16920 minute (string-to-number (match-string 2 ans))
16921 m2 (+ minute (if (match-end 5) (string-to-number
16922 (match-string 5 ans))0)))
16923 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16924 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16925 t t ans)))
16927 ;; Check if there is a time range
16928 (when (boundp 'org-end-time-was-given)
16929 (setq org-time-was-given nil)
16930 (when (and (string-match org-plain-time-of-day-regexp ans)
16931 (match-end 8))
16932 (setq org-end-time-was-given (match-string 8 ans))
16933 (setq ans (concat (substring ans 0 (match-beginning 7))
16934 (substring ans (match-end 7))))))
16936 (setq tl (parse-time-string ans)
16937 day (or (nth 3 tl) (nth 3 org-defdecode))
16938 month
16939 (cond ((nth 4 tl))
16940 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16941 ;; Day was specified. Make sure DAY+MONTH
16942 ;; combination happens in the future.
16943 ((nth 3 tl)
16944 (setq futurep t)
16945 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16946 (nth 4 nowdecode)))
16947 (t (nth 4 org-defdecode)))
16948 year
16949 (cond ((and (not kill-year) (nth 5 tl)))
16950 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16951 ;; Month was guessed in the future and is at least
16952 ;; equal to NOWDECODE's. Fix year accordingly.
16953 (futurep
16954 (if (or (> month (nth 4 nowdecode))
16955 (>= day (nth 3 nowdecode)))
16956 (nth 5 nowdecode)
16957 (1+ (nth 5 nowdecode))))
16958 ;; Month was specified. Make sure MONTH+YEAR
16959 ;; combination happens in the future.
16960 ((nth 4 tl)
16961 (setq futurep t)
16962 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16963 ((< month (nth 5 nowdecode)) (1+ (nth 5 nowdecode)))
16964 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16965 (t (nth 5 nowdecode))))
16966 (t (nth 5 org-defdecode)))
16967 hour (or (nth 2 tl) (nth 2 org-defdecode))
16968 minute (or (nth 1 tl) (nth 1 org-defdecode))
16969 second (or (nth 0 tl) 0)
16970 wday (nth 6 tl))
16972 (when (and (eq org-read-date-prefer-future 'time)
16973 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16974 (equal day (nth 3 nowdecode))
16975 (equal month (nth 4 nowdecode))
16976 (equal year (nth 5 nowdecode))
16977 (nth 2 tl)
16978 (or (< (nth 2 tl) (nth 2 nowdecode))
16979 (and (= (nth 2 tl) (nth 2 nowdecode))
16980 (nth 1 tl)
16981 (< (nth 1 tl) (nth 1 nowdecode)))))
16982 (setq day (1+ day)
16983 futurep t))
16985 ;; Special date definitions below
16986 (cond
16987 (iso-week
16988 ;; There was an iso week
16989 (require 'cal-iso)
16990 (setq futurep nil)
16991 (setq year (or iso-year year)
16992 day (or iso-weekday wday 1)
16993 wday nil ; to make sure that the trigger below does not match
16994 iso-date (calendar-gregorian-from-absolute
16995 (calendar-iso-to-absolute
16996 (list iso-week day year))))
16997 ; FIXME: Should we also push ISO weeks into the future?
16998 ; (when (and org-read-date-prefer-future
16999 ; (not iso-year)
17000 ; (< (calendar-absolute-from-gregorian iso-date)
17001 ; (time-to-days (current-time))))
17002 ; (setq year (1+ year)
17003 ; iso-date (calendar-gregorian-from-absolute
17004 ; (calendar-iso-to-absolute
17005 ; (list iso-week day year)))))
17006 (setq month (car iso-date)
17007 year (nth 2 iso-date)
17008 day (nth 1 iso-date)))
17009 (deltan
17010 (setq futurep nil)
17011 (unless deltadef
17012 (let ((now (decode-time (current-time))))
17013 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17014 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17015 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17016 ((equal deltaw "m") (setq month (+ month deltan)))
17017 ((equal deltaw "y") (setq year (+ year deltan)))))
17018 ((and wday (not (nth 3 tl)))
17019 ;; Weekday was given, but no day, so pick that day in the week
17020 ;; on or after the derived date.
17021 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17022 (unless (equal wday wday1)
17023 (setq day (+ day (% (- wday wday1 -7) 7))))))
17024 (if (and (boundp 'org-time-was-given)
17025 (nth 2 tl))
17026 (setq org-time-was-given t))
17027 (if (< year 100) (setq year (+ 2000 year)))
17028 ;; Check of the date is representable
17029 (if org-read-date-force-compatible-dates
17030 (progn
17031 (if (< year 1970)
17032 (setq year 1970 org-read-date-analyze-forced-year t))
17033 (if (> year 2037)
17034 (setq year 2037 org-read-date-analyze-forced-year t)))
17035 (condition-case nil
17036 (ignore (encode-time second minute hour day month year))
17037 (error
17038 (setq year (nth 5 org-defdecode))
17039 (setq org-read-date-analyze-forced-year t))))
17040 (setq org-read-date-analyze-futurep futurep)
17041 (list second minute hour day month year)))
17043 (defvar parse-time-weekdays)
17044 (defun org-read-date-get-relative (s today default)
17045 "Check string S for special relative date string.
17046 TODAY and DEFAULT are internal times, for today and for a default.
17047 Return shift list (N what def-flag)
17048 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17049 N is the number of WHATs to shift.
17050 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17051 the DEFAULT date rather than TODAY."
17052 (require 'parse-time)
17053 (when (and
17054 (string-match
17055 (concat
17056 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17057 "\\([0-9]+\\)?"
17058 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17059 "\\([ \t]\\|$\\)") s)
17060 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17061 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17062 (string-to-char (substring (match-string 1 s) -1))
17063 ?+))
17064 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17065 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17066 (what (if (match-end 3) (match-string 3 s) "d"))
17067 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17068 (date (if rel default today))
17069 (wday (nth 6 (decode-time date)))
17070 delta)
17071 (if wday1
17072 (progn
17073 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17074 (if (= delta 0) (setq delta 7))
17075 (if (= dir ?-)
17076 (progn
17077 (setq delta (- delta 7))
17078 (if (= delta 0) (setq delta -7))))
17079 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17080 (list delta "d" rel))
17081 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17083 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17084 "Turn a user-specified date into the internal representation.
17085 The internal representation needed by the calendar is (month day year).
17086 This is a wrapper to handle the brain-dead convention in calendar that
17087 user function argument order change dependent on argument order."
17088 (if (boundp 'calendar-date-style)
17089 (cond
17090 ((eq calendar-date-style 'american)
17091 (list arg1 arg2 arg3))
17092 ((eq calendar-date-style 'european)
17093 (list arg2 arg1 arg3))
17094 ((eq calendar-date-style 'iso)
17095 (list arg2 arg3 arg1)))
17096 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17097 (if (org-bound-and-true-p european-calendar-style)
17098 (list arg2 arg1 arg3)
17099 (list arg1 arg2 arg3)))))
17101 (defun org-eval-in-calendar (form &optional keepdate)
17102 "Eval FORM in the calendar window and return to current window.
17103 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17104 otherwise stick to the current value of `org-ans2'."
17105 (let ((sf (selected-frame))
17106 (sw (selected-window)))
17107 (select-window (get-buffer-window "*Calendar*" t))
17108 (eval form)
17109 (when (and (not keepdate) (calendar-cursor-to-date))
17110 (let* ((date (calendar-cursor-to-date))
17111 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17112 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17113 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17114 (select-window sw)
17115 (org-select-frame-set-input-focus sf)))
17117 (defun org-calendar-select ()
17118 "Return to `org-read-date' with the date currently selected.
17119 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17120 (interactive)
17121 (when (calendar-cursor-to-date)
17122 (let* ((date (calendar-cursor-to-date))
17123 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17124 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17125 (if (active-minibuffer-window) (exit-minibuffer))))
17127 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17128 "Insert a date stamp for the date given by the internal TIME.
17129 See `format-time-string' for the format of TIME.
17130 WITH-HM means use the stamp format that includes the time of the day.
17131 INACTIVE means use square brackets instead of angular ones, so that the
17132 stamp will not contribute to the agenda.
17133 PRE and POST are optional strings to be inserted before and after the
17134 stamp.
17135 The command returns the inserted time stamp."
17136 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17137 stamp)
17138 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17139 (insert-before-markers (or pre ""))
17140 (when (listp extra)
17141 (setq extra (car extra))
17142 (if (and (stringp extra)
17143 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17144 (setq extra (format "-%02d:%02d"
17145 (string-to-number (match-string 1 extra))
17146 (string-to-number (match-string 2 extra))))
17147 (setq extra nil)))
17148 (when extra
17149 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17150 (insert-before-markers (setq stamp (format-time-string fmt time)))
17151 (insert-before-markers (or post ""))
17152 (setq org-last-inserted-timestamp stamp)))
17154 (defun org-toggle-time-stamp-overlays ()
17155 "Toggle the use of custom time stamp formats."
17156 (interactive)
17157 (setq org-display-custom-times (not org-display-custom-times))
17158 (unless org-display-custom-times
17159 (let ((p (point-min)) (bmp (buffer-modified-p)))
17160 (while (setq p (next-single-property-change p 'display))
17161 (if (and (get-text-property p 'display)
17162 (eq (get-text-property p 'face) 'org-date))
17163 (remove-text-properties
17164 p (setq p (next-single-property-change p 'display))
17165 '(display t))))
17166 (set-buffer-modified-p bmp)))
17167 (if (featurep 'xemacs)
17168 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17169 (org-restart-font-lock)
17170 (setq org-table-may-need-update t)
17171 (if org-display-custom-times
17172 (message "Time stamps are overlaid with custom format")
17173 (message "Time stamp overlays removed")))
17175 (defun org-display-custom-time (beg end)
17176 "Overlay modified time stamp format over timestamp between BEG and END."
17177 (let* ((ts (buffer-substring beg end))
17178 t1 w1 with-hm tf time str w2 (off 0))
17179 (save-match-data
17180 (setq t1 (org-parse-time-string ts t))
17181 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17182 (setq off (- (match-end 0) (match-beginning 0)))))
17183 (setq end (- end off))
17184 (setq w1 (- end beg)
17185 with-hm (and (nth 1 t1) (nth 2 t1))
17186 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17187 time (org-fix-decoded-time t1)
17188 str (org-add-props
17189 (format-time-string
17190 (substring tf 1 -1) (apply 'encode-time time))
17191 nil 'mouse-face 'highlight)
17192 w2 (length str))
17193 (if (not (= w2 w1))
17194 (add-text-properties (1+ beg) (+ 2 beg)
17195 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17196 (if (featurep 'xemacs)
17197 (progn
17198 (put-text-property beg end 'invisible t)
17199 (put-text-property beg end 'end-glyph (make-glyph str)))
17200 (put-text-property beg end 'display str))))
17202 (defun org-fix-decoded-time (time)
17203 "Set 0 instead of nil for the first 6 elements of time.
17204 Don't touch the rest."
17205 (let ((n 0))
17206 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17208 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17210 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17211 "Difference between TIMESTAMP-STRING and now in days.
17212 If SECONDS is non-nil, return the difference in seconds."
17213 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17214 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17215 (funcall fdiff (current-time)))))
17217 (defun org-deadline-close (timestamp-string &optional ndays)
17218 "Is the time in TIMESTAMP-STRING close to the current date?"
17219 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17220 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17221 (not (org-entry-is-done-p))))
17223 (defun org-get-wdays (ts &optional delay zero-delay)
17224 "Get the deadline lead time appropriate for timestring TS.
17225 When DELAY is non-nil, get the delay time for scheduled items
17226 instead of the deadline lead time. When ZERO-DELAY is non-nil
17227 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17228 don't try to find the delay cookie in the scheduled timestamp."
17229 (let ((tv (if delay org-scheduled-delay-days
17230 org-deadline-warning-days)))
17231 (cond
17232 ((or (and delay (< tv 0))
17233 (and delay zero-delay (<= tv 0))
17234 (and (not delay) (<= tv 0)))
17235 ;; Enforce this value no matter what
17236 (- tv))
17237 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17238 ;; lead time is specified.
17239 (floor (* (string-to-number (match-string 1 ts))
17240 (cdr (assoc (match-string 2 ts)
17241 '(("d" . 1) ("w" . 7)
17242 ("m" . 30.4) ("y" . 365.25)
17243 ("h" . 0.041667)))))))
17244 ;; go for the default.
17245 (t tv))))
17247 (defun org-calendar-select-mouse (ev)
17248 "Return to `org-read-date' with the date currently selected.
17249 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17250 (interactive "e")
17251 (mouse-set-point ev)
17252 (when (calendar-cursor-to-date)
17253 (let* ((date (calendar-cursor-to-date))
17254 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17255 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17256 (if (active-minibuffer-window) (exit-minibuffer))))
17258 (defun org-check-deadlines (ndays)
17259 "Check if there are any deadlines due or past due.
17260 A deadline is considered due if it happens within `org-deadline-warning-days'
17261 days from today's date. If the deadline appears in an entry marked DONE,
17262 it is not shown. The prefix arg NDAYS can be used to test that many
17263 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17264 (interactive "P")
17265 (let* ((org-warn-days
17266 (cond
17267 ((equal ndays '(4)) 100000)
17268 (ndays (prefix-numeric-value ndays))
17269 (t (abs org-deadline-warning-days))))
17270 (case-fold-search nil)
17271 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17272 (callback
17273 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17275 (message "%d deadlines past-due or due within %d days"
17276 (org-occur regexp nil callback)
17277 org-warn-days)))
17279 (defsubst org-re-timestamp (type)
17280 "Return a regexp for timestamp TYPE.
17281 Allowed values for TYPE are:
17283 all: all timestamps
17284 active: only active timestamps (<...>)
17285 inactive: only inactive timestamps ([...])
17286 scheduled: only scheduled timestamps
17287 deadline: only deadline timestamps
17288 closed: only closed time-stamps
17290 When TYPE is nil, fall back on returning a regexp that matches
17291 both scheduled and deadline timestamps."
17292 (case type
17293 (all org-ts-regexp-both)
17294 (active org-ts-regexp)
17295 (inactive org-ts-regexp-inactive)
17296 (scheduled org-scheduled-time-regexp)
17297 (deadline org-deadline-time-regexp)
17298 (closed org-closed-time-regexp)
17299 (otherwise
17300 (concat "\\<"
17301 (regexp-opt (list org-deadline-string org-scheduled-string))
17302 " *<\\([^>]+\\)>"))))
17304 (defun org-check-before-date (date)
17305 "Check if there are deadlines or scheduled entries before DATE."
17306 (interactive (list (org-read-date)))
17307 (let ((case-fold-search nil)
17308 (regexp (org-re-timestamp org-ts-type))
17309 (callback
17310 `(lambda ()
17311 (and ,(if (memq org-ts-type '(active inactive all))
17312 '(eq (org-element-type (org-element-context) 'timestamp))
17313 '(org-at-planning-p))
17314 (time-less-p
17315 (org-time-string-to-time (match-string 1))
17316 (org-time-string-to-time date))))))
17317 (message "%d entries before %s"
17318 (org-occur regexp nil callback) date)))
17320 (defun org-check-after-date (date)
17321 "Check if there are deadlines or scheduled entries after DATE."
17322 (interactive (list (org-read-date)))
17323 (let ((case-fold-search nil)
17324 (regexp (org-re-timestamp org-ts-type))
17325 (callback
17326 `(lambda ()
17327 (and ,(if (memq org-ts-type '(active inactive all))
17328 '(eq (org-element-type (org-element-context) 'timestamp))
17329 '(org-at-planning-p))
17330 (not (time-less-p
17331 (org-time-string-to-time (match-string 1))
17332 (org-time-string-to-time date)))))))
17333 (message "%d entries after %s"
17334 (org-occur regexp nil callback) date)))
17336 (defun org-check-dates-range (start-date end-date)
17337 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17338 (interactive (list (org-read-date nil nil nil "Range starts")
17339 (org-read-date nil nil nil "Range end")))
17340 (let ((case-fold-search nil)
17341 (regexp (org-re-timestamp org-ts-type))
17342 (callback
17343 `(lambda ()
17344 (let ((match (match-string 1)))
17345 (and
17346 ,(if (memq org-ts-type '(active inactive all))
17347 '(eq (org-element-type (org-element-context) 'timestamp))
17348 '(org-at-planning-p))
17349 (not (time-less-p
17350 (org-time-string-to-time match)
17351 (org-time-string-to-time start-date)))
17352 (time-less-p
17353 (org-time-string-to-time match)
17354 (org-time-string-to-time end-date)))))))
17355 (message "%d entries between %s and %s"
17356 (org-occur regexp nil callback) start-date end-date)))
17358 (defun org-evaluate-time-range (&optional to-buffer)
17359 "Evaluate a time range by computing the difference between start and end.
17360 Normally the result is just printed in the echo area, but with prefix arg
17361 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17362 If the time range is actually in a table, the result is inserted into the
17363 next column.
17364 For time difference computation, a year is assumed to be exactly 365
17365 days in order to avoid rounding problems."
17366 (interactive "P")
17368 (org-clock-update-time-maybe)
17369 (save-excursion
17370 (unless (org-at-date-range-p t)
17371 (goto-char (point-at-bol))
17372 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17373 (if (not (org-at-date-range-p t))
17374 (user-error "Not at a time-stamp range, and none found in current line")))
17375 (let* ((ts1 (match-string 1))
17376 (ts2 (match-string 2))
17377 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17378 (match-end (match-end 0))
17379 (time1 (org-time-string-to-time ts1))
17380 (time2 (org-time-string-to-time ts2))
17381 (t1 (org-float-time time1))
17382 (t2 (org-float-time time2))
17383 (diff (abs (- t2 t1)))
17384 (negative (< (- t2 t1) 0))
17385 ;; (ys (floor (* 365 24 60 60)))
17386 (ds (* 24 60 60))
17387 (hs (* 60 60))
17388 (fy "%dy %dd %02d:%02d")
17389 (fy1 "%dy %dd")
17390 (fd "%dd %02d:%02d")
17391 (fd1 "%dd")
17392 (fh "%02d:%02d")
17393 y d h m align)
17394 (if havetime
17395 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17397 d (floor (/ diff ds)) diff (mod diff ds)
17398 h (floor (/ diff hs)) diff (mod diff hs)
17399 m (floor (/ diff 60)))
17400 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17402 d (floor (+ (/ diff ds) 0.5))
17403 h 0 m 0))
17404 (if (not to-buffer)
17405 (message "%s" (org-make-tdiff-string y d h m))
17406 (if (org-at-table-p)
17407 (progn
17408 (goto-char match-end)
17409 (setq align t)
17410 (and (looking-at " *|") (goto-char (match-end 0))))
17411 (goto-char match-end))
17412 (if (looking-at
17413 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17414 (replace-match ""))
17415 (if negative (insert " -"))
17416 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17417 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17418 (insert " " (format fh h m))))
17419 (if align (org-table-align))
17420 (message "Time difference inserted")))))
17422 (defun org-make-tdiff-string (y d h m)
17423 (let ((fmt "")
17424 (l nil))
17425 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17426 l (push y l)))
17427 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17428 l (push d l)))
17429 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17430 l (push h l)))
17431 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17432 l (push m l)))
17433 (apply 'format fmt (nreverse l))))
17435 (defun org-time-string-to-time (s &optional buffer pos)
17436 "Convert a timestamp string into internal time."
17437 (condition-case errdata
17438 (apply 'encode-time (org-parse-time-string s))
17439 (error (error "Bad timestamp `%s'%s\nError was: %s"
17440 s (if (not (and buffer pos))
17442 (format " at %d in buffer `%s'" pos buffer))
17443 (cdr errdata)))))
17445 (defun org-time-string-to-seconds (s)
17446 "Convert a timestamp string to a number of seconds."
17447 (org-float-time (org-time-string-to-time s)))
17449 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17450 "Convert a time stamp to an absolute day number.
17451 If there is a specifier for a cyclic time stamp, get the closest
17452 date to DAYNR.
17453 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17454 The variable `date' is bound by the calendar when this is called."
17455 (cond
17456 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17457 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17458 daynr
17459 (+ daynr 1000)))
17460 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17461 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17462 (time-to-days (current-time))) (match-string 0 s)
17463 prefer show-all))
17464 (t (time-to-days
17465 (condition-case errdata
17466 (apply 'encode-time (org-parse-time-string s))
17467 (error (error "Bad timestamp `%s'%s\nError was: %s"
17468 s (if (not (and buffer pos))
17470 (format " at %d in buffer `%s'" pos buffer))
17471 (cdr errdata))))))))
17473 (defun org-days-to-iso-week (days)
17474 "Return the iso week number."
17475 (require 'cal-iso)
17476 (car (calendar-iso-from-absolute days)))
17478 (defun org-small-year-to-year (year)
17479 "Convert 2-digit years into 4-digit years.
17480 YEAR is expanded into one of the 30 next years, if possible, or
17481 into a past one. Any year larger than 99 is returned unchanged."
17482 (if (>= year 100) year
17483 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17484 (century (/ current 100))
17485 (offset (- year (% current 100))))
17486 (cond ((> offset 30) (+ (* (1- century) 100) year))
17487 ((> offset -70) (+ (* century 100) year))
17488 (t (+ (* (1+ century) 100) year))))))
17490 (defun org-time-from-absolute (d)
17491 "Return the time corresponding to date D.
17492 D may be an absolute day number, or a calendar-type list (month day year)."
17493 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17494 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17496 (defun org-calendar-holiday ()
17497 "List of holidays, for Diary display in Org-mode."
17498 (require 'holidays)
17499 (let ((hl (funcall
17500 (if (fboundp 'calendar-check-holidays)
17501 'calendar-check-holidays 'check-calendar-holidays) date)))
17502 (if hl (mapconcat 'identity hl "; "))))
17504 (defun org-diary-sexp-entry (sexp entry date)
17505 "Process a SEXP diary ENTRY for DATE."
17506 (require 'diary-lib)
17507 (let ((result (if calendar-debug-sexp
17508 (let ((stack-trace-on-error t))
17509 (eval (car (read-from-string sexp))))
17510 (condition-case nil
17511 (eval (car (read-from-string sexp)))
17512 (error
17513 (beep)
17514 (message "Bad sexp at line %d in %s: %s"
17515 (org-current-line)
17516 (buffer-file-name) sexp)
17517 (sleep-for 2))))))
17518 (cond ((stringp result) (split-string result "; "))
17519 ((and (consp result)
17520 (not (consp (cdr result)))
17521 (stringp (cdr result))) (cdr result))
17522 ((and (consp result)
17523 (stringp (car result))) result)
17524 (result entry))))
17526 (defun org-diary-to-ical-string (frombuf)
17527 "Get iCalendar entries from diary entries in buffer FROMBUF.
17528 This uses the icalendar.el library."
17529 (let* ((tmpdir (if (featurep 'xemacs)
17530 (temp-directory)
17531 temporary-file-directory))
17532 (tmpfile (make-temp-name
17533 (expand-file-name "orgics" tmpdir)))
17534 buf rtn b e)
17535 (with-current-buffer frombuf
17536 (icalendar-export-region (point-min) (point-max) tmpfile)
17537 (setq buf (find-buffer-visiting tmpfile))
17538 (set-buffer buf)
17539 (goto-char (point-min))
17540 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17541 (setq b (match-beginning 0)))
17542 (goto-char (point-max))
17543 (if (re-search-backward "^END:VEVENT" nil t)
17544 (setq e (match-end 0)))
17545 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17546 (kill-buffer buf)
17547 (delete-file tmpfile)
17548 rtn))
17550 (defun org-closest-date (start current change prefer show-all)
17551 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17552 When PREFER is `past', return a date that is either CURRENT or past.
17553 When PREFER is `future', return a date that is either CURRENT or future.
17554 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17555 ;; Make the proper lists from the dates
17556 (catch 'exit
17557 (let ((a1 '(("h" . hour)
17558 ("d" . day)
17559 ("w" . week)
17560 ("m" . month)
17561 ("y" . year)))
17562 (shour (nth 2 (org-parse-time-string start)))
17563 dn dw sday cday n1 n2 n0
17564 d m y y1 y2 date1 date2 nmonths nm ny m2)
17566 (setq start (org-date-to-gregorian start)
17567 current (org-date-to-gregorian
17568 (if show-all
17569 current
17570 (time-to-days (current-time))))
17571 sday (calendar-absolute-from-gregorian start)
17572 cday (calendar-absolute-from-gregorian current))
17574 (if (<= cday sday) (throw 'exit sday))
17576 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17577 (setq dn (string-to-number (match-string 1 change))
17578 dw (cdr (assoc (match-string 2 change) a1)))
17579 (user-error "Invalid change specifier: %s" change))
17580 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17581 (cond
17582 ((eq dw 'hour)
17583 (let ((missing-hours
17584 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17585 dn)))
17586 (setq n1 (if (zerop missing-hours) cday
17587 (- cday (1+ (floor (/ missing-hours 24)))))
17588 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17589 ((eq dw 'day)
17590 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17591 n2 (+ n1 dn)))
17592 ((eq dw 'year)
17593 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17594 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17595 (setq date1 (list m d y1)
17596 n1 (calendar-absolute-from-gregorian date1)
17597 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17598 n2 (calendar-absolute-from-gregorian date2)))
17599 ((eq dw 'month)
17600 ;; approx number of month between the two dates
17601 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17602 ;; How often does dn fit in there?
17603 (setq d (nth 1 start) m (car start) y (nth 2 start)
17604 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17605 m (+ m nm)
17606 ny (floor (/ m 12))
17607 y (+ y ny)
17608 m (- m (* ny 12)))
17609 (while (> m 12) (setq m (- m 12) y (1+ y)))
17610 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17611 (setq m2 (+ m dn) y2 y)
17612 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17613 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17614 (while (<= n2 cday)
17615 (setq n1 n2 m m2 y y2)
17616 (setq m2 (+ m dn) y2 y)
17617 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17618 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17619 ;; Make sure n1 is the earlier date
17620 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17621 (if show-all
17622 (cond
17623 ((eq prefer 'past) (if (= cday n2) n2 n1))
17624 ((eq prefer 'future) (if (= cday n1) n1 n2))
17625 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17626 (cond
17627 ((eq prefer 'past) (if (= cday n2) n2 n1))
17628 ((eq prefer 'future) (if (= cday n1) n1 n2))
17629 (t (if (= cday n1) n1 n2)))))))
17631 (defun org-date-to-gregorian (date)
17632 "Turn any specification of DATE into a Gregorian date for the calendar."
17633 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17634 ((and (listp date) (= (length date) 3)) date)
17635 ((stringp date)
17636 (setq date (org-parse-time-string date))
17637 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17638 ((listp date)
17639 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17641 (defun org-parse-time-string (s &optional nodefault)
17642 "Parse the standard Org-mode time string.
17643 This should be a lot faster than the normal `parse-time-string'.
17644 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17645 hour and minute fields will be nil if not given."
17646 (cond ((string-match org-ts-regexp0 s)
17647 (list 0
17648 (if (or (match-beginning 8) (not nodefault))
17649 (string-to-number (or (match-string 8 s) "0")))
17650 (if (or (match-beginning 7) (not nodefault))
17651 (string-to-number (or (match-string 7 s) "0")))
17652 (string-to-number (match-string 4 s))
17653 (string-to-number (match-string 3 s))
17654 (string-to-number (match-string 2 s))
17655 nil nil nil))
17656 ((string-match "^<[^>]+>$" s)
17657 (decode-time (seconds-to-time (org-matcher-time s))))
17658 (t (error "Not a standard Org-mode time string: %s" s))))
17660 (defun org-timestamp-up (&optional arg)
17661 "Increase the date item at the cursor by one.
17662 If the cursor is on the year, change the year. If it is on the month,
17663 the day or the time, change that.
17664 With prefix ARG, change by that many units."
17665 (interactive "p")
17666 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17668 (defun org-timestamp-down (&optional arg)
17669 "Decrease the date item at the cursor by one.
17670 If the cursor is on the year, change the year. If it is on the month,
17671 the day or the time, change that.
17672 With prefix ARG, change by that many units."
17673 (interactive "p")
17674 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17676 (defun org-timestamp-up-day (&optional arg)
17677 "Increase the date in the time stamp by one day.
17678 With prefix ARG, change that many days."
17679 (interactive "p")
17680 (if (and (not (org-at-timestamp-p t))
17681 (org-at-heading-p))
17682 (org-todo 'up)
17683 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17685 (defun org-timestamp-down-day (&optional arg)
17686 "Decrease the date in the time stamp by one day.
17687 With prefix ARG, change that many days."
17688 (interactive "p")
17689 (if (and (not (org-at-timestamp-p t))
17690 (org-at-heading-p))
17691 (org-todo 'down)
17692 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17694 (defun org-at-timestamp-p (&optional inactive-ok)
17695 "Determine if the cursor is in or at a timestamp."
17696 (interactive)
17697 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17698 (pos (point))
17699 (ans (or (looking-at tsr)
17700 (save-excursion
17701 (skip-chars-backward "^[<\n\r\t")
17702 (if (> (point) (point-min)) (backward-char 1))
17703 (and (looking-at tsr)
17704 (> (- (match-end 0) pos) -1))))))
17705 (and ans
17706 (boundp 'org-ts-what)
17707 (setq org-ts-what
17708 (cond
17709 ((= pos (match-beginning 0)) 'bracket)
17710 ;; Point is considered to be "on the bracket" whether
17711 ;; it's really on it or right after it.
17712 ((= pos (1- (match-end 0))) 'bracket)
17713 ((= pos (match-end 0)) 'after)
17714 ((org-pos-in-match-range pos 2) 'year)
17715 ((org-pos-in-match-range pos 3) 'month)
17716 ((org-pos-in-match-range pos 7) 'hour)
17717 ((org-pos-in-match-range pos 8) 'minute)
17718 ((or (org-pos-in-match-range pos 4)
17719 (org-pos-in-match-range pos 5)) 'day)
17720 ((and (> pos (or (match-end 8) (match-end 5)))
17721 (< pos (match-end 0)))
17722 (- pos (or (match-end 8) (match-end 5))))
17723 (t 'day))))
17724 ans))
17726 (defun org-toggle-timestamp-type ()
17727 "Toggle the type (<active> or [inactive]) of a time stamp."
17728 (interactive)
17729 (when (org-at-timestamp-p t)
17730 (let ((beg (match-beginning 0)) (end (match-end 0))
17731 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17732 (save-excursion
17733 (goto-char beg)
17734 (while (re-search-forward "[][<>]" end t)
17735 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17736 t t)))
17737 (message "Timestamp is now %sactive"
17738 (if (equal (char-after beg) ?<) "" "in")))))
17740 (defun org-at-clock-log-p nil
17741 "Is the cursor on the clock log line?"
17742 (save-excursion
17743 (move-beginning-of-line 1)
17744 (looking-at org-clock-line-re)))
17746 (defvar org-clock-history) ; defined in org-clock.el
17747 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17748 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17749 "Change the date in the time stamp at point.
17750 The date will be changed by N times WHAT. WHAT can be `day', `month',
17751 `year', `minute', `second'. If WHAT is not given, the cursor position
17752 in the timestamp determines what will be changed.
17753 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17754 (let ((origin (point)) origin-cat
17755 with-hm inactive
17756 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17757 org-ts-what
17758 extra rem
17759 ts time time0 fixnext clrgx)
17760 (if (not (org-at-timestamp-p t))
17761 (user-error "Not at a timestamp"))
17762 (if (and (not what) (eq org-ts-what 'bracket))
17763 (org-toggle-timestamp-type)
17764 ;; Point isn't on brackets. Remember the part of the time-stamp
17765 ;; the point was in. Indeed, size of time-stamps may change,
17766 ;; but point must be kept in the same category nonetheless.
17767 (setq origin-cat org-ts-what)
17768 (if (and (not what) (not (eq org-ts-what 'day))
17769 org-display-custom-times
17770 (get-text-property (point) 'display)
17771 (not (get-text-property (1- (point)) 'display)))
17772 (setq org-ts-what 'day))
17773 (setq org-ts-what (or what org-ts-what)
17774 inactive (= (char-after (match-beginning 0)) ?\[)
17775 ts (match-string 0))
17776 (replace-match "")
17777 (when (string-match
17778 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17780 (setq extra (match-string 1 ts))
17781 (if suppress-tmp-delay
17782 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17783 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17784 (setq with-hm t))
17785 (setq time0 (org-parse-time-string ts))
17786 (when (and updown
17787 (eq org-ts-what 'minute)
17788 (not current-prefix-arg))
17789 ;; This looks like s-up and s-down. Change by one rounding step.
17790 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17791 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17792 (setcar (cdr time0) (+ (nth 1 time0)
17793 (if (> n 0) (- rem) (- dm rem))))))
17794 (setq time
17795 (encode-time (or (car time0) 0)
17796 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17797 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17798 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17799 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17800 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17801 (nthcdr 6 time0)))
17802 (when (and (member org-ts-what '(hour minute))
17803 extra
17804 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17805 (setq extra (org-modify-ts-extra
17806 extra
17807 (if (eq org-ts-what 'hour) 2 5)
17808 n dm)))
17809 (when (integerp org-ts-what)
17810 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17811 (if (eq what 'calendar)
17812 (let ((cal-date (org-get-date-from-calendar)))
17813 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17814 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17815 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17816 (setcar time0 (or (car time0) 0))
17817 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17818 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17819 (setq time (apply 'encode-time time0))))
17820 ;; Insert the new time-stamp, and ensure point stays in the same
17821 ;; category as before (i.e. not after the last position in that
17822 ;; category).
17823 (let ((pos (point)))
17824 ;; Stay before inserted string. `save-excursion' is of no use.
17825 (setq org-last-changed-timestamp
17826 (org-insert-time-stamp time with-hm inactive nil nil extra))
17827 (goto-char pos))
17828 (save-match-data
17829 (looking-at org-ts-regexp3)
17830 (goto-char (cond
17831 ;; `day' category ends before `hour' if any, or at
17832 ;; the end of the day name.
17833 ((eq origin-cat 'day)
17834 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17835 ((eq origin-cat 'hour) (min (match-end 7) origin))
17836 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17837 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17838 ;; `year' and `month' have both fixed size: point
17839 ;; couldn't have moved into another part.
17840 (t origin))))
17841 ;; Update clock if on a CLOCK line.
17842 (org-clock-update-time-maybe)
17843 ;; Maybe adjust the closest clock in `org-clock-history'
17844 (when org-clock-adjust-closest
17845 (if (not (and (org-at-clock-log-p)
17846 (< 1 (length (delq nil (mapcar 'marker-position
17847 org-clock-history))))))
17848 (message "No clock to adjust")
17849 (cond ((save-excursion ; fix previous clock?
17850 (re-search-backward org-ts-regexp0 nil t)
17851 (org-looking-back (concat org-clock-string " \\[")))
17852 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17853 ((save-excursion ; fix next clock?
17854 (re-search-backward org-ts-regexp0 nil t)
17855 (looking-at (concat org-ts-regexp0 "\\] =>")))
17856 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17857 (save-window-excursion
17858 ;; Find closest clock to point, adjust the previous/next one in history
17859 (let* ((p (save-excursion (org-back-to-heading t)))
17860 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17861 (clfixnth
17862 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17863 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17864 (if (not clfixpos)
17865 (message "No clock to adjust")
17866 (save-excursion
17867 (org-goto-marker-or-bmk clfixpos)
17868 (org-show-subtree)
17869 (when (re-search-forward clrgx nil t)
17870 (goto-char (match-beginning 1))
17871 (let (org-clock-adjust-closest)
17872 (org-timestamp-change n org-ts-what updown))
17873 (message "Clock adjusted in %s for heading: %s"
17874 (file-name-nondirectory (buffer-file-name))
17875 (org-get-heading t t)))))))))
17876 ;; Try to recenter the calendar window, if any.
17877 (if (and org-calendar-follow-timestamp-change
17878 (get-buffer-window "*Calendar*" t)
17879 (memq org-ts-what '(day month year)))
17880 (org-recenter-calendar (time-to-days time))))))
17882 (defun org-modify-ts-extra (s pos n dm)
17883 "Change the different parts of the lead-time and repeat fields in timestamp."
17884 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17885 ng h m new rem)
17886 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17887 (cond
17888 ((or (org-pos-in-match-range pos 2)
17889 (org-pos-in-match-range pos 3))
17890 (setq m (string-to-number (match-string 3 s))
17891 h (string-to-number (match-string 2 s)))
17892 (if (org-pos-in-match-range pos 2)
17893 (setq h (+ h n))
17894 (setq n (* dm (org-no-warnings (signum n))))
17895 (when (not (= 0 (setq rem (% m dm))))
17896 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17897 (setq m (+ m n)))
17898 (if (< m 0) (setq m (+ m 60) h (1- h)))
17899 (if (> m 59) (setq m (- m 60) h (1+ h)))
17900 (setq h (min 24 (max 0 h)))
17901 (setq ng 1 new (format "-%02d:%02d" h m)))
17902 ((org-pos-in-match-range pos 6)
17903 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17904 ((org-pos-in-match-range pos 5)
17905 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17907 ((org-pos-in-match-range pos 9)
17908 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17909 ((org-pos-in-match-range pos 8)
17910 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17912 (when ng
17913 (setq s (concat
17914 (substring s 0 (match-beginning ng))
17916 (substring s (match-end ng))))))
17919 (defun org-recenter-calendar (date)
17920 "If the calendar is visible, recenter it to DATE."
17921 (let ((cwin (get-buffer-window "*Calendar*" t)))
17922 (when cwin
17923 (let ((calendar-move-hook nil))
17924 (with-selected-window cwin
17925 (calendar-goto-date (if (listp date) date
17926 (calendar-gregorian-from-absolute date))))))))
17928 (defun org-goto-calendar (&optional arg)
17929 "Go to the Emacs calendar at the current date.
17930 If there is a time stamp in the current line, go to that date.
17931 A prefix ARG can be used to force the current date."
17932 (interactive "P")
17933 (let ((tsr org-ts-regexp) diff
17934 (calendar-move-hook nil)
17935 (calendar-view-holidays-initially-flag nil)
17936 (calendar-view-diary-initially-flag nil))
17937 (if (or (org-at-timestamp-p)
17938 (save-excursion
17939 (beginning-of-line 1)
17940 (looking-at (concat ".*" tsr))))
17941 (let ((d1 (time-to-days (current-time)))
17942 (d2 (time-to-days
17943 (org-time-string-to-time (match-string 1)))))
17944 (setq diff (- d2 d1))))
17945 (calendar)
17946 (calendar-goto-today)
17947 (if (and diff (not arg)) (calendar-forward-day diff))))
17949 (defun org-get-date-from-calendar ()
17950 "Return a list (month day year) of date at point in calendar."
17951 (with-current-buffer "*Calendar*"
17952 (save-match-data
17953 (calendar-cursor-to-date))))
17955 (defun org-date-from-calendar ()
17956 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17957 If there is already a time stamp at the cursor position, update it."
17958 (interactive)
17959 (if (org-at-timestamp-p t)
17960 (org-timestamp-change 0 'calendar)
17961 (let ((cal-date (org-get-date-from-calendar)))
17962 (org-insert-time-stamp
17963 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17965 (defcustom org-effort-durations
17966 `(("min" . 1)
17967 ("h" . 60)
17968 ("d" . ,(* 60 8))
17969 ("w" . ,(* 60 8 5))
17970 ("m" . ,(* 60 8 5 4))
17971 ("y" . ,(* 60 8 5 40)))
17972 "Conversion factor to minutes for an effort modifier.
17974 Each entry has the form (MODIFIER . MINUTES).
17976 In an effort string, a number followed by MODIFIER is multiplied
17977 by the specified number of MINUTES to obtain an effort in
17978 minutes.
17980 For example, if the value of this variable is ((\"hours\" . 60)), then an
17981 effort string \"2hours\" is equivalent to 120 minutes."
17982 :group 'org-agenda
17983 :version "25.1"
17984 :package-version '(Org . "8.3")
17985 :type '(alist :key-type (string :tag "Modifier")
17986 :value-type (number :tag "Minutes")))
17988 (defun org-minutes-to-clocksum-string (m)
17989 "Format number of minutes as a clocksum string.
17990 The format is determined by `org-time-clocksum-format',
17991 `org-time-clocksum-use-fractional' and
17992 `org-time-clocksum-fractional-format' and
17993 `org-time-clocksum-use-effort-durations'."
17994 (let ((clocksum "")
17995 (m (round m)) ; Don't allow fractions of minutes
17996 h d w mo y fmt n)
17997 (setq h (if org-time-clocksum-use-effort-durations
17998 (cdr (assoc "h" org-effort-durations)) 60)
17999 d (if org-time-clocksum-use-effort-durations
18000 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18001 w (if org-time-clocksum-use-effort-durations
18002 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18003 mo (if org-time-clocksum-use-effort-durations
18004 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18005 y (if org-time-clocksum-use-effort-durations
18006 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18007 ;; fractional format
18008 (if org-time-clocksum-use-fractional
18009 (cond
18010 ;; single format string
18011 ((stringp org-time-clocksum-fractional-format)
18012 (format org-time-clocksum-fractional-format (/ m (float h))))
18013 ;; choice of fractional formats for different time units
18014 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18015 (> (/ (truncate m) (* y d h)) 0))
18016 (format fmt (/ m (* y d (float h)))))
18017 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18018 (> (/ (truncate m) (* mo d h)) 0))
18019 (format fmt (/ m (* mo d (float h)))))
18020 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18021 (> (/ (truncate m) (* w d h)) 0))
18022 (format fmt (/ m (* w d (float h)))))
18023 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18024 (> (/ (truncate m) (* d h)) 0))
18025 (format fmt (/ m (* d (float h)))))
18026 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18027 (> (/ (truncate m) h) 0))
18028 (format fmt (/ m (float h))))
18029 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18030 (format fmt m))
18031 ;; fall back to smallest time unit with a format
18032 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18033 (format fmt (/ m (float h))))
18034 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18035 (format fmt (/ m (* d (float h)))))
18036 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18037 (format fmt (/ m (* w d (float h)))))
18038 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18039 (format fmt (/ m (* mo d (float h)))))
18040 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18041 (format fmt (/ m (* y d (float h))))))
18042 ;; standard (non-fractional) format, with single format string
18043 (if (stringp org-time-clocksum-format)
18044 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18045 ;; separate formats components
18046 (and (setq fmt (plist-get org-time-clocksum-format :years))
18047 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18048 (plist-get org-time-clocksum-format :require-years))
18049 (setq clocksum (concat clocksum (format fmt n))
18050 m (- m (* n y d h))))
18051 (and (setq fmt (plist-get org-time-clocksum-format :months))
18052 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18053 (plist-get org-time-clocksum-format :require-months))
18054 (setq clocksum (concat clocksum (format fmt n))
18055 m (- m (* n mo d h))))
18056 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18057 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18058 (plist-get org-time-clocksum-format :require-weeks))
18059 (setq clocksum (concat clocksum (format fmt n))
18060 m (- m (* n w d h))))
18061 (and (setq fmt (plist-get org-time-clocksum-format :days))
18062 (or (> (setq n (/ (truncate m) (* d h))) 0)
18063 (plist-get org-time-clocksum-format :require-days))
18064 (setq clocksum (concat clocksum (format fmt n))
18065 m (- m (* n d h))))
18066 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18067 (or (> (setq n (/ (truncate m) h)) 0)
18068 (plist-get org-time-clocksum-format :require-hours))
18069 (setq clocksum (concat clocksum (format fmt n))
18070 m (- m (* n h))))
18071 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18072 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18073 (setq clocksum (concat clocksum (format fmt m))))
18074 ;; return formatted time duration
18075 clocksum))))
18077 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18078 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18079 "Org mode version 8.0")
18081 (defun org-hours-to-clocksum-string (n)
18082 (org-minutes-to-clocksum-string (* n 60)))
18084 (defun org-hh:mm-string-to-minutes (s)
18085 "Convert a string H:MM to a number of minutes.
18086 If the string is just a number, interpret it as minutes.
18087 In fact, the first hh:mm or number in the string will be taken,
18088 there can be extra stuff in the string.
18089 If no number is found, the return value is 0."
18090 (cond
18091 ((integerp s) s)
18092 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18093 (+ (* (string-to-number (match-string 1 s)) 60)
18094 (string-to-number (match-string 2 s))))
18095 ((string-match "\\([0-9]+\\)" s)
18096 (string-to-number (match-string 1 s)))
18097 (t 0)))
18099 (defcustom org-image-actual-width t
18100 "Should we use the actual width of images when inlining them?
18102 When set to `t', always use the image width.
18104 When set to a number, use imagemagick (when available) to set
18105 the image's width to this value.
18107 When set to a number in a list, try to get the width from any
18108 #+ATTR.* keyword if it matches a width specification like
18110 #+ATTR_HTML: :width 300px
18112 and fall back on that number if none is found.
18114 When set to nil, try to get the width from an #+ATTR.* keyword
18115 and fall back on the original width if none is found.
18117 This requires Emacs >= 24.1, build with imagemagick support."
18118 :group 'org-appearance
18119 :version "24.4"
18120 :package-version '(Org . "8.0")
18121 :type '(choice
18122 (const :tag "Use the image width" t)
18123 (integer :tag "Use a number of pixels")
18124 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18125 (const :tag "Use #+ATTR* or don't resize" nil)))
18127 (defcustom org-agenda-inhibit-startup nil
18128 "Inhibit startup when preparing agenda buffers.
18129 When this variable is `t', the initialization of the Org agenda
18130 buffers is inhibited: e.g. the visibility state is not set, the
18131 tables are not re-aligned, etc."
18132 :type 'boolean
18133 :version "24.3"
18134 :group 'org-agenda)
18136 (define-obsolete-variable-alias
18137 'org-agenda-ignore-drawer-properties
18138 'org-agenda-ignore-properties "25.1")
18140 (defcustom org-agenda-ignore-properties nil
18141 "Avoid updating text properties when building the agenda.
18142 Properties are used to prepare buffers for effort estimates,
18143 appointments, statistics and subtree-local categories.
18144 If you don't use these in the agenda, you can add them to this
18145 list and agenda building will be a bit faster.
18146 The value is a list, with zero or more of the symbols `effort', `appt',
18147 `stats' or `category'."
18148 :type '(set :greedy t
18149 (const effort)
18150 (const appt)
18151 (const stats)
18152 (const category))
18153 :version "25.1"
18154 :package-version '(Org . "8.3")
18155 :group 'org-agenda)
18157 (defun org-duration-string-to-minutes (s &optional output-to-string)
18158 "Convert a duration string S to minutes.
18160 A bare number is interpreted as minutes, modifiers can be set by
18161 customizing `org-effort-durations' (which see).
18163 Entries containing a colon are interpreted as H:MM by
18164 `org-hh:mm-string-to-minutes'."
18165 (let ((result 0)
18166 (re (concat "\\([0-9.]+\\) *\\("
18167 (regexp-opt (mapcar 'car org-effort-durations))
18168 "\\)")))
18169 (while (string-match re s)
18170 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18171 (string-to-number (match-string 1 s))))
18172 (setq s (replace-match "" nil t s)))
18173 (setq result (floor result))
18174 (incf result (org-hh:mm-string-to-minutes s))
18175 (if output-to-string (number-to-string result) result)))
18177 ;;;; Files
18179 (defun org-save-all-org-buffers ()
18180 "Save all Org-mode buffers without user confirmation."
18181 (interactive)
18182 (message "Saving all Org-mode buffers...")
18183 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18184 (when (featurep 'org-id) (org-id-locations-save))
18185 (message "Saving all Org-mode buffers... done"))
18187 (defun org-revert-all-org-buffers ()
18188 "Revert all Org-mode buffers.
18189 Prompt for confirmation when there are unsaved changes.
18190 Be sure you know what you are doing before letting this function
18191 overwrite your changes.
18193 This function is useful in a setup where one tracks org files
18194 with a version control system, to revert on one machine after pulling
18195 changes from another. I believe the procedure must be like this:
18197 1. M-x org-save-all-org-buffers
18198 2. Pull changes from the other machine, resolve conflicts
18199 3. M-x org-revert-all-org-buffers"
18200 (interactive)
18201 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18202 (user-error "Abort"))
18203 (save-excursion
18204 (save-window-excursion
18205 (mapc
18206 (lambda (b)
18207 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18208 (with-current-buffer b buffer-file-name))
18209 (org-pop-to-buffer-same-window b)
18210 (revert-buffer t 'no-confirm)))
18211 (buffer-list))
18212 (when (and (featurep 'org-id) org-id-track-globally)
18213 (org-id-locations-load)))))
18215 ;;;; Agenda files
18217 ;;;###autoload
18218 (defun org-switchb (&optional arg)
18219 "Switch between Org buffers.
18220 With one prefix argument, restrict available buffers to files.
18221 With two prefix arguments, restrict available buffers to agenda files.
18223 Defaults to `iswitchb' for buffer name completion.
18224 Set `org-completion-use-ido' to make it use ido instead."
18225 (interactive "P")
18226 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18227 ((equal arg '(16)) (org-buffer-list 'agenda))
18228 (t (org-buffer-list))))
18229 (org-completion-use-iswitchb org-completion-use-iswitchb)
18230 (org-completion-use-ido org-completion-use-ido))
18231 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18232 (setq org-completion-use-iswitchb t))
18233 (org-pop-to-buffer-same-window
18234 (org-icompleting-read "Org buffer: "
18235 (mapcar 'list (mapcar 'buffer-name blist))
18236 nil t))))
18238 ;;; Define some older names previously used for this functionality
18239 ;;;###autoload
18240 (defalias 'org-ido-switchb 'org-switchb)
18241 ;;;###autoload
18242 (defalias 'org-iswitchb 'org-switchb)
18244 (defun org-buffer-list (&optional predicate exclude-tmp)
18245 "Return a list of Org buffers.
18246 PREDICATE can be `export', `files' or `agenda'.
18248 export restrict the list to Export buffers.
18249 files restrict the list to buffers visiting Org files.
18250 agenda restrict the list to buffers visiting agenda files.
18252 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18253 (let* ((bfn nil)
18254 (agenda-files (and (eq predicate 'agenda)
18255 (mapcar 'file-truename (org-agenda-files t))))
18256 (filter
18257 (cond
18258 ((eq predicate 'files)
18259 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18260 ((eq predicate 'export)
18261 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18262 ((eq predicate 'agenda)
18263 (lambda (b)
18264 (with-current-buffer b
18265 (and (derived-mode-p 'org-mode)
18266 (setq bfn (buffer-file-name b))
18267 (member (file-truename bfn) agenda-files)))))
18268 (t (lambda (b) (with-current-buffer b
18269 (or (derived-mode-p 'org-mode)
18270 (string-match "\*Org .*Export"
18271 (buffer-name b)))))))))
18272 (delq nil
18273 (mapcar
18274 (lambda(b)
18275 (if (and (funcall filter b)
18276 (or (not exclude-tmp)
18277 (not (string-match "tmp" (buffer-name b)))))
18279 nil))
18280 (buffer-list)))))
18282 (defun org-agenda-files (&optional unrestricted archives)
18283 "Get the list of agenda files.
18284 Optional UNRESTRICTED means return the full list even if a restriction
18285 is currently in place.
18286 When ARCHIVES is t, include all archive files that are really being
18287 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18288 `org-agenda-archives-mode' is t."
18289 (let ((files
18290 (cond
18291 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18292 ((stringp org-agenda-files) (org-read-agenda-file-list))
18293 ((listp org-agenda-files) org-agenda-files)
18294 (t (error "Invalid value of `org-agenda-files'")))))
18295 (setq files (apply 'append
18296 (mapcar (lambda (f)
18297 (if (file-directory-p f)
18298 (directory-files
18299 f t org-agenda-file-regexp)
18300 (list f)))
18301 files)))
18302 (when org-agenda-skip-unavailable-files
18303 (setq files (delq nil
18304 (mapcar (function
18305 (lambda (file)
18306 (and (file-readable-p file) file)))
18307 files))))
18308 (when (or (eq archives t)
18309 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18310 (setq files (org-add-archive-files files)))
18311 files))
18313 (defun org-agenda-file-p (&optional file)
18314 "Return non-nil, if FILE is an agenda file.
18315 If FILE is omitted, use the file associated with the current
18316 buffer."
18317 (let ((fname (or file (buffer-file-name))))
18318 (and fname
18319 (member (file-truename fname)
18320 (mapcar #'file-truename (org-agenda-files t))))))
18322 (defun org-edit-agenda-file-list ()
18323 "Edit the list of agenda files.
18324 Depending on setup, this either uses customize to edit the variable
18325 `org-agenda-files', or it visits the file that is holding the list. In the
18326 latter case, the buffer is set up in a way that saving it automatically kills
18327 the buffer and restores the previous window configuration."
18328 (interactive)
18329 (if (stringp org-agenda-files)
18330 (let ((cw (current-window-configuration)))
18331 (find-file org-agenda-files)
18332 (org-set-local 'org-window-configuration cw)
18333 (org-add-hook 'after-save-hook
18334 (lambda ()
18335 (set-window-configuration
18336 (prog1 org-window-configuration
18337 (kill-buffer (current-buffer))))
18338 (org-install-agenda-files-menu)
18339 (message "New agenda file list installed"))
18340 nil 'local)
18341 (message "%s" (substitute-command-keys
18342 "Edit list and finish with \\[save-buffer]")))
18343 (customize-variable 'org-agenda-files)))
18345 (defun org-store-new-agenda-file-list (list)
18346 "Set new value for the agenda file list and save it correctly."
18347 (if (stringp org-agenda-files)
18348 (let ((fe (org-read-agenda-file-list t)) b u)
18349 (while (setq b (find-buffer-visiting org-agenda-files))
18350 (kill-buffer b))
18351 (with-temp-file org-agenda-files
18352 (insert
18353 (mapconcat
18354 (lambda (f) ;; Keep un-expanded entries.
18355 (if (setq u (assoc f fe))
18356 (cdr u)
18358 list "\n")
18359 "\n")))
18360 (let ((org-mode-hook nil) (org-inhibit-startup t)
18361 (org-insert-mode-line-in-empty-file nil))
18362 (setq org-agenda-files list)
18363 (customize-save-variable 'org-agenda-files org-agenda-files))))
18365 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18366 "Read the list of agenda files from a file.
18367 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18368 filenames, used by `org-store-new-agenda-file-list' to write back
18369 un-expanded file names."
18370 (when (file-directory-p org-agenda-files)
18371 (error "`org-agenda-files' cannot be a single directory"))
18372 (when (stringp org-agenda-files)
18373 (with-temp-buffer
18374 (insert-file-contents org-agenda-files)
18375 (mapcar
18376 (lambda (f)
18377 (let ((e (expand-file-name (substitute-in-file-name f)
18378 org-directory)))
18379 (if pair-with-expansion
18380 (cons e f)
18381 e)))
18382 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18384 ;;;###autoload
18385 (defun org-cycle-agenda-files ()
18386 "Cycle through the files in `org-agenda-files'.
18387 If the current buffer visits an agenda file, find the next one in the list.
18388 If the current buffer does not, find the first agenda file."
18389 (interactive)
18390 (let* ((fs (org-agenda-files t))
18391 (files (append fs (list (car fs))))
18392 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18393 file)
18394 (unless files (user-error "No agenda files"))
18395 (catch 'exit
18396 (while (setq file (pop files))
18397 (if (equal (file-truename file) tcf)
18398 (when (car files)
18399 (find-file (car files))
18400 (throw 'exit t))))
18401 (find-file (car fs)))
18402 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18404 (defun org-agenda-file-to-front (&optional to-end)
18405 "Move/add the current file to the top of the agenda file list.
18406 If the file is not present in the list, it is added to the front. If it is
18407 present, it is moved there. With optional argument TO-END, add/move to the
18408 end of the list."
18409 (interactive "P")
18410 (let ((org-agenda-skip-unavailable-files nil)
18411 (file-alist (mapcar (lambda (x)
18412 (cons (file-truename x) x))
18413 (org-agenda-files t)))
18414 (ctf (file-truename
18415 (or buffer-file-name
18416 (user-error "Please save the current buffer to a file"))))
18417 x had)
18418 (setq x (assoc ctf file-alist) had x)
18420 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18421 (if to-end
18422 (setq file-alist (append (delq x file-alist) (list x)))
18423 (setq file-alist (cons x (delq x file-alist))))
18424 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18425 (org-install-agenda-files-menu)
18426 (message "File %s to %s of agenda file list"
18427 (if had "moved" "added") (if to-end "end" "front"))))
18429 (defun org-remove-file (&optional file)
18430 "Remove current file from the list of files in variable `org-agenda-files'.
18431 These are the files which are being checked for agenda entries.
18432 Optional argument FILE means use this file instead of the current."
18433 (interactive)
18434 (let* ((org-agenda-skip-unavailable-files nil)
18435 (file (or file buffer-file-name
18436 (user-error "Current buffer does not visit a file")))
18437 (true-file (file-truename file))
18438 (afile (abbreviate-file-name file))
18439 (files (delq nil (mapcar
18440 (lambda (x)
18441 (if (equal true-file
18442 (file-truename x))
18443 nil x))
18444 (org-agenda-files t)))))
18445 (if (not (= (length files) (length (org-agenda-files t))))
18446 (progn
18447 (org-store-new-agenda-file-list files)
18448 (org-install-agenda-files-menu)
18449 (message "Removed from Org Agenda list: %s" afile))
18450 (message "File was not in list: %s (not removed)" afile))))
18452 (defun org-file-menu-entry (file)
18453 (vector file (list 'find-file file) t))
18455 (defun org-check-agenda-file (file)
18456 "Make sure FILE exists. If not, ask user what to do."
18457 (when (not (file-exists-p file))
18458 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18459 (abbreviate-file-name file))
18460 (let ((r (downcase (read-char-exclusive))))
18461 (cond
18462 ((equal r ?r)
18463 (org-remove-file file)
18464 (throw 'nextfile t))
18465 (t (user-error "Abort"))))))
18467 (defun org-get-agenda-file-buffer (file)
18468 "Get an agenda buffer visiting FILE.
18469 If the buffer needs to be created, add it to the list of buffers
18470 which might be released later."
18471 (let ((buf (org-find-base-buffer-visiting file)))
18472 (if buf
18473 buf ; just return it
18474 ;; Make a new buffer and remember it
18475 (setq buf (find-file-noselect file))
18476 (if buf (push buf org-agenda-new-buffers))
18477 buf)))
18479 (defun org-release-buffers (blist)
18480 "Release all buffers in list, asking the user for confirmation when needed.
18481 When a buffer is unmodified, it is just killed. When modified, it is saved
18482 \(if the user agrees) and then killed."
18483 (let (buf file)
18484 (while (setq buf (pop blist))
18485 (setq file (buffer-file-name buf))
18486 (when (and (buffer-modified-p buf)
18487 file
18488 (y-or-n-p (format "Save file %s? " file)))
18489 (with-current-buffer buf (save-buffer)))
18490 (kill-buffer buf))))
18492 (defun org-agenda-prepare-buffers (files)
18493 "Create buffers for all agenda files, protect archived trees and comments."
18494 (interactive)
18495 (let ((pa '(:org-archived t))
18496 (pc '(:org-comment t))
18497 (pall '(:org-archived t :org-comment t))
18498 (inhibit-read-only t)
18499 (org-inhibit-startup org-agenda-inhibit-startup)
18500 (rea (concat ":" org-archive-tag ":"))
18501 file re pos)
18502 (setq org-tag-alist-for-agenda nil
18503 org-tag-groups-alist-for-agenda nil)
18504 (save-excursion
18505 (save-restriction
18506 (while (setq file (pop files))
18507 (catch 'nextfile
18508 (if (bufferp file)
18509 (set-buffer file)
18510 (org-check-agenda-file file)
18511 (set-buffer (org-get-agenda-file-buffer file)))
18512 (widen)
18513 (org-set-regexps-and-options 'tags-only)
18514 (setq pos (point))
18515 (or (memq 'category org-agenda-ignore-properties)
18516 (org-refresh-category-properties))
18517 (or (memq 'stats org-agenda-ignore-properties)
18518 (org-refresh-stats-properties))
18519 (or (memq 'effort org-agenda-ignore-properties)
18520 (org-refresh-effort-properties))
18521 (or (memq 'appt org-agenda-ignore-properties)
18522 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18523 (setq org-todo-keywords-for-agenda
18524 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18525 (setq org-done-keywords-for-agenda
18526 (append org-done-keywords-for-agenda org-done-keywords))
18527 (setq org-todo-keyword-alist-for-agenda
18528 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18529 (setq org-tag-alist-for-agenda
18530 (org-uniquify
18531 (append org-tag-alist-for-agenda
18532 org-tag-alist
18533 org-tag-persistent-alist)))
18534 (if org-group-tags
18535 (setq org-tag-groups-alist-for-agenda
18536 (org-uniquify-alist
18537 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18538 (org-with-silent-modifications
18539 (save-excursion
18540 (remove-text-properties (point-min) (point-max) pall)
18541 (when org-agenda-skip-archived-trees
18542 (goto-char (point-min))
18543 (while (re-search-forward rea nil t)
18544 (if (org-at-heading-p t)
18545 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18546 (goto-char (point-min))
18547 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18548 (while (re-search-forward re nil t)
18549 (when (save-match-data (org-in-commented-heading-p t))
18550 (add-text-properties
18551 (match-beginning 0) (org-end-of-subtree t) pc)))))
18552 (goto-char pos)))))
18553 (setq org-todo-keywords-for-agenda
18554 (org-uniquify org-todo-keywords-for-agenda))
18555 (setq org-todo-keyword-alist-for-agenda
18556 (org-uniquify org-todo-keyword-alist-for-agenda))))
18559 ;;;; CDLaTeX minor mode
18561 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18562 "Keymap for the minor `org-cdlatex-mode'.")
18564 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18565 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18566 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18567 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18568 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18570 (defvar org-cdlatex-texmathp-advice-is-done nil
18571 "Flag remembering if we have applied the advice to texmathp already.")
18573 (define-minor-mode org-cdlatex-mode
18574 "Toggle the minor `org-cdlatex-mode'.
18575 This mode supports entering LaTeX environment and math in LaTeX fragments
18576 in Org-mode.
18577 \\{org-cdlatex-mode-map}"
18578 nil " OCDL" nil
18579 (when org-cdlatex-mode
18580 (require 'cdlatex)
18581 (run-hooks 'cdlatex-mode-hook)
18582 (cdlatex-compute-tables))
18583 (unless org-cdlatex-texmathp-advice-is-done
18584 (setq org-cdlatex-texmathp-advice-is-done t)
18585 (defadvice texmathp (around org-math-always-on activate)
18586 "Always return t in org-mode buffers.
18587 This is because we want to insert math symbols without dollars even outside
18588 the LaTeX math segments. If Orgmode thinks that point is actually inside
18589 an embedded LaTeX fragment, let texmathp do its job.
18590 \\[org-cdlatex-mode-map]"
18591 (interactive)
18592 (let (p)
18593 (cond
18594 ((not (derived-mode-p 'org-mode)) ad-do-it)
18595 ((eq this-command 'cdlatex-math-symbol)
18596 (setq ad-return-value t
18597 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18599 (let ((p (org-inside-LaTeX-fragment-p)))
18600 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18601 (setq ad-return-value t
18602 texmathp-why '("Org-mode embedded math" . 0))
18603 (if p ad-do-it)))))))))
18605 (defun turn-on-org-cdlatex ()
18606 "Unconditionally turn on `org-cdlatex-mode'."
18607 (org-cdlatex-mode 1))
18609 (defun org-try-cdlatex-tab ()
18610 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18611 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18612 - inside a LaTeX fragment, or
18613 - after the first word in a line, where an abbreviation expansion could
18614 insert a LaTeX environment."
18615 (when org-cdlatex-mode
18616 (cond
18617 ;; Before any word on the line: No expansion possible.
18618 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18619 ;; Just after first word on the line: Expand it. Make sure it
18620 ;; cannot happen on headlines, though.
18621 ((save-excursion
18622 (skip-chars-backward "a-zA-Z0-9*")
18623 (skip-chars-backward " \t")
18624 (and (bolp) (not (org-at-heading-p))))
18625 (cdlatex-tab) t)
18626 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18628 (defun org-cdlatex-underscore-caret (&optional arg)
18629 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18630 Revert to the normal definition outside of these fragments."
18631 (interactive "P")
18632 (if (org-inside-LaTeX-fragment-p)
18633 (call-interactively 'cdlatex-sub-superscript)
18634 (let (org-cdlatex-mode)
18635 (call-interactively (key-binding (vector last-input-event))))))
18637 (defun org-cdlatex-math-modify (&optional arg)
18638 "Execute `cdlatex-math-modify' in LaTeX fragments.
18639 Revert to the normal definition outside of these fragments."
18640 (interactive "P")
18641 (if (org-inside-LaTeX-fragment-p)
18642 (call-interactively 'cdlatex-math-modify)
18643 (let (org-cdlatex-mode)
18644 (call-interactively (key-binding (vector last-input-event))))))
18646 (defun org-cdlatex-environment-indent (&optional environment item)
18647 "Execute `cdlatex-environment' and indent the inserted environment."
18648 (interactive)
18649 (cdlatex-environment environment item)
18650 (let ((element (org-element-at-point)))
18651 (org-indent-region (org-element-property :begin element)
18652 (org-element-property :end element))))
18655 ;;;; LaTeX fragments
18657 (defun org-inside-LaTeX-fragment-p ()
18658 "Test if point is inside a LaTeX fragment.
18659 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18660 sequence appearing also before point.
18661 Even though the matchers for math are configurable, this function assumes
18662 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18663 delimiters are skipped when they have been removed by customization.
18664 The return value is nil, or a cons cell with the delimiter and the
18665 position of this delimiter.
18667 This function does a reasonably good job, but can locally be fooled by
18668 for example currency specifications. For example it will assume being in
18669 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18670 fragments that are properly closed, but during editing, we have to live
18671 with the uncertainty caused by missing closing delimiters. This function
18672 looks only before point, not after."
18673 (catch 'exit
18674 (let ((pos (point))
18675 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18676 (lim (progn
18677 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18678 (point)))
18679 dd-on str (start 0) m re)
18680 (goto-char pos)
18681 (when dodollar
18682 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18683 re (nth 1 (assoc "$" org-latex-regexps)))
18684 (while (string-match re str start)
18685 (cond
18686 ((= (match-end 0) (length str))
18687 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18688 ((= (match-end 0) (- (length str) 5))
18689 (throw 'exit nil))
18690 (t (setq start (match-end 0))))))
18691 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18692 (goto-char pos)
18693 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18694 (and (match-beginning 2) (throw 'exit nil))
18695 ;; count $$
18696 (while (re-search-backward "\\$\\$" lim t)
18697 (setq dd-on (not dd-on)))
18698 (goto-char pos)
18699 (if dd-on (cons "$$" m))))))
18701 (defun org-inside-latex-macro-p ()
18702 "Is point inside a LaTeX macro or its arguments?"
18703 (save-match-data
18704 (org-in-regexp
18705 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18707 (defvar org-latex-fragment-image-overlays nil
18708 "List of overlays carrying the images of latex fragments.")
18709 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18711 (defun org-remove-latex-fragment-image-overlays ()
18712 "Remove all overlays with LaTeX fragment images in current buffer."
18713 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18714 (setq org-latex-fragment-image-overlays nil))
18716 (define-obsolete-function-alias
18717 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18718 (defun org-toggle-latex-fragment (&optional subtree)
18719 "Preview the LaTeX fragment at point, or all locally or globally.
18720 If the cursor is in a LaTeX fragment, create the image and overlay
18721 it over the source code. If there is no fragment at point, display
18722 all fragments in the current text, from one headline to the next. With
18723 prefix SUBTREE, display all fragments in the current subtree. With a
18724 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18725 the cursor is before the first headline,
18726 display all fragments in the buffer.
18727 The images can be removed again with \\[org-toggle-latex-fragment]."
18728 (interactive "P")
18729 (unless (buffer-file-name (buffer-base-buffer))
18730 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18731 (if org-latex-fragment-image-overlays
18732 (progn (org-remove-latex-fragment-image-overlays)
18733 (message "LaTeX fragments images removed"))
18734 (when (display-graphic-p)
18735 (org-remove-latex-fragment-image-overlays)
18736 (org-with-wide-buffer
18737 (let (beg end msg)
18738 (cond
18739 ((equal subtree '(16))
18740 (setq beg (point-min) end (point-max)
18741 msg "Creating images for buffer...%s"))
18742 ((equal subtree '(4))
18743 (org-back-to-heading)
18744 (setq beg (point) end (org-end-of-subtree t)
18745 msg "Creating images for subtree...%s"))
18746 ((let ((context (org-element-context)))
18747 (when (memq (org-element-type context)
18748 '(latex-environment latex-fragment))
18749 (setq beg (org-element-property :begin context)
18750 end (org-element-property :end context)
18751 msg "Creating image...%s"))))
18752 ((org-before-first-heading-p)
18753 (setq beg (point-min) end (point-max)
18754 msg "Creating images for buffer...%s"))
18756 (org-back-to-heading)
18757 (setq beg (point) end (progn (outline-next-heading) (point))
18758 msg "Creating images for entry...%s")))
18759 (message msg "")
18760 (narrow-to-region beg end)
18761 (goto-char beg)
18762 (org-format-latex
18763 (concat org-latex-preview-ltxpng-directory
18764 (file-name-sans-extension
18765 (file-name-nondirectory
18766 (buffer-file-name (buffer-base-buffer)))))
18767 default-directory 'overlays msg 'forbuffer
18768 org-latex-create-formula-image-program)
18769 (message msg "done. Use `C-c C-x C-l' to remove images."))))))
18771 (defun org-format-latex
18772 (prefix &optional dir overlays msg forbuffer processing-type)
18773 "Replace LaTeX fragments with links to an image, and produce images.
18774 Some of the options can be changed using the variable
18775 `org-format-latex-options'."
18776 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18777 (unless (eq processing-type 'verbatim)
18778 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18779 (cnt 0)
18780 checkdir-flag)
18781 (goto-char (point-min))
18782 (while (re-search-forward math-regexp nil t)
18783 (unless (and overlays
18784 (eq (get-char-property (point) 'org-overlay-type)
18785 'org-latex-overlay))
18786 (let* ((context (org-element-context))
18787 (type (org-element-type context)))
18788 (when (memq type '(latex-environment latex-fragment))
18789 (let ((block-type (eq type 'latex-environment))
18790 (value (org-element-property :value context))
18791 (beg (org-element-property :begin context))
18792 (end (save-excursion
18793 (goto-char (org-element-property :end context))
18794 (skip-chars-backward " \r\t\n")
18795 (point))))
18796 (case processing-type
18797 (mathjax
18798 ;; Prepare for MathJax processing.
18799 (if (eq (char-after beg) ?$)
18800 (save-excursion
18801 (delete-region beg end)
18802 (insert "\\(" (substring value 1 -1) "\\)"))
18803 (goto-char end)))
18804 ((dvipng imagemagick)
18805 ;; Process to an image.
18806 (incf cnt)
18807 (goto-char beg)
18808 (let* ((face (face-at-point))
18809 ;; Get the colors from the face at point.
18811 (let ((color (plist-get org-format-latex-options
18812 :foreground)))
18813 (if (and forbuffer (eq color 'auto))
18814 (face-attribute face :foreground nil 'default)
18815 color)))
18817 (let ((color (plist-get org-format-latex-options
18818 :background)))
18819 (if (and forbuffer (eq color 'auto))
18820 (face-attribute face :background nil 'default)
18821 color)))
18822 (hash (sha1 (prin1-to-string
18823 (list org-format-latex-header
18824 org-latex-default-packages-alist
18825 org-latex-packages-alist
18826 org-format-latex-options
18827 forbuffer value fg bg))))
18828 (absprefix (expand-file-name prefix dir))
18829 (linkfile (format "%s_%s.png" prefix hash))
18830 (movefile (format "%s_%s.png" absprefix hash))
18831 (sep (and block-type "\n\n"))
18832 (link (concat sep "[[file:" linkfile "]]" sep))
18833 (options
18834 (org-combine-plists
18835 org-format-latex-options
18836 `(:foreground ,fg :background ,bg))))
18837 (when msg (message msg cnt))
18838 (unless checkdir-flag ; Ensure the directory exists.
18839 (setq checkdir-flag t)
18840 (let ((todir (file-name-directory absprefix)))
18841 (unless (file-directory-p todir)
18842 (make-directory todir t))))
18843 (unless (file-exists-p movefile)
18844 (org-create-formula-image
18845 value movefile options forbuffer processing-type))
18846 (if overlays
18847 (progn
18848 (dolist (o (overlays-in beg end))
18849 (when (eq (overlay-get o 'org-overlay-type)
18850 'org-latex-overlay)
18851 (delete-overlay o)))
18852 (let ((ov (make-overlay beg end)))
18853 (overlay-put ov
18854 'org-overlay-type
18855 'org-latex-overlay)
18856 (if (featurep 'xemacs)
18857 (progn
18858 (overlay-put ov 'invisible t)
18859 (overlay-put
18860 ov 'end-glyph
18861 (make-glyph
18862 (vector 'png :file movefile))))
18863 (overlay-put
18864 ov 'display
18865 (list 'image
18866 :type 'png
18867 :file movefile
18868 :ascent 'center)))
18869 (push ov org-latex-fragment-image-overlays))
18870 (goto-char end))
18871 (delete-region beg end)
18872 (insert
18873 (org-add-props link
18874 (list 'org-latex-src
18875 (replace-regexp-in-string "\"" "" value)
18876 'org-latex-src-embed-type
18877 (if block-type 'paragraph 'character)))))))
18878 (mathml
18879 ;; Process to MathML.
18880 (unless (org-format-latex-mathml-available-p)
18881 (user-error "LaTeX to MathML converter not configured"))
18882 (incf cnt)
18883 (when msg (message msg cnt))
18884 (goto-char beg)
18885 (delete-region beg end)
18886 (insert (org-format-latex-as-mathml
18887 value block-type prefix dir)))
18888 (otherwise
18889 (error "Unknown conversion type %s for LaTeX fragments"
18890 processing-type)))))))))))
18892 (defun org-create-math-formula (latex-frag &optional mathml-file)
18893 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18894 Use `org-latex-to-mathml-convert-command'. If the conversion is
18895 sucessful, return the portion between \"<math...> </math>\"
18896 elements otherwise return nil. When MATHML-FILE is specified,
18897 write the results in to that file. When invoked as an
18898 interactive command, prompt for LATEX-FRAG, with initial value
18899 set to the current active region and echo the results for user
18900 inspection."
18901 (interactive (list (let ((frag (when (org-region-active-p)
18902 (buffer-substring-no-properties
18903 (region-beginning) (region-end)))))
18904 (read-string "LaTeX Fragment: " frag nil frag))))
18905 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18906 (let* ((tmp-in-file (file-relative-name
18907 (make-temp-name (expand-file-name "ltxmathml-in"))))
18908 (ignore (write-region latex-frag nil tmp-in-file))
18909 (tmp-out-file (file-relative-name
18910 (make-temp-name (expand-file-name "ltxmathml-out"))))
18911 (cmd (format-spec
18912 org-latex-to-mathml-convert-command
18913 `((?j . ,(shell-quote-argument
18914 (expand-file-name org-latex-to-mathml-jar-file)))
18915 (?I . ,(shell-quote-argument tmp-in-file))
18916 (?o . ,(shell-quote-argument tmp-out-file)))))
18917 mathml shell-command-output)
18918 (when (org-called-interactively-p 'any)
18919 (unless (org-format-latex-mathml-available-p)
18920 (user-error "LaTeX to MathML converter not configured")))
18921 (message "Running %s" cmd)
18922 (setq shell-command-output (shell-command-to-string cmd))
18923 (setq mathml
18924 (when (file-readable-p tmp-out-file)
18925 (with-current-buffer (find-file-noselect tmp-out-file t)
18926 (goto-char (point-min))
18927 (when (re-search-forward
18928 (concat
18929 (regexp-quote
18930 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18931 "\\(.\\|\n\\)*"
18932 (regexp-quote "</math>")) nil t)
18933 (prog1 (match-string 0) (kill-buffer))))))
18934 (cond
18935 (mathml
18936 (setq mathml
18937 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18938 (when mathml-file
18939 (write-region mathml nil mathml-file))
18940 (when (org-called-interactively-p 'any)
18941 (message mathml)))
18942 ((message "LaTeX to MathML conversion failed")
18943 (message shell-command-output)))
18944 (delete-file tmp-in-file)
18945 (when (file-exists-p tmp-out-file)
18946 (delete-file tmp-out-file))
18947 mathml))
18949 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18950 prefix &optional dir)
18951 "Use `org-create-math-formula' but check local cache first."
18952 (let* ((absprefix (expand-file-name prefix dir))
18953 (print-length nil) (print-level nil)
18954 (formula-id (concat
18955 "formula-"
18956 (sha1
18957 (prin1-to-string
18958 (list latex-frag
18959 org-latex-to-mathml-convert-command)))))
18960 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18961 (formula-cache-dir (file-name-directory formula-cache)))
18963 (unless (file-directory-p formula-cache-dir)
18964 (make-directory formula-cache-dir t))
18966 (unless (file-exists-p formula-cache)
18967 (org-create-math-formula latex-frag formula-cache))
18969 (if (file-exists-p formula-cache)
18970 ;; Successful conversion. Return the link to MathML file.
18971 (org-add-props
18972 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18973 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18974 'org-latex-src-embed-type (if latex-frag-type
18975 'paragraph 'character)))
18976 ;; Failed conversion. Return the LaTeX fragment verbatim
18977 latex-frag)))
18979 (defun org-create-formula-image (string tofile options buffer &optional type)
18980 "Create an image from LaTeX source using dvipng or convert.
18981 This function calls either `org-create-formula-image-with-dvipng'
18982 or `org-create-formula-image-with-imagemagick' depending on the
18983 value of `org-latex-create-formula-image-program' or on the value
18984 of the optional TYPE variable.
18986 Note: ultimately these two function should be combined as they
18987 share a good deal of logic."
18988 (org-check-external-command
18989 "latex" "needed to convert LaTeX fragments to images")
18990 (funcall
18991 (case (or type org-latex-create-formula-image-program)
18992 ('dvipng
18993 (org-check-external-command
18994 "dvipng" "needed to convert LaTeX fragments to images")
18995 'org-create-formula-image-with-dvipng)
18996 ('imagemagick
18997 (org-check-external-command
18998 "convert" "you need to install imagemagick")
18999 'org-create-formula-image-with-imagemagick)
19000 (t (error
19001 "Invalid value of `org-latex-create-formula-image-program'")))
19002 string tofile options buffer))
19004 (declare-function org-export-get-backend "ox" (name))
19005 (declare-function org-export--get-global-options "ox" (&optional backend))
19006 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19007 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19008 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19009 (defun org-create-formula--latex-header ()
19010 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19011 (let ((info (org-combine-plists (org-export--get-global-options
19012 (org-export-get-backend 'latex))
19013 (org-export--get-inbuffer-options
19014 (org-export-get-backend 'latex)))))
19015 (org-latex-guess-babel-language
19016 (org-latex-guess-inputenc
19017 (org-splice-latex-header
19018 org-format-latex-header
19019 org-latex-default-packages-alist
19020 org-latex-packages-alist t
19021 (plist-get info :latex-header)))
19022 info)))
19024 ;; This function borrows from Ganesh Swami's latex2png.el
19025 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19026 "This calls dvipng."
19027 (require 'ox-latex)
19028 (let* ((tmpdir (if (featurep 'xemacs)
19029 (temp-directory)
19030 temporary-file-directory))
19031 (texfilebase (make-temp-name
19032 (expand-file-name "orgtex" tmpdir)))
19033 (texfile (concat texfilebase ".tex"))
19034 (dvifile (concat texfilebase ".dvi"))
19035 (pngfile (concat texfilebase ".png"))
19036 (fnh (if (featurep 'xemacs)
19037 (font-height (face-font 'default))
19038 (face-attribute 'default :height nil)))
19039 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19040 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
19041 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19042 "Black"))
19043 (bg (or (plist-get options (if buffer :background :html-background))
19044 "Transparent")))
19045 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19046 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19047 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19048 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19049 (let ((latex-header (org-create-formula--latex-header)))
19050 (with-temp-file texfile
19051 (insert latex-header)
19052 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19053 (let ((dir default-directory))
19054 (ignore-errors
19055 (cd tmpdir)
19056 (call-process "latex" nil nil nil texfile))
19057 (cd dir))
19058 (if (not (file-exists-p dvifile))
19059 (progn (message "Failed to create dvi file from %s" texfile) nil)
19060 (ignore-errors
19061 (if (featurep 'xemacs)
19062 (call-process "dvipng" nil nil nil
19063 "-fg" fg "-bg" bg
19064 "-T" "tight"
19065 "-o" pngfile
19066 dvifile)
19067 (call-process "dvipng" nil nil nil
19068 "-fg" fg "-bg" bg
19069 "-D" dpi
19070 ;;"-x" scale "-y" scale
19071 "-T" "tight"
19072 "-o" pngfile
19073 dvifile)))
19074 (if (not (file-exists-p pngfile))
19075 (if org-format-latex-signal-error
19076 (error "Failed to create png file from %s" texfile)
19077 (message "Failed to create png file from %s" texfile)
19078 nil)
19079 ;; Use the requested file name and clean up
19080 (copy-file pngfile tofile 'replace)
19081 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
19082 (if (file-exists-p (concat texfilebase e))
19083 (delete-file (concat texfilebase e))))
19084 pngfile))))
19086 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19087 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19088 "This calls convert, which is included into imagemagick."
19089 (require 'ox-latex)
19090 (let* ((tmpdir (if (featurep 'xemacs)
19091 (temp-directory)
19092 temporary-file-directory))
19093 (texfilebase (make-temp-name
19094 (expand-file-name "orgtex" tmpdir)))
19095 (texfile (concat texfilebase ".tex"))
19096 (pdffile (concat texfilebase ".pdf"))
19097 (pngfile (concat texfilebase ".png"))
19098 (fnh (if (featurep 'xemacs)
19099 (font-height (face-font 'default))
19100 (face-attribute 'default :height nil)))
19101 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19102 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
19103 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19104 "black"))
19105 (bg (or (plist-get options (if buffer :background :html-background))
19106 "white")))
19107 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19108 (setq fg (org-latex-color-format fg)))
19109 (if (eq bg 'default) (setq bg (org-latex-color :background))
19110 (setq bg (org-latex-color-format
19111 (if (string= bg "Transparent") "white" bg))))
19112 (let ((latex-header (org-create-formula--latex-header)))
19113 (with-temp-file texfile
19114 (insert latex-header)
19115 (insert "\n\\begin{document}\n"
19116 "\\definecolor{fg}{rgb}{" fg "}\n"
19117 "\\definecolor{bg}{rgb}{" bg "}\n"
19118 "\n\\pagecolor{bg}\n"
19119 "\n{\\color{fg}\n"
19120 string
19121 "\n}\n"
19122 "\n\\end{document}\n")))
19123 (org-latex-compile texfile t)
19124 (if (not (file-exists-p pdffile))
19125 (progn (message "Failed to create pdf file from %s" texfile) nil)
19126 (ignore-errors
19127 (if (featurep 'xemacs)
19128 (call-process "convert" nil nil nil
19129 "-density" "96"
19130 "-trim"
19131 "-antialias"
19132 pdffile
19133 "-quality" "100"
19134 ;; "-sharpen" "0x1.0"
19135 pngfile)
19136 (call-process "convert" nil nil nil
19137 "-density" dpi
19138 "-trim"
19139 "-antialias"
19140 pdffile
19141 "-quality" "100"
19142 ;; "-sharpen" "0x1.0"
19143 pngfile)))
19144 (if (not (file-exists-p pngfile))
19145 (if org-format-latex-signal-error
19146 (error "Failed to create png file from %s" texfile)
19147 (message "Failed to create png file from %s" texfile)
19148 nil)
19149 ;; Use the requested file name and clean up
19150 (copy-file pngfile tofile 'replace)
19151 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19152 (if (file-exists-p (concat texfilebase e))
19153 (delete-file (concat texfilebase e))))
19154 pngfile))))
19156 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19157 "Fill a LaTeX header template TPL.
19158 In the template, the following place holders will be recognized:
19160 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19161 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19162 [PACKAGES] \\usepackage statements for PKG
19163 [NO-PACKAGES] do not include PKG
19164 [EXTRA] the string EXTRA
19165 [NO-EXTRA] do not include EXTRA
19167 For backward compatibility, if both the positive and the negative place
19168 holder is missing, the positive one (without the \"NO-\") will be
19169 assumed to be present at the end of the template.
19170 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19171 EXTRA is a string.
19172 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19173 (let (rpl (end ""))
19174 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19175 (setq rpl (if (or (match-end 1) (not def-pkg))
19176 "" (org-latex-packages-to-string def-pkg snippets-p t))
19177 tpl (replace-match rpl t t tpl))
19178 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19180 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19181 (setq rpl (if (or (match-end 1) (not pkg))
19182 "" (org-latex-packages-to-string pkg snippets-p t))
19183 tpl (replace-match rpl t t tpl))
19184 (if pkg (setq end
19185 (concat end "\n"
19186 (org-latex-packages-to-string pkg snippets-p)))))
19188 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19189 (setq rpl (if (or (match-end 1) (not extra))
19190 "" (concat extra "\n"))
19191 tpl (replace-match rpl t t tpl))
19192 (if (and extra (string-match "\\S-" extra))
19193 (setq end (concat end "\n" extra))))
19195 (if (string-match "\\S-" end)
19196 (concat tpl "\n" end)
19197 tpl)))
19199 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19200 "Turn an alist of packages into a string with the \\usepackage macros."
19201 (setq pkg (mapconcat (lambda(p)
19202 (cond
19203 ((stringp p) p)
19204 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19205 (format "%% Package %s omitted" (cadr p)))
19206 ((equal "" (car p))
19207 (format "\\usepackage{%s}" (cadr p)))
19209 (format "\\usepackage[%s]{%s}"
19210 (car p) (cadr p)))))
19212 "\n"))
19213 (if newline (concat pkg "\n") pkg))
19215 (defun org-dvipng-color (attr)
19216 "Return a RGB color specification for dvipng."
19217 (apply 'format "rgb %s %s %s"
19218 (mapcar 'org-normalize-color
19219 (if (featurep 'xemacs)
19220 (color-rgb-components
19221 (face-property 'default
19222 (cond ((eq attr :foreground) 'foreground)
19223 ((eq attr :background) 'background))))
19224 (color-values (face-attribute 'default attr nil))))))
19226 (defun org-dvipng-color-format (color-name)
19227 "Convert COLOR-NAME to a RGB color value for dvipng."
19228 (apply 'format "rgb %s %s %s"
19229 (mapcar 'org-normalize-color
19230 (color-values color-name))))
19232 (defun org-latex-color (attr)
19233 "Return a RGB color for the LaTeX color package."
19234 (apply 'format "%s,%s,%s"
19235 (mapcar 'org-normalize-color
19236 (if (featurep 'xemacs)
19237 (color-rgb-components
19238 (face-property 'default
19239 (cond ((eq attr :foreground) 'foreground)
19240 ((eq attr :background) 'background))))
19241 (color-values (face-attribute 'default attr nil))))))
19243 (defun org-latex-color-format (color-name)
19244 "Convert COLOR-NAME to a RGB color value."
19245 (apply 'format "%s,%s,%s"
19246 (mapcar 'org-normalize-color
19247 (color-values color-name))))
19249 (defun org-normalize-color (value)
19250 "Return string to be used as color value for an RGB component."
19251 (format "%g" (/ value 65535.0)))
19255 ;; Image display
19257 (defvar org-inline-image-overlays nil)
19258 (make-variable-buffer-local 'org-inline-image-overlays)
19260 (defun org-toggle-inline-images (&optional include-linked)
19261 "Toggle the display of inline images.
19262 INCLUDE-LINKED is passed to `org-display-inline-images'."
19263 (interactive "P")
19264 (if org-inline-image-overlays
19265 (progn
19266 (org-remove-inline-images)
19267 (message "Inline image display turned off"))
19268 (org-display-inline-images include-linked)
19269 (if (and (org-called-interactively-p)
19270 org-inline-image-overlays)
19271 (message "%d images displayed inline"
19272 (length org-inline-image-overlays))
19273 (message "No images to display inline"))))
19275 (defun org-redisplay-inline-images ()
19276 "Refresh the display of inline images."
19277 (interactive)
19278 (if (not org-inline-image-overlays)
19279 (org-toggle-inline-images)
19280 (org-toggle-inline-images)
19281 (org-toggle-inline-images)))
19283 (defun org-display-inline-images (&optional include-linked refresh beg end)
19284 "Display inline images.
19286 An inline image is a link which follows either of these
19287 conventions:
19289 1. Its path is a file with an extension matching return value
19290 from `image-file-name-regexp' and it has no contents.
19292 2. Its description consists in a single link of the previous
19293 type.
19295 When optional argument INCLUDE-LINKED is non-nil, also links with
19296 a text description part will be inlined. This can be nice for
19297 a quick look at those images, but it does not reflect what
19298 exported files will look like.
19300 When optional argument REFRESH is non-nil, refresh existing
19301 images between BEG and END. This will create new image displays
19302 only if necessary. BEG and END default to the buffer
19303 boundaries."
19304 (interactive "P")
19305 (when (display-graphic-p)
19306 (unless refresh
19307 (org-remove-inline-images)
19308 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19309 (org-with-wide-buffer
19310 (goto-char (or beg (point-min)))
19311 (let ((case-fold-search t)
19312 (file-extension-re (org-image-file-name-regexp)))
19313 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19314 (let ((link (save-match-data (org-element-context))))
19315 ;; Check if we're at an inline image.
19316 (when (and (equal (org-element-property :type link) "file")
19317 (or include-linked
19318 (not (org-element-property :contents-begin link)))
19319 (let ((parent (org-element-property :parent link)))
19320 (or (not (eq (org-element-type parent) 'link))
19321 (not (cdr (org-element-contents parent)))))
19322 (org-string-match-p file-extension-re
19323 (org-element-property :path link)))
19324 (let ((file (expand-file-name (org-element-property :path link))))
19325 (when (file-exists-p file)
19326 (let ((width
19327 ;; Apply `org-image-actual-width' specifications.
19328 (cond
19329 ((not (image-type-available-p 'imagemagick)) nil)
19330 ((eq org-image-actual-width t) nil)
19331 ((listp org-image-actual-width)
19333 ;; First try to find a width among
19334 ;; attributes associated to the paragraph
19335 ;; containing link.
19336 (let ((paragraph
19337 (let ((e link))
19338 (while (and (setq e (org-element-property
19339 :parent e))
19340 (not (eq (org-element-type e)
19341 'paragraph))))
19342 e)))
19343 (when paragraph
19344 (save-excursion
19345 (goto-char (org-element-property :begin paragraph))
19346 (when
19347 (re-search-forward
19348 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19349 (org-element-property
19350 :post-affiliated paragraph)
19352 (string-to-number (match-string 1))))))
19353 ;; Otherwise, fall-back to provided number.
19354 (car org-image-actual-width)))
19355 ((numberp org-image-actual-width)
19356 org-image-actual-width)))
19357 (old (get-char-property-and-overlay
19358 (org-element-property :begin link)
19359 'org-image-overlay)))
19360 (if (and (car-safe old) refresh)
19361 (image-refresh (overlay-get (cdr old) 'display))
19362 (let ((image (create-image file
19363 (and width 'imagemagick)
19365 :width width)))
19366 (when image
19367 (let* ((link
19368 ;; If inline image is the description
19369 ;; of another link, be sure to
19370 ;; consider the latter as the one to
19371 ;; apply the overlay on.
19372 (let ((parent
19373 (org-element-property :parent link)))
19374 (if (eq (org-element-type parent) 'link)
19375 parent
19376 link)))
19377 (ov (make-overlay
19378 (org-element-property :begin link)
19379 (progn
19380 (goto-char
19381 (org-element-property :end link))
19382 (skip-chars-backward " \t")
19383 (point)))))
19384 (overlay-put ov 'display image)
19385 (overlay-put ov 'face 'default)
19386 (overlay-put ov 'org-image-overlay t)
19387 (overlay-put
19388 ov 'modification-hooks
19389 (list 'org-display-inline-remove-overlay))
19390 (push ov org-inline-image-overlays)))))))))))))))
19392 (define-obsolete-function-alias
19393 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19395 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19396 "Remove inline-display overlay if a corresponding region is modified."
19397 (let ((inhibit-modification-hooks t))
19398 (when (and ov after)
19399 (delete ov org-inline-image-overlays)
19400 (delete-overlay ov))))
19402 (defun org-remove-inline-images ()
19403 "Remove inline display of images."
19404 (interactive)
19405 (mapc 'delete-overlay org-inline-image-overlays)
19406 (setq org-inline-image-overlays nil))
19408 ;;;; Key bindings
19410 ;; Outline functions from `outline-mode-prefix-map'
19411 ;; that can be remapped in Org:
19412 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19413 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19414 (define-key org-mode-map [remap outline-forward-same-level]
19415 'org-forward-heading-same-level)
19416 (define-key org-mode-map [remap outline-backward-same-level]
19417 'org-backward-heading-same-level)
19418 (define-key org-mode-map [remap show-branches]
19419 'org-kill-note-or-show-branches)
19420 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19421 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19422 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19424 ;; Outline functions from `outline-mode-prefix-map' that can not
19425 ;; be remapped in Org:
19427 ;; - the column "key binding" shows whether the Outline function is still
19428 ;; available in Org mode on the same key that it has been bound to in
19429 ;; Outline mode:
19430 ;; - "overridden": key used for a different functionality in Org mode
19431 ;; - else: key still bound to the same Outline function in Org mode
19433 ;; | Outline function | key binding | Org replacement |
19434 ;; |------------------------------------+-------------+-----------------------|
19435 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19436 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19437 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19438 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19439 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19440 ;; | `show-entry' | overridden | no replacement |
19441 ;; | `show-children' | `C-c C-i' | visibility cycling |
19442 ;; | `show-branches' | `C-c C-k' | still same function |
19443 ;; | `show-subtree' | overridden | visibility cycling |
19444 ;; | `show-all' | overridden | no replacement |
19445 ;; | `hide-subtree' | overridden | visibility cycling |
19446 ;; | `hide-body' | overridden | no replacement |
19447 ;; | `hide-entry' | overridden | visibility cycling |
19448 ;; | `hide-leaves' | overridden | no replacement |
19449 ;; | `hide-sublevels' | overridden | no replacement |
19450 ;; | `hide-other' | overridden | no replacement |
19452 ;; Make `C-c C-x' a prefix key
19453 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19455 ;; TAB key with modifiers
19456 (org-defkey org-mode-map "\C-i" 'org-cycle)
19457 (org-defkey org-mode-map [(tab)] 'org-cycle)
19458 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19459 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19460 ;; The following line is necessary under Suse GNU/Linux
19461 (unless (featurep 'xemacs)
19462 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19463 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19464 (define-key org-mode-map [backtab] 'org-shifttab)
19466 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19467 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19468 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19470 ;; Cursor keys with modifiers
19471 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19472 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19473 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19474 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19476 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19477 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19478 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19479 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19480 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19481 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19483 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19484 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19485 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19486 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19488 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19489 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19490 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19491 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19493 ;; Babel keys
19494 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19495 (mapc (lambda (pair)
19496 (define-key org-babel-map (car pair) (cdr pair)))
19497 org-babel-key-bindings)
19499 ;;; Extra keys for tty access.
19500 ;; We only set them when really needed because otherwise the
19501 ;; menus don't show the simple keys
19503 (when (or org-use-extra-keys
19504 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19505 (not window-system))
19506 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19507 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19508 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19509 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19510 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19511 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19512 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19513 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19514 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19515 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19516 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19517 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19518 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19519 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19520 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19521 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19522 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19523 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19524 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19525 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19526 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19527 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19528 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19529 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19530 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19531 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19532 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19533 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19535 ;; All the other keys
19537 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19538 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19539 (if (boundp 'narrow-map)
19540 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19541 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19542 (if (boundp 'narrow-map)
19543 (org-defkey narrow-map "b" 'org-narrow-to-block)
19544 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19545 (if (boundp 'narrow-map)
19546 (org-defkey narrow-map "e" 'org-narrow-to-element)
19547 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19548 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19549 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19550 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19551 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19552 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19553 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19554 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19555 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19556 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19557 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19558 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19559 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19560 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19561 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19562 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19563 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19564 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19565 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19566 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19567 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19568 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19569 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19570 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19571 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19572 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19573 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19574 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19575 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19576 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19577 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19578 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19579 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19580 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19581 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19582 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19583 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19584 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19585 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19586 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19587 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19588 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19589 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19590 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19591 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19592 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19593 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19594 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19595 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19596 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19597 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19598 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19599 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19600 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19601 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19602 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19603 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19604 (org-defkey org-mode-map "\C-c^" 'org-sort)
19605 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19606 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19607 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19608 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19609 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19610 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19611 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19612 (org-defkey org-mode-map "\C-m" 'org-return)
19613 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19614 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19615 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19616 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19617 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19618 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19619 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19620 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19621 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19622 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19623 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19624 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19625 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19626 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19627 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19628 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19629 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19630 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19631 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19632 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19633 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19634 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19635 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19636 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19637 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19639 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19640 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19641 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19643 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19644 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19645 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19646 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19647 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19648 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19649 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19650 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19651 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19652 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19653 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19654 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19655 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19656 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19657 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19658 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19659 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19660 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19661 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19662 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19663 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19664 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19665 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19667 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19668 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19669 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19670 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19671 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19673 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19675 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19677 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19678 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19680 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19683 (when (featurep 'xemacs)
19684 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19687 (defconst org-speed-commands-default
19689 ("Outline Navigation")
19690 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19691 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19692 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19693 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19694 ("F" . org-next-block)
19695 ("B" . org-previous-block)
19696 ("u" . (org-speed-move-safe 'outline-up-heading))
19697 ("j" . org-goto)
19698 ("g" . (org-refile t))
19699 ("Outline Visibility")
19700 ("c" . org-cycle)
19701 ("C" . org-shifttab)
19702 (" " . org-display-outline-path)
19703 ("s" . org-narrow-to-subtree)
19704 ("=" . org-columns)
19705 ("Outline Structure Editing")
19706 ("U" . org-metaup)
19707 ("D" . org-metadown)
19708 ("r" . org-metaright)
19709 ("l" . org-metaleft)
19710 ("R" . org-shiftmetaright)
19711 ("L" . org-shiftmetaleft)
19712 ("i" . (progn (forward-char 1) (call-interactively
19713 'org-insert-heading-respect-content)))
19714 ("^" . org-sort)
19715 ("w" . org-refile)
19716 ("a" . org-archive-subtree-default-with-confirmation)
19717 ("@" . org-mark-subtree)
19718 ("#" . org-toggle-comment)
19719 ("Clock Commands")
19720 ("I" . org-clock-in)
19721 ("O" . org-clock-out)
19722 ("Meta Data Editing")
19723 ("t" . org-todo)
19724 ("," . (org-priority))
19725 ("0" . (org-priority ?\ ))
19726 ("1" . (org-priority ?A))
19727 ("2" . (org-priority ?B))
19728 ("3" . (org-priority ?C))
19729 (":" . org-set-tags-command)
19730 ("e" . org-set-effort)
19731 ("E" . org-inc-effort)
19732 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19733 (org-entry-put (point) "APPT_WARNTIME" m)))
19734 ("Agenda Views etc")
19735 ("v" . org-agenda)
19736 ("/" . org-sparse-tree)
19737 ("Misc")
19738 ("o" . org-open-at-point)
19739 ("?" . org-speed-command-help)
19740 ("<" . (org-agenda-set-restriction-lock 'subtree))
19741 (">" . (org-agenda-remove-restriction-lock))
19743 "The default speed commands.")
19745 (defun org-print-speed-command (e)
19746 (if (> (length (car e)) 1)
19747 (progn
19748 (princ "\n")
19749 (princ (car e))
19750 (princ "\n")
19751 (princ (make-string (length (car e)) ?-))
19752 (princ "\n"))
19753 (princ (car e))
19754 (princ " ")
19755 (if (symbolp (cdr e))
19756 (princ (symbol-name (cdr e)))
19757 (prin1 (cdr e)))
19758 (princ "\n")))
19760 (defun org-speed-command-help ()
19761 "Show the available speed commands."
19762 (interactive)
19763 (if (not org-use-speed-commands)
19764 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19765 (with-output-to-temp-buffer "*Help*"
19766 (princ "User-defined Speed commands\n===========================\n")
19767 (mapc 'org-print-speed-command org-speed-commands-user)
19768 (princ "\n")
19769 (princ "Built-in Speed commands\n=======================\n")
19770 (mapc 'org-print-speed-command org-speed-commands-default))
19771 (with-current-buffer "*Help*"
19772 (setq truncate-lines t))))
19774 (defun org-speed-move-safe (cmd)
19775 "Execute CMD, but make sure that the cursor always ends up in a headline.
19776 If not, return to the original position and throw an error."
19777 (interactive)
19778 (let ((pos (point)))
19779 (call-interactively cmd)
19780 (unless (and (bolp) (org-at-heading-p))
19781 (goto-char pos)
19782 (error "Boundary reached while executing %s" cmd))))
19784 (defvar org-self-insert-command-undo-counter 0)
19786 (defvar org-table-auto-blank-field) ; defined in org-table.el
19787 (defvar org-speed-command nil)
19789 (define-obsolete-function-alias
19790 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19792 (defun org-speed-command-activate (keys)
19793 "Hook for activating single-letter speed commands.
19794 `org-speed-commands-default' specifies a minimal command set.
19795 Use `org-speed-commands-user' for further customization."
19796 (when (or (and (bolp) (looking-at org-outline-regexp))
19797 (and (functionp org-use-speed-commands)
19798 (funcall org-use-speed-commands)))
19799 (cdr (assoc keys (append org-speed-commands-user
19800 org-speed-commands-default)))))
19802 (define-obsolete-function-alias
19803 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19805 (defun org-babel-speed-command-activate (keys)
19806 "Hook for activating single-letter code block commands."
19807 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19808 (cdr (assoc keys org-babel-key-bindings))))
19810 (defcustom org-speed-command-hook
19811 '(org-speed-command-default-hook org-babel-speed-command-hook)
19812 "Hook for activating speed commands at strategic locations.
19813 Hook functions are called in sequence until a valid handler is
19814 found.
19816 Each hook takes a single argument, a user-pressed command key
19817 which is also a `self-insert-command' from the global map.
19819 Within the hook, examine the cursor position and the command key
19820 and return nil or a valid handler as appropriate. Handler could
19821 be one of an interactive command, a function, or a form.
19823 Set `org-use-speed-commands' to non-nil value to enable this
19824 hook. The default setting is `org-speed-command-activate'."
19825 :group 'org-structure
19826 :version "24.1"
19827 :type 'hook)
19829 (defun org-self-insert-command (N)
19830 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19831 If the cursor is in a table looking at whitespace, the whitespace is
19832 overwritten, and the table is not marked as requiring realignment."
19833 (interactive "p")
19834 (org-check-before-invisible-edit 'insert)
19835 (cond
19836 ((and org-use-speed-commands
19837 (let ((kv (this-command-keys-vector)))
19838 (setq org-speed-command
19839 (run-hook-with-args-until-success
19840 'org-speed-command-hook
19841 (make-string 1 (aref kv (1- (length kv))))))))
19842 (cond
19843 ((commandp org-speed-command)
19844 (setq this-command org-speed-command)
19845 (call-interactively org-speed-command))
19846 ((functionp org-speed-command)
19847 (funcall org-speed-command))
19848 ((and org-speed-command (listp org-speed-command))
19849 (eval org-speed-command))
19850 (t (let (org-use-speed-commands)
19851 (call-interactively 'org-self-insert-command)))))
19852 ((and
19853 (org-table-p)
19854 (progn
19855 ;; check if we blank the field, and if that triggers align
19856 (and (featurep 'org-table) org-table-auto-blank-field
19857 (memq last-command
19858 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19859 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19860 ;; got extra space, this field does not determine column width
19861 (let (org-table-may-need-update) (org-table-blank-field))
19862 ;; no extra space, this field may determine column width
19863 (org-table-blank-field)))
19865 (eq N 1)
19866 (looking-at "[^|\n]* |"))
19867 (let (org-table-may-need-update)
19868 (goto-char (1- (match-end 0)))
19869 (backward-delete-char 1)
19870 (goto-char (match-beginning 0))
19871 (self-insert-command N)))
19873 (setq org-table-may-need-update t)
19874 (self-insert-command N)
19875 (org-fix-tags-on-the-fly)
19876 (if org-self-insert-cluster-for-undo
19877 (if (not (eq last-command 'org-self-insert-command))
19878 (setq org-self-insert-command-undo-counter 1)
19879 (if (>= org-self-insert-command-undo-counter 20)
19880 (setq org-self-insert-command-undo-counter 1)
19881 (and (> org-self-insert-command-undo-counter 0)
19882 buffer-undo-list (listp buffer-undo-list)
19883 (not (cadr buffer-undo-list)) ; remove nil entry
19884 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19885 (setq org-self-insert-command-undo-counter
19886 (1+ org-self-insert-command-undo-counter))))))))
19888 (defun org-check-before-invisible-edit (kind)
19889 "Check is editing if kind KIND would be dangerous with invisible text around.
19890 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19891 ;; First, try to get out of here as quickly as possible, to reduce overhead
19892 (if (and org-catch-invisible-edits
19893 (or (not (boundp 'visible-mode)) (not visible-mode))
19894 (or (get-char-property (point) 'invisible)
19895 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19896 ;; OK, we need to take a closer look
19897 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19898 (invisible-before-point (if (bobp) nil (get-char-property
19899 (1- (point)) 'invisible)))
19900 (border-and-ok-direction
19902 ;; Check if we are acting predictably before invisible text
19903 (and invisible-at-point (not invisible-before-point)
19904 (memq kind '(insert delete-backward)))
19905 ;; Check if we are acting predictably after invisible text
19906 ;; This works not well, and I have turned it off. It seems
19907 ;; better to always show and stop after invisible text.
19908 ;; (and (not invisible-at-point) invisible-before-point
19909 ;; (memq kind '(insert delete)))
19911 (when (or (memq invisible-at-point '(outline org-hide-block t))
19912 (memq invisible-before-point '(outline org-hide-block t)))
19913 (if (eq org-catch-invisible-edits 'error)
19914 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19915 (if (and org-custom-properties-overlays
19916 (y-or-n-p "Display invisible properties in this buffer? "))
19917 (org-toggle-custom-properties-visibility)
19918 ;; Make the area visible
19919 (save-excursion
19920 (if invisible-before-point
19921 (goto-char (previous-single-char-property-change
19922 (point) 'invisible)))
19923 (show-subtree))
19924 (cond
19925 ((eq org-catch-invisible-edits 'show)
19926 ;; That's it, we do the edit after showing
19927 (message
19928 "Unfolding invisible region around point before editing")
19929 (sit-for 1))
19930 ((and (eq org-catch-invisible-edits 'smart)
19931 border-and-ok-direction)
19932 (message "Unfolding invisible region around point before editing"))
19934 ;; Don't do the edit, make the user repeat it in full visibility
19935 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19937 (defun org-fix-tags-on-the-fly ()
19938 (when (and (equal (char-after (point-at-bol)) ?*)
19939 (org-at-heading-p))
19940 (org-align-tags-here org-tags-column)))
19942 (defun org-delete-backward-char (N)
19943 "Like `delete-backward-char', insert whitespace at field end in tables.
19944 When deleting backwards, in tables this function will insert whitespace in
19945 front of the next \"|\" separator, to keep the table aligned. The table will
19946 still be marked for re-alignment if the field did fill the entire column,
19947 because, in this case the deletion might narrow the column."
19948 (interactive "p")
19949 (save-match-data
19950 (org-check-before-invisible-edit 'delete-backward)
19951 (if (and (org-table-p)
19952 (eq N 1)
19953 (string-match "|" (buffer-substring (point-at-bol) (point)))
19954 (looking-at ".*?|"))
19955 (let ((pos (point))
19956 (noalign (looking-at "[^|\n\r]* |"))
19957 (c org-table-may-need-update))
19958 (backward-delete-char N)
19959 (if (not overwrite-mode)
19960 (progn
19961 (skip-chars-forward "^|")
19962 (insert " ")
19963 (goto-char (1- pos))))
19964 ;; noalign: if there were two spaces at the end, this field
19965 ;; does not determine the width of the column.
19966 (if noalign (setq org-table-may-need-update c)))
19967 (backward-delete-char N)
19968 (org-fix-tags-on-the-fly))))
19970 (defun org-delete-char (N)
19971 "Like `delete-char', but insert whitespace at field end in tables.
19972 When deleting characters, in tables this function will insert whitespace in
19973 front of the next \"|\" separator, to keep the table aligned. The table will
19974 still be marked for re-alignment if the field did fill the entire column,
19975 because, in this case the deletion might narrow the column."
19976 (interactive "p")
19977 (save-match-data
19978 (org-check-before-invisible-edit 'delete)
19979 (if (and (org-table-p)
19980 (not (bolp))
19981 (not (= (char-after) ?|))
19982 (eq N 1))
19983 (if (looking-at ".*?|")
19984 (let ((pos (point))
19985 (noalign (looking-at "[^|\n\r]* |"))
19986 (c org-table-may-need-update))
19987 (replace-match
19988 (concat (substring (match-string 0) 1 -1) " |") nil t)
19989 (goto-char pos)
19990 ;; noalign: if there were two spaces at the end, this field
19991 ;; does not determine the width of the column.
19992 (if noalign (setq org-table-may-need-update c)))
19993 (delete-char N))
19994 (delete-char N)
19995 (org-fix-tags-on-the-fly))))
19997 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19998 (put 'org-self-insert-command 'delete-selection
19999 (lambda ()
20000 (not (run-hook-with-args-until-success
20001 'self-insert-uses-region-functions))))
20002 (put 'orgtbl-self-insert-command 'delete-selection
20003 (lambda ()
20004 (not (run-hook-with-args-until-success
20005 'self-insert-uses-region-functions))))
20006 (put 'org-delete-char 'delete-selection 'supersede)
20007 (put 'org-delete-backward-char 'delete-selection 'supersede)
20008 (put 'org-yank 'delete-selection 'yank)
20010 ;; Make `flyspell-mode' delay after some commands
20011 (put 'org-self-insert-command 'flyspell-delayed t)
20012 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20013 (put 'org-delete-char 'flyspell-delayed t)
20014 (put 'org-delete-backward-char 'flyspell-delayed t)
20016 ;; Make pabbrev-mode expand after org-mode commands
20017 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20018 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20020 (defun org-remap (map &rest commands)
20021 "In MAP, remap the functions given in COMMANDS.
20022 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20023 (let (new old)
20024 (while commands
20025 (setq old (pop commands) new (pop commands))
20026 (if (fboundp 'command-remapping)
20027 (org-defkey map (vector 'remap old) new)
20028 (substitute-key-definition old new map global-map)))))
20030 (defun org-transpose-words ()
20031 "Transpose words for Org.
20032 This uses the `org-mode-transpose-word-syntax-table' syntax
20033 table, which interprets characters in `org-emphasis-alist' as
20034 word constituents."
20035 (interactive)
20036 (with-syntax-table org-mode-transpose-word-syntax-table
20037 (call-interactively 'transpose-words)))
20038 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20040 (when (eq org-enable-table-editor 'optimized)
20041 ;; If the user wants maximum table support, we need to hijack
20042 ;; some standard editing functions
20043 (org-remap org-mode-map
20044 'self-insert-command 'org-self-insert-command
20045 'delete-char 'org-delete-char
20046 'delete-backward-char 'org-delete-backward-char)
20047 (org-defkey org-mode-map "|" 'org-force-self-insert))
20049 (defvar org-ctrl-c-ctrl-c-hook nil
20050 "Hook for functions attaching themselves to `C-c C-c'.
20052 This can be used to add additional functionality to the C-c C-c
20053 key which executes context-dependent commands. This hook is run
20054 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20055 run after the last test.
20057 Each function will be called with no arguments. The function
20058 must check if the context is appropriate for it to act. If yes,
20059 it should do its thing and then return a non-nil value. If the
20060 context is wrong, just do nothing and return nil.")
20062 (defvar org-ctrl-c-ctrl-c-final-hook nil
20063 "Hook for functions attaching themselves to `C-c C-c'.
20065 This can be used to add additional functionality to the C-c C-c
20066 key which executes context-dependent commands. This hook is run
20067 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20068 before the first test.
20070 Each function will be called with no arguments. The function
20071 must check if the context is appropriate for it to act. If yes,
20072 it should do its thing and then return a non-nil value. If the
20073 context is wrong, just do nothing and return nil.")
20075 (defvar org-tab-first-hook nil
20076 "Hook for functions to attach themselves to TAB.
20077 See `org-ctrl-c-ctrl-c-hook' for more information.
20078 This hook runs as the first action when TAB is pressed, even before
20079 `org-cycle' messes around with the `outline-regexp' to cater for
20080 inline tasks and plain list item folding.
20081 If any function in this hook returns t, any other actions that
20082 would have been caused by TAB (such as table field motion or visibility
20083 cycling) will not occur.")
20085 (defvar org-tab-after-check-for-table-hook nil
20086 "Hook for functions to attach themselves to TAB.
20087 See `org-ctrl-c-ctrl-c-hook' for more information.
20088 This hook runs after it has been established that the cursor is not in a
20089 table, but before checking if the cursor is in a headline or if global cycling
20090 should be done.
20091 If any function in this hook returns t, not other actions like visibility
20092 cycling will be done.")
20094 (defvar org-tab-after-check-for-cycling-hook nil
20095 "Hook for functions to attach themselves to TAB.
20096 See `org-ctrl-c-ctrl-c-hook' for more information.
20097 This hook runs after it has been established that not table field motion and
20098 not visibility should be done because of current context. This is probably
20099 the place where a package like yasnippets can hook in.")
20101 (defvar org-tab-before-tab-emulation-hook nil
20102 "Hook for functions to attach themselves to TAB.
20103 See `org-ctrl-c-ctrl-c-hook' for more information.
20104 This hook runs after every other options for TAB have been exhausted, but
20105 before indentation and \t insertion takes place.")
20107 (defvar org-metaleft-hook nil
20108 "Hook for functions attaching themselves to `M-left'.
20109 See `org-ctrl-c-ctrl-c-hook' for more information.")
20110 (defvar org-metaright-hook nil
20111 "Hook for functions attaching themselves to `M-right'.
20112 See `org-ctrl-c-ctrl-c-hook' for more information.")
20113 (defvar org-metaup-hook nil
20114 "Hook for functions attaching themselves to `M-up'.
20115 See `org-ctrl-c-ctrl-c-hook' for more information.")
20116 (defvar org-metadown-hook nil
20117 "Hook for functions attaching themselves to `M-down'.
20118 See `org-ctrl-c-ctrl-c-hook' for more information.")
20119 (defvar org-shiftmetaleft-hook nil
20120 "Hook for functions attaching themselves to `M-S-left'.
20121 See `org-ctrl-c-ctrl-c-hook' for more information.")
20122 (defvar org-shiftmetaright-hook nil
20123 "Hook for functions attaching themselves to `M-S-right'.
20124 See `org-ctrl-c-ctrl-c-hook' for more information.")
20125 (defvar org-shiftmetaup-hook nil
20126 "Hook for functions attaching themselves to `M-S-up'.
20127 See `org-ctrl-c-ctrl-c-hook' for more information.")
20128 (defvar org-shiftmetadown-hook nil
20129 "Hook for functions attaching themselves to `M-S-down'.
20130 See `org-ctrl-c-ctrl-c-hook' for more information.")
20131 (defvar org-metareturn-hook nil
20132 "Hook for functions attaching themselves to `M-RET'.
20133 See `org-ctrl-c-ctrl-c-hook' for more information.")
20134 (defvar org-shiftup-hook nil
20135 "Hook for functions attaching themselves to `S-up'.
20136 See `org-ctrl-c-ctrl-c-hook' for more information.")
20137 (defvar org-shiftup-final-hook nil
20138 "Hook for functions attaching themselves to `S-up'.
20139 This one runs after all other options except shift-select have been excluded.
20140 See `org-ctrl-c-ctrl-c-hook' for more information.")
20141 (defvar org-shiftdown-hook nil
20142 "Hook for functions attaching themselves to `S-down'.
20143 See `org-ctrl-c-ctrl-c-hook' for more information.")
20144 (defvar org-shiftdown-final-hook nil
20145 "Hook for functions attaching themselves to `S-down'.
20146 This one runs after all other options except shift-select have been excluded.
20147 See `org-ctrl-c-ctrl-c-hook' for more information.")
20148 (defvar org-shiftleft-hook nil
20149 "Hook for functions attaching themselves to `S-left'.
20150 See `org-ctrl-c-ctrl-c-hook' for more information.")
20151 (defvar org-shiftleft-final-hook nil
20152 "Hook for functions attaching themselves to `S-left'.
20153 This one runs after all other options except shift-select have been excluded.
20154 See `org-ctrl-c-ctrl-c-hook' for more information.")
20155 (defvar org-shiftright-hook nil
20156 "Hook for functions attaching themselves to `S-right'.
20157 See `org-ctrl-c-ctrl-c-hook' for more information.")
20158 (defvar org-shiftright-final-hook nil
20159 "Hook for functions attaching themselves to `S-right'.
20160 This one runs after all other options except shift-select have been excluded.
20161 See `org-ctrl-c-ctrl-c-hook' for more information.")
20163 (defun org-modifier-cursor-error ()
20164 "Throw an error, a modified cursor command was applied in wrong context."
20165 (user-error "This command is active in special context like tables, headlines or items"))
20167 (defun org-shiftselect-error ()
20168 "Throw an error because Shift-Cursor command was applied in wrong context."
20169 (if (and (boundp 'shift-select-mode) shift-select-mode)
20170 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20171 (user-error "This command works only in special context like headlines or timestamps")))
20173 (defun org-call-for-shift-select (cmd)
20174 (let ((this-command-keys-shift-translated t))
20175 (call-interactively cmd)))
20177 (defun org-shifttab (&optional arg)
20178 "Global visibility cycling or move to previous table field.
20179 Call `org-table-previous-field' within a table.
20180 When ARG is nil, cycle globally through visibility states.
20181 When ARG is a numeric prefix, show contents of this level."
20182 (interactive "P")
20183 (cond
20184 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20185 ((integerp arg)
20186 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20187 (message "Content view to level: %d" arg)
20188 (org-content (prefix-numeric-value arg2))
20189 (org-cycle-show-empty-lines t)
20190 (setq org-cycle-global-status 'overview)))
20191 (t (call-interactively 'org-global-cycle))))
20193 (defun org-shiftmetaleft ()
20194 "Promote subtree or delete table column.
20195 Calls `org-promote-subtree', `org-outdent-item-tree', or
20196 `org-table-delete-column', depending on context. See the
20197 individual commands for more information."
20198 (interactive)
20199 (cond
20200 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20201 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20202 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20203 ((if (not (org-region-active-p)) (org-at-item-p)
20204 (save-excursion (goto-char (region-beginning))
20205 (org-at-item-p)))
20206 (call-interactively 'org-outdent-item-tree))
20207 (t (org-modifier-cursor-error))))
20209 (defun org-shiftmetaright ()
20210 "Demote subtree or insert table column.
20211 Calls `org-demote-subtree', `org-indent-item-tree', or
20212 `org-table-insert-column', depending on context. See the
20213 individual commands for more information."
20214 (interactive)
20215 (cond
20216 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20217 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20218 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20219 ((if (not (org-region-active-p)) (org-at-item-p)
20220 (save-excursion (goto-char (region-beginning))
20221 (org-at-item-p)))
20222 (call-interactively 'org-indent-item-tree))
20223 (t (org-modifier-cursor-error))))
20225 (defun org-shiftmetaup (&optional arg)
20226 "Drag the line at point up.
20227 In a table, kill the current row.
20228 On a clock timestamp, update the value of the timestamp like `S-<up>'
20229 but also adjust the previous clocked item in the clock history.
20230 Everywhere else, drag the line at point up."
20231 (interactive "P")
20232 (cond
20233 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20234 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20235 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20236 (call-interactively 'org-timestamp-up)))
20237 (t (call-interactively 'org-drag-line-backward))))
20239 (defun org-shiftmetadown (&optional arg)
20240 "Drag the line at point down.
20241 In a table, insert an empty row at the current line.
20242 On a clock timestamp, update the value of the timestamp like `S-<down>'
20243 but also adjust the previous clocked item in the clock history.
20244 Everywhere else, drag the line at point down."
20245 (interactive "P")
20246 (cond
20247 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20248 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20249 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20250 (call-interactively 'org-timestamp-down)))
20251 (t (call-interactively 'org-drag-line-forward))))
20253 (defsubst org-hidden-tree-error ()
20254 (user-error
20255 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20257 (defun org-metaleft (&optional arg)
20258 "Promote heading or move table column to left.
20259 Calls `org-do-promote' or `org-table-move-column', depending on context.
20260 With no specific context, calls the Emacs default `backward-word'.
20261 See the individual commands for more information."
20262 (interactive "P")
20263 (cond
20264 ((run-hook-with-args-until-success 'org-metaleft-hook))
20265 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20266 ((org-with-limited-levels
20267 (or (org-at-heading-p)
20268 (and (org-region-active-p)
20269 (save-excursion
20270 (goto-char (region-beginning))
20271 (org-at-heading-p)))))
20272 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20273 (call-interactively 'org-do-promote))
20274 ;; At an inline task.
20275 ((org-at-heading-p)
20276 (call-interactively 'org-inlinetask-promote))
20277 ((or (org-at-item-p)
20278 (and (org-region-active-p)
20279 (save-excursion
20280 (goto-char (region-beginning))
20281 (org-at-item-p))))
20282 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20283 (call-interactively 'org-outdent-item))
20284 (t (call-interactively 'backward-word))))
20286 (defun org-metaright (&optional arg)
20287 "Demote a subtree, a list item or move table column to right.
20288 In front of a drawer or a block keyword, indent it correctly.
20289 With no specific context, calls the Emacs default `forward-word'.
20290 See the individual commands for more information."
20291 (interactive "P")
20292 (cond
20293 ((run-hook-with-args-until-success 'org-metaright-hook))
20294 ((org-at-table-p) (call-interactively 'org-table-move-column))
20295 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20296 ((org-at-block-p) (call-interactively 'org-indent-block))
20297 ((org-with-limited-levels
20298 (or (org-at-heading-p)
20299 (and (org-region-active-p)
20300 (save-excursion
20301 (goto-char (region-beginning))
20302 (org-at-heading-p)))))
20303 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20304 (call-interactively 'org-do-demote))
20305 ;; At an inline task.
20306 ((org-at-heading-p)
20307 (call-interactively 'org-inlinetask-demote))
20308 ((or (org-at-item-p)
20309 (and (org-region-active-p)
20310 (save-excursion
20311 (goto-char (region-beginning))
20312 (org-at-item-p))))
20313 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20314 (call-interactively 'org-indent-item))
20315 (t (call-interactively 'forward-word))))
20317 (defun org-check-for-hidden (what)
20318 "Check if there are hidden headlines/items in the current visual line.
20319 WHAT can be either `headlines' or `items'. If the current line is
20320 an outline or item heading and it has a folded subtree below it,
20321 this function returns t, nil otherwise."
20322 (let ((re (cond
20323 ((eq what 'headlines) org-outline-regexp-bol)
20324 ((eq what 'items) (org-item-beginning-re))
20325 (t (error "This should not happen"))))
20326 beg end)
20327 (save-excursion
20328 (catch 'exit
20329 (unless (org-region-active-p)
20330 (setq beg (point-at-bol))
20331 (beginning-of-line 2)
20332 (while (and (not (eobp)) ;; this is like `next-line'
20333 (get-char-property (1- (point)) 'invisible))
20334 (beginning-of-line 2))
20335 (setq end (point))
20336 (goto-char beg)
20337 (goto-char (point-at-eol))
20338 (setq end (max end (point)))
20339 (while (re-search-forward re end t)
20340 (if (get-char-property (match-beginning 0) 'invisible)
20341 (throw 'exit t))))
20342 nil))))
20344 (defun org-metaup (&optional arg)
20345 "Move subtree up or move table row up.
20346 Calls `org-move-subtree-up' or `org-table-move-row' or
20347 `org-move-item-up', depending on context. See the individual commands
20348 for more information."
20349 (interactive "P")
20350 (cond
20351 ((run-hook-with-args-until-success 'org-metaup-hook))
20352 ((org-region-active-p)
20353 (let* ((a (min (region-beginning) (region-end)))
20354 (b (1- (max (region-beginning) (region-end))))
20355 (c (save-excursion (goto-char a)
20356 (move-beginning-of-line 0)))
20357 (d (save-excursion (goto-char a)
20358 (move-end-of-line 0) (point))))
20359 (transpose-regions a b c d)
20360 (goto-char c)))
20361 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20362 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20363 ((org-at-item-p) (call-interactively 'org-move-item-up))
20364 (t (org-drag-element-backward))))
20366 (defun org-metadown (&optional arg)
20367 "Move subtree down or move table row down.
20368 Calls `org-move-subtree-down' or `org-table-move-row' or
20369 `org-move-item-down', depending on context. See the individual
20370 commands for more information."
20371 (interactive "P")
20372 (cond
20373 ((run-hook-with-args-until-success 'org-metadown-hook))
20374 ((org-region-active-p)
20375 (let* ((a (min (region-beginning) (region-end)))
20376 (b (max (region-beginning) (region-end)))
20377 (c (save-excursion (goto-char b)
20378 (move-beginning-of-line 1)))
20379 (d (save-excursion (goto-char b)
20380 (move-end-of-line 1) (1+ (point)))))
20381 (transpose-regions a b c d)
20382 (goto-char d)))
20383 ((org-at-table-p) (call-interactively 'org-table-move-row))
20384 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20385 ((org-at-item-p) (call-interactively 'org-move-item-down))
20386 (t (org-drag-element-forward))))
20388 (defun org-shiftup (&optional arg)
20389 "Increase item in timestamp or increase priority of current headline.
20390 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20391 depending on context. See the individual commands for more information."
20392 (interactive "P")
20393 (cond
20394 ((run-hook-with-args-until-success 'org-shiftup-hook))
20395 ((and org-support-shift-select (org-region-active-p))
20396 (org-call-for-shift-select 'previous-line))
20397 ((org-at-timestamp-p t)
20398 (call-interactively (if org-edit-timestamp-down-means-later
20399 'org-timestamp-down 'org-timestamp-up)))
20400 ((and (not (eq org-support-shift-select 'always))
20401 org-enable-priority-commands
20402 (org-at-heading-p))
20403 (call-interactively 'org-priority-up))
20404 ((and (not org-support-shift-select) (org-at-item-p))
20405 (call-interactively 'org-previous-item))
20406 ((org-clocktable-try-shift 'up arg))
20407 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20408 (org-support-shift-select
20409 (org-call-for-shift-select 'previous-line))
20410 (t (org-shiftselect-error))))
20412 (defun org-shiftdown (&optional arg)
20413 "Decrease item in timestamp or decrease priority of current headline.
20414 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20415 depending on context. See the individual commands for more information."
20416 (interactive "P")
20417 (cond
20418 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20419 ((and org-support-shift-select (org-region-active-p))
20420 (org-call-for-shift-select 'next-line))
20421 ((org-at-timestamp-p t)
20422 (call-interactively (if org-edit-timestamp-down-means-later
20423 'org-timestamp-up 'org-timestamp-down)))
20424 ((and (not (eq org-support-shift-select 'always))
20425 org-enable-priority-commands
20426 (org-at-heading-p))
20427 (call-interactively 'org-priority-down))
20428 ((and (not org-support-shift-select) (org-at-item-p))
20429 (call-interactively 'org-next-item))
20430 ((org-clocktable-try-shift 'down arg))
20431 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20432 (org-support-shift-select
20433 (org-call-for-shift-select 'next-line))
20434 (t (org-shiftselect-error))))
20436 (defun org-shiftright (&optional arg)
20437 "Cycle the thing at point or in the current line, depending on context.
20438 Depending on context, this does one of the following:
20440 - switch a timestamp at point one day into the future
20441 - on a headline, switch to the next TODO keyword.
20442 - on an item, switch entire list to the next bullet type
20443 - on a property line, switch to the next allowed value
20444 - on a clocktable definition line, move time block into the future"
20445 (interactive "P")
20446 (cond
20447 ((run-hook-with-args-until-success 'org-shiftright-hook))
20448 ((and org-support-shift-select (org-region-active-p))
20449 (org-call-for-shift-select 'forward-char))
20450 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20451 ((and (not (eq org-support-shift-select 'always))
20452 (org-at-heading-p))
20453 (let ((org-inhibit-logging
20454 (not org-treat-S-cursor-todo-selection-as-state-change))
20455 (org-inhibit-blocking
20456 (not org-treat-S-cursor-todo-selection-as-state-change)))
20457 (org-call-with-arg 'org-todo 'right)))
20458 ((or (and org-support-shift-select
20459 (not (eq org-support-shift-select 'always))
20460 (org-at-item-bullet-p))
20461 (and (not org-support-shift-select) (org-at-item-p)))
20462 (org-call-with-arg 'org-cycle-list-bullet nil))
20463 ((and (not (eq org-support-shift-select 'always))
20464 (org-at-property-p))
20465 (call-interactively 'org-property-next-allowed-value))
20466 ((org-clocktable-try-shift 'right arg))
20467 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20468 (org-support-shift-select
20469 (org-call-for-shift-select 'forward-char))
20470 (t (org-shiftselect-error))))
20472 (defun org-shiftleft (&optional arg)
20473 "Cycle the thing at point or in the current line, depending on context.
20474 Depending on context, this does one of the following:
20476 - switch a timestamp at point one day into the past
20477 - on a headline, switch to the previous TODO keyword.
20478 - on an item, switch entire list to the previous bullet type
20479 - on a property line, switch to the previous allowed value
20480 - on a clocktable definition line, move time block into the past"
20481 (interactive "P")
20482 (cond
20483 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20484 ((and org-support-shift-select (org-region-active-p))
20485 (org-call-for-shift-select 'backward-char))
20486 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20487 ((and (not (eq org-support-shift-select 'always))
20488 (org-at-heading-p))
20489 (let ((org-inhibit-logging
20490 (not org-treat-S-cursor-todo-selection-as-state-change))
20491 (org-inhibit-blocking
20492 (not org-treat-S-cursor-todo-selection-as-state-change)))
20493 (org-call-with-arg 'org-todo 'left)))
20494 ((or (and org-support-shift-select
20495 (not (eq org-support-shift-select 'always))
20496 (org-at-item-bullet-p))
20497 (and (not org-support-shift-select) (org-at-item-p)))
20498 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20499 ((and (not (eq org-support-shift-select 'always))
20500 (org-at-property-p))
20501 (call-interactively 'org-property-previous-allowed-value))
20502 ((org-clocktable-try-shift 'left arg))
20503 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20504 (org-support-shift-select
20505 (org-call-for-shift-select 'backward-char))
20506 (t (org-shiftselect-error))))
20508 (defun org-shiftcontrolright ()
20509 "Switch to next TODO set."
20510 (interactive)
20511 (cond
20512 ((and org-support-shift-select (org-region-active-p))
20513 (org-call-for-shift-select 'forward-word))
20514 ((and (not (eq org-support-shift-select 'always))
20515 (org-at-heading-p))
20516 (org-call-with-arg 'org-todo 'nextset))
20517 (org-support-shift-select
20518 (org-call-for-shift-select 'forward-word))
20519 (t (org-shiftselect-error))))
20521 (defun org-shiftcontrolleft ()
20522 "Switch to previous TODO set."
20523 (interactive)
20524 (cond
20525 ((and org-support-shift-select (org-region-active-p))
20526 (org-call-for-shift-select 'backward-word))
20527 ((and (not (eq org-support-shift-select 'always))
20528 (org-at-heading-p))
20529 (org-call-with-arg 'org-todo 'previousset))
20530 (org-support-shift-select
20531 (org-call-for-shift-select 'backward-word))
20532 (t (org-shiftselect-error))))
20534 (defun org-shiftcontrolup (&optional n)
20535 "Change timestamps synchronously up in CLOCK log lines.
20536 Optional argument N tells to change by that many units."
20537 (interactive "P")
20538 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20539 (let (org-support-shift-select)
20540 (org-clock-timestamps-up n))
20541 (user-error "Not at a clock log")))
20543 (defun org-shiftcontroldown (&optional n)
20544 "Change timestamps synchronously down in CLOCK log lines.
20545 Optional argument N tells to change by that many units."
20546 (interactive "P")
20547 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20548 (let (org-support-shift-select)
20549 (org-clock-timestamps-down n))
20550 (user-error "Not at a clock log")))
20552 (defun org-increase-number-at-point (&optional inc)
20553 "Increment the number at point.
20554 With an optional prefix numeric argument INC, increment using
20555 this numeric value."
20556 (interactive "p")
20557 (if (not (number-at-point))
20558 (user-error "Not on a number")
20559 (unless inc (setq inc 1))
20560 (let ((pos (point))
20561 (beg (skip-chars-backward "-+^/*0-9eE."))
20562 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20563 (setq nap (buffer-substring-no-properties
20564 (+ pos beg) (+ pos beg end)))
20565 (delete-region (+ pos beg) (+ pos beg end))
20566 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20567 (when (org-at-table-p)
20568 (org-table-align)
20569 (org-table-end-of-field 1))))
20571 (defun org-decrease-number-at-point (&optional inc)
20572 "Decrement the number at point.
20573 With an optional prefix numeric argument INC, decrement using
20574 this numeric value."
20575 (interactive "p")
20576 (org-increase-number-at-point (- inc)))
20578 (defun org-ctrl-c-ret ()
20579 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20580 (interactive)
20581 (cond
20582 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20583 (t (call-interactively 'org-insert-heading))))
20585 (defun org-find-visible ()
20586 (let ((s (point)))
20587 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20588 (get-char-property s 'invisible)))
20590 (defun org-find-invisible ()
20591 (let ((s (point)))
20592 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20593 (not (get-char-property s 'invisible))))
20596 (defun org-copy-visible (beg end)
20597 "Copy the visible parts of the region."
20598 (interactive "r")
20599 (let (snippets s)
20600 (save-excursion
20601 (save-restriction
20602 (narrow-to-region beg end)
20603 (setq s (goto-char (point-min)))
20604 (while (not (= (point) (point-max)))
20605 (goto-char (org-find-invisible))
20606 (push (buffer-substring s (point)) snippets)
20607 (setq s (goto-char (org-find-visible))))))
20608 (kill-new (apply 'concat (nreverse snippets)))))
20610 (defun org-copy-special ()
20611 "Copy region in table or copy current subtree.
20612 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20613 See the individual commands for more information."
20614 (interactive)
20615 (call-interactively
20616 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20618 (defun org-cut-special ()
20619 "Cut region in table or cut current subtree.
20620 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20621 See the individual commands for more information."
20622 (interactive)
20623 (call-interactively
20624 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20626 (defun org-paste-special (arg)
20627 "Paste rectangular region into table, or past subtree relative to level.
20628 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20629 See the individual commands for more information."
20630 (interactive "P")
20631 (if (org-at-table-p)
20632 (org-table-paste-rectangle)
20633 (org-paste-subtree arg)))
20635 (defsubst org-in-fixed-width-region-p ()
20636 "Is point in a fixed-width region?"
20637 (save-match-data
20638 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20640 (defun org-edit-special (&optional arg)
20641 "Call a special editor for the element at point.
20642 When at a table, call the formula editor with `org-table-edit-formulas'.
20643 When in a source code block, call `org-edit-src-code'.
20644 When in a fixed-width region, call `org-edit-fixed-width-region'.
20645 When in an export block, call `org-edit-export-block'.
20646 When at an #+INCLUDE keyword, visit the included file.
20647 On a link, call `ffap' to visit the link at point.
20648 Otherwise, return a user error."
20649 (interactive "P")
20650 (let ((element (org-element-at-point)))
20651 (assert (not buffer-read-only) nil
20652 "Buffer is read-only: %s" (buffer-name))
20653 (case (org-element-type element)
20654 (src-block
20655 (if (not arg) (org-edit-src-code)
20656 (let* ((info (org-babel-get-src-block-info))
20657 (lang (nth 0 info))
20658 (params (nth 2 info))
20659 (session (cdr (assq :session params))))
20660 (if (not session) (org-edit-src-code)
20661 ;; At a src-block with a session and function called with
20662 ;; an ARG: switch to the buffer related to the inferior
20663 ;; process.
20664 (switch-to-buffer
20665 (funcall (intern (concat "org-babel-prep-session:" lang))
20666 session params))))))
20667 (keyword
20668 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20669 (org-open-link-from-string
20670 (format "[[%s]]"
20671 (expand-file-name
20672 (let ((value (org-element-property :value element)))
20673 (cond ((not (org-string-nw-p value))
20674 (user-error "No file to edit"))
20675 ((string-match "\\`\"\\(.*?\\)\"" value)
20676 (match-string 1 value))
20677 ((string-match "\\`[^ \t\"]\\S-*" value)
20678 (match-string 0 value))
20679 (t (user-error "No valid file specified")))))))
20680 (user-error "No special environment to edit here")))
20681 (table
20682 (if (eq (org-element-property :type element) 'table.el)
20683 (org-edit-table.el)
20684 (call-interactively 'org-table-edit-formulas)))
20685 ;; Only Org tables contain `table-row' type elements.
20686 (table-row (call-interactively 'org-table-edit-formulas))
20687 ((example-block src-block) (org-edit-src-code))
20688 (export-block (org-edit-export-block))
20689 (fixed-width (org-edit-fixed-width-region))
20690 (otherwise
20691 ;; No notable element at point. Though, we may be at a link,
20692 ;; which is an object. Thus, scan deeper.
20693 (if (eq (org-element-type (org-element-context element)) 'link)
20694 (call-interactively 'ffap)
20695 (user-error "No special environment to edit here"))))))
20697 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20698 (defun org-ctrl-c-ctrl-c (&optional arg)
20699 "Set tags in headline, or update according to changed information at point.
20701 This command does many different things, depending on context:
20703 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20704 this is what we do.
20706 - If the cursor is on a statistics cookie, update it.
20708 - If the cursor is in a headline, prompt for tags and insert them
20709 into the current line, aligned to `org-tags-column'. When called
20710 with prefix arg, realign all tags in the current buffer.
20712 - If the cursor is in one of the special #+KEYWORD lines, this
20713 triggers scanning the buffer for these lines and updating the
20714 information.
20716 - If the cursor is inside a table, realign the table. This command
20717 works even if the automatic table editor has been turned off.
20719 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20720 the entire table.
20722 - If the cursor is at a footnote reference or definition, jump to
20723 the corresponding definition or references, respectively.
20725 - If the cursor is a the beginning of a dynamic block, update it.
20727 - If the current buffer is a capture buffer, close note and file it.
20729 - If the cursor is on a <<<target>>>, update radio targets and
20730 corresponding links in this buffer.
20732 - If the cursor is on a numbered item in a plain list, renumber the
20733 ordered list.
20735 - If the cursor is on a checkbox, toggle it.
20737 - If the cursor is on a code block, evaluate it. The variable
20738 `org-confirm-babel-evaluate' can be used to control prompting
20739 before code block evaluation, by default every code block
20740 evaluation requires confirmation. Code block evaluation can be
20741 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20742 (interactive "P")
20743 (cond
20744 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20745 org-occur-highlights)
20746 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20747 (org-remove-occur-highlights)
20748 (message "Temporary highlights/overlays removed from current buffer"))
20749 ((and (local-variable-p 'org-finish-function (current-buffer))
20750 (fboundp org-finish-function))
20751 (funcall org-finish-function))
20752 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20754 (let* ((context (org-element-context)) (type (org-element-type context)))
20755 ;; Test if point is within a blank line.
20756 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20757 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20758 (user-error "C-c C-c can do nothing useful at this location"))
20759 (case type
20760 ;; When at a link, act according to the parent instead.
20761 (link (setq context (org-element-property :parent context))
20762 (setq type (org-element-type context)))
20763 ;; Unsupported object types: refer to the first supported
20764 ;; element or object containing it.
20765 ((bold code entity export-snippet inline-babel-call inline-src-block
20766 italic latex-fragment line-break macro strike-through subscript
20767 superscript underline verbatim)
20768 (while (and (setq context (org-element-property :parent context))
20769 (not (memq (setq type (org-element-type context))
20770 '(radio-target paragraph verse-block
20771 table-cell)))))))
20772 ;; For convenience: at the first line of a paragraph on the
20773 ;; same line as an item, apply function on that item instead.
20774 (when (eq type 'paragraph)
20775 (let ((parent (org-element-property :parent context)))
20776 (when (and (eq (org-element-type parent) 'item)
20777 (= (point-at-bol) (org-element-property :begin parent)))
20778 (setq context parent type 'item))))
20779 ;; Act according to type of element or object at point.
20780 (case type
20781 (clock (org-clock-update-time-maybe))
20782 (dynamic-block
20783 (save-excursion
20784 (goto-char (org-element-property :post-affiliated context))
20785 (org-update-dblock)))
20786 (footnote-definition
20787 (goto-char (org-element-property :post-affiliated context))
20788 (call-interactively 'org-footnote-action))
20789 (footnote-reference (call-interactively 'org-footnote-action))
20790 ((headline inlinetask)
20791 (save-excursion (goto-char (org-element-property :begin context))
20792 (call-interactively 'org-set-tags)))
20793 (item
20794 ;; At an item: a double C-u set checkbox to "[-]"
20795 ;; unconditionally, whereas a single one will toggle its
20796 ;; presence. Without an universal argument, if the item
20797 ;; has a checkbox, toggle it. Otherwise repair the list.
20798 (let* ((box (org-element-property :checkbox context))
20799 (struct (org-element-property :structure context))
20800 (old-struct (copy-tree struct))
20801 (parents (org-list-parents-alist struct))
20802 (prevs (org-list-prevs-alist struct))
20803 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20804 (org-list-set-checkbox
20805 (org-element-property :begin context) struct
20806 (cond ((equal arg '(16)) "[-]")
20807 ((and (not box) (equal arg '(4))) "[ ]")
20808 ((or (not box) (equal arg '(4))) nil)
20809 ((eq box 'on) "[ ]")
20810 (t "[X]")))
20811 ;; Mimic `org-list-write-struct' but with grabbing
20812 ;; a return value from `org-list-struct-fix-box'.
20813 (org-list-struct-fix-ind struct parents 2)
20814 (org-list-struct-fix-item-end struct)
20815 (org-list-struct-fix-bul struct prevs)
20816 (org-list-struct-fix-ind struct parents)
20817 (let ((block-item
20818 (org-list-struct-fix-box struct parents prevs orderedp)))
20819 (if (and box (equal struct old-struct))
20820 (if (equal arg '(16))
20821 (message "Checkboxes already reset")
20822 (user-error "Cannot toggle this checkbox: %s"
20823 (if (eq box 'on)
20824 "all subitems checked"
20825 "unchecked subitems")))
20826 (org-list-struct-apply-struct struct old-struct)
20827 (org-update-checkbox-count-maybe))
20828 (when block-item
20829 (message "Checkboxes were removed due to empty box at line %d"
20830 (org-current-line block-item))))))
20831 (keyword
20832 (let ((org-inhibit-startup-visibility-stuff t)
20833 (org-startup-align-all-tables nil))
20834 (when (boundp 'org-table-coordinate-overlays)
20835 (mapc 'delete-overlay org-table-coordinate-overlays)
20836 (setq org-table-coordinate-overlays nil))
20837 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20838 (message "Local setup has been refreshed"))
20839 (plain-list
20840 ;; At a plain list, with a double C-u argument, set
20841 ;; checkboxes of each item to "[-]", whereas a single one
20842 ;; will toggle their presence according to the state of the
20843 ;; first item in the list. Without an argument, repair the
20844 ;; list.
20845 (let* ((begin (org-element-property :contents-begin context))
20846 (beginm (move-marker (make-marker) begin))
20847 (struct (org-element-property :structure context))
20848 (old-struct (copy-tree struct))
20849 (first-box (save-excursion
20850 (goto-char begin)
20851 (looking-at org-list-full-item-re)
20852 (match-string-no-properties 3)))
20853 (new-box (cond ((equal arg '(16)) "[-]")
20854 ((equal arg '(4)) (unless first-box "[ ]"))
20855 ((equal first-box "[X]") "[ ]")
20856 (t "[X]"))))
20857 (cond
20858 (arg
20859 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20860 (org-list-get-all-items
20861 begin struct (org-list-prevs-alist struct))))
20862 ((and first-box (eq (point) begin))
20863 ;; For convenience, when point is at bol on the first
20864 ;; item of the list and no argument is provided, simply
20865 ;; toggle checkbox of that item, if any.
20866 (org-list-set-checkbox begin struct new-box)))
20867 (org-list-write-struct
20868 struct (org-list-parents-alist struct) old-struct)
20869 (org-update-checkbox-count-maybe)
20870 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20871 ((property-drawer node-property)
20872 (call-interactively 'org-property-action))
20873 ((radio-target target)
20874 (call-interactively 'org-update-radio-target-regexp))
20875 (statistics-cookie
20876 (call-interactively 'org-update-statistics-cookies))
20877 ((table table-cell table-row)
20878 ;; At a table, recalculate every field and align it. Also
20879 ;; send the table if necessary. If the table has
20880 ;; a `table.el' type, just give up. At a table row or
20881 ;; cell, maybe recalculate line but always align table.
20882 (if (eq (org-element-property :type context) 'table.el)
20883 (message "Use C-c ' to edit table.el tables")
20884 (let ((org-enable-table-editor t))
20885 (if (or (eq type 'table)
20886 ;; Check if point is at a TBLFM line.
20887 (and (eq type 'table-row)
20888 (= (point) (org-element-property :end context))))
20889 (save-excursion
20890 (if (org-at-TBLFM-p)
20891 (progn (require 'org-table)
20892 (org-table-calc-current-TBLFM))
20893 (goto-char (org-element-property :contents-begin context))
20894 (org-call-with-arg 'org-table-recalculate (or arg t))
20895 (orgtbl-send-table 'maybe)))
20896 (org-table-maybe-eval-formula)
20897 (cond (arg (call-interactively 'org-table-recalculate))
20898 ((org-table-maybe-recalculate-line))
20899 (t (org-table-align)))))))
20900 (timestamp (org-timestamp-change 0 'day))
20901 (otherwise
20902 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20903 (user-error
20904 "C-c C-c can do nothing useful at this location")))))))))
20906 (defun org-mode-restart ()
20907 (interactive)
20908 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20909 (funcall major-mode)
20910 (hack-local-variables)
20911 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20912 (org-indent-mode -1)))
20913 (message "%s restarted" major-mode))
20915 (defun org-kill-note-or-show-branches ()
20916 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20917 (interactive)
20918 (if (not org-finish-function)
20919 (progn
20920 (hide-subtree)
20921 (call-interactively 'show-branches))
20922 (let ((org-note-abort t))
20923 (funcall org-finish-function))))
20925 (defun org-open-line (n)
20926 "Insert a new row in tables, call `open-line' elsewhere.
20927 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20928 (interactive "*p")
20929 (cond
20930 ((not org-special-ctrl-o)
20931 (open-line n))
20932 ((org-at-table-p)
20933 (org-table-insert-row))
20935 (open-line n))))
20937 (defun org-return (&optional indent)
20938 "Goto next table row or insert a newline.
20940 Calls `org-table-next-row' or `newline', depending on context.
20942 When optional INDENT argument is non-nil, call
20943 `newline-and-indent' instead of `newline'.
20945 When `org-return-follows-link' is non-nil and point is on
20946 a timestamp or a link, call `org-open-at-point'. However, it
20947 will not happen if point is in a table or on a \"dead\"
20948 object (e.g., within a comment). In these case, you need to use
20949 `org-open-at-point' directly."
20950 (interactive)
20951 (if (and (save-excursion
20952 (beginning-of-line)
20953 (looking-at org-todo-line-regexp))
20954 (match-beginning 3)
20955 (>= (point) (match-beginning 3)))
20956 ;; Point is on headline tags. Do not break them: add a newline
20957 ;; after the headline instead.
20958 (progn (org-show-entry)
20959 (end-of-line)
20960 (if indent (newline-and-indent) (newline)))
20961 (let* ((context (if org-return-follows-link (org-element-context)
20962 (org-element-at-point)))
20963 (type (org-element-type context)))
20964 (cond
20965 ;; In a table, call `org-table-next-row'.
20966 ((or (and (eq type 'table)
20967 (>= (point) (org-element-property :contents-begin context))
20968 (< (point) (org-element-property :contents-end context)))
20969 (org-element-lineage context '(table-row table-cell) t))
20970 (org-table-justify-field-maybe)
20971 (call-interactively #'org-table-next-row))
20972 ;; On a link or a timestamp but not on white spaces after it,
20973 ;; call `org-open-line' if `org-return-follows-link' allows it.
20974 ((and org-return-follows-link
20975 (memq type '(link timestamp))
20976 (< (point)
20977 (save-excursion (goto-char (org-element-property :end context))
20978 (skip-chars-backward " \t")
20979 (point))))
20980 (call-interactively #'org-open-at-point))
20981 ;; In a list, make sure indenting keeps trailing text within.
20982 ((and indent
20983 (not (eolp))
20984 (org-element-lineage context '(item plain-list) t))
20985 (let ((trailing-data
20986 (delete-and-extract-region (point) (line-end-position))))
20987 (newline-and-indent)
20988 (save-excursion (insert trailing-data))))
20989 (t (if indent (newline-and-indent) (newline)))))))
20991 (defun org-return-indent ()
20992 "Goto next table row or insert a newline and indent.
20993 Calls `org-table-next-row' or `newline-and-indent', depending on
20994 context. See the individual commands for more information."
20995 (interactive)
20996 (org-return t))
20998 (defun org-ctrl-c-star ()
20999 "Compute table, or change heading status of lines.
21000 Calls `org-table-recalculate' or `org-toggle-heading',
21001 depending on context."
21002 (interactive)
21003 (cond
21004 ((org-at-table-p)
21005 (call-interactively 'org-table-recalculate))
21007 ;; Convert all lines in region to list items
21008 (call-interactively 'org-toggle-heading))))
21010 (defun org-ctrl-c-minus ()
21011 "Insert separator line in table or modify bullet status of line.
21012 Also turns a plain line or a region of lines into list items.
21013 Calls `org-table-insert-hline', `org-toggle-item', or
21014 `org-cycle-list-bullet', depending on context."
21015 (interactive)
21016 (cond
21017 ((org-at-table-p)
21018 (call-interactively 'org-table-insert-hline))
21019 ((org-region-active-p)
21020 (call-interactively 'org-toggle-item))
21021 ((org-in-item-p)
21022 (call-interactively 'org-cycle-list-bullet))
21024 (call-interactively 'org-toggle-item))))
21026 (defun org-toggle-item (arg)
21027 "Convert headings or normal lines to items, items to normal lines.
21028 If there is no active region, only the current line is considered.
21030 If the first non blank line in the region is a headline, convert
21031 all headlines to items, shifting text accordingly.
21033 If it is an item, convert all items to normal lines.
21035 If it is normal text, change region into a list of items.
21036 With a prefix argument ARG, change the region in a single item."
21037 (interactive "P")
21038 (let ((shift-text
21039 (function
21040 ;; Shift text in current section to IND, from point to END.
21041 ;; The function leaves point to END line.
21042 (lambda (ind end)
21043 (let ((min-i 1000) (end (copy-marker end)))
21044 ;; First determine the minimum indentation (MIN-I) of
21045 ;; the text.
21046 (save-excursion
21047 (catch 'exit
21048 (while (< (point) end)
21049 (let ((i (org-get-indentation)))
21050 (cond
21051 ;; Skip blank lines and inline tasks.
21052 ((looking-at "^[ \t]*$"))
21053 ((looking-at org-outline-regexp-bol))
21054 ;; We can't find less than 0 indentation.
21055 ((zerop i) (throw 'exit (setq min-i 0)))
21056 ((< i min-i) (setq min-i i))))
21057 (forward-line))))
21058 ;; Then indent each line so that a line indented to
21059 ;; MIN-I becomes indented to IND. Ignore blank lines
21060 ;; and inline tasks in the process.
21061 (let ((delta (- ind min-i)))
21062 (while (< (point) end)
21063 (unless (or (looking-at "^[ \t]*$")
21064 (looking-at org-outline-regexp-bol))
21065 (org-indent-line-to (+ (org-get-indentation) delta)))
21066 (forward-line)))))))
21067 (skip-blanks
21068 (function
21069 ;; Return beginning of first non-blank line, starting from
21070 ;; line at POS.
21071 (lambda (pos)
21072 (save-excursion
21073 (goto-char pos)
21074 (skip-chars-forward " \r\t\n")
21075 (point-at-bol)))))
21076 beg end)
21077 ;; Determine boundaries of changes.
21078 (if (org-region-active-p)
21079 (setq beg (funcall skip-blanks (region-beginning))
21080 end (copy-marker (region-end)))
21081 (setq beg (funcall skip-blanks (point-at-bol))
21082 end (copy-marker (point-at-eol))))
21083 ;; Depending on the starting line, choose an action on the text
21084 ;; between BEG and END.
21085 (org-with-limited-levels
21086 (save-excursion
21087 (goto-char beg)
21088 (cond
21089 ;; Case 1. Start at an item: de-itemize. Note that it only
21090 ;; happens when a region is active: `org-ctrl-c-minus'
21091 ;; would call `org-cycle-list-bullet' otherwise.
21092 ((org-at-item-p)
21093 (while (< (point) end)
21094 (when (org-at-item-p)
21095 (skip-chars-forward " \t")
21096 (delete-region (point) (match-end 0)))
21097 (forward-line)))
21098 ;; Case 2. Start at an heading: convert to items.
21099 ((org-at-heading-p)
21100 (let* ((bul (org-list-bullet-string "-"))
21101 (bul-len (length bul))
21102 (done (org-entry-is-done-p))
21103 (todo (org-entry-is-todo-p))
21104 ;; Indentation of the first heading. It should be
21105 ;; relative to the indentation of its parent, if any.
21106 (start-ind (save-excursion
21107 (cond
21108 ((not org-adapt-indentation) 0)
21109 ((not (outline-previous-heading)) 0)
21110 (t (length (match-string 0))))))
21111 ;; Level of first heading. Further headings will be
21112 ;; compared to it to determine hierarchy in the list.
21113 (ref-level (org-reduced-level (org-outline-level))))
21114 (when (or done todo) (org-todo ""))
21115 (while (< (point) end)
21116 (let* ((level (org-reduced-level (org-outline-level)))
21117 (delta (max 0 (- level ref-level))))
21118 ;; If current headline is less indented than the first
21119 ;; one, set it as reference, in order to preserve
21120 ;; subtrees.
21121 (when (< level ref-level) (setq ref-level level))
21122 (replace-match bul t t)
21123 (org-indent-line-to (+ start-ind (* delta bul-len)))
21124 (when (or done todo)
21125 (let* ((struct (org-list-struct))
21126 (old (copy-tree struct)))
21127 (org-list-set-checkbox (line-beginning-position)
21128 struct
21129 (if done "[X]" "[ ]"))
21130 (org-list-write-struct struct
21131 (org-list-parents-alist struct)
21132 old)))
21133 ;; Ensure all text down to END (or SECTION-END) belongs
21134 ;; to the newly created item.
21135 (let ((section-end (save-excursion
21136 (or (outline-next-heading) (point)))))
21137 (forward-line)
21138 (funcall shift-text
21139 (+ start-ind (* (1+ delta) bul-len))
21140 (min end section-end)))))))
21141 ;; Case 3. Normal line with ARG: make the first line of region
21142 ;; an item, and shift indentation of others lines to
21143 ;; set them as item's body.
21144 (arg (let* ((bul (org-list-bullet-string "-"))
21145 (bul-len (length bul))
21146 (ref-ind (org-get-indentation)))
21147 (skip-chars-forward " \t")
21148 (insert bul)
21149 (forward-line)
21150 (while (< (point) end)
21151 ;; Ensure that lines less indented than first one
21152 ;; still get included in item body.
21153 (funcall shift-text
21154 (+ ref-ind bul-len)
21155 (min end (save-excursion (or (outline-next-heading)
21156 (point)))))
21157 (forward-line))))
21158 ;; Case 4. Normal line without ARG: turn each non-item line
21159 ;; into an item.
21161 (while (< (point) end)
21162 (unless (or (org-at-heading-p) (org-at-item-p))
21163 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21164 (replace-match
21165 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21166 (forward-line))))))))
21168 (defun org-toggle-heading (&optional nstars)
21169 "Convert headings to normal text, or items or text to headings.
21170 If there is no active region, only convert the current line.
21172 With a \\[universal-argument] prefix, convert the whole list at
21173 point into heading.
21175 In a region:
21177 - If the first non blank line is a headline, remove the stars
21178 from all headlines in the region.
21180 - If it is a normal line, turn each and every normal line (i.e.,
21181 not an heading or an item) in the region into headings. If you
21182 want to convert only the first line of this region, use one
21183 universal prefix argument.
21185 - If it is a plain list item, turn all plain list items into headings.
21187 When converting a line into a heading, the number of stars is chosen
21188 such that the lines become children of the current entry. However,
21189 when a numeric prefix argument is given, its value determines the
21190 number of stars to add."
21191 (interactive "P")
21192 (let ((skip-blanks
21193 (function
21194 ;; Return beginning of first non-blank line, starting from
21195 ;; line at POS.
21196 (lambda (pos)
21197 (save-excursion
21198 (goto-char pos)
21199 (while (org-at-comment-p) (forward-line))
21200 (skip-chars-forward " \r\t\n")
21201 (point-at-bol)))))
21202 beg end toggled)
21203 ;; Determine boundaries of changes. If a universal prefix has
21204 ;; been given, put the list in a region. If region ends at a bol,
21205 ;; do not consider the last line to be in the region.
21207 (when (and current-prefix-arg (org-at-item-p))
21208 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21209 (org-mark-element))
21211 (if (org-region-active-p)
21212 (setq beg (funcall skip-blanks (region-beginning))
21213 end (copy-marker (save-excursion
21214 (goto-char (region-end))
21215 (if (bolp) (point) (point-at-eol)))))
21216 (setq beg (funcall skip-blanks (point-at-bol))
21217 end (copy-marker (point-at-eol))))
21218 ;; Ensure inline tasks don't count as headings.
21219 (org-with-limited-levels
21220 (save-excursion
21221 (goto-char beg)
21222 (cond
21223 ;; Case 1. Started at an heading: de-star headings.
21224 ((org-at-heading-p)
21225 (while (< (point) end)
21226 (when (org-at-heading-p t)
21227 (looking-at org-outline-regexp) (replace-match "")
21228 (setq toggled t))
21229 (forward-line)))
21230 ;; Case 2. Started at an item: change items into headlines.
21231 ;; One star will be added by `org-list-to-subtree'.
21232 ((org-at-item-p)
21233 (let* ((stars (make-string
21234 ;; subtract the star that will be added again by
21235 ;; `org-list-to-subtree'
21236 (if (numberp nstars) (1- nstars)
21237 (or (org-current-level) 0))
21238 ?*))
21239 (add-stars
21240 (cond (nstars "") ; stars from prefix only
21241 ((equal stars "") "") ; before first heading
21242 (org-odd-levels-only "*") ; inside heading, odd
21243 (t "")))) ; inside heading, oddeven
21244 (while (< (point) end)
21245 (when (org-at-item-p)
21246 ;; Pay attention to cases when region ends before list.
21247 (let* ((struct (org-list-struct))
21248 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21249 (save-restriction
21250 (narrow-to-region (point) list-end)
21251 (insert
21252 (org-list-to-subtree
21253 (org-list-parse-list t)
21254 '(:istart (concat stars add-stars (funcall get-stars depth))
21255 :icount (concat stars add-stars (funcall get-stars depth)))))))
21256 (setq toggled t))
21257 (forward-line))))
21258 ;; Case 3. Started at normal text: make every line an heading,
21259 ;; skipping headlines and items.
21260 (t (let* ((stars
21261 (make-string
21262 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21263 (add-stars
21264 (cond (nstars "") ; stars from prefix only
21265 ((equal stars "") "*") ; before first heading
21266 (org-odd-levels-only "**") ; inside heading, odd
21267 (t "*"))) ; inside heading, oddeven
21268 (rpl (concat stars add-stars " "))
21269 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21270 (while (< (point) (if (equal nstars '(4)) lend end))
21271 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21272 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21273 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21274 (forward-line)))))))
21275 (unless toggled (message "Cannot toggle heading from here"))))
21277 (defun org-meta-return (&optional arg)
21278 "Insert a new heading or wrap a region in a table.
21279 Calls `org-insert-heading' or `org-table-wrap-region', depending
21280 on context. See the individual commands for more information."
21281 (interactive "P")
21282 (org-check-before-invisible-edit 'insert)
21283 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21284 (let* ((element (org-element-at-point))
21285 (type (org-element-type element)))
21286 (when (eq type 'table-row)
21287 (setq element (org-element-property :parent element))
21288 (setq type 'table))
21289 (if (and (eq type 'table)
21290 (eq (org-element-property :type element) 'org)
21291 (>= (point) (org-element-property :contents-begin element))
21292 (< (point) (org-element-property :contents-end element)))
21293 (call-interactively 'org-table-wrap-region)
21294 (call-interactively 'org-insert-heading)))))
21296 ;;; Menu entries
21298 (defsubst org-in-subtree-not-table-p ()
21299 "Are we in a subtree and not in a table?"
21300 (and (not (org-before-first-heading-p))
21301 (not (org-at-table-p))))
21303 ;; Define the Org-mode menus
21304 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21305 '("Tbl"
21306 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21307 ["Next Field" org-cycle (org-at-table-p)]
21308 ["Previous Field" org-shifttab (org-at-table-p)]
21309 ["Next Row" org-return (org-at-table-p)]
21310 "--"
21311 ["Blank Field" org-table-blank-field (org-at-table-p)]
21312 ["Edit Field" org-table-edit-field (org-at-table-p)]
21313 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21314 "--"
21315 ("Column"
21316 ["Move Column Left" org-metaleft (org-at-table-p)]
21317 ["Move Column Right" org-metaright (org-at-table-p)]
21318 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21319 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21320 ("Row"
21321 ["Move Row Up" org-metaup (org-at-table-p)]
21322 ["Move Row Down" org-metadown (org-at-table-p)]
21323 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21324 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21325 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21326 "--"
21327 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21328 ("Rectangle"
21329 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21330 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21331 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21332 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21333 "--"
21334 ("Calculate"
21335 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21336 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21337 ["Edit Formulas" org-edit-special (org-at-table-p)]
21338 "--"
21339 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21340 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21341 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21342 "--"
21343 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21344 "--"
21345 ["Sum Column/Rectangle" org-table-sum
21346 (or (org-at-table-p) (org-region-active-p))]
21347 ["Which Column?" org-table-current-column (org-at-table-p)])
21348 ["Debug Formulas"
21349 org-table-toggle-formula-debugger
21350 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21351 ["Show Col/Row Numbers"
21352 org-table-toggle-coordinate-overlays
21353 :style toggle
21354 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21355 "--"
21356 ["Create" org-table-create (and (not (org-at-table-p))
21357 org-enable-table-editor)]
21358 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21359 ["Import from File" org-table-import (not (org-at-table-p))]
21360 ["Export to File" org-table-export (org-at-table-p)]
21361 "--"
21362 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21363 "--"
21364 ("Plot"
21365 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21366 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21368 (easy-menu-define org-org-menu org-mode-map "Org menu"
21369 '("Org"
21370 ("Show/Hide"
21371 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21372 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21373 ["Sparse Tree..." org-sparse-tree t]
21374 ["Reveal Context" org-reveal t]
21375 ["Show All" show-all t]
21376 "--"
21377 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21378 "--"
21379 ["New Heading" org-insert-heading t]
21380 ("Navigate Headings"
21381 ["Up" outline-up-heading t]
21382 ["Next" outline-next-visible-heading t]
21383 ["Previous" outline-previous-visible-heading t]
21384 ["Next Same Level" outline-forward-same-level t]
21385 ["Previous Same Level" outline-backward-same-level t]
21386 "--"
21387 ["Jump" org-goto t])
21388 ("Edit Structure"
21389 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21390 "--"
21391 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21392 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21393 "--"
21394 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21395 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21396 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21397 "--"
21398 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21399 "--"
21400 ["Copy visible text" org-copy-visible t]
21401 "--"
21402 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21403 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21404 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21405 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21406 "--"
21407 ["Sort Region/Children" org-sort t]
21408 "--"
21409 ["Convert to odd levels" org-convert-to-odd-levels t]
21410 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21411 ("Editing"
21412 ["Emphasis..." org-emphasize t]
21413 ["Edit Source Example" org-edit-special t]
21414 "--"
21415 ["Footnote new/jump" org-footnote-action t]
21416 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21417 ("Archive"
21418 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21419 "--"
21420 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21421 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21422 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21424 "--"
21425 ("Hyperlinks"
21426 ["Store Link (Global)" org-store-link t]
21427 ["Find existing link to here" org-occur-link-in-agenda-files t]
21428 ["Insert Link" org-insert-link t]
21429 ["Follow Link" org-open-at-point t]
21430 "--"
21431 ["Next link" org-next-link t]
21432 ["Previous link" org-previous-link t]
21433 "--"
21434 ["Descriptive Links"
21435 org-toggle-link-display
21436 :style radio
21437 :selected org-descriptive-links
21439 ["Literal Links"
21440 org-toggle-link-display
21441 :style radio
21442 :selected (not org-descriptive-links)])
21443 "--"
21444 ("TODO Lists"
21445 ["TODO/DONE/-" org-todo t]
21446 ("Select keyword"
21447 ["Next keyword" org-shiftright (org-at-heading-p)]
21448 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21449 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21450 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21451 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21452 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21453 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21454 "--"
21455 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21456 :selected org-enforce-todo-dependencies :style toggle :active t]
21457 "Settings for tree at point"
21458 ["Do Children sequentially" org-toggle-ordered-property :style radio
21459 :selected (org-entry-get nil "ORDERED")
21460 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21461 ["Do Children parallel" org-toggle-ordered-property :style radio
21462 :selected (not (org-entry-get nil "ORDERED"))
21463 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21464 "--"
21465 ["Set Priority" org-priority t]
21466 ["Priority Up" org-shiftup t]
21467 ["Priority Down" org-shiftdown t]
21468 "--"
21469 ["Get news from all feeds" org-feed-update-all t]
21470 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21471 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21472 ("TAGS and Properties"
21473 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21474 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21475 "--"
21476 ["Set property" org-set-property (not (org-before-first-heading-p))]
21477 ["Column view of properties" org-columns t]
21478 ["Insert Column View DBlock" org-insert-columns-dblock t])
21479 ("Dates and Scheduling"
21480 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21481 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21482 ("Change Date"
21483 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21484 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21485 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21486 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21487 ["Compute Time Range" org-evaluate-time-range t]
21488 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21489 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21490 "--"
21491 ["Custom time format" org-toggle-time-stamp-overlays
21492 :style radio :selected org-display-custom-times]
21493 "--"
21494 ["Goto Calendar" org-goto-calendar t]
21495 ["Date from Calendar" org-date-from-calendar t]
21496 "--"
21497 ["Start/Restart Timer" org-timer-start t]
21498 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21499 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21500 ["Insert Timer String" org-timer t]
21501 ["Insert Timer Item" org-timer-item t])
21502 ("Logging work"
21503 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21504 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21505 ["Clock out" org-clock-out t]
21506 ["Clock cancel" org-clock-cancel t]
21507 "--"
21508 ["Mark as default task" org-clock-mark-default-task t]
21509 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21510 ["Goto running clock" org-clock-goto t]
21511 "--"
21512 ["Display times" org-clock-display t]
21513 ["Create clock table" org-clock-report t]
21514 "--"
21515 ["Record DONE time"
21516 (progn (setq org-log-done (not org-log-done))
21517 (message "Switching to %s will %s record a timestamp"
21518 (car org-done-keywords)
21519 (if org-log-done "automatically" "not")))
21520 :style toggle :selected org-log-done])
21521 "--"
21522 ["Agenda Command..." org-agenda t]
21523 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21524 ("File List for Agenda")
21525 ("Special views current file"
21526 ["TODO Tree" org-show-todo-tree t]
21527 ["Check Deadlines" org-check-deadlines t]
21528 ["Timeline" org-timeline t]
21529 ["Tags/Property tree" org-match-sparse-tree t])
21530 "--"
21531 ["Export/Publish..." org-export-dispatch t]
21532 ("LaTeX"
21533 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21534 :selected org-cdlatex-mode]
21535 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21536 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21537 ["Modify math symbol" org-cdlatex-math-modify
21538 (org-inside-LaTeX-fragment-p)]
21539 ["Insert citation" org-reftex-citation t]
21540 "--"
21541 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21542 "--"
21543 ("MobileOrg"
21544 ["Push Files and Views" org-mobile-push t]
21545 ["Get Captured and Flagged" org-mobile-pull t]
21546 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21547 "--"
21548 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21549 "--"
21550 ("Documentation"
21551 ["Show Version" org-version t]
21552 ["Info Documentation" org-info t])
21553 ("Customize"
21554 ["Browse Org Group" org-customize t]
21555 "--"
21556 ["Expand This Menu" org-create-customize-menu
21557 (fboundp 'customize-menu-create)])
21558 ["Send bug report" org-submit-bug-report t]
21559 "--"
21560 ("Refresh/Reload"
21561 ["Refresh setup current buffer" org-mode-restart t]
21562 ["Reload Org (after update)" org-reload t]
21563 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21566 (defun org-info (&optional node)
21567 "Read documentation for Org-mode in the info system.
21568 With optional NODE, go directly to that node."
21569 (interactive)
21570 (info (format "(org)%s" (or node ""))))
21572 ;;;###autoload
21573 (defun org-submit-bug-report ()
21574 "Submit a bug report on Org-mode via mail.
21576 Don't hesitate to report any problems or inaccurate documentation.
21578 If you don't have setup sending mail from (X)Emacs, please copy the
21579 output buffer into your mail program, as it gives us important
21580 information about your Org-mode version and configuration."
21581 (interactive)
21582 (require 'reporter)
21583 (org-load-modules-maybe)
21584 (org-require-autoloaded-modules)
21585 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21586 (reporter-submit-bug-report
21587 "emacs-orgmode@gnu.org"
21588 (org-version nil 'full)
21589 (let (list)
21590 (save-window-excursion
21591 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21592 (delete-other-windows)
21593 (erase-buffer)
21594 (insert "You are about to submit a bug report to the Org-mode mailing list.
21596 We would like to add your full Org-mode and Outline configuration to the
21597 bug report. This greatly simplifies the work of the maintainer and
21598 other experts on the mailing list.
21600 HOWEVER, some variables you have customized may contain private
21601 information. The names of customers, colleagues, or friends, might
21602 appear in the form of file names, tags, todo states, or search strings.
21603 If you answer yes to the prompt, you might want to check and remove
21604 such private information before sending the email.")
21605 (add-text-properties (point-min) (point-max) '(face org-warning))
21606 (when (yes-or-no-p "Include your Org-mode configuration ")
21607 (mapatoms
21608 (lambda (v)
21609 (and (boundp v)
21610 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21611 (or (and (symbol-value v)
21612 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21613 (and
21614 (get v 'custom-type) (get v 'standard-value)
21615 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21616 (push v list)))))
21617 (kill-buffer (get-buffer "*Warn about privacy*"))
21618 list))
21619 nil nil
21620 "Remember to cover the basics, that is, what you expected to happen and
21621 what in fact did happen. You don't know how to make a good report? See
21623 http://orgmode.org/manual/Feedback.html#Feedback
21625 Your bug report will be posted to the Org-mode mailing list.
21626 ------------------------------------------------------------------------")
21627 (save-excursion
21628 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21629 (replace-match "\\1Bug: \\3 [\\2]")))))
21632 (defun org-install-agenda-files-menu ()
21633 (let ((bl (buffer-list)))
21634 (save-excursion
21635 (while bl
21636 (set-buffer (pop bl))
21637 (if (derived-mode-p 'org-mode) (setq bl nil)))
21638 (when (derived-mode-p 'org-mode)
21639 (easy-menu-change
21640 '("Org") "File List for Agenda"
21641 (append
21642 (list
21643 ["Edit File List" (org-edit-agenda-file-list) t]
21644 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21645 ["Remove Current File from List" org-remove-file t]
21646 ["Cycle through agenda files" org-cycle-agenda-files t]
21647 ["Occur in all agenda files" org-occur-in-agenda-files t]
21648 "--")
21649 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21651 ;;;; Documentation
21653 (defun org-require-autoloaded-modules ()
21654 (interactive)
21655 (mapc 'require
21656 '(org-agenda org-archive org-attach org-clock org-colview org-id
21657 org-table org-timer)))
21659 ;;;###autoload
21660 (defun org-reload (&optional uncompiled)
21661 "Reload all org lisp files.
21662 With prefix arg UNCOMPILED, load the uncompiled versions."
21663 (interactive "P")
21664 (require 'loadhist)
21665 (let* ((org-dir (org-find-library-dir "org"))
21666 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21667 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21668 (remove-re (mapconcat 'identity
21669 (mapcar (lambda (f) (concat "^" f "$"))
21670 (list (if (featurep 'xemacs)
21671 "org-colview"
21672 "org-colview-xemacs")
21673 "org" "org-loaddefs" "org-version"))
21674 "\\|"))
21675 (feats (delete-dups
21676 (mapcar 'file-name-sans-extension
21677 (mapcar 'file-name-nondirectory
21678 (delq nil
21679 (mapcar 'feature-file
21680 features))))))
21681 (lfeat (append
21682 (sort
21683 (setq feats
21684 (delq nil (mapcar
21685 (lambda (f)
21686 (if (and (string-match feature-re f)
21687 (not (string-match remove-re f)))
21688 f nil))
21689 feats)))
21690 'string-lessp)
21691 (list "org-version" "org")))
21692 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21693 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21694 load-uncore load-misses)
21695 (setq load-misses
21696 (delq 't
21697 (mapcar (lambda (f)
21698 (or (org-load-noerror-mustsuffix (concat org-dir f))
21699 (and (string= org-dir contrib-dir)
21700 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21701 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21702 (add-to-list 'load-uncore f 'append)
21705 lfeat)))
21706 (if load-uncore
21707 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21708 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21709 (if load-misses
21710 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21711 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21712 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21714 ;;;###autoload
21715 (defun org-customize ()
21716 "Call the customize function with org as argument."
21717 (interactive)
21718 (org-load-modules-maybe)
21719 (org-require-autoloaded-modules)
21720 (customize-browse 'org))
21722 (defun org-create-customize-menu ()
21723 "Create a full customization menu for Org-mode, insert it into the menu."
21724 (interactive)
21725 (org-load-modules-maybe)
21726 (org-require-autoloaded-modules)
21727 (if (fboundp 'customize-menu-create)
21728 (progn
21729 (easy-menu-change
21730 '("Org") "Customize"
21731 `(["Browse Org group" org-customize t]
21732 "--"
21733 ,(customize-menu-create 'org)
21734 ["Set" Custom-set t]
21735 ["Save" Custom-save t]
21736 ["Reset to Current" Custom-reset-current t]
21737 ["Reset to Saved" Custom-reset-saved t]
21738 ["Reset to Standard Settings" Custom-reset-standard t]))
21739 (message "\"Org\"-menu now contains full customization menu"))
21740 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21742 ;;;; Miscellaneous stuff
21744 ;;; Generally useful functions
21746 (defsubst org-get-at-eol (property n)
21747 "Get text property PROPERTY at the end of line less N characters."
21748 (get-text-property (- (point-at-eol) n) property))
21750 (defun org-find-text-property-in-string (prop s)
21751 "Return the first non-nil value of property PROP in string S."
21752 (or (get-text-property 0 prop s)
21753 (get-text-property (or (next-single-property-change 0 prop s) 0)
21754 prop s)))
21756 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21757 "Display the given MESSAGE as a warning."
21758 (if (fboundp 'display-warning)
21759 (display-warning 'org message
21760 (if (featurep 'xemacs) 'warning :warning))
21761 (let ((buf (get-buffer-create "*Org warnings*")))
21762 (with-current-buffer buf
21763 (goto-char (point-max))
21764 (insert "Warning (Org): " message)
21765 (unless (bolp)
21766 (newline)))
21767 (display-buffer buf)
21768 (sit-for 0))))
21770 (defun org-eval (form)
21771 "Eval FORM and return result."
21772 (condition-case error
21773 (eval form)
21774 (error (format "%%![Error: %s]" error))))
21776 (defun org-in-clocktable-p ()
21777 "Check if the cursor is in a clocktable."
21778 (let ((pos (point)) start)
21779 (save-excursion
21780 (end-of-line 1)
21781 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21782 (setq start (match-beginning 0))
21783 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21784 (>= (match-end 0) pos)
21785 start))))
21787 (defun org-in-verbatim-emphasis ()
21788 (save-match-data
21789 (and (org-in-regexp org-emph-re 2)
21790 (>= (point) (match-beginning 3))
21791 (<= (point) (match-end 4))
21792 (member (match-string 3) '("=" "~")))))
21794 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21795 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21796 (if (and marker (marker-buffer marker)
21797 (buffer-live-p (marker-buffer marker)))
21798 (progn
21799 (org-pop-to-buffer-same-window (marker-buffer marker))
21800 (if (or (> marker (point-max)) (< marker (point-min)))
21801 (widen))
21802 (goto-char marker)
21803 (org-show-context 'org-goto))
21804 (if bookmark
21805 (bookmark-jump bookmark)
21806 (error "Cannot find location"))))
21808 (defun org-quote-csv-field (s)
21809 "Quote field for inclusion in CSV material."
21810 (if (string-match "[\",]" s)
21811 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21814 (defun org-force-self-insert (N)
21815 "Needed to enforce self-insert under remapping."
21816 (interactive "p")
21817 (self-insert-command N))
21819 (defun org-string-width (s)
21820 "Compute width of string, ignoring invisible characters.
21821 This ignores character with invisibility property `org-link', and also
21822 characters with property `org-cwidth', because these will become invisible
21823 upon the next fontification round."
21824 (let (b l)
21825 (when (or (eq t buffer-invisibility-spec)
21826 (assq 'org-link buffer-invisibility-spec))
21827 (while (setq b (text-property-any 0 (length s)
21828 'invisible 'org-link s))
21829 (setq s (concat (substring s 0 b)
21830 (substring s (or (next-single-property-change
21831 b 'invisible s) (length s)))))))
21832 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21833 (setq s (concat (substring s 0 b)
21834 (substring s (or (next-single-property-change
21835 b 'org-cwidth s) (length s))))))
21836 (setq l (string-width s) b -1)
21837 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21838 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21841 (defun org-shorten-string (s maxlength)
21842 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21843 If the string is shorter or has length MAXLENGTH, just return the
21844 original string. If it is longer, the functions finds a space in the
21845 string, breaks this string off at that locations and adds three dots
21846 as ellipsis. Including the ellipsis, the string will not be longer
21847 than MAXLENGTH. If finding a good breaking point in the string does
21848 not work, the string is just chopped off in the middle of a word
21849 if necessary."
21850 (if (<= (length s) maxlength)
21852 (let* ((n (max (- maxlength 4) 1))
21853 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21854 (if (string-match re s)
21855 (concat (match-string 1 s) "...")
21856 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21858 (defun org-get-indentation (&optional line)
21859 "Get the indentation of the current line, interpreting tabs.
21860 When LINE is given, assume it represents a line and compute its indentation."
21861 (if line
21862 (if (string-match "^ *" (org-remove-tabs line))
21863 (match-end 0))
21864 (save-excursion
21865 (beginning-of-line 1)
21866 (skip-chars-forward " \t")
21867 (current-column))))
21869 (defun org-get-string-indentation (s)
21870 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21871 (let ((n -1) (i 0) (w tab-width) c)
21872 (catch 'exit
21873 (while (< (setq n (1+ n)) (length s))
21874 (setq c (aref s n))
21875 (cond ((= c ?\ ) (setq i (1+ i)))
21876 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21877 (t (throw 'exit t)))))
21880 (defun org-remove-tabs (s &optional width)
21881 "Replace tabulators in S with spaces.
21882 Assumes that s is a single line, starting in column 0."
21883 (setq width (or width tab-width))
21884 (while (string-match "\t" s)
21885 (setq s (replace-match
21886 (make-string
21887 (- (* width (/ (+ (match-beginning 0) width) width))
21888 (match-beginning 0)) ?\ )
21889 t t s)))
21892 (defun org-fix-indentation (line ind)
21893 "Fix indentation in LINE.
21894 IND is a cons cell with target and minimum indentation.
21895 If the current indentation in LINE is smaller than the minimum,
21896 leave it alone. If it is larger than ind, set it to the target."
21897 (let* ((l (org-remove-tabs line))
21898 (i (org-get-indentation l))
21899 (i1 (car ind)) (i2 (cdr ind)))
21900 (if (>= i i2) (setq l (substring line i2)))
21901 (if (> i1 0)
21902 (concat (make-string i1 ?\ ) l)
21903 l)))
21905 (defun org-remove-indentation (code &optional n)
21906 "Remove the maximum common indentation from the lines in CODE.
21907 N may optionally be the number of spaces to remove."
21908 (with-temp-buffer
21909 (insert code)
21910 (org-do-remove-indentation n)
21911 (buffer-string)))
21913 (defun org-do-remove-indentation (&optional n)
21914 "Remove the maximum common indentation from the buffer."
21915 (untabify (point-min) (point-max))
21916 (let ((min 10000) re)
21917 (if n
21918 (setq min n)
21919 (goto-char (point-min))
21920 (while (re-search-forward "^ *[^ \n]" nil t)
21921 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21922 (unless (or (= min 0) (= min 10000))
21923 (setq re (format "^ \\{%d\\}" min))
21924 (goto-char (point-min))
21925 (while (re-search-forward re nil t)
21926 (replace-match "")
21927 (end-of-line 1))
21928 min)))
21930 (defun org-fill-template (template alist)
21931 "Find each %key of ALIST in TEMPLATE and replace it."
21932 (let ((case-fold-search nil)
21933 entry key value)
21934 (setq alist (sort (copy-sequence alist)
21935 (lambda (a b) (< (length (car a)) (length (car b))))))
21936 (while (setq entry (pop alist))
21937 (setq template
21938 (replace-regexp-in-string
21939 (concat "%" (regexp-quote (car entry)))
21940 (or (cdr entry) "") template t t)))
21941 template))
21943 (defun org-base-buffer (buffer)
21944 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21945 (if (not buffer)
21946 buffer
21947 (or (buffer-base-buffer buffer)
21948 buffer)))
21950 (defun org-wrap (string &optional width lines)
21951 "Wrap string to either a number of lines, or a width in characters.
21952 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21953 that costs. If there is a word longer than WIDTH, the text is actually
21954 wrapped to the length of that word.
21955 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21956 many lines, whatever width that takes.
21957 The return value is a list of lines, without newlines at the end."
21958 (let* ((words (org-split-string string "[ \t\n]+"))
21959 (maxword (apply 'max (mapcar 'org-string-width words)))
21960 w ll)
21961 (cond (width
21962 (org-do-wrap words (max maxword width)))
21963 (lines
21964 (setq w maxword)
21965 (setq ll (org-do-wrap words maxword))
21966 (if (<= (length ll) lines)
21968 (setq ll words)
21969 (while (> (length ll) lines)
21970 (setq w (1+ w))
21971 (setq ll (org-do-wrap words w)))
21972 ll))
21973 (t (error "Cannot wrap this")))))
21975 (defun org-do-wrap (words width)
21976 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21977 (let (lines line)
21978 (while words
21979 (setq line (pop words))
21980 (while (and words (< (+ (length line) (length (car words))) width))
21981 (setq line (concat line " " (pop words))))
21982 (setq lines (push line lines)))
21983 (nreverse lines)))
21985 (defun org-split-string (string &optional separators)
21986 "Splits STRING into substrings at SEPARATORS.
21987 No empty strings are returned if there are matches at the beginning
21988 and end of string."
21989 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21990 (start 0)
21991 notfirst
21992 (list nil))
21993 (while (and (string-match rexp string
21994 (if (and notfirst
21995 (= start (match-beginning 0))
21996 (< start (length string)))
21997 (1+ start) start))
21998 (< (match-beginning 0) (length string)))
21999 (setq notfirst t)
22000 (or (eq (match-beginning 0) 0)
22001 (and (eq (match-beginning 0) (match-end 0))
22002 (eq (match-beginning 0) start))
22003 (setq list
22004 (cons (substring string start (match-beginning 0))
22005 list)))
22006 (setq start (match-end 0)))
22007 (or (eq start (length string))
22008 (setq list
22009 (cons (substring string start)
22010 list)))
22011 (nreverse list)))
22013 (defun org-quote-vert (s)
22014 "Replace \"|\" with \"\\vert\"."
22015 (while (string-match "|" s)
22016 (setq s (replace-match "\\vert" t t s)))
22019 (defun org-uuidgen-p (s)
22020 "Is S an ID created by UUIDGEN?"
22021 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22023 (defun org-in-src-block-p (&optional inside)
22024 "Whether point is in a code source block.
22025 When INSIDE is non-nil, don't consider we are within a src block
22026 when point is at #+BEGIN_SRC or #+END_SRC."
22027 (let ((case-fold-search t) ov)
22028 (or (and (eq (get-char-property (point) 'src-block) t))
22029 (and (not inside)
22030 (save-match-data
22031 (save-excursion
22032 (beginning-of-line)
22033 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22035 (defun org-context ()
22036 "Return a list of contexts of the current cursor position.
22037 If several contexts apply, all are returned.
22038 Each context entry is a list with a symbol naming the context, and
22039 two positions indicating start and end of the context. Possible
22040 contexts are:
22042 :headline anywhere in a headline
22043 :headline-stars on the leading stars in a headline
22044 :todo-keyword on a TODO keyword (including DONE) in a headline
22045 :tags on the TAGS in a headline
22046 :priority on the priority cookie in a headline
22047 :item on the first line of a plain list item
22048 :item-bullet on the bullet/number of a plain list item
22049 :checkbox on the checkbox in a plain list item
22050 :table in an org-mode table
22051 :table-special on a special filed in a table
22052 :table-table in a table.el table
22053 :clocktable in a clocktable
22054 :src-block in a source block
22055 :link on a hyperlink
22056 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22057 :target on a <<target>>
22058 :radio-target on a <<<radio-target>>>
22059 :latex-fragment on a LaTeX fragment
22060 :latex-preview on a LaTeX fragment with overlaid preview image
22062 This function expects the position to be visible because it uses font-lock
22063 faces as a help to recognize the following contexts: :table-special, :link,
22064 and :keyword."
22065 (let* ((f (get-text-property (point) 'face))
22066 (faces (if (listp f) f (list f)))
22067 (case-fold-search t)
22068 (p (point)) clist o)
22069 ;; First the large context
22070 (cond
22071 ((org-at-heading-p t)
22072 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22073 (when (progn
22074 (beginning-of-line 1)
22075 (looking-at org-todo-line-tags-regexp))
22076 (push (org-point-in-group p 1 :headline-stars) clist)
22077 (push (org-point-in-group p 2 :todo-keyword) clist)
22078 (push (org-point-in-group p 4 :tags) clist))
22079 (goto-char p)
22080 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22081 (if (looking-at "\\[#[A-Z0-9]\\]")
22082 (push (org-point-in-group p 0 :priority) clist)))
22084 ((org-at-item-p)
22085 (push (org-point-in-group p 2 :item-bullet) clist)
22086 (push (list :item (point-at-bol)
22087 (save-excursion (org-end-of-item) (point)))
22088 clist)
22089 (and (org-at-item-checkbox-p)
22090 (push (org-point-in-group p 0 :checkbox) clist)))
22092 ((org-at-table-p)
22093 (push (list :table (org-table-begin) (org-table-end)) clist)
22094 (if (memq 'org-formula faces)
22095 (push (list :table-special
22096 (previous-single-property-change p 'face)
22097 (next-single-property-change p 'face)) clist)))
22098 ((org-at-table-p 'any)
22099 (push (list :table-table) clist)))
22100 (goto-char p)
22102 (let ((case-fold-search t))
22103 ;; New the "medium" contexts: clocktables, source blocks
22104 (cond ((org-in-clocktable-p)
22105 (push (list :clocktable
22106 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22107 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22108 (match-beginning 1))
22109 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22110 (match-end 0))) clist))
22111 ((org-in-src-block-p)
22112 (push (list :src-block
22113 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22114 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22115 (match-beginning 1))
22116 (and (search-forward "#+END_SRC" nil t)
22117 (match-beginning 0))) clist))))
22118 (goto-char p)
22120 ;; Now the small context
22121 (cond
22122 ((org-at-timestamp-p)
22123 (push (org-point-in-group p 0 :timestamp) clist))
22124 ((memq 'org-link faces)
22125 (push (list :link
22126 (previous-single-property-change p 'face)
22127 (next-single-property-change p 'face)) clist))
22128 ((memq 'org-special-keyword faces)
22129 (push (list :keyword
22130 (previous-single-property-change p 'face)
22131 (next-single-property-change p 'face)) clist))
22132 ((org-at-target-p)
22133 (push (org-point-in-group p 0 :target) clist)
22134 (goto-char (1- (match-beginning 0)))
22135 (if (looking-at org-radio-target-regexp)
22136 (push (org-point-in-group p 0 :radio-target) clist))
22137 (goto-char p))
22138 ((setq o (car (delq nil
22139 (mapcar
22140 (lambda (x)
22141 (if (memq x org-latex-fragment-image-overlays) x))
22142 (overlays-at (point))))))
22143 (push (list :latex-fragment
22144 (overlay-start o) (overlay-end o)) clist)
22145 (push (list :latex-preview
22146 (overlay-start o) (overlay-end o)) clist))
22147 ((org-inside-LaTeX-fragment-p)
22148 ;; FIXME: positions wrong.
22149 (push (list :latex-fragment (point) (point)) clist)))
22151 (setq clist (nreverse (delq nil clist)))
22152 clist))
22154 ;; FIXME: Compare with at-regexp-p Do we need both?
22155 (defun org-in-regexp (re &optional nlines visually)
22156 "Check if point is inside a match of regexp.
22157 Normally only the current line is checked, but you can include NLINES extra
22158 lines both before and after point into the search.
22159 If VISUALLY is set, require that the cursor is not after the match but
22160 really on, so that the block visually is on the match."
22161 (catch 'exit
22162 (let ((pos (point))
22163 (eol (point-at-eol (+ 1 (or nlines 0))))
22164 (inc (if visually 1 0)))
22165 (save-excursion
22166 (beginning-of-line (- 1 (or nlines 0)))
22167 (while (re-search-forward re eol t)
22168 (if (and (<= (match-beginning 0) pos)
22169 (>= (+ inc (match-end 0)) pos))
22170 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
22172 (defun org-at-regexp-p (regexp)
22173 "Is point inside a match of REGEXP in the current line?"
22174 (catch 'exit
22175 (save-excursion
22176 (let ((pos (point)) (end (point-at-eol)))
22177 (beginning-of-line 1)
22178 (while (re-search-forward regexp end t)
22179 (if (and (<= (match-beginning 0) pos)
22180 (>= (match-end 0) pos))
22181 (throw 'exit t)))
22182 nil))))
22184 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22185 "Non-nil when point is between matches of START-RE and END-RE.
22187 Also return a non-nil value when point is on one of the matches.
22189 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22190 buffer positions. Default values are the positions of headlines
22191 surrounding the point.
22193 The functions returns a cons cell whose car (resp. cdr) is the
22194 position before START-RE (resp. after END-RE)."
22195 (save-match-data
22196 (let ((pos (point))
22197 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22198 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22199 beg end)
22200 (save-excursion
22201 ;; Point is on a block when on START-RE or if START-RE can be
22202 ;; found before it...
22203 (and (or (org-at-regexp-p start-re)
22204 (re-search-backward start-re limit-up t))
22205 (setq beg (match-beginning 0))
22206 ;; ... and END-RE after it...
22207 (goto-char (match-end 0))
22208 (re-search-forward end-re limit-down t)
22209 (> (setq end (match-end 0)) pos)
22210 ;; ... without another START-RE in-between.
22211 (goto-char (match-beginning 0))
22212 (not (re-search-backward start-re (1+ beg) t))
22213 ;; Return value.
22214 (cons beg end))))))
22216 (defun org-in-block-p (names)
22217 "Non-nil when point belongs to a block whose name belongs to NAMES.
22219 NAMES is a list of strings containing names of blocks.
22221 Return first block name matched, or nil. Beware that in case of
22222 nested blocks, the returned name may not belong to the closest
22223 block from point."
22224 (save-match-data
22225 (catch 'exit
22226 (let ((case-fold-search t)
22227 (lim-up (save-excursion (outline-previous-heading)))
22228 (lim-down (save-excursion (outline-next-heading))))
22229 (mapc (lambda (name)
22230 (let ((n (regexp-quote name)))
22231 (when (org-between-regexps-p
22232 (concat "^[ \t]*#\\+begin_" n)
22233 (concat "^[ \t]*#\\+end_" n)
22234 lim-up lim-down)
22235 (throw 'exit n))))
22236 names))
22237 nil)))
22239 (defun org-occur-in-agenda-files (regexp &optional nlines)
22240 "Call `multi-occur' with buffers for all agenda files."
22241 (interactive "sOrg-files matching: \np")
22242 (let* ((files (org-agenda-files))
22243 (tnames (mapcar 'file-truename files))
22244 (extra org-agenda-text-search-extra-files)
22246 (when (eq (car extra) 'agenda-archives)
22247 (setq extra (cdr extra))
22248 (setq files (org-add-archive-files files)))
22249 (while (setq f (pop extra))
22250 (unless (member (file-truename f) tnames)
22251 (add-to-list 'files f 'append)
22252 (add-to-list 'tnames (file-truename f) 'append)))
22253 (multi-occur
22254 (mapcar (lambda (x)
22255 (with-current-buffer
22256 (or (get-file-buffer x) (find-file-noselect x))
22257 (widen)
22258 (current-buffer)))
22259 files)
22260 regexp)))
22262 (if (boundp 'occur-mode-find-occurrence-hook)
22263 ;; Emacs 23
22264 (add-hook 'occur-mode-find-occurrence-hook
22265 (lambda ()
22266 (when (derived-mode-p 'org-mode)
22267 (org-reveal))))
22268 ;; Emacs 22
22269 (defadvice occur-mode-goto-occurrence
22270 (after org-occur-reveal activate)
22271 (and (derived-mode-p 'org-mode) (org-reveal)))
22272 (defadvice occur-mode-goto-occurrence-other-window
22273 (after org-occur-reveal activate)
22274 (and (derived-mode-p 'org-mode) (org-reveal)))
22275 (defadvice occur-mode-display-occurrence
22276 (after org-occur-reveal activate)
22277 (when (derived-mode-p 'org-mode)
22278 (let ((pos (occur-mode-find-occurrence)))
22279 (with-current-buffer (marker-buffer pos)
22280 (save-excursion
22281 (goto-char pos)
22282 (org-reveal)))))))
22284 (defun org-occur-link-in-agenda-files ()
22285 "Create a link and search for it in the agendas.
22286 The link is not stored in `org-stored-links', it is just created
22287 for the search purpose."
22288 (interactive)
22289 (let ((link (condition-case nil
22290 (org-store-link nil)
22291 (error "Unable to create a link to here"))))
22292 (org-occur-in-agenda-files (regexp-quote link))))
22294 (defun org-reverse-string (string)
22295 "Return the reverse of STRING."
22296 (apply 'string (reverse (string-to-list string))))
22298 ;; defsubst org-uniquify must be defined before first use
22300 (defun org-uniquify-alist (alist)
22301 "Merge elements of ALIST with the same key.
22303 For example, in this alist:
22305 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22306 => '((a 1 3) (b 2))
22308 merge (a 1) and (a 3) into (a 1 3).
22310 The function returns the new ALIST."
22311 (let (rtn)
22312 (mapc
22313 (lambda (e)
22314 (let (n)
22315 (if (not (assoc (car e) rtn))
22316 (push e rtn)
22317 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22318 (setq rtn (assq-delete-all (car e) rtn))
22319 (push n rtn))))
22320 alist)
22321 rtn))
22323 (defun org-delete-all (elts list)
22324 "Remove all elements in ELTS from LIST."
22325 (while elts
22326 (setq list (delete (pop elts) list)))
22327 list)
22329 (defun org-count (cl-item cl-seq)
22330 "Count the number of occurrences of ITEM in SEQ.
22331 Taken from `count' in cl-seq.el with all keyword arguments removed."
22332 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22333 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22334 (while (< cl-start cl-end)
22335 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22336 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22337 (setq cl-start (1+ cl-start)))
22338 cl-count))
22340 (defun org-remove-if (predicate seq)
22341 "Remove everything from SEQ that fulfills PREDICATE."
22342 (let (res e)
22343 (while seq
22344 (setq e (pop seq))
22345 (if (not (funcall predicate e)) (push e res)))
22346 (nreverse res)))
22348 (defun org-remove-if-not (predicate seq)
22349 "Remove everything from SEQ that does not fulfill PREDICATE."
22350 (let (res e)
22351 (while seq
22352 (setq e (pop seq))
22353 (if (funcall predicate e) (push e res)))
22354 (nreverse res)))
22356 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22357 "Reduce two-argument FUNCTION across SEQ.
22358 Taken from `reduce' in cl-seq.el with all keyword arguments but
22359 \":initial-value\" removed."
22360 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22361 (cadr (memq :initial-value cl-keys)))
22362 (cl-seq (pop cl-seq))
22363 (t (funcall cl-func)))))
22364 (while cl-seq
22365 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22366 cl-accum))
22368 (defun org-every (pred seq)
22369 "Return true if PREDICATE is true of every element of SEQ.
22370 Adapted from `every' in cl.el."
22371 (catch 'org-every
22372 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22375 (defun org-some (pred seq)
22376 "Return true if PREDICATE is true of any element of SEQ.
22377 Adapted from `some' in cl.el."
22378 (catch 'org-some
22379 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22380 nil))
22382 (defun org-back-over-empty-lines ()
22383 "Move backwards over whitespace, to the beginning of the first empty line.
22384 Returns the number of empty lines passed."
22385 (let ((pos (point)))
22386 (if (cdr (assoc 'heading org-blank-before-new-entry))
22387 (skip-chars-backward " \t\n\r")
22388 (unless (eobp)
22389 (forward-line -1)))
22390 (beginning-of-line 2)
22391 (goto-char (min (point) pos))
22392 (count-lines (point) pos)))
22394 (defun org-skip-whitespace ()
22395 (skip-chars-forward " \t\n\r"))
22397 (defun org-point-in-group (point group &optional context)
22398 "Check if POINT is in match-group GROUP.
22399 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22400 match. If the match group does not exist or point is not inside it,
22401 return nil."
22402 (and (match-beginning group)
22403 (>= point (match-beginning group))
22404 (<= point (match-end group))
22405 (if context
22406 (list context (match-beginning group) (match-end group))
22407 t)))
22409 (defun org-switch-to-buffer-other-window (&rest args)
22410 "Switch to buffer in a second window on the current frame.
22411 In particular, do not allow pop-up frames.
22412 Returns the newly created buffer."
22413 (org-no-popups
22414 (apply 'switch-to-buffer-other-window args)))
22416 (defun org-combine-plists (&rest plists)
22417 "Create a single property list from all plists in PLISTS.
22418 The process starts by copying the first list, and then setting properties
22419 from the other lists. Settings in the last list are the most significant
22420 ones and overrule settings in the other lists."
22421 (let ((rtn (copy-sequence (pop plists)))
22422 p v ls)
22423 (while plists
22424 (setq ls (pop plists))
22425 (while ls
22426 (setq p (pop ls) v (pop ls))
22427 (setq rtn (plist-put rtn p v))))
22428 rtn))
22430 (defun org-replace-escapes (string table)
22431 "Replace %-escapes in STRING with values in TABLE.
22432 TABLE is an association list with keys like \"%a\" and string values.
22433 The sequences in STRING may contain normal field width and padding information,
22434 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22435 so values can contain further %-escapes if they are define later in TABLE."
22436 (let ((tbl (copy-alist table))
22437 (case-fold-search nil)
22438 (pchg 0)
22439 e re rpl)
22440 (while (setq e (pop tbl))
22441 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22442 (when (and (cdr e) (string-match re (cdr e)))
22443 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22444 (safe "SREF"))
22445 (add-text-properties 0 3 (list 'sref sref) safe)
22446 (setcdr e (replace-match safe t t (cdr e)))))
22447 (while (string-match re string)
22448 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22449 (cdr e)))
22450 (setq string (replace-match rpl t t string))))
22451 (while (setq pchg (next-property-change pchg string))
22452 (let ((sref (get-text-property pchg 'sref string)))
22453 (when (and sref (string-match "SREF" string pchg))
22454 (setq string (replace-match sref t t string)))))
22455 string))
22457 (defun org-sublist (list start end)
22458 "Return a section of LIST, from START to END.
22459 Counting starts at 1."
22460 (let (rtn (c start))
22461 (setq list (nthcdr (1- start) list))
22462 (while (and list (<= c end))
22463 (push (pop list) rtn)
22464 (setq c (1+ c)))
22465 (nreverse rtn)))
22467 (defun org-find-base-buffer-visiting (file)
22468 "Like `find-buffer-visiting' but always return the base buffer and
22469 not an indirect buffer."
22470 (let ((buf (or (get-file-buffer file)
22471 (find-buffer-visiting file))))
22472 (if buf
22473 (or (buffer-base-buffer buf) buf)
22474 nil)))
22476 (defun org-image-file-name-regexp (&optional extensions)
22477 "Return regexp matching the file names of images.
22478 If EXTENSIONS is given, only match these."
22479 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22480 (image-file-name-regexp)
22481 (let ((image-file-name-extensions
22482 (or extensions
22483 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22484 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22485 (concat "\\."
22486 (regexp-opt (nconc (mapcar 'upcase
22487 image-file-name-extensions)
22488 image-file-name-extensions)
22490 "\\'"))))
22492 (defun org-file-image-p (file &optional extensions)
22493 "Return non-nil if FILE is an image."
22494 (save-match-data
22495 (string-match (org-image-file-name-regexp extensions) file)))
22497 (defun org-get-cursor-date (&optional with-time)
22498 "Return the date at cursor in as a time.
22499 This works in the calendar and in the agenda, anywhere else it just
22500 returns the current time.
22501 If WITH-TIME is non-nil, returns the time of the event at point (in
22502 the agenda) or the current time of the day."
22503 (let (date day defd tp tm hod mod)
22504 (when with-time
22505 (setq tp (get-text-property (point) 'time))
22506 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22507 (setq hod (string-to-number (match-string 1 tp))
22508 mod (string-to-number (match-string 2 tp))))
22509 (or tp (setq hod (nth 2 (decode-time (current-time)))
22510 mod (nth 1 (decode-time (current-time))))))
22511 (cond
22512 ((eq major-mode 'calendar-mode)
22513 (setq date (calendar-cursor-to-date)
22514 defd (encode-time 0 (or mod 0) (or hod 0)
22515 (nth 1 date) (nth 0 date) (nth 2 date))))
22516 ((eq major-mode 'org-agenda-mode)
22517 (setq day (get-text-property (point) 'day))
22518 (if day
22519 (setq date (calendar-gregorian-from-absolute day)
22520 defd (encode-time 0 (or mod 0) (or hod 0)
22521 (nth 1 date) (nth 0 date) (nth 2 date))))))
22522 (or defd (current-time))))
22524 (defun org-mark-subtree (&optional up)
22525 "Mark the current subtree.
22526 This puts point at the start of the current subtree, and mark at
22527 the end. If a numeric prefix UP is given, move up into the
22528 hierarchy of headlines by UP levels before marking the subtree."
22529 (interactive "P")
22530 (org-with-limited-levels
22531 (cond ((org-at-heading-p) (beginning-of-line))
22532 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22533 (t (outline-previous-visible-heading 1))))
22534 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22535 (if (org-called-interactively-p 'any)
22536 (call-interactively 'org-mark-element)
22537 (org-mark-element)))
22540 ;;; Indentation
22542 (defun org--get-expected-indentation (element contentsp)
22543 "Expected indentation column for current line, according to ELEMENT.
22544 ELEMENT is an element containing point. CONTENTSP is non-nil
22545 when indentation is to be computed according to contents of
22546 ELEMENT."
22547 (let ((type (org-element-type element))
22548 (start (org-element-property :begin element)))
22549 (org-with-wide-buffer
22550 (cond
22551 (contentsp
22552 (case type
22553 (footnote-definition 0)
22554 ((headline inlinetask nil)
22555 (if (not org-adapt-indentation) 0
22556 (let ((level (org-current-level)))
22557 (if level (1+ level) 0))))
22558 (item
22559 (org-list-item-body-column
22560 (org-element-property :post-affiliated element)))
22561 (plain-list
22562 (save-excursion
22563 (goto-char (org-element-property :post-affiliated element))
22564 (org-get-indentation)))
22565 (otherwise
22566 (goto-char start)
22567 (org-get-indentation))))
22568 ((memq type '(headline inlinetask nil))
22569 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22570 (org--get-expected-indentation element t)
22572 ((eq type 'footnote-definition) 0)
22573 ;; First paragraph of a footnote definition or an item.
22574 ;; Indent like parent.
22575 ((< (line-beginning-position) start)
22576 (org--get-expected-indentation
22577 (org-element-property :parent element) t))
22578 ;; At first line: indent according to previous sibling, if any,
22579 ;; ignoring footnote definitions and inline tasks, or parent's
22580 ;; contents.
22581 ((= (line-beginning-position) start)
22582 (catch 'exit
22583 (while t
22584 (if (= (point-min) start) (throw 'exit 0)
22585 (goto-char (1- start))
22586 (let* ((previous (org-element-at-point))
22587 (parent previous))
22588 (while (and parent (<= (org-element-property :end parent) start))
22589 (setq previous parent
22590 parent (org-element-property :parent parent)))
22591 (cond
22592 ((not previous) (throw 'exit 0))
22593 ((> (org-element-property :end previous) start)
22594 (throw 'exit (org--get-expected-indentation previous t)))
22595 ((memq (org-element-type previous)
22596 '(footnote-definition inlinetask))
22597 (setq start (org-element-property :begin previous)))
22598 (t (goto-char (org-element-property :begin previous))
22599 (throw 'exit
22600 (if (bolp) (org-get-indentation)
22601 ;; At first paragraph in an item or
22602 ;; a footnote definition.
22603 (org--get-expected-indentation
22604 (org-element-property :parent previous) t))))))))))
22605 ;; Otherwise, move to the first non-blank line above.
22607 (beginning-of-line)
22608 (let ((pos (point)))
22609 (skip-chars-backward " \r\t\n")
22610 (cond
22611 ;; Two blank lines end a footnote definition or a plain
22612 ;; list. When we indent an empty line after them, the
22613 ;; containing list or footnote definition is over, so it
22614 ;; qualifies as a previous sibling. Therefore, we indent
22615 ;; like its first line.
22616 ((and (memq type '(footnote-definition plain-list))
22617 (> (count-lines (point) pos) 2))
22618 (goto-char start)
22619 (org-get-indentation))
22620 ;; Line above is the first one of a paragraph at the
22621 ;; beginning of an item or a footnote definition. Indent
22622 ;; like parent.
22623 ((< (line-beginning-position) start)
22624 (org--get-expected-indentation
22625 (org-element-property :parent element) t))
22626 ;; POS is after contents in a greater element. Indent like
22627 ;; the beginning of the element.
22629 ;; As a special case, if point is at the end of a footnote
22630 ;; definition or an item, indent like the very last element
22631 ;; within.
22632 ((and (not (eq type 'paragraph))
22633 (let ((cend (org-element-property :contents-end element)))
22634 (and cend (<= cend pos))))
22635 (if (memq type '(footnote-definition item plain-list))
22636 (org--get-expected-indentation (org-element-at-point) nil)
22637 (goto-char start)
22638 (org-get-indentation)))
22639 ;; In any other case, indent like the current line.
22640 (t (org-get-indentation)))))))))
22642 (defun org--align-node-property ()
22643 "Align node property at point.
22644 Alignment is done according to `org-property-format', which see."
22645 (when (save-excursion
22646 (beginning-of-line)
22647 (looking-at org-property-re))
22648 (replace-match
22649 (concat (match-string 4)
22650 (org-trim
22651 (format org-property-format (match-string 1) (match-string 3))))
22652 t t)))
22654 (defun org-indent-line ()
22655 "Indent line depending on context.
22657 Indentation is done according to the following rules:
22659 - Footnote definitions, headlines and inline tasks have to
22660 start at column 0.
22662 - On the very first line of an element, consider, in order, the
22663 next rules until one matches:
22665 1. If there's a sibling element before, ignoring footnote
22666 definitions and inline tasks, indent like its first line.
22668 2. If element has a parent, indent like its contents. More
22669 precisely, if parent is an item, indent after the
22670 description part, if any, or the bullet (see
22671 `org-list-description-max-indent'). Else, indent like
22672 parent's first line.
22674 3. Otherwise, indent relatively to current level, if
22675 `org-adapt-indentation' is non-nil, or to left margin.
22677 - On a blank line at the end of an element, indent according to
22678 the type of the element. More precisely
22680 1. If element is a plain list, an item, or a footnote
22681 definition, indent like the very last element within.
22683 2. If element is a paragraph, indent like its last non blank
22684 line.
22686 3. Otherwise, indent like its very first line.
22688 - In the code part of a source block, use language major mode
22689 to indent current line if `org-src-tab-acts-natively' is
22690 non-nil. If it is nil, do nothing.
22692 - Otherwise, indent like the first non-blank line above.
22694 The function doesn't indent an item as it could break the whole
22695 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22696 \\[org-shiftmetaright].
22698 Also align node properties according to `org-property-format'."
22699 (interactive)
22700 (cond
22701 (orgstruct-is-++
22702 (let ((indent-line-function
22703 (cadadr (assq 'indent-line-function org-fb-vars))))
22704 (indent-according-to-mode)))
22705 ((org-at-heading-p) 'noindent)
22707 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22708 (type (org-element-type element)))
22709 (cond ((and (memq type '(plain-list item))
22710 (= (line-beginning-position)
22711 (org-element-property :post-affiliated element)))
22712 'noindent)
22713 ((and (eq type 'src-block)
22714 org-src-tab-acts-natively
22715 (> (line-beginning-position)
22716 (org-element-property :post-affiliated element))
22717 (< (line-beginning-position)
22718 (org-with-wide-buffer
22719 (goto-char (org-element-property :end element))
22720 (skip-chars-backward " \r\t\n")
22721 (line-beginning-position))))
22722 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22724 (let ((column (org--get-expected-indentation element nil)))
22725 ;; Preserve current column.
22726 (if (<= (current-column) (current-indentation))
22727 (org-indent-line-to column)
22728 (save-excursion (org-indent-line-to column))))
22729 ;; Align node property. Also preserve current column.
22730 (when (eq type 'node-property)
22731 (let ((column (current-column)))
22732 (org--align-node-property)
22733 (org-move-to-column column)))))))))
22735 (defun org-indent-region (start end)
22736 "Indent each non-blank line in the region.
22737 Called from a program, START and END specify the region to
22738 indent. The function will not indent contents of example blocks,
22739 verse blocks and export blocks as leading white spaces are
22740 assumed to be significant there."
22741 (interactive "r")
22742 (save-excursion
22743 (goto-char start)
22744 (skip-chars-forward " \r\t\n")
22745 (unless (eobp) (beginning-of-line))
22746 (let ((indent-to
22747 (lambda (ind pos)
22748 ;; Set IND as indentation for all lines between point and
22749 ;; POS or END, whichever comes first. Blank lines are
22750 ;; ignored. Leave point after POS once done.
22751 (let ((limit (copy-marker (min end pos))))
22752 (while (< (point) limit)
22753 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22754 (forward-line))
22755 (set-marker limit nil))))
22756 (end (copy-marker end)))
22757 (while (< (point) end)
22758 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22759 (let* ((element (org-element-at-point))
22760 (type (org-element-type element))
22761 (element-end (copy-marker (org-element-property :end element)))
22762 (ind (org--get-expected-indentation element nil)))
22763 (cond
22764 ((or (memq type '(paragraph table table-row))
22765 (not (or (org-element-property :contents-begin element)
22766 (memq type
22767 '(example-block export-block src-block)))))
22768 ;; Elements here are indented as a single block. Also
22769 ;; align node properties.
22770 (when (eq type 'node-property)
22771 (org--align-node-property)
22772 (beginning-of-line))
22773 (funcall indent-to ind element-end))
22775 ;; Elements in this category consist of three parts:
22776 ;; before the contents, the contents, and after the
22777 ;; contents. The contents are treated specially,
22778 ;; according to the element type, or not indented at
22779 ;; all. Other parts are indented as a single block.
22780 (let* ((post (copy-marker
22781 (org-element-property :post-affiliated element)))
22782 (cbeg
22783 (copy-marker
22784 (cond
22785 ((not (org-element-property :contents-begin element))
22786 ;; Fake contents for source blocks.
22787 (org-with-wide-buffer
22788 (goto-char post)
22789 (forward-line)
22790 (point)))
22791 ((memq type '(footnote-definition item plain-list))
22792 ;; Contents in these elements could start on
22793 ;; the same line as the beginning of the
22794 ;; element. Make sure we start indenting
22795 ;; from the second line.
22796 (org-with-wide-buffer
22797 (goto-char post)
22798 (end-of-line)
22799 (skip-chars-forward " \r\t\n")
22800 (if (eobp) (point) (line-beginning-position))))
22801 (t (org-element-property :contents-begin element)))))
22802 (cend (copy-marker
22803 (or (org-element-property :contents-end element)
22804 ;; Fake contents for source blocks.
22805 (org-with-wide-buffer
22806 (goto-char element-end)
22807 (skip-chars-backward " \r\t\n")
22808 (line-beginning-position)))
22809 t)))
22810 ;; Do not change items indentation individually as it
22811 ;; might break the list as a whole. On the other
22812 ;; hand, when at a plain list, indent it as a whole.
22813 (cond ((eq type 'plain-list)
22814 (let ((offset (- ind (org-get-indentation))))
22815 (unless (zerop offset)
22816 (indent-rigidly (org-element-property :begin element)
22817 (org-element-property :end element)
22818 offset))
22819 (goto-char cbeg)))
22820 ((eq type 'item) (goto-char cbeg))
22821 (t (funcall indent-to ind cbeg)))
22822 (when (< (point) end)
22823 (case type
22824 ((example-block export-block verse-block))
22825 (src-block
22826 ;; In a source block, indent source code
22827 ;; according to language major mode, but only if
22828 ;; `org-src-tab-acts-natively' is non-nil.
22829 (when (and (< (point) end) org-src-tab-acts-natively)
22830 (ignore-errors
22831 (org-babel-do-in-edit-buffer
22832 (indent-region (point-min) (point-max))))))
22833 (t (org-indent-region (point) (min cend end))))
22834 (goto-char (min cend end))
22835 (when (< (point) end) (funcall indent-to ind element-end)))
22836 (set-marker post nil)
22837 (set-marker cbeg nil)
22838 (set-marker cend nil))))
22839 (set-marker element-end nil))))
22840 (set-marker end nil))))
22842 (defun org-indent-drawer ()
22843 "Indent the drawer at point."
22844 (interactive)
22845 (unless (save-excursion
22846 (beginning-of-line)
22847 (org-looking-at-p org-drawer-regexp))
22848 (user-error "Not at a drawer"))
22849 (let ((element (org-element-at-point)))
22850 (unless (memq (org-element-type element) '(drawer property-drawer))
22851 (user-error "Not at a drawer"))
22852 (org-with-wide-buffer
22853 (org-indent-region (org-element-property :begin element)
22854 (org-element-property :end element))))
22855 (message "Drawer at point indented"))
22857 (defun org-indent-block ()
22858 "Indent the block at point."
22859 (interactive)
22860 (unless (save-excursion
22861 (beginning-of-line)
22862 (let ((case-fold-search t))
22863 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22864 (user-error "Not at a block"))
22865 (let ((element (org-element-at-point)))
22866 (unless (memq (org-element-type element)
22867 '(comment-block center-block dynamic-block example-block
22868 export-block quote-block special-block
22869 src-block verse-block))
22870 (user-error "Not at a block"))
22871 (org-with-wide-buffer
22872 (org-indent-region (org-element-property :begin element)
22873 (org-element-property :end element))))
22874 (message "Block at point indented"))
22877 ;;; Filling
22879 ;; We use our own fill-paragraph and auto-fill functions.
22881 ;; `org-fill-paragraph' relies on adaptive filling and context
22882 ;; checking. Appropriate `fill-prefix' is computed with
22883 ;; `org-adaptive-fill-function'.
22885 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22886 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22887 ;; `org-adaptive-fill-function' value. Internally,
22888 ;; `org-comment-line-break-function' breaks the line.
22890 ;; `org-setup-filling' installs filling and auto-filling related
22891 ;; variables during `org-mode' initialization.
22893 (defvar org-element-paragraph-separate) ; org-element.el
22894 (defun org-setup-filling ()
22895 (require 'org-element)
22896 ;; Prevent auto-fill from inserting unwanted new items.
22897 (when (boundp 'fill-nobreak-predicate)
22898 (org-set-local
22899 'fill-nobreak-predicate
22900 (org-uniquify
22901 (append fill-nobreak-predicate
22902 '(org-fill-line-break-nobreak-p
22903 org-fill-paragraph-with-timestamp-nobreak-p)))))
22904 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22905 (org-set-local 'paragraph-start paragraph-ending)
22906 (org-set-local 'paragraph-separate paragraph-ending))
22907 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22908 (org-set-local 'auto-fill-inhibit-regexp nil)
22909 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22910 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22911 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22913 (defun org-fill-line-break-nobreak-p ()
22914 "Non-nil when a new line at point would create an Org line break."
22915 (save-excursion
22916 (skip-chars-backward "[ \t]")
22917 (skip-chars-backward "\\\\")
22918 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22920 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22921 "Non-nil when a new line at point would split a timestamp."
22922 (and (org-at-timestamp-p t)
22923 (not (looking-at org-ts-regexp-both))))
22925 (declare-function message-in-body-p "message" ())
22926 (defvar orgtbl-line-start-regexp) ; From org-table.el
22927 (defun org-adaptive-fill-function ()
22928 "Compute a fill prefix for the current line.
22929 Return fill prefix, as a string, or nil if current line isn't
22930 meant to be filled. For convenience, if `adaptive-fill-regexp'
22931 matches in paragraphs or comments, use it."
22932 (catch 'exit
22933 (when (derived-mode-p 'message-mode)
22934 (save-excursion
22935 (beginning-of-line)
22936 (cond ((or (not (message-in-body-p))
22937 (looking-at orgtbl-line-start-regexp))
22938 (throw 'exit nil))
22939 ((looking-at message-cite-prefix-regexp)
22940 (throw 'exit (match-string-no-properties 0)))
22941 ((looking-at org-outline-regexp)
22942 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22943 (org-with-wide-buffer
22944 (unless (org-at-heading-p)
22945 (let* ((p (line-beginning-position))
22946 (element (save-excursion
22947 (beginning-of-line)
22948 (org-element-at-point)))
22949 (type (org-element-type element))
22950 (post-affiliated (org-element-property :post-affiliated element)))
22951 (unless (< p post-affiliated)
22952 (case type
22953 (comment
22954 (save-excursion
22955 (beginning-of-line)
22956 (looking-at "[ \t]*")
22957 (concat (match-string 0) "# ")))
22958 (footnote-definition "")
22959 ((item plain-list)
22960 (make-string (org-list-item-body-column post-affiliated) ?\s))
22961 (paragraph
22962 ;; Fill prefix is usually the same as the current line,
22963 ;; unless the paragraph is at the beginning of an item.
22964 (let ((parent (org-element-property :parent element)))
22965 (save-excursion
22966 (beginning-of-line)
22967 (cond ((eq (org-element-type parent) 'item)
22968 (make-string (org-list-item-body-column
22969 (org-element-property :begin parent))
22970 ?\s))
22971 ((and adaptive-fill-regexp
22972 ;; Locally disable
22973 ;; `adaptive-fill-function' to let
22974 ;; `fill-context-prefix' handle
22975 ;; `adaptive-fill-regexp' variable.
22976 (let (adaptive-fill-function)
22977 (fill-context-prefix
22978 post-affiliated
22979 (org-element-property :end element)))))
22980 ((looking-at "[ \t]+") (match-string 0))
22981 (t "")))))
22982 (comment-block
22983 ;; Only fill contents if P is within block boundaries.
22984 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22985 (forward-line)
22986 (point)))
22987 (cend (save-excursion
22988 (goto-char (org-element-property :end element))
22989 (skip-chars-backward " \r\t\n")
22990 (line-beginning-position))))
22991 (when (and (>= p cbeg) (< p cend))
22992 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22993 (match-string 0)
22994 "")))))))))))
22996 (declare-function message-goto-body "message" ())
22997 (defvar message-cite-prefix-regexp) ; From message.el
22998 (defun org-fill-paragraph (&optional justify)
22999 "Fill element at point, when applicable.
23001 This function only applies to comment blocks, comments, example
23002 blocks and paragraphs. Also, as a special case, re-align table
23003 when point is at one.
23005 If JUSTIFY is non-nil (interactively, with prefix argument),
23006 justify as well. If `sentence-end-double-space' is non-nil, then
23007 period followed by one space does not end a sentence, so don't
23008 break a line there. The variable `fill-column' controls the
23009 width for filling.
23011 For convenience, when point is at a plain list, an item or
23012 a footnote definition, try to fill the first paragraph within."
23013 (interactive)
23014 (if (and (derived-mode-p 'message-mode)
23015 (or (not (message-in-body-p))
23016 (save-excursion (move-beginning-of-line 1)
23017 (looking-at message-cite-prefix-regexp))))
23018 ;; First ensure filling is correct in message-mode.
23019 (let ((fill-paragraph-function
23020 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
23021 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
23022 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
23023 (paragraph-separate
23024 (cadadr (assoc 'paragraph-separate org-fb-vars))))
23025 (fill-paragraph nil))
23026 (with-syntax-table org-mode-transpose-word-syntax-table
23027 ;; Move to end of line in order to get the first paragraph
23028 ;; within a plain list or a footnote definition.
23029 (let ((element (save-excursion
23030 (end-of-line)
23031 (or (ignore-errors (org-element-at-point))
23032 (user-error "An element cannot be parsed line %d"
23033 (line-number-at-pos (point)))))))
23034 ;; First check if point is in a blank line at the beginning of
23035 ;; the buffer. In that case, ignore filling.
23036 (case (org-element-type element)
23037 ;; Use major mode filling function is src blocks.
23038 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23039 ;; Align Org tables, leave table.el tables as-is.
23040 (table-row (org-table-align) t)
23041 (table
23042 (when (eq (org-element-property :type element) 'org)
23043 (save-excursion
23044 (goto-char (org-element-property :post-affiliated element))
23045 (org-table-align)))
23047 (paragraph
23048 ;; Paragraphs may contain `line-break' type objects.
23049 (let ((beg (max (point-min)
23050 (org-element-property :contents-begin element)))
23051 (end (min (point-max)
23052 (org-element-property :contents-end element))))
23053 ;; Do nothing if point is at an affiliated keyword.
23054 (if (< (line-end-position) beg) t
23055 (when (derived-mode-p 'message-mode)
23056 ;; In `message-mode', do not fill following citation
23057 ;; in current paragraph nor text before message body.
23058 (let ((body-start (save-excursion (message-goto-body))))
23059 (when body-start (setq beg (max body-start beg))))
23060 (when (save-excursion
23061 (re-search-forward
23062 (concat "^" message-cite-prefix-regexp) end t))
23063 (setq end (match-beginning 0))))
23064 ;; Fill paragraph, taking line breaks into account.
23065 (save-excursion
23066 (goto-char beg)
23067 (let ((cuts (list beg)))
23068 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23069 (when (eq 'line-break
23070 (org-element-type
23071 (save-excursion (backward-char)
23072 (org-element-context))))
23073 (push (point) cuts)))
23074 (dolist (c (delq end cuts))
23075 (fill-region-as-paragraph c end justify)
23076 (setq end c))))
23077 t)))
23078 ;; Contents of `comment-block' type elements should be
23079 ;; filled as plain text, but only if point is within block
23080 ;; markers.
23081 (comment-block
23082 (let* ((case-fold-search t)
23083 (beg (save-excursion
23084 (goto-char (org-element-property :begin element))
23085 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23086 (forward-line)
23087 (point)))
23088 (end (save-excursion
23089 (goto-char (org-element-property :end element))
23090 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23091 (line-beginning-position))))
23092 (if (or (< (point) beg) (> (point) end)) t
23093 (fill-region-as-paragraph
23094 (save-excursion (end-of-line)
23095 (re-search-backward "^[ \t]*$" beg 'move)
23096 (line-beginning-position))
23097 (save-excursion (beginning-of-line)
23098 (re-search-forward "^[ \t]*$" end 'move)
23099 (line-beginning-position))
23100 justify))))
23101 ;; Fill comments.
23102 (comment
23103 (let ((begin (org-element-property :post-affiliated element))
23104 (end (org-element-property :end element)))
23105 (when (and (>= (point) begin) (<= (point) end))
23106 (let ((begin (save-excursion
23107 (end-of-line)
23108 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23109 (progn (forward-line) (point))
23110 begin)))
23111 (end (save-excursion
23112 (end-of-line)
23113 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23114 (1- (line-beginning-position))
23115 (skip-chars-backward " \r\t\n")
23116 (line-end-position)))))
23117 ;; Do not fill comments when at a blank line.
23118 (when (> end begin)
23119 (let ((fill-prefix
23120 (save-excursion
23121 (beginning-of-line)
23122 (looking-at "[ \t]*#")
23123 (let ((comment-prefix (match-string 0)))
23124 (goto-char (match-end 0))
23125 (if (looking-at adaptive-fill-regexp)
23126 (concat comment-prefix (match-string 0))
23127 (concat comment-prefix " "))))))
23128 (save-excursion
23129 (fill-region-as-paragraph begin end justify))))))
23131 ;; Ignore every other element.
23132 (otherwise t))))))
23134 (defun org-auto-fill-function ()
23135 "Auto-fill function."
23136 ;; Check if auto-filling is meaningful.
23137 (let ((fc (current-fill-column)))
23138 (when (and fc (> (current-column) fc))
23139 (let* ((fill-prefix (org-adaptive-fill-function))
23140 ;; Enforce empty fill prefix, if required. Otherwise, it
23141 ;; will be computed again.
23142 (adaptive-fill-mode (not (equal fill-prefix ""))))
23143 (when fill-prefix (do-auto-fill))))))
23145 (defun org-comment-line-break-function (&optional soft)
23146 "Break line at point and indent, continuing comment if within one.
23147 The inserted newline is marked hard if variable
23148 `use-hard-newlines' is true, unless optional argument SOFT is
23149 non-nil."
23150 (if soft (insert-and-inherit ?\n) (newline 1))
23151 (save-excursion (forward-char -1) (delete-horizontal-space))
23152 (delete-horizontal-space)
23153 (indent-to-left-margin)
23154 (insert-before-markers-and-inherit fill-prefix))
23157 ;;; Fixed Width Areas
23159 (defun org-toggle-fixed-width ()
23160 "Toggle fixed-width markup.
23162 Add or remove fixed-width markup on current line, whenever it
23163 makes sense. Return an error otherwise.
23165 If a region is active and if it contains only fixed-width areas
23166 or blank lines, remove all fixed-width markup in it. If the
23167 region contains anything else, convert all non-fixed-width lines
23168 to fixed-width ones.
23170 Blank lines at the end of the region are ignored unless the
23171 region only contains such lines."
23172 (interactive)
23173 (if (not (org-region-active-p))
23174 ;; No region:
23176 ;; Remove fixed width marker only in a fixed-with element.
23178 ;; Add fixed width maker in paragraphs, in blank lines after
23179 ;; elements or at the beginning of a headline or an inlinetask,
23180 ;; and before any one-line elements (e.g., a clock).
23181 (progn
23182 (beginning-of-line)
23183 (let* ((element (org-element-at-point))
23184 (type (org-element-type element)))
23185 (cond
23186 ((and (eq type 'fixed-width)
23187 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23188 (replace-match
23189 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23190 ((and (memq type '(babel-call clock comment diary-sexp headline
23191 horizontal-rule keyword paragraph
23192 planning))
23193 (<= (org-element-property :post-affiliated element) (point)))
23194 (skip-chars-forward " \t")
23195 (insert ": "))
23196 ((and (org-looking-at-p "[ \t]*$")
23197 (or (eq type 'inlinetask)
23198 (save-excursion
23199 (skip-chars-forward " \r\t\n")
23200 (<= (org-element-property :end element) (point)))))
23201 (delete-region (point) (line-end-position))
23202 (org-indent-line)
23203 (insert ": "))
23204 (t (user-error "Cannot insert a fixed-width line here")))))
23205 ;; Region active.
23206 (let* ((begin (save-excursion
23207 (goto-char (region-beginning))
23208 (line-beginning-position)))
23209 (end (copy-marker
23210 (save-excursion
23211 (goto-char (region-end))
23212 (unless (eolp) (beginning-of-line))
23213 (if (save-excursion (re-search-backward "\\S-" begin t))
23214 (progn (skip-chars-backward " \r\t\n") (point))
23215 (point)))))
23216 (all-fixed-width-p
23217 (catch 'not-all-p
23218 (save-excursion
23219 (goto-char begin)
23220 (skip-chars-forward " \r\t\n")
23221 (when (eobp) (throw 'not-all-p nil))
23222 (while (< (point) end)
23223 (let ((element (org-element-at-point)))
23224 (if (eq (org-element-type element) 'fixed-width)
23225 (goto-char (org-element-property :end element))
23226 (throw 'not-all-p nil))))
23227 t))))
23228 (if all-fixed-width-p
23229 (save-excursion
23230 (goto-char begin)
23231 (while (< (point) end)
23232 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23233 (replace-match
23234 "" nil nil nil
23235 (if (= (line-end-position) (match-end 0)) 0 1)))
23236 (forward-line)))
23237 (let ((min-ind (point-max)))
23238 ;; Find minimum indentation across all lines.
23239 (save-excursion
23240 (goto-char begin)
23241 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23242 (setq min-ind 0)
23243 (catch 'zerop
23244 (while (< (point) end)
23245 (unless (org-looking-at-p "[ \t]*$")
23246 (let ((ind (org-get-indentation)))
23247 (setq min-ind (min min-ind ind))
23248 (when (zerop ind) (throw 'zerop t))))
23249 (forward-line)))))
23250 ;; Loop over all lines and add fixed-width markup everywhere
23251 ;; but in fixed-width lines.
23252 (save-excursion
23253 (goto-char begin)
23254 (while (< (point) end)
23255 (cond
23256 ((org-at-heading-p)
23257 (insert ": ")
23258 (forward-line)
23259 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23260 (insert ":")
23261 (forward-line)))
23262 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23263 (let* ((element (org-element-at-point))
23264 (element-end (org-element-property :end element)))
23265 (if (eq (org-element-type element) 'fixed-width)
23266 (progn (goto-char element-end)
23267 (skip-chars-backward " \r\t\n")
23268 (forward-line))
23269 (let ((limit (min end element-end)))
23270 (while (< (point) limit)
23271 (org-move-to-column min-ind t)
23272 (insert ": ")
23273 (forward-line))))))
23275 (org-move-to-column min-ind t)
23276 (insert ": ")
23277 (forward-line)))))))
23278 (set-marker end nil))))
23281 ;;; Comments
23283 ;; Org comments syntax is quite complex. It requires the entire line
23284 ;; to be just a comment. Also, even with the right syntax at the
23285 ;; beginning of line, some some elements (i.e. verse-block or
23286 ;; example-block) don't accept comments. Usual Emacs comment commands
23287 ;; cannot cope with those requirements. Therefore, Org replaces them.
23289 ;; Org still relies on `comment-dwim', but cannot trust
23290 ;; `comment-only-p'. So, `comment-region-function' and
23291 ;; `uncomment-region-function' both point
23292 ;; to`org-comment-or-uncomment-region'. Eventually,
23293 ;; `org-insert-comment' takes care of insertion of comments at the
23294 ;; beginning of line.
23296 ;; `org-setup-comments-handling' install comments related variables
23297 ;; during `org-mode' initialization.
23299 (defun org-setup-comments-handling ()
23300 (interactive)
23301 (org-set-local 'comment-use-syntax nil)
23302 (org-set-local 'comment-start "# ")
23303 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23304 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23305 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23306 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23308 (defun org-insert-comment ()
23309 "Insert an empty comment above current line.
23310 If the line is empty, insert comment at its beginning. When
23311 point is within a source block, comment according to the related
23312 major mode."
23313 (if (let ((element (org-element-at-point)))
23314 (and (eq (org-element-type element) 'src-block)
23315 (< (save-excursion
23316 (goto-char (org-element-property :post-affiliated element))
23317 (line-end-position))
23318 (point))
23319 (> (save-excursion
23320 (goto-char (org-element-property :end element))
23321 (skip-chars-backward " \r\t\n")
23322 (line-beginning-position))
23323 (point))))
23324 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23325 (beginning-of-line)
23326 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23327 (open-line 1))
23328 (org-indent-line)
23329 (insert "# ")))
23331 (defvar comment-empty-lines) ; From newcomment.el.
23332 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23333 "Comment or uncomment each non-blank line in the region.
23334 Uncomment each non-blank line between BEG and END if it only
23335 contains commented lines. Otherwise, comment them. If region is
23336 strictly within a source block, use appropriate comment syntax."
23337 (if (let ((element (org-element-at-point)))
23338 (and (eq (org-element-type element) 'src-block)
23339 (< (save-excursion
23340 (goto-char (org-element-property :post-affiliated element))
23341 (line-end-position))
23342 beg)
23343 (>= (save-excursion
23344 (goto-char (org-element-property :end element))
23345 (skip-chars-backward " \r\t\n")
23346 (line-beginning-position))
23347 end)))
23348 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23349 (save-restriction
23350 ;; Restrict region
23351 (narrow-to-region (save-excursion (goto-char beg)
23352 (skip-chars-forward " \r\t\n" end)
23353 (line-beginning-position))
23354 (save-excursion (goto-char end)
23355 (skip-chars-backward " \r\t\n" beg)
23356 (line-end-position)))
23357 (let ((uncommentp
23358 ;; UNCOMMENTP is non-nil when every non blank line between
23359 ;; BEG and END is a comment.
23360 (save-excursion
23361 (goto-char (point-min))
23362 (while (and (not (eobp))
23363 (let ((element (org-element-at-point)))
23364 (and (eq (org-element-type element) 'comment)
23365 (goto-char (min (point-max)
23366 (org-element-property
23367 :end element)))))))
23368 (eobp))))
23369 (if uncommentp
23370 ;; Only blank lines and comments in region: uncomment it.
23371 (save-excursion
23372 (goto-char (point-min))
23373 (while (not (eobp))
23374 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23375 (replace-match "" nil nil nil 1))
23376 (forward-line)))
23377 ;; Comment each line in region.
23378 (let ((min-indent (point-max)))
23379 ;; First find the minimum indentation across all lines.
23380 (save-excursion
23381 (goto-char (point-min))
23382 (while (and (not (eobp)) (not (zerop min-indent)))
23383 (unless (looking-at "[ \t]*$")
23384 (setq min-indent (min min-indent (current-indentation))))
23385 (forward-line)))
23386 ;; Then loop over all lines.
23387 (save-excursion
23388 (goto-char (point-min))
23389 (while (not (eobp))
23390 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23391 ;; Don't get fooled by invisible text (e.g. link path)
23392 ;; when moving to column MIN-INDENT.
23393 (let ((buffer-invisibility-spec nil))
23394 (org-move-to-column min-indent t))
23395 (insert comment-start))
23396 (forward-line)))))))))
23398 (defun org-comment-dwim (arg)
23399 "Call `comment-dwim' within a source edit buffer if needed."
23400 (interactive "*P")
23401 (if (org-in-src-block-p)
23402 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23403 (call-interactively 'comment-dwim)))
23406 ;;; Timestamps API
23408 ;; This section contains tools to operate on timestamp objects, as
23409 ;; returned by, e.g. `org-element-context'.
23411 (defun org-timestamp-has-time-p (timestamp)
23412 "Non-nil when TIMESTAMP has a time specified."
23413 (org-element-property :hour-start timestamp))
23415 (defun org-timestamp-format (timestamp format &optional end utc)
23416 "Format a TIMESTAMP element into a string.
23418 FORMAT is a format specifier to be passed to
23419 `format-time-string'.
23421 When optional argument END is non-nil, use end of date-range or
23422 time-range, if possible.
23424 When optional argument UTC is non-nil, time will be expressed as
23425 Universal Time."
23426 (format-time-string
23427 format
23428 (apply 'encode-time
23429 (cons 0
23430 (mapcar
23431 (lambda (prop) (or (org-element-property prop timestamp) 0))
23432 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23433 '(:minute-start :hour-start :day-start :month-start
23434 :year-start)))))
23435 utc))
23437 (defun org-timestamp-split-range (timestamp &optional end)
23438 "Extract a timestamp object from a date or time range.
23440 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23441 the end of the range. Otherwise, extract its start.
23443 Return a new timestamp object sharing the same parent as
23444 TIMESTAMP."
23445 (let ((type (org-element-property :type timestamp)))
23446 (if (memq type '(active inactive diary)) timestamp
23447 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23448 ;; Set new type.
23449 (org-element-put-property
23450 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23451 ;; Copy start properties over end properties if END is
23452 ;; non-nil. Otherwise, copy end properties over `start' ones.
23453 (let ((p-alist '((:minute-start . :minute-end)
23454 (:hour-start . :hour-end)
23455 (:day-start . :day-end)
23456 (:month-start . :month-end)
23457 (:year-start . :year-end))))
23458 (dolist (p-cell p-alist)
23459 (org-element-put-property
23460 split-ts
23461 (funcall (if end 'car 'cdr) p-cell)
23462 (org-element-property
23463 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23464 ;; Eventually refresh `:raw-value'.
23465 (org-element-put-property split-ts :raw-value nil)
23466 (org-element-put-property
23467 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23469 (defun org-timestamp-translate (timestamp &optional boundary)
23470 "Translate TIMESTAMP object to custom format.
23472 Format string is defined in `org-time-stamp-custom-formats',
23473 which see.
23475 When optional argument BOUNDARY is non-nil, it is either the
23476 symbol `start' or `end'. In this case, only translate the
23477 starting or ending part of TIMESTAMP if it is a date or time
23478 range. Otherwise, translate both parts.
23480 Return timestamp as-is if `org-display-custom-times' is nil or if
23481 it has a `diary' type."
23482 (let ((type (org-element-property :type timestamp)))
23483 (if (or (not org-display-custom-times) (eq type 'diary))
23484 (org-element-interpret-data timestamp)
23485 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23486 org-time-stamp-custom-formats)))
23487 (if (and (not boundary) (memq type '(active-range inactive-range)))
23488 (concat (org-timestamp-format timestamp fmt)
23489 "--"
23490 (org-timestamp-format timestamp fmt t))
23491 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23495 ;;; Other stuff.
23497 (defun org-reftex-citation ()
23498 "Use reftex-citation to insert a citation into the buffer.
23499 This looks for a line like
23501 #+BIBLIOGRAPHY: foo plain option:-d
23503 and derives from it that foo.bib is the bibliography file relevant
23504 for this document. It then installs the necessary environment for RefTeX
23505 to work in this buffer and calls `reftex-citation' to insert a citation
23506 into the buffer.
23508 Export of such citations to both LaTeX and HTML is handled by the contributed
23509 package ox-bibtex by Taru Karttunen."
23510 (interactive)
23511 (let ((reftex-docstruct-symbol 'rds)
23512 (reftex-cite-format "\\cite{%l}")
23513 rds bib)
23514 (save-excursion
23515 (save-restriction
23516 (widen)
23517 (let ((case-fold-search t)
23518 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23519 (if (not (save-excursion
23520 (or (re-search-forward re nil t)
23521 (re-search-backward re nil t))))
23522 (user-error "No bibliography defined in file")
23523 (setq bib (concat (match-string 1) ".bib")
23524 rds (list (list 'bib bib)))))))
23525 (call-interactively 'reftex-citation)))
23527 ;;;; Functions extending outline functionality
23529 (defun org-beginning-of-line (&optional arg)
23530 "Go to the beginning of the current line. If that is invisible, continue
23531 to a visible line beginning. This makes the function of C-a more intuitive.
23532 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23533 first attempt, and only move to after the tags when the cursor is already
23534 beyond the end of the headline."
23535 (interactive "P")
23536 (let ((pos (point))
23537 (special (if (consp org-special-ctrl-a/e)
23538 (car org-special-ctrl-a/e)
23539 org-special-ctrl-a/e))
23540 deactivate-mark refpos)
23541 (if (org-bound-and-true-p visual-line-mode)
23542 (beginning-of-visual-line 1)
23543 (beginning-of-line 1))
23544 (if (and arg (fboundp 'move-beginning-of-line))
23545 (call-interactively 'move-beginning-of-line)
23546 (if (bobp)
23548 (backward-char 1)
23549 (if (org-truely-invisible-p)
23550 (while (and (not (bobp)) (org-truely-invisible-p))
23551 (backward-char 1)
23552 (beginning-of-line 1))
23553 (forward-char 1))))
23554 (when special
23555 (cond
23556 ((and (looking-at org-complex-heading-regexp)
23557 (= (char-after (match-end 1)) ?\ ))
23558 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23559 (point-at-eol)))
23560 (goto-char
23561 (if (eq special t)
23562 (cond ((> pos refpos) refpos)
23563 ((= pos (point)) refpos)
23564 (t (point)))
23565 (cond ((> pos (point)) (point))
23566 ((not (eq last-command this-command)) (point))
23567 (t refpos)))))
23568 ((org-at-item-p)
23569 ;; Being at an item and not looking at an the item means point
23570 ;; was previously moved to beginning of a visual line, which
23571 ;; doesn't contain the item. Therefore, do nothing special,
23572 ;; just stay here.
23573 (when (looking-at org-list-full-item-re)
23574 ;; Set special position at first white space character after
23575 ;; bullet, and check-box, if any.
23576 (let ((after-bullet
23577 (let ((box (match-end 3)))
23578 (if (not box) (match-end 1)
23579 (let ((after (char-after box)))
23580 (if (and after (= after ? )) (1+ box) box))))))
23581 ;; Special case: Move point to special position when
23582 ;; currently after it or at beginning of line.
23583 (if (eq special t)
23584 (when (or (> pos after-bullet) (= (point) pos))
23585 (goto-char after-bullet))
23586 ;; Reversed case: Move point to special position when
23587 ;; point was already at beginning of line and command is
23588 ;; repeated.
23589 (when (and (= (point) pos) (eq last-command this-command))
23590 (goto-char after-bullet))))))))
23591 (org-no-warnings
23592 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23593 (setq disable-point-adjustment
23594 (or (not (invisible-p (point)))
23595 (not (invisible-p (max (point-min) (1- (point))))))))
23597 (defun org-end-of-line (&optional arg)
23598 "Go to the end of the line.
23599 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23600 tags on the first attempt, and only move to after the tags when
23601 the cursor is already beyond the end of the headline."
23602 (interactive "P")
23603 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23604 org-special-ctrl-a/e))
23605 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23606 'end-of-visual-line)
23607 ((fboundp 'move-end-of-line) 'move-end-of-line)
23608 (t 'end-of-line)))
23609 deactivate-mark)
23610 (if (or (not special) arg) (call-interactively move-fun)
23611 (let* ((element (save-excursion (beginning-of-line)
23612 (org-element-at-point)))
23613 (type (org-element-type element)))
23614 (cond
23615 ((memq type '(headline inlinetask))
23616 (let ((pos (point)))
23617 (beginning-of-line 1)
23618 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23619 (if (eq special t)
23620 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23621 (goto-char (match-beginning 1))
23622 (goto-char (match-end 0)))
23623 (if (or (< pos (match-end 0))
23624 (not (eq this-command last-command)))
23625 (goto-char (match-end 0))
23626 (goto-char (match-beginning 1))))
23627 (call-interactively move-fun))))
23628 ((outline-invisible-p (line-end-position))
23629 ;; If element is hidden, `move-end-of-line' would put point
23630 ;; after it. Use `end-of-line' to stay on current line.
23631 (call-interactively 'end-of-line))
23632 (t (call-interactively move-fun)))))
23633 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23634 (setq disable-point-adjustment
23635 (or (not (invisible-p (point)))
23636 (not (invisible-p (max (point-min) (1- (point))))))))
23638 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23639 (define-key org-mode-map "\C-e" 'org-end-of-line)
23641 (defun org-backward-sentence (&optional arg)
23642 "Go to beginning of sentence, or beginning of table field.
23643 This will call `backward-sentence' or `org-table-beginning-of-field',
23644 depending on context."
23645 (interactive "P")
23646 (cond
23647 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23648 (t (call-interactively 'backward-sentence))))
23650 (defun org-forward-sentence (&optional arg)
23651 "Go to end of sentence, or end of table field.
23652 This will call `forward-sentence' or `org-table-end-of-field',
23653 depending on context."
23654 (interactive "P")
23655 (cond
23656 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23657 (t (call-interactively 'forward-sentence))))
23659 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23660 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23662 (defun org-kill-line (&optional arg)
23663 "Kill line, to tags or end of line."
23664 (interactive "P")
23665 (cond
23666 ((or (not org-special-ctrl-k)
23667 (bolp)
23668 (not (org-at-heading-p)))
23669 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23670 org-ctrl-k-protect-subtree)
23671 (if (or (eq org-ctrl-k-protect-subtree 'error)
23672 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23673 (user-error "C-k aborted as it would kill a hidden subtree")))
23674 (call-interactively
23675 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23676 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23677 (kill-region (point) (match-beginning 1))
23678 (org-set-tags nil t))
23679 (t (kill-region (point) (point-at-eol)))))
23681 (define-key org-mode-map "\C-k" 'org-kill-line)
23683 (defun org-yank (&optional arg)
23684 "Yank. If the kill is a subtree, treat it specially.
23685 This command will look at the current kill and check if is a single
23686 subtree, or a series of subtrees[1]. If it passes the test, and if the
23687 cursor is at the beginning of a line or after the stars of a currently
23688 empty headline, then the yank is handled specially. How exactly depends
23689 on the value of the following variables, both set by default.
23691 `org-yank-folded-subtrees'
23692 When set, the subtree(s) will be folded after insertion, but only
23693 if doing so would now swallow text after the yanked text.
23695 `org-yank-adjusted-subtrees'
23696 When set, the subtree will be promoted or demoted in order to
23697 fit into the local outline tree structure, which means that the
23698 level will be adjusted so that it becomes the smaller one of the
23699 two *visible* surrounding headings.
23701 Any prefix to this command will cause `yank' to be called directly with
23702 no special treatment. In particular, a simple \\[universal-argument] prefix \
23703 will just
23704 plainly yank the text as it is.
23706 \[1] The test checks if the first non-white line is a heading
23707 and if there are no other headings with fewer stars."
23708 (interactive "P")
23709 (org-yank-generic 'yank arg))
23711 (defun org-yank-generic (command arg)
23712 "Perform some yank-like command.
23714 This function implements the behavior described in the `org-yank'
23715 documentation. However, it has been generalized to work for any
23716 interactive command with similar behavior."
23718 ;; pretend to be command COMMAND
23719 (setq this-command command)
23721 (if arg
23722 (call-interactively command)
23724 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23725 (and (org-kill-is-subtree-p)
23726 (or (bolp)
23727 (and (looking-at "[ \t]*$")
23728 (string-match
23729 "\\`\\*+\\'"
23730 (buffer-substring (point-at-bol) (point)))))))
23731 swallowp)
23732 (cond
23733 ((and subtreep org-yank-folded-subtrees)
23734 (let ((beg (point))
23735 end)
23736 (if (and subtreep org-yank-adjusted-subtrees)
23737 (org-paste-subtree nil nil 'for-yank)
23738 (call-interactively command))
23740 (setq end (point))
23741 (goto-char beg)
23742 (when (and (bolp) subtreep
23743 (not (setq swallowp
23744 (org-yank-folding-would-swallow-text beg end))))
23745 (org-with-limited-levels
23746 (or (looking-at org-outline-regexp)
23747 (re-search-forward org-outline-regexp-bol end t))
23748 (while (and (< (point) end) (looking-at org-outline-regexp))
23749 (hide-subtree)
23750 (org-cycle-show-empty-lines 'folded)
23751 (condition-case nil
23752 (outline-forward-same-level 1)
23753 (error (goto-char end))))))
23754 (when swallowp
23755 (message
23756 "Inserted text not folded because that would swallow text"))
23758 (goto-char end)
23759 (skip-chars-forward " \t\n\r")
23760 (beginning-of-line 1)
23761 (push-mark beg 'nomsg)))
23762 ((and subtreep org-yank-adjusted-subtrees)
23763 (let ((beg (point-at-bol)))
23764 (org-paste-subtree nil nil 'for-yank)
23765 (push-mark beg 'nomsg)))
23767 (call-interactively command))))))
23769 (defun org-yank-folding-would-swallow-text (beg end)
23770 "Would hide-subtree at BEG swallow any text after END?"
23771 (let (level)
23772 (org-with-limited-levels
23773 (save-excursion
23774 (goto-char beg)
23775 (when (or (looking-at org-outline-regexp)
23776 (re-search-forward org-outline-regexp-bol end t))
23777 (setq level (org-outline-level)))
23778 (goto-char end)
23779 (skip-chars-forward " \t\r\n\v\f")
23780 (if (or (eobp)
23781 (and (bolp) (looking-at org-outline-regexp)
23782 (<= (org-outline-level) level)))
23783 nil ; Nothing would be swallowed
23784 t))))) ; something would swallow
23786 (define-key org-mode-map "\C-y" 'org-yank)
23788 (defun org-truely-invisible-p ()
23789 "Check if point is at a character currently not visible.
23790 This version does not only check the character property, but also
23791 `visible-mode'."
23792 ;; Early versions of noutline don't have `outline-invisible-p'.
23793 (if (org-bound-and-true-p visible-mode)
23795 (outline-invisible-p)))
23797 (defun org-invisible-p2 ()
23798 "Check if point is at a character currently not visible."
23799 (save-excursion
23800 (if (and (eolp) (not (bobp))) (backward-char 1))
23801 ;; Early versions of noutline don't have `outline-invisible-p'.
23802 (outline-invisible-p)))
23804 (defun org-back-to-heading (&optional invisible-ok)
23805 "Call `outline-back-to-heading', but provide a better error message."
23806 (condition-case nil
23807 (outline-back-to-heading invisible-ok)
23808 (error (error "Before first headline at position %d in buffer %s"
23809 (point) (current-buffer)))))
23811 (defun org-before-first-heading-p ()
23812 "Before first heading?"
23813 (save-excursion
23814 (end-of-line)
23815 (null (re-search-backward org-outline-regexp-bol nil t))))
23817 (defun org-at-heading-p (&optional ignored)
23818 (outline-on-heading-p t))
23819 ;; Compatibility alias with Org versions < 7.8.03
23820 (defalias 'org-on-heading-p 'org-at-heading-p)
23822 (defun org-in-commented-heading-p (&optional no-inheritance)
23823 "Non-nil if point is under a commented heading.
23824 This function also checks ancestors of the current headline,
23825 unless optional argument NO-INHERITANCE is non-nil."
23826 (cond
23827 ((org-before-first-heading-p) nil)
23828 ((let ((headline (nth 4 (org-heading-components))))
23829 (and headline
23830 (let ((case-fold-search nil))
23831 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23832 headline)))))
23833 (no-inheritance nil)
23835 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23837 (defun org-at-comment-p nil
23838 "Is cursor in a commented line?"
23839 (save-excursion
23840 (save-match-data
23841 (beginning-of-line)
23842 (looking-at "^[ \t]*# "))))
23844 (defun org-at-drawer-p nil
23845 "Is cursor at a drawer keyword?"
23846 (save-excursion
23847 (move-beginning-of-line 1)
23848 (looking-at org-drawer-regexp)))
23850 (defun org-at-block-p nil
23851 "Is cursor at a block keyword?"
23852 (save-excursion
23853 (move-beginning-of-line 1)
23854 (looking-at org-block-regexp)))
23856 (defun org-point-at-end-of-empty-headline ()
23857 "If point is at the end of an empty headline, return t, else nil.
23858 If the heading only contains a TODO keyword, it is still still considered
23859 empty."
23860 (and (looking-at "[ \t]*$")
23861 (when org-todo-line-regexp
23862 (save-excursion
23863 (beginning-of-line 1)
23864 (let ((case-fold-search nil))
23865 (looking-at org-todo-line-regexp)
23866 (string= (match-string 3) ""))))))
23868 (defun org-at-heading-or-item-p ()
23869 (or (org-at-heading-p) (org-at-item-p)))
23871 (defun org-at-target-p ()
23872 (or (org-in-regexp org-radio-target-regexp)
23873 (org-in-regexp org-target-regexp)))
23874 ;; Compatibility alias with Org versions < 7.8.03
23875 (defalias 'org-on-target-p 'org-at-target-p)
23877 (defun org-up-heading-all (arg)
23878 "Move to the heading line of which the present line is a subheading.
23879 This function considers both visible and invisible heading lines.
23880 With argument, move up ARG levels."
23881 (if (fboundp 'outline-up-heading-all)
23882 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23883 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23885 (defun org-up-heading-safe ()
23886 "Move to the heading line of which the present line is a subheading.
23887 This version will not throw an error. It will return the level of the
23888 headline found, or nil if no higher level is found.
23890 Also, this function will be a lot faster than `outline-up-heading',
23891 because it relies on stars being the outline starters. This can really
23892 make a significant difference in outlines with very many siblings."
23893 (when (ignore-errors (org-back-to-heading t))
23894 (let ((level-up (1- (funcall outline-level))))
23895 (and (> level-up 0)
23896 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23897 (funcall outline-level)))))
23899 (defun org-first-sibling-p ()
23900 "Is this heading the first child of its parents?"
23901 (interactive)
23902 (let ((re org-outline-regexp-bol)
23903 level l)
23904 (unless (org-at-heading-p t)
23905 (user-error "Not at a heading"))
23906 (setq level (funcall outline-level))
23907 (save-excursion
23908 (if (not (re-search-backward re nil t))
23910 (setq l (funcall outline-level))
23911 (< l level)))))
23913 (defun org-goto-sibling (&optional previous)
23914 "Goto the next sibling, even if it is invisible.
23915 When PREVIOUS is set, go to the previous sibling instead. Returns t
23916 when a sibling was found. When none is found, return nil and don't
23917 move point."
23918 (let ((fun (if previous 're-search-backward 're-search-forward))
23919 (pos (point))
23920 (re org-outline-regexp-bol)
23921 level l)
23922 (when (ignore-errors (org-back-to-heading t))
23923 (setq level (funcall outline-level))
23924 (catch 'exit
23925 (or previous (forward-char 1))
23926 (while (funcall fun re nil t)
23927 (setq l (funcall outline-level))
23928 (when (< l level) (goto-char pos) (throw 'exit nil))
23929 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23930 (goto-char pos)
23931 nil))))
23933 (defun org-show-siblings ()
23934 "Show all siblings of the current headline."
23935 (save-excursion
23936 (while (org-goto-sibling) (org-flag-heading nil)))
23937 (save-excursion
23938 (while (org-goto-sibling 'previous)
23939 (org-flag-heading nil))))
23941 (defun org-goto-first-child ()
23942 "Goto the first child, even if it is invisible.
23943 Return t when a child was found. Otherwise don't move point and
23944 return nil."
23945 (let (level (pos (point)) (re org-outline-regexp-bol))
23946 (when (ignore-errors (org-back-to-heading t))
23947 (setq level (outline-level))
23948 (forward-char 1)
23949 (if (and (re-search-forward re nil t) (> (outline-level) level))
23950 (progn (goto-char (match-beginning 0)) t)
23951 (goto-char pos) nil))))
23953 (defun org-show-hidden-entry ()
23954 "Show an entry where even the heading is hidden."
23955 (save-excursion
23956 (org-show-entry)))
23958 (defun org-flag-heading (flag &optional entry)
23959 "Flag the current heading. FLAG non-nil means make invisible.
23960 When ENTRY is non-nil, show the entire entry."
23961 (save-excursion
23962 (org-back-to-heading t)
23963 ;; Check if we should show the entire entry
23964 (if entry
23965 (progn
23966 (org-show-entry)
23967 (save-excursion
23968 (and (outline-next-heading)
23969 (org-flag-heading nil))))
23970 (outline-flag-region (max (point-min) (1- (point)))
23971 (save-excursion (outline-end-of-heading) (point))
23972 flag))))
23974 (defun org-get-next-sibling ()
23975 "Move to next heading of the same level, and return point.
23976 If there is no such heading, return nil.
23977 This is like outline-next-sibling, but invisible headings are ok."
23978 (let ((level (funcall outline-level)))
23979 (outline-next-heading)
23980 (while (and (not (eobp)) (> (funcall outline-level) level))
23981 (outline-next-heading))
23982 (if (or (eobp) (< (funcall outline-level) level))
23984 (point))))
23986 (defun org-get-last-sibling ()
23987 "Move to previous heading of the same level, and return point.
23988 If there is no such heading, return nil."
23989 (let ((opoint (point))
23990 (level (funcall outline-level)))
23991 (outline-previous-heading)
23992 (when (and (/= (point) opoint) (outline-on-heading-p t))
23993 (while (and (> (funcall outline-level) level)
23994 (not (bobp)))
23995 (outline-previous-heading))
23996 (if (< (funcall outline-level) level)
23998 (point)))))
24000 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24001 "Goto to the end of a subtree."
24002 ;; This contains an exact copy of the original function, but it uses
24003 ;; `org-back-to-heading', to make it work also in invisible
24004 ;; trees. And is uses an invisible-ok argument.
24005 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24006 ;; Furthermore, when used inside Org, finding the end of a large subtree
24007 ;; with many children and grandchildren etc, this can be much faster
24008 ;; than the outline version.
24009 (org-back-to-heading invisible-ok)
24010 (let ((first t)
24011 (level (funcall outline-level)))
24012 (if (and (derived-mode-p 'org-mode) (< level 1000))
24013 ;; A true heading (not a plain list item), in Org-mode
24014 ;; This means we can easily find the end by looking
24015 ;; only for the right number of stars. Using a regexp to do
24016 ;; this is so much faster than using a Lisp loop.
24017 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24018 (forward-char 1)
24019 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24020 ;; something else, do it the slow way
24021 (while (and (not (eobp))
24022 (or first (> (funcall outline-level) level)))
24023 (setq first nil)
24024 (outline-next-heading)))
24025 (unless to-heading
24026 (if (memq (preceding-char) '(?\n ?\^M))
24027 (progn
24028 ;; Go to end of line before heading
24029 (forward-char -1)
24030 (if (memq (preceding-char) '(?\n ?\^M))
24031 ;; leave blank line before heading
24032 (forward-char -1))))))
24033 (point))
24035 (defun org-end-of-meta-data-and-drawers ()
24036 "Jump to the first text after meta data and drawers in the current entry.
24037 This will move over empty lines, lines with planning time stamps,
24038 clocking lines, and drawers."
24039 (org-back-to-heading t)
24040 (let ((end (save-excursion (outline-next-heading) (point)))
24041 (re (concat "\\(" org-drawer-regexp "\\)"
24042 "\\|" "[ \t]*" org-keyword-time-regexp)))
24043 (forward-line 1)
24044 (while (re-search-forward re end t)
24045 (if (not (match-end 1))
24046 ;; empty or planning line
24047 (forward-line 1)
24048 ;; a drawer, find the end
24049 (re-search-forward "^[ \t]*:END:" end 'move)
24050 (forward-line 1)))
24051 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
24052 (point)))
24054 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24055 "Move forward to the ARG'th subheading at same level as this one.
24056 Stop at the first and last subheadings of a superior heading.
24057 Normally this only looks at visible headings, but when INVISIBLE-OK is
24058 non-nil it will also look at invisible ones."
24059 (interactive "p")
24060 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24061 (if (and arg (< arg 0))
24062 (goto-char (point-min))
24063 (outline-next-heading))
24064 (org-at-heading-p)
24065 (let ((level (- (match-end 0) (match-beginning 0) 1))
24066 (f (if (and arg (< arg 0))
24067 're-search-backward
24068 're-search-forward))
24069 (count (if arg (abs arg) 1))
24070 (result (point)))
24071 (while (and (prog1 (> count 0)
24072 (forward-char (if (and arg (< arg 0)) -1 1)))
24073 (funcall f org-outline-regexp-bol nil 'move))
24074 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24075 (cond ((< l level) (setq count 0))
24076 ((and (= l level)
24077 (or invisible-ok
24078 (progn
24079 (goto-char (line-beginning-position))
24080 (not (outline-invisible-p)))))
24081 (setq count (1- count))
24082 (when (eq l level)
24083 (setq result (point)))))))
24084 (goto-char result))
24085 (beginning-of-line 1)))
24087 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24088 "Move backward to the ARG'th subheading at same level as this one.
24089 Stop at the first and last subheadings of a superior heading."
24090 (interactive "p")
24091 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24093 (defun org-next-block (arg &optional backward block-regexp)
24094 "Jump to the next block.
24095 With a prefix argument ARG, jump forward ARG many source blocks.
24096 When BACKWARD is non-nil, jump to the previous block.
24097 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24098 (interactive "p")
24099 (let ((re (or block-regexp org-block-regexp))
24100 (re-search-fn (or (and backward 're-search-backward)
24101 're-search-forward)))
24102 (if (looking-at re) (forward-char 1))
24103 (condition-case nil
24104 (funcall re-search-fn re nil nil arg)
24105 (error (user-error "No %s code blocks"
24106 (if backward "previous" "further" ))))
24107 (goto-char (match-beginning 0)) (org-show-context)))
24109 (defun org-previous-block (arg &optional block-regexp)
24110 "Jump to the previous block.
24111 With a prefix argument ARG, jump backward ARG many source blocks.
24112 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24113 (interactive "p")
24114 (org-next-block arg t block-regexp))
24116 (defun org-forward-paragraph ()
24117 "Move forward to beginning of next paragraph or equivalent.
24119 The function moves point to the beginning of the next visible
24120 structural element, which can be a paragraph, a table, a list
24121 item, etc. It also provides some special moves for convenience:
24123 - On an affiliated keyword, jump to the beginning of the
24124 relative element.
24125 - On an item or a footnote definition, move to the second
24126 element inside, if any.
24127 - On a table or a property drawer, jump after it.
24128 - On a verse or source block, stop after blank lines."
24129 (interactive)
24130 (when (eobp) (user-error "Cannot move further down"))
24131 (let* ((deactivate-mark nil)
24132 (element (org-element-at-point))
24133 (type (org-element-type element))
24134 (post-affiliated (org-element-property :post-affiliated element))
24135 (contents-begin (org-element-property :contents-begin element))
24136 (contents-end (org-element-property :contents-end element))
24137 (end (let ((end (org-element-property :end element)) (parent element))
24138 (while (and (setq parent (org-element-property :parent parent))
24139 (= (org-element-property :contents-end parent) end))
24140 (setq end (org-element-property :end parent)))
24141 end)))
24142 (cond ((not element)
24143 (skip-chars-forward " \r\t\n")
24144 (or (eobp) (beginning-of-line)))
24145 ;; On affiliated keywords, move to element's beginning.
24146 ((< (point) post-affiliated)
24147 (goto-char post-affiliated))
24148 ;; At a table row, move to the end of the table. Similarly,
24149 ;; at a node property, move to the end of the property
24150 ;; drawer.
24151 ((memq type '(node-property table-row))
24152 (goto-char (org-element-property
24153 :end (org-element-property :parent element))))
24154 ((memq type '(property-drawer table)) (goto-char end))
24155 ;; Consider blank lines as separators in verse and source
24156 ;; blocks to ease editing.
24157 ((memq type '(src-block verse-block))
24158 (when (eq type 'src-block)
24159 (setq contents-end
24160 (save-excursion (goto-char end)
24161 (skip-chars-backward " \r\t\n")
24162 (line-beginning-position))))
24163 (beginning-of-line)
24164 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24165 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24166 (goto-char end)
24167 (skip-chars-forward " \r\t\n")
24168 (if (= (point) contents-end) (goto-char end)
24169 (beginning-of-line))))
24170 ;; With no contents, just skip element.
24171 ((not contents-begin) (goto-char end))
24172 ;; If contents are invisible, skip the element altogether.
24173 ((outline-invisible-p (line-end-position))
24174 (case type
24175 (headline
24176 (org-with-limited-levels (outline-next-visible-heading 1)))
24177 ;; At a plain list, make sure we move to the next item
24178 ;; instead of skipping the whole list.
24179 (plain-list (forward-char)
24180 (org-forward-paragraph))
24181 (otherwise (goto-char end))))
24182 ((>= (point) contents-end) (goto-char end))
24183 ((>= (point) contents-begin)
24184 ;; This can only happen on paragraphs and plain lists.
24185 (case type
24186 (paragraph (goto-char end))
24187 ;; At a plain list, try to move to second element in
24188 ;; first item, if possible.
24189 (plain-list (end-of-line)
24190 (org-forward-paragraph))))
24191 ;; When contents start on the middle of a line (e.g. in
24192 ;; items and footnote definitions), try to reach first
24193 ;; element starting after current line.
24194 ((> (line-end-position) contents-begin)
24195 (end-of-line)
24196 (org-forward-paragraph))
24197 (t (goto-char contents-begin)))))
24199 (defun org-backward-paragraph ()
24200 "Move backward to start of previous paragraph or equivalent.
24202 The function moves point to the beginning of the current
24203 structural element, which can be a paragraph, a table, a list
24204 item, etc., or to the beginning of the previous visible one if
24205 point is already there. It also provides some special moves for
24206 convenience:
24208 - On an affiliated keyword, jump to the first one.
24209 - On a table or a property drawer, move to its beginning.
24210 - On a verse or source block, stop before blank lines."
24211 (interactive)
24212 (when (bobp) (user-error "Cannot move further up"))
24213 (let* ((deactivate-mark nil)
24214 (element (org-element-at-point))
24215 (type (org-element-type element))
24216 (contents-begin (org-element-property :contents-begin element))
24217 (contents-end (org-element-property :contents-end element))
24218 (post-affiliated (org-element-property :post-affiliated element))
24219 (begin (org-element-property :begin element)))
24220 (cond
24221 ((not element) (goto-char (point-min)))
24222 ((= (point) begin)
24223 (backward-char)
24224 (org-backward-paragraph))
24225 ((<= (point) post-affiliated) (goto-char begin))
24226 ((memq type '(node-property table-row))
24227 (goto-char (org-element-property
24228 :post-affiliated (org-element-property :parent element))))
24229 ((memq type '(property-drawer table)) (goto-char begin))
24230 ((memq type '(src-block verse-block))
24231 (when (eq type 'src-block)
24232 (setq contents-begin
24233 (save-excursion (goto-char begin) (forward-line) (point))))
24234 (if (= (point) contents-begin) (goto-char post-affiliated)
24235 ;; Inside a verse block, see blank lines as paragraph
24236 ;; separators.
24237 (let ((origin (point)))
24238 (skip-chars-backward " \r\t\n" contents-begin)
24239 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24240 (skip-chars-forward " \r\t\n" origin)
24241 (if (= (point) origin) (goto-char contents-begin)
24242 (beginning-of-line))))))
24243 ((not contents-begin) (goto-char (or post-affiliated begin)))
24244 ((eq type 'paragraph)
24245 (goto-char contents-begin)
24246 ;; When at first paragraph in an item or a footnote definition,
24247 ;; move directly to beginning of line.
24248 (let ((parent-contents
24249 (org-element-property
24250 :contents-begin (org-element-property :parent element))))
24251 (when (and parent-contents (= parent-contents contents-begin))
24252 (beginning-of-line))))
24253 ;; At the end of a greater element, move to the beginning of the
24254 ;; last element within.
24255 ((>= (point) contents-end)
24256 (goto-char (1- contents-end))
24257 (org-backward-paragraph))
24258 (t (goto-char (or post-affiliated begin))))
24259 ;; Ensure we never leave point invisible.
24260 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24262 (defun org-forward-element ()
24263 "Move forward by one element.
24264 Move to the next element at the same level, when possible."
24265 (interactive)
24266 (cond ((eobp) (user-error "Cannot move further down"))
24267 ((org-with-limited-levels (org-at-heading-p))
24268 (let ((origin (point)))
24269 (goto-char (org-end-of-subtree nil t))
24270 (unless (org-with-limited-levels (org-at-heading-p))
24271 (goto-char origin)
24272 (user-error "Cannot move further down"))))
24274 (let* ((elem (org-element-at-point))
24275 (end (org-element-property :end elem))
24276 (parent (org-element-property :parent elem)))
24277 (cond ((and parent (= (org-element-property :contents-end parent) end))
24278 (goto-char (org-element-property :end parent)))
24279 ((integer-or-marker-p end) (goto-char end))
24280 (t (message "No element at point")))))))
24282 (defun org-backward-element ()
24283 "Move backward by one element.
24284 Move to the previous element at the same level, when possible."
24285 (interactive)
24286 (cond ((bobp) (user-error "Cannot move further up"))
24287 ((org-with-limited-levels (org-at-heading-p))
24288 ;; At a headline, move to the previous one, if any, or stay
24289 ;; here.
24290 (let ((origin (point)))
24291 (org-with-limited-levels (org-backward-heading-same-level 1))
24292 ;; When current headline has no sibling above, move to its
24293 ;; parent.
24294 (when (= (point) origin)
24295 (or (org-with-limited-levels (org-up-heading-safe))
24296 (progn (goto-char origin)
24297 (user-error "Cannot move further up"))))))
24299 (let* ((elem (org-element-at-point))
24300 (beg (org-element-property :begin elem)))
24301 (cond
24302 ;; Move to beginning of current element if point isn't
24303 ;; there already.
24304 ((null beg) (message "No element at point"))
24305 ((/= (point) beg) (goto-char beg))
24306 (t (goto-char beg)
24307 (skip-chars-backward " \r\t\n")
24308 (unless (bobp)
24309 (let ((prev (org-element-at-point)))
24310 (goto-char (org-element-property :begin prev))
24311 (while (and (setq prev (org-element-property :parent prev))
24312 (<= (org-element-property :end prev) beg))
24313 (goto-char (org-element-property :begin prev)))))))))))
24315 (defun org-up-element ()
24316 "Move to upper element."
24317 (interactive)
24318 (if (org-with-limited-levels (org-at-heading-p))
24319 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24320 (let* ((elem (org-element-at-point))
24321 (parent (org-element-property :parent elem)))
24322 (if parent (goto-char (org-element-property :begin parent))
24323 (if (org-with-limited-levels (org-before-first-heading-p))
24324 (user-error "No surrounding element")
24325 (org-with-limited-levels (org-back-to-heading)))))))
24327 (defvar org-element-greater-elements)
24328 (defun org-down-element ()
24329 "Move to inner element."
24330 (interactive)
24331 (let ((element (org-element-at-point)))
24332 (cond
24333 ((memq (org-element-type element) '(plain-list table))
24334 (goto-char (org-element-property :contents-begin element))
24335 (forward-char))
24336 ((memq (org-element-type element) org-element-greater-elements)
24337 ;; If contents are hidden, first disclose them.
24338 (when (outline-invisible-p (line-end-position)) (org-cycle))
24339 (goto-char (or (org-element-property :contents-begin element)
24340 (user-error "No content for this element"))))
24341 (t (user-error "No inner element")))))
24343 (defun org-drag-element-backward ()
24344 "Move backward element at point."
24345 (interactive)
24346 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24347 (let* ((elem (org-element-at-point))
24348 (prev-elem
24349 (save-excursion
24350 (goto-char (org-element-property :begin elem))
24351 (skip-chars-backward " \r\t\n")
24352 (unless (bobp)
24353 (let* ((beg (org-element-property :begin elem))
24354 (prev (org-element-at-point))
24355 (up prev))
24356 (while (and (setq up (org-element-property :parent up))
24357 (<= (org-element-property :end up) beg))
24358 (setq prev up))
24359 prev)))))
24360 ;; Error out if no previous element or previous element is
24361 ;; a parent of the current one.
24362 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24363 (user-error "Cannot drag element backward")
24364 (let ((pos (point)))
24365 (org-element-swap-A-B prev-elem elem)
24366 (goto-char (+ (org-element-property :begin prev-elem)
24367 (- pos (org-element-property :begin elem)))))))))
24369 (defun org-drag-element-forward ()
24370 "Move forward element at point."
24371 (interactive)
24372 (let* ((pos (point))
24373 (elem (org-element-at-point)))
24374 (when (= (point-max) (org-element-property :end elem))
24375 (user-error "Cannot drag element forward"))
24376 (goto-char (org-element-property :end elem))
24377 (let ((next-elem (org-element-at-point)))
24378 (when (or (org-element-nested-p elem next-elem)
24379 (and (eq (org-element-type next-elem) 'headline)
24380 (not (eq (org-element-type elem) 'headline))))
24381 (goto-char pos)
24382 (user-error "Cannot drag element forward"))
24383 ;; Compute new position of point: it's shifted by NEXT-ELEM
24384 ;; body's length (without final blanks) and by the length of
24385 ;; blanks between ELEM and NEXT-ELEM.
24386 (let ((size-next (- (save-excursion
24387 (goto-char (org-element-property :end next-elem))
24388 (skip-chars-backward " \r\t\n")
24389 (forward-line)
24390 ;; Small correction if buffer doesn't end
24391 ;; with a newline character.
24392 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24393 (org-element-property :begin next-elem)))
24394 (size-blank (- (org-element-property :end elem)
24395 (save-excursion
24396 (goto-char (org-element-property :end elem))
24397 (skip-chars-backward " \r\t\n")
24398 (forward-line)
24399 (point)))))
24400 (org-element-swap-A-B elem next-elem)
24401 (goto-char (+ pos size-next size-blank))))))
24403 (defun org-drag-line-forward (arg)
24404 "Drag the line at point ARG lines forward."
24405 (interactive "p")
24406 (dotimes (n (abs arg))
24407 (let ((c (current-column)))
24408 (if (< 0 arg)
24409 (progn
24410 (beginning-of-line 2)
24411 (transpose-lines 1)
24412 (beginning-of-line 0))
24413 (transpose-lines 1)
24414 (beginning-of-line -1))
24415 (org-move-to-column c))))
24417 (defun org-drag-line-backward (arg)
24418 "Drag the line at point ARG lines backward."
24419 (interactive "p")
24420 (org-drag-line-forward (- arg)))
24422 (defun org-mark-element ()
24423 "Put point at beginning of this element, mark at end.
24425 Interactively, if this command is repeated or (in Transient Mark
24426 mode) if the mark is active, it marks the next element after the
24427 ones already marked."
24428 (interactive)
24429 (let (deactivate-mark)
24430 (if (and (org-called-interactively-p 'any)
24431 (or (and (eq last-command this-command) (mark t))
24432 (and transient-mark-mode mark-active)))
24433 (set-mark
24434 (save-excursion
24435 (goto-char (mark))
24436 (goto-char (org-element-property :end (org-element-at-point)))))
24437 (let ((element (org-element-at-point)))
24438 (end-of-line)
24439 (push-mark (org-element-property :end element) t t)
24440 (goto-char (org-element-property :begin element))))))
24442 (defun org-narrow-to-element ()
24443 "Narrow buffer to current element."
24444 (interactive)
24445 (let ((elem (org-element-at-point)))
24446 (cond
24447 ((eq (car elem) 'headline)
24448 (narrow-to-region
24449 (org-element-property :begin elem)
24450 (org-element-property :end elem)))
24451 ((memq (car elem) org-element-greater-elements)
24452 (narrow-to-region
24453 (org-element-property :contents-begin elem)
24454 (org-element-property :contents-end elem)))
24456 (narrow-to-region
24457 (org-element-property :begin elem)
24458 (org-element-property :end elem))))))
24460 (defun org-transpose-element ()
24461 "Transpose current and previous elements, keeping blank lines between.
24462 Point is moved after both elements."
24463 (interactive)
24464 (org-skip-whitespace)
24465 (let ((end (org-element-property :end (org-element-at-point))))
24466 (org-drag-element-backward)
24467 (goto-char end)))
24469 (defun org-unindent-buffer ()
24470 "Un-indent the visible part of the buffer.
24471 Relative indentation (between items, inside blocks, etc.) isn't
24472 modified."
24473 (interactive)
24474 (unless (eq major-mode 'org-mode)
24475 (user-error "Cannot un-indent a buffer not in Org mode"))
24476 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24477 unindent-tree ; For byte-compiler.
24478 (unindent-tree
24479 (function
24480 (lambda (contents)
24481 (mapc
24482 (lambda (element)
24483 (if (memq (org-element-type element) '(headline section))
24484 (funcall unindent-tree (org-element-contents element))
24485 (save-excursion
24486 (save-restriction
24487 (narrow-to-region
24488 (org-element-property :begin element)
24489 (org-element-property :end element))
24490 (org-do-remove-indentation)))))
24491 (reverse contents))))))
24492 (funcall unindent-tree (org-element-contents parse-tree))))
24494 (defun org-show-subtree ()
24495 "Show everything after this heading at deeper levels."
24496 (interactive)
24497 (outline-flag-region
24498 (point)
24499 (save-excursion
24500 (org-end-of-subtree t t))
24501 nil))
24503 (defun org-show-entry ()
24504 "Show the body directly following this heading.
24505 Show the heading too, if it is currently invisible."
24506 (interactive)
24507 (save-excursion
24508 (ignore-errors
24509 (org-back-to-heading t)
24510 (outline-flag-region
24511 (max (point-min) (1- (point)))
24512 (save-excursion
24513 (if (re-search-forward
24514 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24515 (match-beginning 1)
24516 (point-max)))
24517 nil)
24518 (org-cycle-hide-drawers 'children))))
24520 (defun org-make-options-regexp (kwds &optional extra)
24521 "Make a regular expression for keyword lines.
24522 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24523 when non-nil, is a regexp matching keywords names."
24524 (concat "^[ \t]*#\\+\\("
24525 (regexp-opt kwds)
24526 (and extra (concat (and kwds "\\|") extra))
24527 "\\):[ \t]*\\(.*\\)"))
24529 ;; Make isearch reveal the necessary context
24530 (defun org-isearch-end ()
24531 "Reveal context after isearch exits."
24532 (when isearch-success ; only if search was successful
24533 (if (featurep 'xemacs)
24534 ;; Under XEmacs, the hook is run in the correct place,
24535 ;; we directly show the context.
24536 (org-show-context 'isearch)
24537 ;; In Emacs the hook runs *before* restoring the overlays.
24538 ;; So we have to use a one-time post-command-hook to do this.
24539 ;; (Emacs 22 has a special variable, see function `org-mode')
24540 (unless (and (boundp 'isearch-mode-end-hook-quit)
24541 isearch-mode-end-hook-quit)
24542 ;; Only when the isearch was not quitted.
24543 (org-add-hook 'post-command-hook 'org-isearch-post-command
24544 'append 'local)))))
24546 (defun org-isearch-post-command ()
24547 "Remove self from hook, and show context."
24548 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24549 (org-show-context 'isearch))
24552 ;;;; Integration with and fixes for other packages
24554 ;;; Imenu support
24556 (defvar org-imenu-markers nil
24557 "All markers currently used by Imenu.")
24558 (make-variable-buffer-local 'org-imenu-markers)
24560 (defun org-imenu-new-marker (&optional pos)
24561 "Return a new marker for use by Imenu, and remember the marker."
24562 (let ((m (make-marker)))
24563 (move-marker m (or pos (point)))
24564 (push m org-imenu-markers)
24567 (defun org-imenu-get-tree ()
24568 "Produce the index for Imenu."
24569 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24570 (setq org-imenu-markers nil)
24571 (let* ((n org-imenu-depth)
24572 (re (concat "^" (org-get-limited-outline-regexp)))
24573 (subs (make-vector (1+ n) nil))
24574 (last-level 0)
24575 m level head0 head)
24576 (save-excursion
24577 (save-restriction
24578 (widen)
24579 (goto-char (point-max))
24580 (while (re-search-backward re nil t)
24581 (setq level (org-reduced-level (funcall outline-level)))
24582 (when (and (<= level n)
24583 (looking-at org-complex-heading-regexp)
24584 (setq head0 (org-match-string-no-properties 4)))
24585 (setq head (org-link-display-format head0)
24586 m (org-imenu-new-marker))
24587 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24588 (if (>= level last-level)
24589 (push (cons head m) (aref subs level))
24590 (push (cons head (aref subs (1+ level))) (aref subs level))
24591 (loop for i from (1+ level) to n do (aset subs i nil)))
24592 (setq last-level level)))))
24593 (aref subs 1)))
24595 (eval-after-load "imenu"
24596 '(progn
24597 (add-hook 'imenu-after-jump-hook
24598 (lambda ()
24599 (if (derived-mode-p 'org-mode)
24600 (org-show-context 'org-goto))))))
24602 (defun org-link-display-format (link)
24603 "Replace a link with its the description.
24604 If there is no description, use the link target."
24605 (save-match-data
24606 (if (string-match org-bracket-link-analytic-regexp link)
24607 (replace-match (if (match-end 5)
24608 (match-string 5 link)
24609 (concat (match-string 1 link)
24610 (match-string 3 link)))
24611 nil t link)
24612 link)))
24614 (defun org-toggle-link-display ()
24615 "Toggle the literal or descriptive display of links."
24616 (interactive)
24617 (if org-descriptive-links
24618 (progn (org-remove-from-invisibility-spec '(org-link))
24619 (org-restart-font-lock)
24620 (setq org-descriptive-links nil))
24621 (progn (add-to-invisibility-spec '(org-link))
24622 (org-restart-font-lock)
24623 (setq org-descriptive-links t))))
24625 ;; Speedbar support
24627 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24628 "Overlay marking the agenda restriction line in speedbar.")
24629 (overlay-put org-speedbar-restriction-lock-overlay
24630 'face 'org-agenda-restriction-lock)
24631 (overlay-put org-speedbar-restriction-lock-overlay
24632 'help-echo "Agendas are currently limited to this item.")
24633 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24635 (defun org-speedbar-set-agenda-restriction ()
24636 "Restrict future agenda commands to the location at point in speedbar.
24637 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24638 (interactive)
24639 (require 'org-agenda)
24640 (let (p m tp np dir txt)
24641 (cond
24642 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24643 'org-imenu t))
24644 (setq m (get-text-property p 'org-imenu-marker))
24645 (with-current-buffer (marker-buffer m)
24646 (goto-char m)
24647 (org-agenda-set-restriction-lock 'subtree)))
24648 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24649 'speedbar-function 'speedbar-find-file))
24650 (setq tp (previous-single-property-change
24651 (1+ p) 'speedbar-function)
24652 np (next-single-property-change
24653 tp 'speedbar-function)
24654 dir (speedbar-line-directory)
24655 txt (buffer-substring-no-properties (or tp (point-min))
24656 (or np (point-max))))
24657 (with-current-buffer (find-file-noselect
24658 (let ((default-directory dir))
24659 (expand-file-name txt)))
24660 (unless (derived-mode-p 'org-mode)
24661 (user-error "Cannot restrict to non-Org-mode file"))
24662 (org-agenda-set-restriction-lock 'file)))
24663 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24664 (move-overlay org-speedbar-restriction-lock-overlay
24665 (point-at-bol) (point-at-eol))
24666 (setq current-prefix-arg nil)
24667 (org-agenda-maybe-redo)))
24669 (defvar speedbar-file-key-map)
24670 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24671 (eval-after-load "speedbar"
24672 '(progn
24673 (speedbar-add-supported-extension ".org")
24674 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24675 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24676 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24677 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24678 (add-hook 'speedbar-visiting-tag-hook
24679 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24681 ;;; Fixes and Hacks for problems with other packages
24683 (defun org--flyspell-object-check-p (element)
24684 "Non-nil when Flyspell can check object at point.
24685 ELEMENT is the element at point."
24686 (let ((object (save-excursion
24687 (when (org-looking-at-p "\\>") (backward-char))
24688 (org-element-context element))))
24689 (case (org-element-type object)
24690 ;; Prevent checks in links due to keybinding conflict with
24691 ;; Flyspell.
24692 ((code entity export-snippet inline-babel-call
24693 inline-src-block line-break latex-fragment link macro
24694 statistics-cookie target timestamp verbatim)
24695 nil)
24696 (footnote-reference
24697 ;; Only in inline footnotes, within the definition.
24698 (and (eq (org-element-property :type object) 'inline)
24699 (< (save-excursion
24700 (goto-char (org-element-property :begin object))
24701 (search-forward ":" nil t 2))
24702 (point))))
24703 (otherwise t))))
24705 (defun org-mode-flyspell-verify ()
24706 "Function used for `flyspell-generic-check-word-predicate'."
24707 (if (org-at-heading-p)
24708 ;; At a headline or an inlinetask, check title only. This is
24709 ;; faster than relying on `org-element-at-point'.
24710 (and (save-excursion (beginning-of-line)
24711 (and (let ((case-fold-search t))
24712 (not (looking-at "\\*+ END[ \t]*$")))
24713 (looking-at org-complex-heading-regexp)))
24714 (match-beginning 4)
24715 (>= (point) (match-beginning 4))
24716 (or (not (match-beginning 5))
24717 (< (point) (match-beginning 5))))
24718 (let* ((element (org-element-at-point))
24719 (post-affiliated (org-element-property :post-affiliated element)))
24720 (cond
24721 ;; Ignore checks in all affiliated keywords but captions.
24722 ((< (point) post-affiliated)
24723 (and (save-excursion
24724 (beginning-of-line)
24725 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24726 (> (point) (match-end 0))
24727 (org--flyspell-object-check-p element)))
24728 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24729 ((let ((log (org-log-into-drawer)))
24730 (and log
24731 (let ((drawer (org-element-lineage element '(drawer))))
24732 (and drawer
24733 (eq (compare-strings
24734 log nil nil
24735 (org-element-property :drawer-name drawer) nil nil t)
24736 t)))))
24737 nil)
24739 (case (org-element-type element)
24740 ((comment quote-section) t)
24741 (comment-block
24742 ;; Allow checks between block markers, not on them.
24743 (and (> (line-beginning-position) post-affiliated)
24744 (save-excursion
24745 (end-of-line)
24746 (skip-chars-forward " \r\t\n")
24747 (< (point) (org-element-property :end element)))))
24748 ;; Arbitrary list of keywords where checks are meaningful.
24749 ;; Make sure point is on the value part of the element.
24750 (keyword
24751 (and (member (org-element-property :key element)
24752 '("DESCRIPTION" "TITLE"))
24753 (< (save-excursion
24754 (beginning-of-line) (search-forward ":") (point))
24755 (point))))
24756 ;; Check is globally allowed in paragraphs verse blocks and
24757 ;; table rows (after affiliated keywords) but some objects
24758 ;; must not be affected.
24759 ((paragraph table-row verse-block)
24760 (let ((cbeg (org-element-property :contents-begin element))
24761 (cend (org-element-property :contents-end element)))
24762 (and cbeg (>= (point) cbeg) (< (point) cend)
24763 (org--flyspell-object-check-p element))))))))))
24764 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24766 (defun org-remove-flyspell-overlays-in (beg end)
24767 "Remove flyspell overlays in region."
24768 (and (org-bound-and-true-p flyspell-mode)
24769 (fboundp 'flyspell-delete-region-overlays)
24770 (flyspell-delete-region-overlays beg end)))
24772 (defvar flyspell-delayed-commands)
24773 (eval-after-load "flyspell"
24774 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24776 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24777 (eval-after-load "bookmark"
24778 '(if (boundp 'bookmark-after-jump-hook)
24779 ;; We can use the hook
24780 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24781 ;; Hook not available, use advice
24782 (defadvice bookmark-jump (after org-make-visible activate)
24783 "Make the position visible."
24784 (org-bookmark-jump-unhide))))
24786 ;; Make sure saveplace shows the location if it was hidden
24787 (eval-after-load "saveplace"
24788 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24789 "Make the position visible."
24790 (org-bookmark-jump-unhide)))
24792 ;; Make sure ecb shows the location if it was hidden
24793 (eval-after-load "ecb"
24794 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24795 "Make hierarchy visible when jumping into location from ECB tree buffer."
24796 (if (derived-mode-p 'org-mode)
24797 (org-show-context))))
24799 (defun org-bookmark-jump-unhide ()
24800 "Unhide the current position, to show the bookmark location."
24801 (and (derived-mode-p 'org-mode)
24802 (or (outline-invisible-p)
24803 (save-excursion (goto-char (max (point-min) (1- (point))))
24804 (outline-invisible-p)))
24805 (org-show-context 'bookmark-jump)))
24807 (defun org-mark-jump-unhide ()
24808 "Make the point visible with `org-show-context' after jumping to the mark."
24809 (when (and (derived-mode-p 'org-mode)
24810 (outline-invisible-p))
24811 (org-show-context 'mark-goto)))
24813 (eval-after-load "simple"
24814 '(defadvice pop-to-mark-command (after org-make-visible activate)
24815 "Make the point visible with `org-show-context'."
24816 (org-mark-jump-unhide)))
24818 (eval-after-load "simple"
24819 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24820 "Make the point visible with `org-show-context'."
24821 (org-mark-jump-unhide)))
24823 (eval-after-load "simple"
24824 '(defadvice pop-global-mark (after org-make-visible activate)
24825 "Make the point visible with `org-show-context'."
24826 (org-mark-jump-unhide)))
24828 ;; Make session.el ignore our circular variable
24829 (defvar session-globals-exclude)
24830 (eval-after-load "session"
24831 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24833 ;;;; Finish up
24835 (provide 'org)
24837 (run-hooks 'org-load-hook)
24839 ;;; org.el ends here