Sanitize link encoding
[org-mode/org-tableheadings.git] / lisp / org.el
blob7b720f842da2e5a0706bf00801daf8c147f829da
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2015 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (equal this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
114 (unless (boundp 'calendar-view-holidays-initially-flag)
115 (org-defvaralias 'calendar-view-holidays-initially-flag
116 'view-calendar-holidays-initially))
117 (unless (boundp 'calendar-view-diary-initially-flag)
118 (org-defvaralias 'calendar-view-diary-initially-flag
119 'view-diary-entries-initially))
120 (unless (boundp 'diary-fancy-buffer)
121 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
123 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
124 (declare-function org-add-archive-files "org-archive" (files))
125 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
126 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
127 (declare-function org-agenda-redo "org-agenda" (&optional all))
128 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
129 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
130 (declare-function org-beamer-mode "ox-beamer" ())
131 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
132 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
133 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
134 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
135 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
136 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
137 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
138 (declare-function org-clock-update-time-maybe "org-clock" ())
139 (declare-function org-clocktable-shift "org-clock" (dir n))
140 (declare-function org-element-at-point "org-element" ())
141 (declare-function org-element-cache-refresh "org-element" (pos))
142 (declare-function org-element-cache-reset "org-element" (&optional all))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-copy "org-element" (datum))
146 (declare-function org-element-interpret-data "org-element" (data &optional parent))
147 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
148 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
149 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
150 (declare-function org-element-property "org-element" (property element))
151 (declare-function org-element-put-property "org-element" (element property value))
152 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
153 (declare-function org-element-type "org-element" (element))
154 (declare-function org-element-update-syntax "org-element" ())
155 (declare-function org-id-find-id-file "org-id" (id))
156 (declare-function org-id-get-create "org-id" (&optional force))
157 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
158 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
159 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
160 (declare-function org-plot/gnuplot "org-plot" (&optional params))
161 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
162 (declare-function org-table-align "org-table" ())
163 (declare-function org-table-begin "org-table" (&optional table-type))
164 (declare-function org-table-beginning-of-field "org-table" (&optional n))
165 (declare-function org-table-blank-field "org-table" ())
166 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
167 (declare-function org-table-edit-field "org-table" (arg))
168 (declare-function org-table-end "org-table" (&optional table-type))
169 (declare-function org-table-end-of-field "org-table" (&optional n))
170 (declare-function org-table-insert-row "org-table" (&optional arg))
171 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
172 (declare-function org-table-maybe-eval-formula "org-table" ())
173 (declare-function org-table-maybe-recalculate-line "org-table" ())
174 (declare-function org-table-next-row "org-table" ())
175 (declare-function org-table-paste-rectangle "org-table" ())
176 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
177 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
178 (declare-function orgtbl-mode "org-table" (&optional arg))
180 (defsubst org-uniquify (list)
181 "Non-destructively remove duplicate elements from LIST."
182 (let ((res (copy-sequence list))) (delete-dups res)))
184 (defsubst org-get-at-bol (property)
185 "Get text property PROPERTY at the beginning of line."
186 (get-text-property (point-at-bol) property))
188 (defsubst org-trim (s)
189 "Remove whitespace at the beginning and the end of string S."
190 (replace-regexp-in-string
191 "\\`[ \t\n\r]+" ""
192 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
194 ;; load languages based on value of `org-babel-load-languages'
195 (defvar org-babel-load-languages)
197 ;;;###autoload
198 (defun org-babel-do-load-languages (sym value)
199 "Load the languages defined in `org-babel-load-languages'."
200 (set-default sym value)
201 (mapc (lambda (pair)
202 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
203 (if active
204 (progn
205 (require (intern (concat "ob-" lang))))
206 (progn
207 (funcall 'fmakunbound
208 (intern (concat "org-babel-execute:" lang)))
209 (funcall 'fmakunbound
210 (intern (concat "org-babel-expand-body:" lang)))))))
211 org-babel-load-languages))
213 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
214 ;;;###autoload
215 (defun org-babel-load-file (file &optional compile)
216 "Load Emacs Lisp source code blocks in the Org-mode FILE.
217 This function exports the source code using `org-babel-tangle'
218 and then loads the resulting file using `load-file'. With prefix
219 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
220 file to byte-code before it is loaded."
221 (interactive "fFile to load: \nP")
222 (let* ((age (lambda (file)
223 (float-time
224 (time-subtract (current-time)
225 (nth 5 (or (file-attributes (file-truename file))
226 (file-attributes file)))))))
227 (base-name (file-name-sans-extension file))
228 (exported-file (concat base-name ".el")))
229 ;; tangle if the org-mode file is newer than the elisp file
230 (unless (and (file-exists-p exported-file)
231 (> (funcall age file) (funcall age exported-file)))
232 ;; Tangle-file traversal returns reversed list of tangled files
233 ;; and we want to evaluate the first target.
234 (setq exported-file
235 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
236 (message "%s %s"
237 (if compile
238 (progn (byte-compile-file exported-file 'load)
239 "Compiled and loaded")
240 (progn (load-file exported-file) "Loaded"))
241 exported-file)))
243 (defcustom org-babel-load-languages '((emacs-lisp . t))
244 "Languages which can be evaluated in Org-mode buffers.
245 This list can be used to load support for any of the languages
246 below, note that each language will depend on a different set of
247 system executables and/or Emacs modes. When a language is
248 \"loaded\", then code blocks in that language can be evaluated
249 with `org-babel-execute-src-block' bound by default to C-c
250 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
251 be set to remove code block evaluation from the C-c C-c
252 keybinding. By default only Emacs Lisp (which has no
253 requirements) is loaded."
254 :group 'org-babel
255 :set 'org-babel-do-load-languages
256 :version "24.1"
257 :type '(alist :tag "Babel Languages"
258 :key-type
259 (choice
260 (const :tag "Awk" awk)
261 (const :tag "C" C)
262 (const :tag "R" R)
263 (const :tag "Asymptote" asymptote)
264 (const :tag "Calc" calc)
265 (const :tag "Clojure" clojure)
266 (const :tag "CSS" css)
267 (const :tag "Ditaa" ditaa)
268 (const :tag "Dot" dot)
269 (const :tag "Emacs Lisp" emacs-lisp)
270 (const :tag "Forth" forth)
271 (const :tag "Fortran" fortran)
272 (const :tag "Gnuplot" gnuplot)
273 (const :tag "Haskell" haskell)
274 (const :tag "IO" io)
275 (const :tag "J" J)
276 (const :tag "Java" java)
277 (const :tag "Javascript" js)
278 (const :tag "LaTeX" latex)
279 (const :tag "Ledger" ledger)
280 (const :tag "Lilypond" lilypond)
281 (const :tag "Lisp" lisp)
282 (const :tag "Makefile" makefile)
283 (const :tag "Maxima" maxima)
284 (const :tag "Matlab" matlab)
285 (const :tag "Mscgen" mscgen)
286 (const :tag "Ocaml" ocaml)
287 (const :tag "Octave" octave)
288 (const :tag "Org" org)
289 (const :tag "Perl" perl)
290 (const :tag "Pico Lisp" picolisp)
291 (const :tag "PlantUML" plantuml)
292 (const :tag "Python" python)
293 (const :tag "Ruby" ruby)
294 (const :tag "Sass" sass)
295 (const :tag "Scala" scala)
296 (const :tag "Scheme" scheme)
297 (const :tag "Screen" screen)
298 (const :tag "Shell Script" shell)
299 (const :tag "Shen" shen)
300 (const :tag "Sql" sql)
301 (const :tag "Sqlite" sqlite)
302 (const :tag "ebnf2ps" ebnf2ps))
303 :value-type (boolean :tag "Activate" :value t)))
305 ;;;; Customization variables
306 (defcustom org-clone-delete-id nil
307 "Remove ID property of clones of a subtree.
308 When non-nil, clones of a subtree don't inherit the ID property.
309 Otherwise they inherit the ID property with a new unique
310 identifier."
311 :type 'boolean
312 :version "24.1"
313 :group 'org-id)
315 ;;; Version
316 (org-check-version)
318 ;;;###autoload
319 (defun org-version (&optional here full message)
320 "Show the org-mode version.
321 Interactively, or when MESSAGE is non-nil, show it in echo area.
322 With prefix argument, or when HERE is non-nil, insert it at point.
323 In non-interactive uses, a reduced version string is output unless
324 FULL is given."
325 (interactive (list current-prefix-arg t (not current-prefix-arg)))
326 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
327 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
328 (load-suffixes (list ".el"))
329 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
330 (org-trash (or
331 (and (fboundp 'org-release) (fboundp 'org-git-version))
332 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
333 (load-suffixes save-load-suffixes)
334 (org-version (org-release))
335 (git-version (org-git-version))
336 (version (format "Org-mode version %s (%s @ %s)"
337 org-version
338 git-version
339 (if org-install-dir
340 (if (string= org-dir org-install-dir)
341 org-install-dir
342 (concat "mixed installation! " org-install-dir " and " org-dir))
343 "org-loaddefs.el can not be found!")))
344 (version1 (if full version org-version)))
345 (when here (insert version1))
346 (when message (message "%s" version1))
347 version1))
349 (defconst org-version (org-version))
352 ;;; Syntax Constants
354 ;;;; Block
356 (defconst org-block-regexp
357 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
358 "Regular expression for hiding blocks.")
360 (defconst org-dblock-start-re
361 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
362 "Matches the start line of a dynamic block, with parameters.")
364 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
365 "Matches the end of a dynamic block.")
367 ;;;; Clock and Planning
369 (defconst org-clock-string "CLOCK:"
370 "String used as prefix for timestamps clocking work hours on an item.")
372 (defvar org-closed-string "CLOSED:"
373 "String used as the prefix for timestamps logging closing a TODO entry.")
375 (defvar org-deadline-string "DEADLINE:"
376 "String to mark deadline entries.
377 A deadline is this string, followed by a time stamp. Should be a word,
378 terminated by a colon. You can insert a schedule keyword and
379 a timestamp with \\[org-deadline].")
381 (defvar org-scheduled-string "SCHEDULED:"
382 "String to mark scheduled TODO entries.
383 A schedule is this string, followed by a time stamp. Should be a word,
384 terminated by a colon. You can insert a schedule keyword and
385 a timestamp with \\[org-schedule].")
387 (defconst org-ds-keyword-length
388 (+ 2
389 (apply #'max
390 (mapcar #'length
391 (list org-deadline-string org-scheduled-string
392 org-clock-string org-closed-string))))
393 "Maximum length of the DEADLINE and SCHEDULED keywords.")
395 (defconst org-planning-line-re
396 (concat "^[ \t]*"
397 (regexp-opt
398 (list org-closed-string org-deadline-string org-scheduled-string)
400 "Matches a line with planning info.
401 Matched keyword is in group 1.")
403 (defconst org-clock-line-re
404 (concat "^[ \t]*" org-clock-string)
405 "Matches a line with clock info.")
407 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
408 "Matches the DEADLINE keyword.")
410 (defconst org-deadline-time-regexp
411 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
412 "Matches the DEADLINE keyword together with a time stamp.")
414 (defconst org-deadline-time-hour-regexp
415 (concat "\\<" org-deadline-string
416 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
417 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
419 (defconst org-deadline-line-regexp
420 (concat "\\<\\(" org-deadline-string "\\).*")
421 "Matches the DEADLINE keyword and the rest of the line.")
423 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
424 "Matches the SCHEDULED keyword.")
426 (defconst org-scheduled-time-regexp
427 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
428 "Matches the SCHEDULED keyword together with a time stamp.")
430 (defconst org-scheduled-time-hour-regexp
431 (concat "\\<" org-scheduled-string
432 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
433 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
435 (defconst org-closed-time-regexp
436 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
437 "Matches the CLOSED keyword together with a time stamp.")
439 (defconst org-keyword-time-regexp
440 (concat "\\<"
441 (regexp-opt
442 (list org-scheduled-string org-deadline-string org-closed-string
443 org-clock-string)
445 " *[[<]\\([^]>]+\\)[]>]")
446 "Matches any of the 4 keywords, together with the time stamp.")
448 (defconst org-keyword-time-not-clock-regexp
449 (concat
450 "\\<"
451 (regexp-opt
452 (list org-scheduled-string org-deadline-string org-closed-string) t)
453 " *[[<]\\([^]>]+\\)[]>]")
454 "Matches any of the 3 keywords, together with the time stamp.")
456 (defconst org-maybe-keyword-time-regexp
457 (concat "\\(\\<"
458 (regexp-opt
459 (list org-scheduled-string org-deadline-string org-closed-string
460 org-clock-string)
462 "\\)?"
463 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
464 "\\|"
465 "<%%([^\r\n>]*>\\)")
466 "Matches a timestamp, possibly preceded by a keyword.")
468 (defconst org-all-time-keywords
469 (mapcar (lambda (w) (substring w 0 -1))
470 (list org-scheduled-string org-deadline-string
471 org-clock-string org-closed-string))
472 "List of time keywords.")
474 ;;;; Drawer
476 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
477 "Matches first or last line of a hidden block.
478 Group 1 contains drawer's name or \"END\".")
480 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
481 "Regular expression matching the first line of a property drawer.")
483 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
484 "Regular expression matching the last line of a property drawer.")
486 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
487 "Regular expression matching the first line of a clock drawer.")
489 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
490 "Regular expression matching the last line of a clock drawer.")
492 (defconst org-property-drawer-re
493 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
494 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*"
495 "[ \t]*:END:[ \t]*$")
496 "Matches an entire property drawer.")
498 (defconst org-clock-drawer-re
499 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
500 org-clock-drawer-end-re "\\)\n?")
501 "Matches an entire clock drawer.")
503 ;;;; Headline
505 (defconst org-heading-keyword-regexp-format
506 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
507 "Printf format for a regexp matching a headline with some keyword.
508 This regexp will match the headline of any node which has the
509 exact keyword that is put into the format. The keyword isn't in
510 any group by default, but the stars and the body are.")
512 (defconst org-heading-keyword-maybe-regexp-format
513 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
514 "Printf format for a regexp matching a headline, possibly with some keyword.
515 This regexp can match any headline with the specified keyword, or
516 without a keyword. The keyword isn't in any group by default,
517 but the stars and the body are.")
519 (defconst org-archive-tag "ARCHIVE"
520 "The tag that marks a subtree as archived.
521 An archived subtree does not open during visibility cycling, and does
522 not contribute to the agenda listings.")
524 (defconst org-comment-string "COMMENT"
525 "Entries starting with this keyword will never be exported.
526 An entry can be toggled between COMMENT and normal with
527 \\[org-toggle-comment].")
530 ;;;; LaTeX Environments and Fragments
532 (defconst org-latex-regexps
533 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
534 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
535 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
536 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
537 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
538 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
539 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
540 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
541 "Regular expressions for matching embedded LaTeX.")
543 ;;;; Node Property
545 (defconst org-effort-property "Effort"
546 "The property that is being used to keep track of effort estimates.
547 Effort estimates given in this property need to have the format H:MM.")
549 ;;;; Table
551 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
552 "Detect an org-type or table-type table.")
554 (defconst org-table-line-regexp "^[ \t]*|"
555 "Detect an org-type table line.")
557 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
558 "Detect an org-type table line.")
560 (defconst org-table-hline-regexp "^[ \t]*|-"
561 "Detect an org-type table hline.")
563 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
564 "Detect a table-type table hline.")
566 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
567 "Detect the first line outside a table when searching from within it.
568 This works for both table types.")
570 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
571 "Detect a #+TBLFM line.")
573 ;;;; Timestamp
575 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
576 "Regular expression for fast time stamp matching.")
578 (defconst org-ts-regexp-inactive
579 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
580 "Regular expression for fast inactive time stamp matching.")
582 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
583 "Regular expression for fast time stamp matching.")
585 (defconst org-ts-regexp0
586 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
587 "Regular expression matching time strings for analysis.
588 This one does not require the space after the date, so it can be used
589 on a string that terminates immediately after the date.")
591 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
592 "Regular expression matching time strings for analysis.")
594 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
595 "Regular expression matching time stamps, with groups.")
597 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
598 "Regular expression matching time stamps (also [..]), with groups.")
600 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
601 "Regular expression matching a time stamp range.")
603 (defconst org-tr-regexp-both
604 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
605 "Regular expression matching a time stamp range.")
607 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
608 org-ts-regexp "\\)?")
609 "Regular expression matching a time stamp or time stamp range.")
611 (defconst org-tsr-regexp-both
612 (concat org-ts-regexp-both "\\(--?-?"
613 org-ts-regexp-both "\\)?")
614 "Regular expression matching a time stamp or time stamp range.
615 The time stamps may be either active or inactive.")
617 (defconst org-repeat-re
618 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
619 "Regular expression for specifying repeated events.
620 After a match, group 1 contains the repeat expression.")
622 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
623 "Formats for `format-time-string' which are used for time stamps.")
626 ;;; The custom variables
628 (defgroup org nil
629 "Outline-based notes management and organizer."
630 :tag "Org"
631 :group 'outlines
632 :group 'calendar)
634 (defcustom org-mode-hook nil
635 "Mode hook for Org-mode, run after the mode was turned on."
636 :group 'org
637 :type 'hook)
639 (defcustom org-load-hook nil
640 "Hook that is run after org.el has been loaded."
641 :group 'org
642 :type 'hook)
644 (defcustom org-log-buffer-setup-hook nil
645 "Hook that is run after an Org log buffer is created."
646 :group 'org
647 :version "24.1"
648 :type 'hook)
650 (defvar org-modules) ; defined below
651 (defvar org-modules-loaded nil
652 "Have the modules been loaded already?")
654 (defun org-load-modules-maybe (&optional force)
655 "Load all extensions listed in `org-modules'."
656 (when (or force (not org-modules-loaded))
657 (mapc (lambda (ext)
658 (condition-case nil (require ext)
659 (error (message "Problems while trying to load feature `%s'" ext))))
660 org-modules)
661 (setq org-modules-loaded t)))
663 (defun org-set-modules (var value)
664 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
665 (set var value)
666 (when (featurep 'org)
667 (org-load-modules-maybe 'force)
668 (org-element-cache-reset 'all)))
670 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
671 "Modules that should always be loaded together with org.el.
673 If a description starts with <C>, the file is not part of Emacs
674 and loading it will require that you have downloaded and properly
675 installed the Org mode distribution.
677 You can also use this system to load external packages (i.e. neither Org
678 core modules, nor modules from the CONTRIB directory). Just add symbols
679 to the end of the list. If the package is called org-xyz.el, then you need
680 to add the symbol `xyz', and the package must have a call to:
682 \(provide 'org-xyz)
684 For export specific modules, see also `org-export-backends'."
685 :group 'org
686 :set 'org-set-modules
687 :version "24.4"
688 :package-version '(Org . "8.0")
689 :type
690 '(set :greedy t
691 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
692 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
693 (const :tag " crypt: Encryption of subtrees" org-crypt)
694 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
695 (const :tag " docview: Links to doc-view buffers" org-docview)
696 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
697 (const :tag " habit: Track your consistency with habits" org-habit)
698 (const :tag " id: Global IDs for identifying entries" org-id)
699 (const :tag " info: Links to Info nodes" org-info)
700 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
701 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
702 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
703 (const :tag " mouse: Additional mouse support" org-mouse)
704 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
705 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
706 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
708 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
709 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
710 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
711 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
712 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
713 (const :tag "C collector: Collect properties into tables" org-collector)
714 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
715 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
716 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
717 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
718 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
719 (const :tag "C eval: Include command output as text" org-eval)
720 (const :tag "C eww: Store link to url of eww" org-eww)
721 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
722 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
723 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
724 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
725 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
726 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
727 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
728 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
729 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
730 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
731 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
732 (const :tag "C mew: Links to Mew folders/messages" org-mew)
733 (const :tag "C mtags: Support for muse-like tags" org-mtags)
734 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
735 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
736 (const :tag "C registry: A registry for Org-mode links" org-registry)
737 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
738 (const :tag "C secretary: Team management with org-mode" org-secretary)
739 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
740 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
741 (const :tag "C track: Keep up with Org-mode development" org-track)
742 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
743 (const :tag "C vm: Links to VM folders/messages" org-vm)
744 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
745 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
746 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
748 (defvar org-export-registered-backends) ; From ox.el.
749 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
750 (declare-function org-export-backend-name "ox" (backend))
751 (defcustom org-export-backends '(ascii html icalendar latex)
752 "List of export back-ends that should be always available.
754 If a description starts with <C>, the file is not part of Emacs
755 and loading it will require that you have downloaded and properly
756 installed the Org mode distribution.
758 Unlike to `org-modules', libraries in this list will not be
759 loaded along with Org, but only once the export framework is
760 needed.
762 This variable needs to be set before org.el is loaded. If you
763 need to make a change while Emacs is running, use the customize
764 interface or run the following code, where VAL stands for the new
765 value of the variable, after updating it:
767 \(progn
768 \(setq org-export-registered-backends
769 \(org-remove-if-not
770 \(lambda (backend)
771 \(let ((name (org-export-backend-name backend)))
772 \(or (memq name val)
773 \(catch 'parentp
774 \(dolist (b val)
775 \(and (org-export-derived-backend-p b name)
776 \(throw 'parentp t)))))))
777 org-export-registered-backends))
778 \(let ((new-list (mapcar #'org-export-backend-name
779 org-export-registered-backends)))
780 \(dolist (backend val)
781 \(cond
782 \((not (load (format \"ox-%s\" backend) t t))
783 \(message \"Problems while trying to load export back-end `%s'\"
784 backend))
785 \((not (memq backend new-list)) (push backend new-list))))
786 \(set-default 'org-export-backends new-list)))
788 Adding a back-end to this list will also pull the back-end it
789 depends on, if any."
790 :group 'org
791 :group 'org-export
792 :version "24.4"
793 :package-version '(Org . "8.0")
794 :initialize 'custom-initialize-set
795 :set (lambda (var val)
796 (if (not (featurep 'ox)) (set-default var val)
797 ;; Any back-end not required anymore (not present in VAL and not
798 ;; a parent of any back-end in the new value) is removed from the
799 ;; list of registered back-ends.
800 (setq org-export-registered-backends
801 (org-remove-if-not
802 (lambda (backend)
803 (let ((name (org-export-backend-name backend)))
804 (or (memq name val)
805 (catch 'parentp
806 (dolist (b val)
807 (and (org-export-derived-backend-p b name)
808 (throw 'parentp t)))))))
809 org-export-registered-backends))
810 ;; Now build NEW-LIST of both new back-ends and required
811 ;; parents.
812 (let ((new-list (mapcar #'org-export-backend-name
813 org-export-registered-backends)))
814 (dolist (backend val)
815 (cond
816 ((not (load (format "ox-%s" backend) t t))
817 (message "Problems while trying to load export back-end `%s'"
818 backend))
819 ((not (memq backend new-list)) (push backend new-list))))
820 ;; Set VAR to that list with fixed dependencies.
821 (set-default var new-list))))
822 :type '(set :greedy t
823 (const :tag " ascii Export buffer to ASCII format" ascii)
824 (const :tag " beamer Export buffer to Beamer presentation" beamer)
825 (const :tag " html Export buffer to HTML format" html)
826 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
827 (const :tag " latex Export buffer to LaTeX format" latex)
828 (const :tag " man Export buffer to MAN format" man)
829 (const :tag " md Export buffer to Markdown format" md)
830 (const :tag " odt Export buffer to ODT format" odt)
831 (const :tag " org Export buffer to Org format" org)
832 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
833 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
834 (const :tag "C deck Export buffer to deck.js presentations" deck)
835 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
836 (const :tag "C groff Export buffer to Groff format" groff)
837 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
838 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
839 (const :tag "C s5 Export buffer to s5 presentations" s5)
840 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
842 (eval-after-load 'ox
843 '(mapc
844 (lambda (backend)
845 (condition-case nil (require (intern (format "ox-%s" backend)))
846 (error (message "Problems while trying to load export back-end `%s'"
847 backend))))
848 org-export-backends))
850 (defcustom org-support-shift-select nil
851 "Non-nil means make shift-cursor commands select text when possible.
853 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
854 start selecting a region, or enlarge regions started in this way.
855 In Org-mode, in special contexts, these same keys are used for
856 other purposes, important enough to compete with shift selection.
857 Org tries to balance these needs by supporting `shift-select-mode'
858 outside these special contexts, under control of this variable.
860 The default of this variable is nil, to avoid confusing behavior. Shifted
861 cursor keys will then execute Org commands in the following contexts:
862 - on a headline, changing TODO state (left/right) and priority (up/down)
863 - on a time stamp, changing the time
864 - in a plain list item, changing the bullet type
865 - in a property definition line, switching between allowed values
866 - in the BEGIN line of a clock table (changing the time block).
867 Outside these contexts, the commands will throw an error.
869 When this variable is t and the cursor is not in a special
870 context, Org-mode will support shift-selection for making and
871 enlarging regions. To make this more effective, the bullet
872 cycling will no longer happen anywhere in an item line, but only
873 if the cursor is exactly on the bullet.
875 If you set this variable to the symbol `always', then the keys
876 will not be special in headlines, property lines, and item lines,
877 to make shift selection work there as well. If this is what you
878 want, you can use the following alternative commands: `C-c C-t'
879 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
880 can be used to switch TODO sets, `C-c -' to cycle item bullet
881 types, and properties can be edited by hand or in column view.
883 However, when the cursor is on a timestamp, shift-cursor commands
884 will still edit the time stamp - this is just too good to give up.
886 XEmacs user should have this variable set to nil, because
887 `shift-select-mode' is in Emacs 23 or later only."
888 :group 'org
889 :type '(choice
890 (const :tag "Never" nil)
891 (const :tag "When outside special context" t)
892 (const :tag "Everywhere except timestamps" always)))
894 (defcustom org-loop-over-headlines-in-active-region nil
895 "Shall some commands act upon headlines in the active region?
897 When set to `t', some commands will be performed in all headlines
898 within the active region.
900 When set to `start-level', some commands will be performed in all
901 headlines within the active region, provided that these headlines
902 are of the same level than the first one.
904 When set to a string, those commands will be performed on the
905 matching headlines within the active region. Such string must be
906 a tags/property/todo match as it is used in the agenda tags view.
908 The list of commands is: `org-schedule', `org-deadline',
909 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
910 `org-archive-to-archive-sibling'. The archiving commands skip
911 already archived entries."
912 :type '(choice (const :tag "Don't loop" nil)
913 (const :tag "All headlines in active region" t)
914 (const :tag "In active region, headlines at the same level than the first one" start-level)
915 (string :tag "Tags/Property/Todo matcher"))
916 :version "24.1"
917 :group 'org-todo
918 :group 'org-archive)
920 (defgroup org-startup nil
921 "Options concerning startup of Org-mode."
922 :tag "Org Startup"
923 :group 'org)
925 (defcustom org-startup-folded t
926 "Non-nil means entering Org-mode will switch to OVERVIEW.
927 This can also be configured on a per-file basis by adding one of
928 the following lines anywhere in the buffer:
930 #+STARTUP: fold (or `overview', this is equivalent)
931 #+STARTUP: nofold (or `showall', this is equivalent)
932 #+STARTUP: content
933 #+STARTUP: showeverything
935 By default, this option is ignored when Org opens agenda files
936 for the first time. If you want the agenda to honor the startup
937 option, set `org-agenda-inhibit-startup' to nil."
938 :group 'org-startup
939 :type '(choice
940 (const :tag "nofold: show all" nil)
941 (const :tag "fold: overview" t)
942 (const :tag "content: all headlines" content)
943 (const :tag "show everything, even drawers" showeverything)))
945 (defcustom org-startup-truncated t
946 "Non-nil means entering Org-mode will set `truncate-lines'.
947 This is useful since some lines containing links can be very long and
948 uninteresting. Also tables look terrible when wrapped."
949 :group 'org-startup
950 :type 'boolean)
952 (defcustom org-startup-indented nil
953 "Non-nil means turn on `org-indent-mode' on startup.
954 This can also be configured on a per-file basis by adding one of
955 the following lines anywhere in the buffer:
957 #+STARTUP: indent
958 #+STARTUP: noindent"
959 :group 'org-structure
960 :type '(choice
961 (const :tag "Not" nil)
962 (const :tag "Globally (slow on startup in large files)" t)))
964 (defcustom org-use-sub-superscripts t
965 "Non-nil means interpret \"_\" and \"^\" for display.
967 If you want to control how Org exports those characters, see
968 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
969 used to be an alias for `org-export-with-sub-superscripts' in
970 Org <8.0, it is not anymore.
972 When this option is turned on, you can use TeX-like syntax for
973 sub- and superscripts within the buffer. Several characters after
974 \"_\" or \"^\" will be considered as a single item - so grouping
975 with {} is normally not needed. For example, the following things
976 will be parsed as single sub- or superscripts:
978 10^24 or 10^tau several digits will be considered 1 item.
979 10^-12 or 10^-tau a leading sign with digits or a word
980 x^2-y^3 will be read as x^2 - y^3, because items are
981 terminated by almost any nonword/nondigit char.
982 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
984 Still, ambiguity is possible. So when in doubt, use {} to enclose
985 the sub/superscript. If you set this variable to the symbol `{}',
986 the braces are *required* in order to trigger interpretations as
987 sub/superscript. This can be helpful in documents that need \"_\"
988 frequently in plain text."
989 :group 'org-startup
990 :version "24.4"
991 :package-version '(Org . "8.0")
992 :type '(choice
993 (const :tag "Always interpret" t)
994 (const :tag "Only with braces" {})
995 (const :tag "Never interpret" nil)))
997 (defcustom org-startup-with-beamer-mode nil
998 "Non-nil means turn on `org-beamer-mode' on startup.
999 This can also be configured on a per-file basis by adding one of
1000 the following lines anywhere in the buffer:
1002 #+STARTUP: beamer"
1003 :group 'org-startup
1004 :version "24.1"
1005 :type 'boolean)
1007 (defcustom org-startup-align-all-tables nil
1008 "Non-nil means align all tables when visiting a file.
1009 This is useful when the column width in tables is forced with <N> cookies
1010 in table fields. Such tables will look correct only after the first re-align.
1011 This can also be configured on a per-file basis by adding one of
1012 the following lines anywhere in the buffer:
1013 #+STARTUP: align
1014 #+STARTUP: noalign"
1015 :group 'org-startup
1016 :type 'boolean)
1018 (defcustom org-startup-with-inline-images nil
1019 "Non-nil means show inline images when loading a new Org file.
1020 This can also be configured on a per-file basis by adding one of
1021 the following lines anywhere in the buffer:
1022 #+STARTUP: inlineimages
1023 #+STARTUP: noinlineimages"
1024 :group 'org-startup
1025 :version "24.1"
1026 :type 'boolean)
1028 (defcustom org-startup-with-latex-preview nil
1029 "Non-nil means preview LaTeX fragments when loading a new Org file.
1031 This can also be configured on a per-file basis by adding one of
1032 the following lines anywhere in the buffer:
1033 #+STARTUP: latexpreview
1034 #+STARTUP: nolatexpreview"
1035 :group 'org-startup
1036 :version "24.4"
1037 :package-version '(Org . "8.0")
1038 :type 'boolean)
1040 (defcustom org-insert-mode-line-in-empty-file nil
1041 "Non-nil means insert the first line setting Org-mode in empty files.
1042 When the function `org-mode' is called interactively in an empty file, this
1043 normally means that the file name does not automatically trigger Org-mode.
1044 To ensure that the file will always be in Org-mode in the future, a
1045 line enforcing Org-mode will be inserted into the buffer, if this option
1046 has been set."
1047 :group 'org-startup
1048 :type 'boolean)
1050 (defcustom org-replace-disputed-keys nil
1051 "Non-nil means use alternative key bindings for some keys.
1052 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1053 These keys are also used by other packages like shift-selection-mode'
1054 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1055 If you want to use Org-mode together with one of these other modes,
1056 or more generally if you would like to move some Org-mode commands to
1057 other keys, set this variable and configure the keys with the variable
1058 `org-disputed-keys'.
1060 This option is only relevant at load-time of Org-mode, and must be set
1061 *before* org.el is loaded. Changing it requires a restart of Emacs to
1062 become effective."
1063 :group 'org-startup
1064 :type 'boolean)
1066 (defcustom org-use-extra-keys nil
1067 "Non-nil means use extra key sequence definitions for certain commands.
1068 This happens automatically if you run XEmacs or if `window-system'
1069 is nil. This variable lets you do the same manually. You must
1070 set it before loading org.
1072 Example: on Carbon Emacs 22 running graphically, with an external
1073 keyboard on a Powerbook, the default way of setting M-left might
1074 not work for either Alt or ESC. Setting this variable will make
1075 it work for ESC."
1076 :group 'org-startup
1077 :type 'boolean)
1079 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1081 (defcustom org-disputed-keys
1082 '(([(shift up)] . [(meta p)])
1083 ([(shift down)] . [(meta n)])
1084 ([(shift left)] . [(meta -)])
1085 ([(shift right)] . [(meta +)])
1086 ([(control shift right)] . [(meta shift +)])
1087 ([(control shift left)] . [(meta shift -)]))
1088 "Keys for which Org-mode and other modes compete.
1089 This is an alist, cars are the default keys, second element specifies
1090 the alternative to use when `org-replace-disputed-keys' is t.
1092 Keys can be specified in any syntax supported by `define-key'.
1093 The value of this option takes effect only at Org-mode's startup,
1094 therefore you'll have to restart Emacs to apply it after changing."
1095 :group 'org-startup
1096 :type 'alist)
1098 (defun org-key (key)
1099 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1100 Or return the original if not disputed.
1101 Also apply the translations defined in `org-xemacs-key-equivalents'."
1102 (when org-replace-disputed-keys
1103 (let* ((nkey (key-description key))
1104 (x (org-find-if (lambda (x)
1105 (equal (key-description (car x)) nkey))
1106 org-disputed-keys)))
1107 (setq key (if x (cdr x) key))))
1108 (when (featurep 'xemacs)
1109 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1110 key)
1112 (defun org-find-if (predicate seq)
1113 (catch 'exit
1114 (while seq
1115 (if (funcall predicate (car seq))
1116 (throw 'exit (car seq))
1117 (pop seq)))))
1119 (defun org-defkey (keymap key def)
1120 "Define a key, possibly translated, as returned by `org-key'."
1121 (define-key keymap (org-key key) def))
1123 (defcustom org-ellipsis nil
1124 "The ellipsis to use in the Org-mode outline.
1125 When nil, just use the standard three dots.
1126 When a string, use that string instead.
1127 When a face, use the standard 3 dots, but with the specified face.
1128 The change affects only Org-mode (which will then use its own display table).
1129 Changing this requires executing \\[org-mode] in a buffer to become
1130 effective."
1131 :group 'org-startup
1132 :type '(choice (const :tag "Default" nil)
1133 (face :tag "Face" :value org-warning)
1134 (string :tag "String" :value "...#")))
1136 (defvar org-display-table nil
1137 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1139 (defgroup org-keywords nil
1140 "Keywords in Org-mode."
1141 :tag "Org Keywords"
1142 :group 'org)
1144 (defcustom org-closed-keep-when-no-todo nil
1145 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1146 :group 'org-todo
1147 :group 'org-keywords
1148 :version "24.4"
1149 :package-version '(Org . "8.0")
1150 :type 'boolean)
1152 (defgroup org-structure nil
1153 "Options concerning the general structure of Org-mode files."
1154 :tag "Org Structure"
1155 :group 'org)
1157 (defgroup org-reveal-location nil
1158 "Options about how to make context of a location visible."
1159 :tag "Org Reveal Location"
1160 :group 'org-structure)
1162 (defcustom org-show-context-detail '((isearch . lineage)
1163 (bookmark-jump . lineage)
1164 (default . ancestors))
1165 "Alist between context and visibility span when revealing a location.
1167 \\<org-mode-map>Some actions may move point into invisible
1168 locations. As a consequence, Org always expose a neighborhood
1169 around point. How much is shown depends on the initial action,
1170 or context. Valid contexts are
1172 agenda when exposing an entry from the agenda
1173 org-goto when using the command `org-goto' (\\[org-goto])
1174 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1175 tags-tree when constructing a sparse tree based on tags matches
1176 link-search when exposing search matches associated with a link
1177 mark-goto when exposing the jump goal of a mark
1178 bookmark-jump when exposing a bookmark location
1179 isearch when exiting from an incremental search
1180 default default for all contexts not set explicitly
1182 Allowed visibility spans are
1184 minimal show current headline; if point is not on headline,
1185 also show entry
1187 local show current headline, entry and next headline
1189 ancestors show current headline and its direct ancestors; if
1190 point is not on headline, also show entry
1192 lineage show current headline, its direct ancestors and all
1193 their children; if point is not on headline, also show
1194 entry and first child
1196 tree show current headline, its direct ancestors and all
1197 their children; if point is not on headline, also show
1198 entry and all children
1200 canonical show current headline, its direct ancestors along with
1201 their entries and children; if point is not located on
1202 the headline, also show current entry and all children
1204 As special cases, a nil or t value means show all contexts in
1205 `minimal' or `canonical' view, respectively.
1207 Some views can make displayed information very compact, but also
1208 make it harder to edit the location of the match. In such
1209 a case, use the command `org-reveal' (\\[org-reveal]) to show
1210 more context."
1211 :group 'org-reveal-location
1212 :version "25.1"
1213 :package-version '(Org . "8.3")
1214 :type '(choice
1215 (const :tag "Canonical" t)
1216 (const :tag "Minimal" nil)
1217 (repeat :greedy t :tag "Individual contexts"
1218 (cons
1219 (choice :tag "Context"
1220 (const agenda)
1221 (const org-goto)
1222 (const occur-tree)
1223 (const tags-tree)
1224 (const link-search)
1225 (const mark-goto)
1226 (const bookmark-jump)
1227 (const isearch)
1228 (const default))
1229 (choice :tag "Detail level"
1230 (const minimal)
1231 (const local)
1232 (const ancestors)
1233 (const lineage)
1234 (const tree)
1235 (const canonical))))))
1237 (defcustom org-indirect-buffer-display 'other-window
1238 "How should indirect tree buffers be displayed?
1239 This applies to indirect buffers created with the commands
1240 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1241 Valid values are:
1242 current-window Display in the current window
1243 other-window Just display in another window.
1244 dedicated-frame Create one new frame, and re-use it each time.
1245 new-frame Make a new frame each time. Note that in this case
1246 previously-made indirect buffers are kept, and you need to
1247 kill these buffers yourself."
1248 :group 'org-structure
1249 :group 'org-agenda-windows
1250 :type '(choice
1251 (const :tag "In current window" current-window)
1252 (const :tag "In current frame, other window" other-window)
1253 (const :tag "Each time a new frame" new-frame)
1254 (const :tag "One dedicated frame" dedicated-frame)))
1256 (defcustom org-use-speed-commands nil
1257 "Non-nil means activate single letter commands at beginning of a headline.
1258 This may also be a function to test for appropriate locations where speed
1259 commands should be active.
1261 For example, to activate speed commands when the point is on any
1262 star at the beginning of the headline, you can do this:
1264 (setq org-use-speed-commands
1265 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1266 :group 'org-structure
1267 :type '(choice
1268 (const :tag "Never" nil)
1269 (const :tag "At beginning of headline stars" t)
1270 (function)))
1272 (defcustom org-speed-commands-user nil
1273 "Alist of additional speed commands.
1274 This list will be checked before `org-speed-commands-default'
1275 when the variable `org-use-speed-commands' is non-nil
1276 and when the cursor is at the beginning of a headline.
1277 The car if each entry is a string with a single letter, which must
1278 be assigned to `self-insert-command' in the global map.
1279 The cdr is either a command to be called interactively, a function
1280 to be called, or a form to be evaluated.
1281 An entry that is just a list with a single string will be interpreted
1282 as a descriptive headline that will be added when listing the speed
1283 commands in the Help buffer using the `?' speed command."
1284 :group 'org-structure
1285 :type '(repeat :value ("k" . ignore)
1286 (choice :value ("k" . ignore)
1287 (list :tag "Descriptive Headline" (string :tag "Headline"))
1288 (cons :tag "Letter and Command"
1289 (string :tag "Command letter")
1290 (choice
1291 (function)
1292 (sexp))))))
1294 (defcustom org-bookmark-names-plist
1295 '(:last-capture "org-capture-last-stored"
1296 :last-refile "org-refile-last-stored"
1297 :last-capture-marker "org-capture-last-stored-marker")
1298 "Names for bookmarks automatically set by some Org commands.
1299 This can provide strings as names for a number of bookmarks Org sets
1300 automatically. The following keys are currently implemented:
1301 :last-capture
1302 :last-capture-marker
1303 :last-refile
1304 When a key does not show up in the property list, the corresponding bookmark
1305 is not set."
1306 :group 'org-structure
1307 :type 'plist)
1309 (defgroup org-cycle nil
1310 "Options concerning visibility cycling in Org-mode."
1311 :tag "Org Cycle"
1312 :group 'org-structure)
1314 (defcustom org-cycle-skip-children-state-if-no-children t
1315 "Non-nil means skip CHILDREN state in entries that don't have any."
1316 :group 'org-cycle
1317 :type 'boolean)
1319 (defcustom org-cycle-max-level nil
1320 "Maximum level which should still be subject to visibility cycling.
1321 Levels higher than this will, for cycling, be treated as text, not a headline.
1322 When `org-odd-levels-only' is set, a value of N in this variable actually
1323 means 2N-1 stars as the limiting headline.
1324 When nil, cycle all levels.
1325 Note that the limiting level of cycling is also influenced by
1326 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1327 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1328 than its value."
1329 :group 'org-cycle
1330 :type '(choice
1331 (const :tag "No limit" nil)
1332 (integer :tag "Maximum level")))
1334 (defcustom org-hide-block-startup nil
1335 "Non-nil means entering Org-mode will fold all blocks.
1336 This can also be set in on a per-file basis with
1338 #+STARTUP: hideblocks
1339 #+STARTUP: showblocks"
1340 :group 'org-startup
1341 :group 'org-cycle
1342 :type 'boolean)
1344 (defcustom org-cycle-global-at-bob nil
1345 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1346 This makes it possible to do global cycling without having to use S-TAB or
1347 \\[universal-argument] TAB. For this special case to work, the first line
1348 of the buffer must not be a headline -- it may be empty or some other text.
1349 When used in this way, `org-cycle-hook' is disabled temporarily to make
1350 sure the cursor stays at the beginning of the buffer. When this option is
1351 nil, don't do anything special at the beginning of the buffer."
1352 :group 'org-cycle
1353 :type 'boolean)
1355 (defcustom org-cycle-level-after-item/entry-creation t
1356 "Non-nil means cycle entry level or item indentation in new empty entries.
1358 When the cursor is at the end of an empty headline, i.e., with only stars
1359 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1360 and then all possible ancestor states, before returning to the original state.
1361 This makes data entry extremely fast: M-RET to create a new headline,
1362 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1364 When the cursor is at the end of an empty plain list item, one TAB will
1365 make it a subitem, two or more tabs will back up to make this an item
1366 higher up in the item hierarchy."
1367 :group 'org-cycle
1368 :type 'boolean)
1370 (defcustom org-cycle-emulate-tab t
1371 "Where should `org-cycle' emulate TAB.
1372 nil Never
1373 white Only in completely white lines
1374 whitestart Only at the beginning of lines, before the first non-white char
1375 t Everywhere except in headlines
1376 exc-hl-bol Everywhere except at the start of a headline
1377 If TAB is used in a place where it does not emulate TAB, the current subtree
1378 visibility is cycled."
1379 :group 'org-cycle
1380 :type '(choice (const :tag "Never" nil)
1381 (const :tag "Only in completely white lines" white)
1382 (const :tag "Before first char in a line" whitestart)
1383 (const :tag "Everywhere except in headlines" t)
1384 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1386 (defcustom org-cycle-separator-lines 2
1387 "Number of empty lines needed to keep an empty line between collapsed trees.
1388 If you leave an empty line between the end of a subtree and the following
1389 headline, this empty line is hidden when the subtree is folded.
1390 Org-mode will leave (exactly) one empty line visible if the number of
1391 empty lines is equal or larger to the number given in this variable.
1392 So the default 2 means at least 2 empty lines after the end of a subtree
1393 are needed to produce free space between a collapsed subtree and the
1394 following headline.
1396 If the number is negative, and the number of empty lines is at least -N,
1397 all empty lines are shown.
1399 Special case: when 0, never leave empty lines in collapsed view."
1400 :group 'org-cycle
1401 :type 'integer)
1402 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1404 (defcustom org-pre-cycle-hook nil
1405 "Hook that is run before visibility cycling is happening.
1406 The function(s) in this hook must accept a single argument which indicates
1407 the new state that will be set right after running this hook. The
1408 argument is a symbol. Before a global state change, it can have the values
1409 `overview', `content', or `all'. Before a local state change, it can have
1410 the values `folded', `children', or `subtree'."
1411 :group 'org-cycle
1412 :type 'hook)
1414 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1415 org-cycle-hide-drawers
1416 org-cycle-show-empty-lines
1417 org-optimize-window-after-visibility-change)
1418 "Hook that is run after `org-cycle' has changed the buffer visibility.
1419 The function(s) in this hook must accept a single argument which indicates
1420 the new state that was set by the most recent `org-cycle' command. The
1421 argument is a symbol. After a global state change, it can have the values
1422 `overview', `contents', or `all'. After a local state change, it can have
1423 the values `folded', `children', or `subtree'."
1424 :group 'org-cycle
1425 :type 'hook
1426 :version "25.1"
1427 :package-version '(Org . "8.3"))
1429 (defgroup org-edit-structure nil
1430 "Options concerning structure editing in Org-mode."
1431 :tag "Org Edit Structure"
1432 :group 'org-structure)
1434 (defcustom org-odd-levels-only nil
1435 "Non-nil means skip even levels and only use odd levels for the outline.
1436 This has the effect that two stars are being added/taken away in
1437 promotion/demotion commands. It also influences how levels are
1438 handled by the exporters.
1439 Changing it requires restart of `font-lock-mode' to become effective
1440 for fontification also in regions already fontified.
1441 You may also set this on a per-file basis by adding one of the following
1442 lines to the buffer:
1444 #+STARTUP: odd
1445 #+STARTUP: oddeven"
1446 :group 'org-edit-structure
1447 :group 'org-appearance
1448 :type 'boolean)
1450 (defcustom org-adapt-indentation t
1451 "Non-nil means adapt indentation to outline node level.
1453 When this variable is set, Org assumes that you write outlines by
1454 indenting text in each node to align with the headline (after the
1455 stars). The following issues are influenced by this variable:
1457 - The indentation is increased by one space in a demotion
1458 command, and decreased by one in a promotion command. However,
1459 in the latter case, if shifting some line in the entry body
1460 would alter document structure (e.g., insert a new headline),
1461 indentation is not changed at all.
1463 - Property drawers and planning information is inserted indented
1464 when this variable is set. When nil, they will not be indented.
1466 - TAB indents a line relative to current level. The lines below
1467 a headline will be indented when this variable is set.
1469 Note that this is all about true indentation, by adding and
1470 removing space characters. See also `org-indent.el' which does
1471 level-dependent indentation in a virtual way, i.e. at display
1472 time in Emacs."
1473 :group 'org-edit-structure
1474 :type 'boolean)
1476 (defcustom org-special-ctrl-a/e nil
1477 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1479 When t, `C-a' will bring back the cursor to the beginning of the
1480 headline text, i.e. after the stars and after a possible TODO
1481 keyword. In an item, this will be the position after bullet and
1482 check-box, if any. When the cursor is already at that position,
1483 another `C-a' will bring it to the beginning of the line.
1485 `C-e' will jump to the end of the headline, ignoring the presence
1486 of tags in the headline. A second `C-e' will then jump to the
1487 true end of the line, after any tags. This also means that, when
1488 this variable is non-nil, `C-e' also will never jump beyond the
1489 end of the heading of a folded section, i.e. not after the
1490 ellipses.
1492 When set to the symbol `reversed', the first `C-a' or `C-e' works
1493 normally, going to the true line boundary first. Only a directly
1494 following, identical keypress will bring the cursor to the
1495 special positions.
1497 This may also be a cons cell where the behavior for `C-a' and
1498 `C-e' is set separately."
1499 :group 'org-edit-structure
1500 :type '(choice
1501 (const :tag "off" nil)
1502 (const :tag "on: after stars/bullet and before tags first" t)
1503 (const :tag "reversed: true line boundary first" reversed)
1504 (cons :tag "Set C-a and C-e separately"
1505 (choice :tag "Special C-a"
1506 (const :tag "off" nil)
1507 (const :tag "on: after stars/bullet first" t)
1508 (const :tag "reversed: before stars/bullet first" reversed))
1509 (choice :tag "Special C-e"
1510 (const :tag "off" nil)
1511 (const :tag "on: before tags first" t)
1512 (const :tag "reversed: after tags first" reversed)))))
1513 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1515 (defcustom org-special-ctrl-k nil
1516 "Non-nil means `C-k' will behave specially in headlines.
1517 When nil, `C-k' will call the default `kill-line' command.
1518 When t, the following will happen while the cursor is in the headline:
1520 - When the cursor is at the beginning of a headline, kill the entire
1521 line and possible the folded subtree below the line.
1522 - When in the middle of the headline text, kill the headline up to the tags.
1523 - When after the headline text, kill the tags."
1524 :group 'org-edit-structure
1525 :type 'boolean)
1527 (defcustom org-ctrl-k-protect-subtree nil
1528 "Non-nil means, do not delete a hidden subtree with C-k.
1529 When set to the symbol `error', simply throw an error when C-k is
1530 used to kill (part-of) a headline that has hidden text behind it.
1531 Any other non-nil value will result in a query to the user, if it is
1532 OK to kill that hidden subtree. When nil, kill without remorse."
1533 :group 'org-edit-structure
1534 :version "24.1"
1535 :type '(choice
1536 (const :tag "Do not protect hidden subtrees" nil)
1537 (const :tag "Protect hidden subtrees with a security query" t)
1538 (const :tag "Never kill a hidden subtree with C-k" error)))
1540 (defcustom org-special-ctrl-o t
1541 "Non-nil means, make `C-o' insert a row in tables."
1542 :group 'org-edit-structure
1543 :type 'boolean)
1545 (defcustom org-catch-invisible-edits nil
1546 "Check if in invisible region before inserting or deleting a character.
1547 Valid values are:
1549 nil Do not check, so just do invisible edits.
1550 error Throw an error and do nothing.
1551 show Make point visible, and do the requested edit.
1552 show-and-error Make point visible, then throw an error and abort the edit.
1553 smart Make point visible, and do insertion/deletion if it is
1554 adjacent to visible text and the change feels predictable.
1555 Never delete a previously invisible character or add in the
1556 middle or right after an invisible region. Basically, this
1557 allows insertion and backward-delete right before ellipses.
1558 FIXME: maybe in this case we should not even show?"
1559 :group 'org-edit-structure
1560 :version "24.1"
1561 :type '(choice
1562 (const :tag "Do not check" nil)
1563 (const :tag "Throw error when trying to edit" error)
1564 (const :tag "Unhide, but do not do the edit" show-and-error)
1565 (const :tag "Show invisible part and do the edit" show)
1566 (const :tag "Be smart and do the right thing" smart)))
1568 (defcustom org-yank-folded-subtrees t
1569 "Non-nil means when yanking subtrees, fold them.
1570 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1571 it starts with a heading and all other headings in it are either children
1572 or siblings, then fold all the subtrees. However, do this only if no
1573 text after the yank would be swallowed into a folded tree by this action."
1574 :group 'org-edit-structure
1575 :type 'boolean)
1577 (defcustom org-yank-adjusted-subtrees nil
1578 "Non-nil means when yanking subtrees, adjust the level.
1579 With this setting, `org-paste-subtree' is used to insert the subtree, see
1580 this function for details."
1581 :group 'org-edit-structure
1582 :type 'boolean)
1584 (defcustom org-M-RET-may-split-line '((default . t))
1585 "Non-nil means M-RET will split the line at the cursor position.
1586 When nil, it will go to the end of the line before making a
1587 new line.
1588 You may also set this option in a different way for different
1589 contexts. Valid contexts are:
1591 headline when creating a new headline
1592 item when creating a new item
1593 table in a table field
1594 default the value to be used for all contexts not explicitly
1595 customized"
1596 :group 'org-structure
1597 :group 'org-table
1598 :type '(choice
1599 (const :tag "Always" t)
1600 (const :tag "Never" nil)
1601 (repeat :greedy t :tag "Individual contexts"
1602 (cons
1603 (choice :tag "Context"
1604 (const headline)
1605 (const item)
1606 (const table)
1607 (const default))
1608 (boolean)))))
1611 (defcustom org-insert-heading-respect-content nil
1612 "Non-nil means insert new headings after the current subtree.
1613 When nil, the new heading is created directly after the current line.
1614 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1615 this variable on for the duration of the command."
1616 :group 'org-structure
1617 :type 'boolean)
1619 (defcustom org-blank-before-new-entry '((heading . auto)
1620 (plain-list-item . auto))
1621 "Should `org-insert-heading' leave a blank line before new heading/item?
1622 The value is an alist, with `heading' and `plain-list-item' as CAR,
1623 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1624 which case Org will look at the surrounding headings/items and try to
1625 make an intelligent decision whether to insert a blank line or not.
1627 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1628 the setting here is ignored and no empty line is inserted to avoid breaking
1629 the list structure."
1630 :group 'org-edit-structure
1631 :type '(list
1632 (cons (const heading)
1633 (choice (const :tag "Never" nil)
1634 (const :tag "Always" t)
1635 (const :tag "Auto" auto)))
1636 (cons (const plain-list-item)
1637 (choice (const :tag "Never" nil)
1638 (const :tag "Always" t)
1639 (const :tag "Auto" auto)))))
1641 (defcustom org-insert-heading-hook nil
1642 "Hook being run after inserting a new heading."
1643 :group 'org-edit-structure
1644 :type 'hook)
1646 (defcustom org-enable-fixed-width-editor t
1647 "Non-nil means lines starting with \":\" are treated as fixed-width.
1648 This currently only means they are never auto-wrapped.
1649 When nil, such lines will be treated like ordinary lines."
1650 :group 'org-edit-structure
1651 :type 'boolean)
1653 (defcustom org-goto-auto-isearch t
1654 "Non-nil means typing characters in `org-goto' starts incremental search.
1655 When nil, you can use these keybindings to navigate the buffer:
1657 q Quit the org-goto interface
1658 n Go to the next visible heading
1659 p Go to the previous visible heading
1660 f Go one heading forward on same level
1661 b Go one heading backward on same level
1662 u Go one heading up"
1663 :group 'org-edit-structure
1664 :type 'boolean)
1666 (defgroup org-sparse-trees nil
1667 "Options concerning sparse trees in Org-mode."
1668 :tag "Org Sparse Trees"
1669 :group 'org-structure)
1671 (defcustom org-highlight-sparse-tree-matches t
1672 "Non-nil means highlight all matches that define a sparse tree.
1673 The highlights will automatically disappear the next time the buffer is
1674 changed by an edit command."
1675 :group 'org-sparse-trees
1676 :type 'boolean)
1678 (defcustom org-remove-highlights-with-change t
1679 "Non-nil means any change to the buffer will remove temporary highlights.
1680 Such highlights are created by `org-occur' and `org-clock-display'.
1681 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1682 The highlights created by `org-toggle-latex-fragment' always need
1683 `C-c C-x C-l' to be removed."
1684 :group 'org-sparse-trees
1685 :group 'org-time
1686 :type 'boolean)
1689 (defcustom org-occur-hook '(org-first-headline-recenter)
1690 "Hook that is run after `org-occur' has constructed a sparse tree.
1691 This can be used to recenter the window to show as much of the structure
1692 as possible."
1693 :group 'org-sparse-trees
1694 :type 'hook)
1696 (defgroup org-imenu-and-speedbar nil
1697 "Options concerning imenu and speedbar in Org-mode."
1698 :tag "Org Imenu and Speedbar"
1699 :group 'org-structure)
1701 (defcustom org-imenu-depth 2
1702 "The maximum level for Imenu access to Org-mode headlines.
1703 This also applied for speedbar access."
1704 :group 'org-imenu-and-speedbar
1705 :type 'integer)
1707 (defgroup org-table nil
1708 "Options concerning tables in Org-mode."
1709 :tag "Org Table"
1710 :group 'org)
1712 (defcustom org-enable-table-editor 'optimized
1713 "Non-nil means lines starting with \"|\" are handled by the table editor.
1714 When nil, such lines will be treated like ordinary lines.
1716 When equal to the symbol `optimized', the table editor will be optimized to
1717 do the following:
1718 - Automatic overwrite mode in front of whitespace in table fields.
1719 This makes the structure of the table stay in tact as long as the edited
1720 field does not exceed the column width.
1721 - Minimize the number of realigns. Normally, the table is aligned each time
1722 TAB or RET are pressed to move to another field. With optimization this
1723 happens only if changes to a field might have changed the column width.
1724 Optimization requires replacing the functions `self-insert-command',
1725 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1726 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1727 very good at guessing when a re-align will be necessary, but you can always
1728 force one with \\[org-ctrl-c-ctrl-c].
1730 If you would like to use the optimized version in Org-mode, but the
1731 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1733 This variable can be used to turn on and off the table editor during a session,
1734 but in order to toggle optimization, a restart is required.
1736 See also the variable `org-table-auto-blank-field'."
1737 :group 'org-table
1738 :type '(choice
1739 (const :tag "off" nil)
1740 (const :tag "on" t)
1741 (const :tag "on, optimized" optimized)))
1743 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1744 (version<= emacs-version "24.1"))
1745 "Non-nil means cluster self-insert commands for undo when possible.
1746 If this is set, then, like in the Emacs command loop, 20 consecutive
1747 characters will be undone together.
1748 This is configurable, because there is some impact on typing performance."
1749 :group 'org-table
1750 :type 'boolean)
1752 (defcustom org-table-tab-recognizes-table.el t
1753 "Non-nil means TAB will automatically notice a table.el table.
1754 When it sees such a table, it moves point into it and - if necessary -
1755 calls `table-recognize-table'."
1756 :group 'org-table-editing
1757 :type 'boolean)
1759 (defgroup org-link nil
1760 "Options concerning links in Org-mode."
1761 :tag "Org Link"
1762 :group 'org)
1764 (defvar org-link-abbrev-alist-local nil
1765 "Buffer-local version of `org-link-abbrev-alist', which see.
1766 The value of this is taken from the #+LINK lines.")
1767 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1769 (defcustom org-link-abbrev-alist nil
1770 "Alist of link abbreviations.
1771 The car of each element is a string, to be replaced at the start of a link.
1772 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1773 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1775 [[linkkey:tag][description]]
1777 The 'linkkey' must be a word word, starting with a letter, followed
1778 by letters, numbers, '-' or '_'.
1780 If REPLACE is a string, the tag will simply be appended to create the link.
1781 If the string contains \"%s\", the tag will be inserted there. If the string
1782 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1783 at that point (see the function `url-hexify-string'). If the string contains
1784 the specifier \"%(my-function)\", then the custom function `my-function' will
1785 be invoked: this function takes the tag as its only argument and must return
1786 a string.
1788 REPLACE may also be a function that will be called with the tag as the
1789 only argument to create the link, which should be returned as a string.
1791 See the manual for examples."
1792 :group 'org-link
1793 :type '(repeat
1794 (cons
1795 (string :tag "Protocol")
1796 (choice
1797 (string :tag "Format")
1798 (function)))))
1800 (defcustom org-descriptive-links t
1801 "Non-nil means Org will display descriptive links.
1802 E.g. [[http://orgmode.org][Org website]] will be displayed as
1803 \"Org Website\", hiding the link itself and just displaying its
1804 description. When set to `nil', Org will display the full links
1805 literally.
1807 You can interactively set the value of this variable by calling
1808 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1809 :group 'org-link
1810 :type 'boolean)
1812 (defcustom org-link-file-path-type 'adaptive
1813 "How the path name in file links should be stored.
1814 Valid values are:
1816 relative Relative to the current directory, i.e. the directory of the file
1817 into which the link is being inserted.
1818 absolute Absolute path, if possible with ~ for home directory.
1819 noabbrev Absolute path, no abbreviation of home directory.
1820 adaptive Use relative path for files in the current directory and sub-
1821 directories of it. For other files, use an absolute path."
1822 :group 'org-link
1823 :type '(choice
1824 (const relative)
1825 (const absolute)
1826 (const noabbrev)
1827 (const adaptive)))
1829 (defvaralias 'org-activate-links 'org-highlight-links)
1830 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1831 "Types of links that should be highlighted in Org-mode files.
1833 This is a list of symbols, each one of them leading to the
1834 highlighting of a certain link type.
1836 You can still open links that are not highlighted.
1838 In principle, it does not hurt to turn on highlighting for all
1839 link types. There may be a small gain when turning off unused
1840 link types. The types are:
1842 bracket The recommended [[link][description]] or [[link]] links with hiding.
1843 angle Links in angular brackets that may contain whitespace like
1844 <bbdb:Carsten Dominik>.
1845 plain Plain links in normal text, no whitespace, like http://google.com.
1846 radio Text that is matched by a radio target, see manual for details.
1847 tag Tag settings in a headline (link to tag search).
1848 date Time stamps (link to calendar).
1849 footnote Footnote labels.
1851 If you set this variable during an Emacs session, use `org-mode-restart'
1852 in the Org buffer so that the change takes effect."
1853 :group 'org-link
1854 :group 'org-appearance
1855 :type '(set :greedy t
1856 (const :tag "Double bracket links" bracket)
1857 (const :tag "Angular bracket links" angle)
1858 (const :tag "Plain text links" plain)
1859 (const :tag "Radio target matches" radio)
1860 (const :tag "Tags" tag)
1861 (const :tag "Timestamps" date)
1862 (const :tag "Footnotes" footnote)))
1864 (defcustom org-make-link-description-function nil
1865 "Function to use for generating link descriptions from links.
1866 When nil, the link location will be used. This function must take
1867 two parameters: the first one is the link, the second one is the
1868 description generated by `org-insert-link'. The function should
1869 return the description to use."
1870 :group 'org-link
1871 :type '(choice (const nil) (function)))
1873 (defgroup org-link-store nil
1874 "Options concerning storing links in Org-mode."
1875 :tag "Org Store Link"
1876 :group 'org-link)
1878 (defcustom org-url-hexify-p t
1879 "When non-nil, hexify URL when creating a link."
1880 :type 'boolean
1881 :version "24.3"
1882 :group 'org-link-store)
1884 (defcustom org-email-link-description-format "Email %c: %.30s"
1885 "Format of the description part of a link to an email or usenet message.
1886 The following %-escapes will be replaced by corresponding information:
1888 %F full \"From\" field
1889 %f name, taken from \"From\" field, address if no name
1890 %T full \"To\" field
1891 %t first name in \"To\" field, address if no name
1892 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1893 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1894 %s subject
1895 %d date
1896 %m message-id.
1898 You may use normal field width specification between the % and the letter.
1899 This is for example useful to limit the length of the subject.
1901 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1902 :group 'org-link-store
1903 :type 'string)
1905 (defcustom org-from-is-user-regexp
1906 (let (r1 r2)
1907 (when (and user-mail-address (not (string= user-mail-address "")))
1908 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1909 (when (and user-full-name (not (string= user-full-name "")))
1910 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1911 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1912 "Regexp matched against the \"From:\" header of an email or usenet message.
1913 It should match if the message is from the user him/herself."
1914 :group 'org-link-store
1915 :type 'regexp)
1917 (defcustom org-context-in-file-links t
1918 "Non-nil means file links from `org-store-link' contain context.
1919 A search string will be added to the file name with :: as separator and
1920 used to find the context when the link is activated by the command
1921 `org-open-at-point'. When this option is t, the entire active region
1922 will be placed in the search string of the file link. If set to a
1923 positive integer, only the first n lines of context will be stored.
1925 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1926 negates this setting for the duration of the command."
1927 :group 'org-link-store
1928 :type '(choice boolean integer))
1930 (defcustom org-keep-stored-link-after-insertion nil
1931 "Non-nil means keep link in list for entire session.
1933 The command `org-store-link' adds a link pointing to the current
1934 location to an internal list. These links accumulate during a session.
1935 The command `org-insert-link' can be used to insert links into any
1936 Org-mode file (offering completion for all stored links). When this
1937 option is nil, every link which has been inserted once using \\[org-insert-link]
1938 will be removed from the list, to make completing the unused links
1939 more efficient."
1940 :group 'org-link-store
1941 :type 'boolean)
1943 (defgroup org-link-follow nil
1944 "Options concerning following links in Org-mode."
1945 :tag "Org Follow Link"
1946 :group 'org-link)
1948 (defcustom org-link-translation-function nil
1949 "Function to translate links with different syntax to Org syntax.
1950 This can be used to translate links created for example by the Planner
1951 or emacs-wiki packages to Org syntax.
1952 The function must accept two parameters, a TYPE containing the link
1953 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1954 which is everything after the link protocol. It should return a cons
1955 with possibly modified values of type and path.
1956 Org contains a function for this, so if you set this variable to
1957 `org-translate-link-from-planner', you should be able follow many
1958 links created by planner."
1959 :group 'org-link-follow
1960 :type '(choice (const nil) (function)))
1962 (defcustom org-follow-link-hook nil
1963 "Hook that is run after a link has been followed."
1964 :group 'org-link-follow
1965 :type 'hook)
1967 (defcustom org-tab-follows-link nil
1968 "Non-nil means on links TAB will follow the link.
1969 Needs to be set before org.el is loaded.
1970 This really should not be used, it does not make sense, and the
1971 implementation is bad."
1972 :group 'org-link-follow
1973 :type 'boolean)
1975 (defcustom org-return-follows-link nil
1976 "Non-nil means on links RET will follow the link.
1977 In tables, the special behavior of RET has precedence."
1978 :group 'org-link-follow
1979 :type 'boolean)
1981 (defcustom org-mouse-1-follows-link
1982 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1983 "Non-nil means mouse-1 on a link will follow the link.
1984 A longer mouse click will still set point. Does not work on XEmacs.
1985 Needs to be set before org.el is loaded."
1986 :group 'org-link-follow
1987 :version "24.4"
1988 :package-version '(Org . "8.3")
1989 :type '(choice
1990 (const :tag "A double click follows the link" double)
1991 (const :tag "Unconditionally follow the link with mouse-1" t)
1992 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1994 (defcustom org-mark-ring-length 4
1995 "Number of different positions to be recorded in the ring.
1996 Changing this requires a restart of Emacs to work correctly."
1997 :group 'org-link-follow
1998 :type 'integer)
2000 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2001 "Non-nil means internal links in Org files must exactly match a headline.
2002 When nil, the link search tries to match a phrase with all words
2003 in the search text."
2004 :group 'org-link-follow
2005 :version "24.1"
2006 :type '(choice
2007 (const :tag "Use fuzzy text search" nil)
2008 (const :tag "Match only exact headline" t)
2009 (const :tag "Match exact headline or query to create it"
2010 query-to-create)))
2012 (defcustom org-link-frame-setup
2013 '((vm . vm-visit-folder-other-frame)
2014 (vm-imap . vm-visit-imap-folder-other-frame)
2015 (gnus . org-gnus-no-new-news)
2016 (file . find-file-other-window)
2017 (wl . wl-other-frame))
2018 "Setup the frame configuration for following links.
2019 When following a link with Emacs, it may often be useful to display
2020 this link in another window or frame. This variable can be used to
2021 set this up for the different types of links.
2022 For VM, use any of
2023 `vm-visit-folder'
2024 `vm-visit-folder-other-window'
2025 `vm-visit-folder-other-frame'
2026 For Gnus, use any of
2027 `gnus'
2028 `gnus-other-frame'
2029 `org-gnus-no-new-news'
2030 For FILE, use any of
2031 `find-file'
2032 `find-file-other-window'
2033 `find-file-other-frame'
2034 For Wanderlust use any of
2035 `wl'
2036 `wl-other-frame'
2037 For the calendar, use the variable `calendar-setup'.
2038 For BBDB, it is currently only possible to display the matches in
2039 another window."
2040 :group 'org-link-follow
2041 :type '(list
2042 (cons (const vm)
2043 (choice
2044 (const vm-visit-folder)
2045 (const vm-visit-folder-other-window)
2046 (const vm-visit-folder-other-frame)))
2047 (cons (const vm-imap)
2048 (choice
2049 (const vm-visit-imap-folder)
2050 (const vm-visit-imap-folder-other-window)
2051 (const vm-visit-imap-folder-other-frame)))
2052 (cons (const gnus)
2053 (choice
2054 (const gnus)
2055 (const gnus-other-frame)
2056 (const org-gnus-no-new-news)))
2057 (cons (const file)
2058 (choice
2059 (const find-file)
2060 (const find-file-other-window)
2061 (const find-file-other-frame)))
2062 (cons (const wl)
2063 (choice
2064 (const wl)
2065 (const wl-other-frame)))))
2067 (defcustom org-display-internal-link-with-indirect-buffer nil
2068 "Non-nil means use indirect buffer to display infile links.
2069 Activating internal links (from one location in a file to another location
2070 in the same file) normally just jumps to the location. When the link is
2071 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2072 is displayed in
2073 another window. When this option is set, the other window actually displays
2074 an indirect buffer clone of the current buffer, to avoid any visibility
2075 changes to the current buffer."
2076 :group 'org-link-follow
2077 :type 'boolean)
2079 (defcustom org-open-non-existing-files nil
2080 "Non-nil means `org-open-file' will open non-existing files.
2081 When nil, an error will be generated.
2082 This variable applies only to external applications because they
2083 might choke on non-existing files. If the link is to a file that
2084 will be opened in Emacs, the variable is ignored."
2085 :group 'org-link-follow
2086 :type 'boolean)
2088 (defcustom org-open-directory-means-index-dot-org nil
2089 "Non-nil means a link to a directory really means to index.org.
2090 When nil, following a directory link will run dired or open a finder/explorer
2091 window on that directory."
2092 :group 'org-link-follow
2093 :type 'boolean)
2095 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2096 "Non-nil means ask for confirmation before executing shell links.
2097 Shell links can be dangerous: just think about a link
2099 [[shell:rm -rf ~/*][Google Search]]
2101 This link would show up in your Org-mode document as \"Google Search\",
2102 but really it would remove your entire home directory.
2103 Therefore we advise against setting this variable to nil.
2104 Just change it to `y-or-n-p' if you want to confirm with a
2105 single keystroke rather than having to type \"yes\"."
2106 :group 'org-link-follow
2107 :type '(choice
2108 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2109 (const :tag "with y-or-n (faster)" y-or-n-p)
2110 (const :tag "no confirmation (dangerous)" nil)))
2111 (put 'org-confirm-shell-link-function
2112 'safe-local-variable
2113 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2115 (defcustom org-confirm-shell-link-not-regexp ""
2116 "A regexp to skip confirmation for shell links."
2117 :group 'org-link-follow
2118 :version "24.1"
2119 :type 'regexp)
2121 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2122 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2123 Elisp links can be dangerous: just think about a link
2125 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2127 This link would show up in your Org-mode document as \"Google Search\",
2128 but really it would remove your entire home directory.
2129 Therefore we advise against setting this variable to nil.
2130 Just change it to `y-or-n-p' if you want to confirm with a
2131 single keystroke rather than having to type \"yes\"."
2132 :group 'org-link-follow
2133 :type '(choice
2134 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2135 (const :tag "with y-or-n (faster)" y-or-n-p)
2136 (const :tag "no confirmation (dangerous)" nil)))
2137 (put 'org-confirm-shell-link-function
2138 'safe-local-variable
2139 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2141 (defcustom org-confirm-elisp-link-not-regexp ""
2142 "A regexp to skip confirmation for Elisp links."
2143 :group 'org-link-follow
2144 :version "24.1"
2145 :type 'regexp)
2147 (defconst org-file-apps-defaults-gnu
2148 '((remote . emacs)
2149 (system . mailcap)
2150 (t . mailcap))
2151 "Default file applications on a UNIX or GNU/Linux system.
2152 See `org-file-apps'.")
2154 (defconst org-file-apps-defaults-macosx
2155 '((remote . emacs)
2156 (t . "open %s")
2157 (system . "open %s")
2158 ("ps.gz" . "gv %s")
2159 ("eps.gz" . "gv %s")
2160 ("dvi" . "xdvi %s")
2161 ("fig" . "xfig %s"))
2162 "Default file applications on a MacOS X system.
2163 The system \"open\" is known as a default, but we use X11 applications
2164 for some files for which the OS does not have a good default.
2165 See `org-file-apps'.")
2167 (defconst org-file-apps-defaults-windowsnt
2168 (list
2169 '(remote . emacs)
2170 (cons t
2171 (list (if (featurep 'xemacs)
2172 'mswindows-shell-execute
2173 'w32-shell-execute)
2174 "open" 'file))
2175 (cons 'system
2176 (list (if (featurep 'xemacs)
2177 'mswindows-shell-execute
2178 'w32-shell-execute)
2179 "open" 'file)))
2180 "Default file applications on a Windows NT system.
2181 The system \"open\" is used for most files.
2182 See `org-file-apps'.")
2184 (defcustom org-file-apps
2185 '((auto-mode . emacs)
2186 ("\\.mm\\'" . default)
2187 ("\\.x?html?\\'" . default)
2188 ("\\.pdf\\'" . default))
2189 "External applications for opening `file:path' items in a document.
2190 Org-mode uses system defaults for different file types, but
2191 you can use this variable to set the application for a given file
2192 extension. The entries in this list are cons cells where the car identifies
2193 files and the cdr the corresponding command. Possible values for the
2194 file identifier are
2195 \"string\" A string as a file identifier can be interpreted in different
2196 ways, depending on its contents:
2198 - Alphanumeric characters only:
2199 Match links with this file extension.
2200 Example: (\"pdf\" . \"evince %s\")
2201 to open PDFs with evince.
2203 - Regular expression: Match links where the
2204 filename matches the regexp. If you want to
2205 use groups here, use shy groups.
2207 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2208 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2209 to open *.html and *.xhtml with firefox.
2211 - Regular expression which contains (non-shy) groups:
2212 Match links where the whole link, including \"::\", and
2213 anything after that, matches the regexp.
2214 In a custom command string, %1, %2, etc. are replaced with
2215 the parts of the link that were matched by the groups.
2216 For backwards compatibility, if a command string is given
2217 that does not use any of the group matches, this case is
2218 handled identically to the second one (i.e. match against
2219 file name only).
2220 In a custom lisp form, you can access the group matches with
2221 (match-string n link).
2223 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2224 to open [[file:document.pdf::5]] with evince at page 5.
2226 `directory' Matches a directory
2227 `remote' Matches a remote file, accessible through tramp or efs.
2228 Remote files most likely should be visited through Emacs
2229 because external applications cannot handle such paths.
2230 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2231 so all files Emacs knows how to handle. Using this with
2232 command `emacs' will open most files in Emacs. Beware that this
2233 will also open html files inside Emacs, unless you add
2234 (\"html\" . default) to the list as well.
2235 t Default for files not matched by any of the other options.
2236 `system' The system command to open files, like `open' on Windows
2237 and Mac OS X, and mailcap under GNU/Linux. This is the command
2238 that will be selected if you call `C-c C-o' with a double
2239 \\[universal-argument] \\[universal-argument] prefix.
2241 Possible values for the command are:
2242 `emacs' The file will be visited by the current Emacs process.
2243 `default' Use the default application for this file type, which is the
2244 association for t in the list, most likely in the system-specific
2245 part.
2246 This can be used to overrule an unwanted setting in the
2247 system-specific variable.
2248 `system' Use the system command for opening files, like \"open\".
2249 This command is specified by the entry whose car is `system'.
2250 Most likely, the system-specific version of this variable
2251 does define this command, but you can overrule/replace it
2252 here.
2253 string A command to be executed by a shell; %s will be replaced
2254 by the path to the file.
2255 sexp A Lisp form which will be evaluated. The file path will
2256 be available in the Lisp variable `file'.
2257 For more examples, see the system specific constants
2258 `org-file-apps-defaults-macosx'
2259 `org-file-apps-defaults-windowsnt'
2260 `org-file-apps-defaults-gnu'."
2261 :group 'org-link-follow
2262 :type '(repeat
2263 (cons (choice :value ""
2264 (string :tag "Extension")
2265 (const :tag "System command to open files" system)
2266 (const :tag "Default for unrecognized files" t)
2267 (const :tag "Remote file" remote)
2268 (const :tag "Links to a directory" directory)
2269 (const :tag "Any files that have Emacs modes"
2270 auto-mode))
2271 (choice :value ""
2272 (const :tag "Visit with Emacs" emacs)
2273 (const :tag "Use default" default)
2274 (const :tag "Use the system command" system)
2275 (string :tag "Command")
2276 (sexp :tag "Lisp form")))))
2278 (defcustom org-doi-server-url "http://dx.doi.org/"
2279 "The URL of the DOI server."
2280 :type 'string
2281 :version "24.3"
2282 :group 'org-link-follow)
2284 (defgroup org-refile nil
2285 "Options concerning refiling entries in Org-mode."
2286 :tag "Org Refile"
2287 :group 'org)
2289 (defcustom org-directory "~/org"
2290 "Directory with org files.
2291 This is just a default location to look for Org files. There is no need
2292 at all to put your files into this directory. It is only used in the
2293 following situations:
2295 1. When a capture template specifies a target file that is not an
2296 absolute path. The path will then be interpreted relative to
2297 `org-directory'
2298 2. When a capture note is filed away in an interactive way (when exiting the
2299 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2300 with `org-directory' as the default path."
2301 :group 'org-refile
2302 :group 'org-capture
2303 :type 'directory)
2305 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2306 "Default target for storing notes.
2307 Used as a fall back file for org-capture.el, for templates that
2308 do not specify a target file."
2309 :group 'org-refile
2310 :group 'org-capture
2311 :type 'file)
2313 (defcustom org-goto-interface 'outline
2314 "The default interface to be used for `org-goto'.
2315 Allowed values are:
2316 outline The interface shows an outline of the relevant file
2317 and the correct heading is found by moving through
2318 the outline or by searching with incremental search.
2319 outline-path-completion Headlines in the current buffer are offered via
2320 completion. This is the interface also used by
2321 the refile command."
2322 :group 'org-refile
2323 :type '(choice
2324 (const :tag "Outline" outline)
2325 (const :tag "Outline-path-completion" outline-path-completion)))
2327 (defcustom org-goto-max-level 5
2328 "Maximum target level when running `org-goto' with refile interface."
2329 :group 'org-refile
2330 :type 'integer)
2332 (defcustom org-reverse-note-order nil
2333 "Non-nil means store new notes at the beginning of a file or entry.
2334 When nil, new notes will be filed to the end of a file or entry.
2335 This can also be a list with cons cells of regular expressions that
2336 are matched against file names, and values."
2337 :group 'org-capture
2338 :group 'org-refile
2339 :type '(choice
2340 (const :tag "Reverse always" t)
2341 (const :tag "Reverse never" nil)
2342 (repeat :tag "By file name regexp"
2343 (cons regexp boolean))))
2345 (defcustom org-log-refile nil
2346 "Information to record when a task is refiled.
2348 Possible values are:
2350 nil Don't add anything
2351 time Add a time stamp to the task
2352 note Prompt for a note and add it with template `org-log-note-headings'
2354 This option can also be set with on a per-file-basis with
2356 #+STARTUP: nologrefile
2357 #+STARTUP: logrefile
2358 #+STARTUP: lognoterefile
2360 You can have local logging settings for a subtree by setting the LOGGING
2361 property to one or more of these keywords.
2363 When bulk-refiling from the agenda, the value `note' is forbidden and
2364 will temporarily be changed to `time'."
2365 :group 'org-refile
2366 :group 'org-progress
2367 :version "24.1"
2368 :type '(choice
2369 (const :tag "No logging" nil)
2370 (const :tag "Record timestamp" time)
2371 (const :tag "Record timestamp with note." note)))
2373 (defcustom org-refile-targets nil
2374 "Targets for refiling entries with \\[org-refile].
2375 This is a list of cons cells. Each cell contains:
2376 - a specification of the files to be considered, either a list of files,
2377 or a symbol whose function or variable value will be used to retrieve
2378 a file name or a list of file names. If you use `org-agenda-files' for
2379 that, all agenda files will be scanned for targets. Nil means consider
2380 headings in the current buffer.
2381 - A specification of how to find candidate refile targets. This may be
2382 any of:
2383 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2384 This tag has to be present in all target headlines, inheritance will
2385 not be considered.
2386 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2387 todo keyword.
2388 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2389 headlines that are refiling targets.
2390 - a cons cell (:level . N). Any headline of level N is considered a target.
2391 Note that, when `org-odd-levels-only' is set, level corresponds to
2392 order in hierarchy, not to the number of stars.
2393 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2394 Note that, when `org-odd-levels-only' is set, level corresponds to
2395 order in hierarchy, not to the number of stars.
2397 Each element of this list generates a set of possible targets.
2398 The union of these sets is presented (with completion) to
2399 the user by `org-refile'.
2401 You can set the variable `org-refile-target-verify-function' to a function
2402 to verify each headline found by the simple criteria above.
2404 When this variable is nil, all top-level headlines in the current buffer
2405 are used, equivalent to the value `((nil . (:level . 1))'."
2406 :group 'org-refile
2407 :type '(repeat
2408 (cons
2409 (choice :value org-agenda-files
2410 (const :tag "All agenda files" org-agenda-files)
2411 (const :tag "Current buffer" nil)
2412 (function) (variable) (file))
2413 (choice :tag "Identify target headline by"
2414 (cons :tag "Specific tag" (const :value :tag) (string))
2415 (cons :tag "TODO keyword" (const :value :todo) (string))
2416 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2417 (cons :tag "Level number" (const :value :level) (integer))
2418 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2420 (defcustom org-refile-target-verify-function nil
2421 "Function to verify if the headline at point should be a refile target.
2422 The function will be called without arguments, with point at the
2423 beginning of the headline. It should return t and leave point
2424 where it is if the headline is a valid target for refiling.
2426 If the target should not be selected, the function must return nil.
2427 In addition to this, it may move point to a place from where the search
2428 should be continued. For example, the function may decide that the entire
2429 subtree of the current entry should be excluded and move point to the end
2430 of the subtree."
2431 :group 'org-refile
2432 :type '(choice
2433 (const nil)
2434 (function)))
2436 (defcustom org-refile-use-cache nil
2437 "Non-nil means cache refile targets to speed up the process.
2438 The cache for a particular file will be updated automatically when
2439 the buffer has been killed, or when any of the marker used for flagging
2440 refile targets no longer points at a live buffer.
2441 If you have added new entries to a buffer that might themselves be targets,
2442 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2443 find that easier, `C-u C-u C-u C-c C-w'."
2444 :group 'org-refile
2445 :version "24.1"
2446 :type 'boolean)
2448 (defcustom org-refile-use-outline-path nil
2449 "Non-nil means provide refile targets as paths.
2450 So a level 3 headline will be available as level1/level2/level3.
2452 When the value is `file', also include the file name (without directory)
2453 into the path. In this case, you can also stop the completion after
2454 the file name, to get entries inserted as top level in the file.
2456 When `full-file-path', include the full file path."
2457 :group 'org-refile
2458 :type '(choice
2459 (const :tag "Not" nil)
2460 (const :tag "Yes" t)
2461 (const :tag "Start with file name" file)
2462 (const :tag "Start with full file path" full-file-path)))
2464 (defcustom org-outline-path-complete-in-steps t
2465 "Non-nil means complete the outline path in hierarchical steps.
2466 When Org-mode uses the refile interface to select an outline path
2467 \(see variable `org-refile-use-outline-path'), the completion of
2468 the path can be done in a single go, or it can be done in steps down
2469 the headline hierarchy. Going in steps is probably the best if you
2470 do not use a special completion package like `ido' or `icicles'.
2471 However, when using these packages, going in one step can be very
2472 fast, while still showing the whole path to the entry."
2473 :group 'org-refile
2474 :type 'boolean)
2476 (defcustom org-refile-allow-creating-parent-nodes nil
2477 "Non-nil means allow to create new nodes as refile targets.
2478 New nodes are then created by adding \"/new node name\" to the completion
2479 of an existing node. When the value of this variable is `confirm',
2480 new node creation must be confirmed by the user (recommended).
2481 When nil, the completion must match an existing entry.
2483 Note that, if the new heading is not seen by the criteria
2484 listed in `org-refile-targets', multiple instances of the same
2485 heading would be created by trying again to file under the new
2486 heading."
2487 :group 'org-refile
2488 :type '(choice
2489 (const :tag "Never" nil)
2490 (const :tag "Always" t)
2491 (const :tag "Prompt for confirmation" confirm)))
2493 (defcustom org-refile-active-region-within-subtree nil
2494 "Non-nil means also refile active region within a subtree.
2496 By default `org-refile' doesn't allow refiling regions if they
2497 don't contain a set of subtrees, but it might be convenient to
2498 do so sometimes: in that case, the first line of the region is
2499 converted to a headline before refiling."
2500 :group 'org-refile
2501 :version "24.1"
2502 :type 'boolean)
2504 (defgroup org-todo nil
2505 "Options concerning TODO items in Org-mode."
2506 :tag "Org TODO"
2507 :group 'org)
2509 (defgroup org-progress nil
2510 "Options concerning Progress logging in Org-mode."
2511 :tag "Org Progress"
2512 :group 'org-time)
2514 (defvar org-todo-interpretation-widgets
2515 '((:tag "Sequence (cycling hits every state)" sequence)
2516 (:tag "Type (cycling directly to DONE)" type))
2517 "The available interpretation symbols for customizing `org-todo-keywords'.
2518 Interested libraries should add to this list.")
2520 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2521 "List of TODO entry keyword sequences and their interpretation.
2522 \\<org-mode-map>This is a list of sequences.
2524 Each sequence starts with a symbol, either `sequence' or `type',
2525 indicating if the keywords should be interpreted as a sequence of
2526 action steps, or as different types of TODO items. The first
2527 keywords are states requiring action - these states will select a headline
2528 for inclusion into the global TODO list Org-mode produces. If one of
2529 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2530 signify that no further action is necessary. If \"|\" is not found,
2531 the last keyword is treated as the only DONE state of the sequence.
2533 The command \\[org-todo] cycles an entry through these states, and one
2534 additional state where no keyword is present. For details about this
2535 cycling, see the manual.
2537 TODO keywords and interpretation can also be set on a per-file basis with
2538 the special #+SEQ_TODO and #+TYP_TODO lines.
2540 Each keyword can optionally specify a character for fast state selection
2541 \(in combination with the variable `org-use-fast-todo-selection')
2542 and specifiers for state change logging, using the same syntax that
2543 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2544 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2545 indicates to record a time stamp each time this state is selected.
2547 Each keyword may also specify if a timestamp or a note should be
2548 recorded when entering or leaving the state, by adding additional
2549 characters in the parenthesis after the keyword. This looks like this:
2550 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2551 record only the time of the state change. With X and Y being either
2552 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2553 Y when leaving the state if and only if the *target* state does not
2554 define X. You may omit any of the fast-selection key or X or /Y,
2555 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2557 For backward compatibility, this variable may also be just a list
2558 of keywords. In this case the interpretation (sequence or type) will be
2559 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2560 :group 'org-todo
2561 :group 'org-keywords
2562 :type '(choice
2563 (repeat :tag "Old syntax, just keywords"
2564 (string :tag "Keyword"))
2565 (repeat :tag "New syntax"
2566 (cons
2567 (choice
2568 :tag "Interpretation"
2569 ;;Quick and dirty way to see
2570 ;;`org-todo-interpretations'. This takes the
2571 ;;place of item arguments
2572 :convert-widget
2573 (lambda (widget)
2574 (widget-put widget
2575 :args (mapcar
2576 (lambda (x)
2577 (widget-convert
2578 (cons 'const x)))
2579 org-todo-interpretation-widgets))
2580 widget))
2581 (repeat
2582 (string :tag "Keyword"))))))
2584 (defvar org-todo-keywords-1 nil
2585 "All TODO and DONE keywords active in a buffer.")
2586 (make-variable-buffer-local 'org-todo-keywords-1)
2587 (defvar org-todo-keywords-for-agenda nil)
2588 (defvar org-done-keywords-for-agenda nil)
2589 (defvar org-todo-keyword-alist-for-agenda nil)
2590 (defvar org-tag-alist-for-agenda nil
2591 "Alist of all tags from all agenda files.")
2592 (defvar org-tag-groups-alist-for-agenda nil
2593 "Alist of all groups tags from all current agenda files.")
2594 (defvar org-tag-groups-alist nil)
2595 (make-variable-buffer-local 'org-tag-groups-alist)
2596 (defvar org-agenda-contributing-files nil)
2597 (defvar org-not-done-keywords nil)
2598 (make-variable-buffer-local 'org-not-done-keywords)
2599 (defvar org-done-keywords nil)
2600 (make-variable-buffer-local 'org-done-keywords)
2601 (defvar org-todo-heads nil)
2602 (make-variable-buffer-local 'org-todo-heads)
2603 (defvar org-todo-sets nil)
2604 (make-variable-buffer-local 'org-todo-sets)
2605 (defvar org-todo-log-states nil)
2606 (make-variable-buffer-local 'org-todo-log-states)
2607 (defvar org-todo-kwd-alist nil)
2608 (make-variable-buffer-local 'org-todo-kwd-alist)
2609 (defvar org-todo-key-alist nil)
2610 (make-variable-buffer-local 'org-todo-key-alist)
2611 (defvar org-todo-key-trigger nil)
2612 (make-variable-buffer-local 'org-todo-key-trigger)
2614 (defcustom org-todo-interpretation 'sequence
2615 "Controls how TODO keywords are interpreted.
2616 This variable is in principle obsolete and is only used for
2617 backward compatibility, if the interpretation of todo keywords is
2618 not given already in `org-todo-keywords'. See that variable for
2619 more information."
2620 :group 'org-todo
2621 :group 'org-keywords
2622 :type '(choice (const sequence)
2623 (const type)))
2625 (defcustom org-use-fast-todo-selection t
2626 "Non-nil means use the fast todo selection scheme with C-c C-t.
2627 This variable describes if and under what circumstances the cycling
2628 mechanism for TODO keywords will be replaced by a single-key, direct
2629 selection scheme.
2631 When nil, fast selection is never used.
2633 When the symbol `prefix', it will be used when `org-todo' is called
2634 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2635 `C-u t' in an agenda buffer.
2637 When t, fast selection is used by default. In this case, the prefix
2638 argument forces cycling instead.
2640 In all cases, the special interface is only used if access keys have
2641 actually been assigned by the user, i.e. if keywords in the configuration
2642 are followed by a letter in parenthesis, like TODO(t)."
2643 :group 'org-todo
2644 :type '(choice
2645 (const :tag "Never" nil)
2646 (const :tag "By default" t)
2647 (const :tag "Only with C-u C-c C-t" prefix)))
2649 (defcustom org-provide-todo-statistics t
2650 "Non-nil means update todo statistics after insert and toggle.
2651 ALL-HEADLINES means update todo statistics by including headlines
2652 with no TODO keyword as well, counting them as not done.
2653 A list of TODO keywords means the same, but skip keywords that are
2654 not in this list.
2655 When set to a list of two lists, the first list contains keywords
2656 to consider as TODO keywords, the second list contains keywords
2657 to consider as DONE keywords.
2659 When this is set, todo statistics is updated in the parent of the
2660 current entry each time a todo state is changed."
2661 :group 'org-todo
2662 :type '(choice
2663 (const :tag "Yes, only for TODO entries" t)
2664 (const :tag "Yes, including all entries" all-headlines)
2665 (repeat :tag "Yes, for TODOs in this list"
2666 (string :tag "TODO keyword"))
2667 (list :tag "Yes, for TODOs and DONEs in these lists"
2668 (repeat (string :tag "TODO keyword"))
2669 (repeat (string :tag "DONE keyword")))
2670 (other :tag "No TODO statistics" nil)))
2672 (defcustom org-hierarchical-todo-statistics t
2673 "Non-nil means TODO statistics covers just direct children.
2674 When nil, all entries in the subtree are considered.
2675 This has only an effect if `org-provide-todo-statistics' is set.
2676 To set this to nil for only a single subtree, use a COOKIE_DATA
2677 property and include the word \"recursive\" into the value."
2678 :group 'org-todo
2679 :type 'boolean)
2681 (defcustom org-after-todo-state-change-hook nil
2682 "Hook which is run after the state of a TODO item was changed.
2683 The new state (a string with a TODO keyword, or nil) is available in the
2684 Lisp variable `org-state'."
2685 :group 'org-todo
2686 :type 'hook)
2688 (defvar org-blocker-hook nil
2689 "Hook for functions that are allowed to block a state change.
2691 Functions in this hook should not modify the buffer.
2692 Each function gets as its single argument a property list,
2693 see `org-trigger-hook' for more information about this list.
2695 If any of the functions in this hook returns nil, the state change
2696 is blocked.")
2698 (defvar org-trigger-hook nil
2699 "Hook for functions that are triggered by a state change.
2701 Each function gets as its single argument a property list with at
2702 least the following elements:
2704 (:type type-of-change :position pos-at-entry-start
2705 :from old-state :to new-state)
2707 Depending on the type, more properties may be present.
2709 This mechanism is currently implemented for:
2711 TODO state changes
2712 ------------------
2713 :type todo-state-change
2714 :from previous state (keyword as a string), or nil, or a symbol
2715 'todo' or 'done', to indicate the general type of state.
2716 :to new state, like in :from")
2718 (defcustom org-enforce-todo-dependencies nil
2719 "Non-nil means undone TODO entries will block switching the parent to DONE.
2720 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2721 be blocked if any prior sibling is not yet done.
2722 Finally, if the parent is blocked because of ordered siblings of its own,
2723 the child will also be blocked."
2724 :set (lambda (var val)
2725 (set var val)
2726 (if val
2727 (add-hook 'org-blocker-hook
2728 'org-block-todo-from-children-or-siblings-or-parent)
2729 (remove-hook 'org-blocker-hook
2730 'org-block-todo-from-children-or-siblings-or-parent)))
2731 :group 'org-todo
2732 :type 'boolean)
2734 (defcustom org-enforce-todo-checkbox-dependencies nil
2735 "Non-nil means unchecked boxes will block switching the parent to DONE.
2736 When this is nil, checkboxes have no influence on switching TODO states.
2737 When non-nil, you first need to check off all check boxes before the TODO
2738 entry can be switched to DONE.
2739 This variable needs to be set before org.el is loaded, and you need to
2740 restart Emacs after a change to make the change effective. The only way
2741 to change is while Emacs is running is through the customize interface."
2742 :set (lambda (var val)
2743 (set var val)
2744 (if val
2745 (add-hook 'org-blocker-hook
2746 'org-block-todo-from-checkboxes)
2747 (remove-hook 'org-blocker-hook
2748 'org-block-todo-from-checkboxes)))
2749 :group 'org-todo
2750 :type 'boolean)
2752 (defcustom org-treat-insert-todo-heading-as-state-change nil
2753 "Non-nil means inserting a TODO heading is treated as state change.
2754 So when the command \\[org-insert-todo-heading] is used, state change
2755 logging will apply if appropriate. When nil, the new TODO item will
2756 be inserted directly, and no logging will take place."
2757 :group 'org-todo
2758 :type 'boolean)
2760 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2761 "Non-nil means switching TODO states with S-cursor counts as state change.
2762 This is the default behavior. However, setting this to nil allows a
2763 convenient way to select a TODO state and bypass any logging associated
2764 with that."
2765 :group 'org-todo
2766 :type 'boolean)
2768 (defcustom org-todo-state-tags-triggers nil
2769 "Tag changes that should be triggered by TODO state changes.
2770 This is a list. Each entry is
2772 (state-change (tag . flag) .......)
2774 State-change can be a string with a state, and empty string to indicate the
2775 state that has no TODO keyword, or it can be one of the symbols `todo'
2776 or `done', meaning any not-done or done state, respectively."
2777 :group 'org-todo
2778 :group 'org-tags
2779 :type '(repeat
2780 (cons (choice :tag "When changing to"
2781 (const :tag "Not-done state" todo)
2782 (const :tag "Done state" done)
2783 (string :tag "State"))
2784 (repeat
2785 (cons :tag "Tag action"
2786 (string :tag "Tag")
2787 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2789 (defcustom org-log-done nil
2790 "Information to record when a task moves to the DONE state.
2792 Possible values are:
2794 nil Don't add anything, just change the keyword
2795 time Add a time stamp to the task
2796 note Prompt for a note and add it with template `org-log-note-headings'
2798 This option can also be set with on a per-file-basis with
2800 #+STARTUP: nologdone
2801 #+STARTUP: logdone
2802 #+STARTUP: lognotedone
2804 You can have local logging settings for a subtree by setting the LOGGING
2805 property to one or more of these keywords."
2806 :group 'org-todo
2807 :group 'org-progress
2808 :type '(choice
2809 (const :tag "No logging" nil)
2810 (const :tag "Record CLOSED timestamp" time)
2811 (const :tag "Record CLOSED timestamp with note." note)))
2813 ;; Normalize old uses of org-log-done.
2814 (cond
2815 ((eq org-log-done t) (setq org-log-done 'time))
2816 ((and (listp org-log-done) (memq 'done org-log-done))
2817 (setq org-log-done 'note)))
2819 (defcustom org-log-reschedule nil
2820 "Information to record when the scheduling date of a tasks is modified.
2822 Possible values are:
2824 nil Don't add anything, just change the date
2825 time Add a time stamp to the task
2826 note Prompt for a note and add it with template `org-log-note-headings'
2828 This option can also be set with on a per-file-basis with
2830 #+STARTUP: nologreschedule
2831 #+STARTUP: logreschedule
2832 #+STARTUP: lognotereschedule"
2833 :group 'org-todo
2834 :group 'org-progress
2835 :type '(choice
2836 (const :tag "No logging" nil)
2837 (const :tag "Record timestamp" time)
2838 (const :tag "Record timestamp with note." note)))
2840 (defcustom org-log-redeadline nil
2841 "Information to record when the deadline date of a tasks is modified.
2843 Possible values are:
2845 nil Don't add anything, just change the date
2846 time Add a time stamp to the task
2847 note Prompt for a note and add it with template `org-log-note-headings'
2849 This option can also be set with on a per-file-basis with
2851 #+STARTUP: nologredeadline
2852 #+STARTUP: logredeadline
2853 #+STARTUP: lognoteredeadline
2855 You can have local logging settings for a subtree by setting the LOGGING
2856 property to one or more of these keywords."
2857 :group 'org-todo
2858 :group 'org-progress
2859 :type '(choice
2860 (const :tag "No logging" nil)
2861 (const :tag "Record timestamp" time)
2862 (const :tag "Record timestamp with note." note)))
2864 (defcustom org-log-note-clock-out nil
2865 "Non-nil means record a note when clocking out of an item.
2866 This can also be configured on a per-file basis by adding one of
2867 the following lines anywhere in the buffer:
2869 #+STARTUP: lognoteclock-out
2870 #+STARTUP: nolognoteclock-out"
2871 :group 'org-todo
2872 :group 'org-progress
2873 :type 'boolean)
2875 (defcustom org-log-done-with-time t
2876 "Non-nil means the CLOSED time stamp will contain date and time.
2877 When nil, only the date will be recorded."
2878 :group 'org-progress
2879 :type 'boolean)
2881 (defcustom org-log-note-headings
2882 '((done . "CLOSING NOTE %t")
2883 (state . "State %-12s from %-12S %t")
2884 (note . "Note taken on %t")
2885 (reschedule . "Rescheduled from %S on %t")
2886 (delschedule . "Not scheduled, was %S on %t")
2887 (redeadline . "New deadline from %S on %t")
2888 (deldeadline . "Removed deadline, was %S on %t")
2889 (refile . "Refiled on %t")
2890 (clock-out . ""))
2891 "Headings for notes added to entries.
2892 The value is an alist, with the car being a symbol indicating the note
2893 context, and the cdr is the heading to be used. The heading may also be the
2894 empty string.
2895 %t in the heading will be replaced by a time stamp.
2896 %T will be an active time stamp instead the default inactive one
2897 %d will be replaced by a short-format time stamp.
2898 %D will be replaced by an active short-format time stamp.
2899 %s will be replaced by the new TODO state, in double quotes.
2900 %S will be replaced by the old TODO state, in double quotes.
2901 %u will be replaced by the user name.
2902 %U will be replaced by the full user name.
2904 In fact, it is not a good idea to change the `state' entry, because
2905 agenda log mode depends on the format of these entries."
2906 :group 'org-todo
2907 :group 'org-progress
2908 :type '(list :greedy t
2909 (cons (const :tag "Heading when closing an item" done) string)
2910 (cons (const :tag
2911 "Heading when changing todo state (todo sequence only)"
2912 state) string)
2913 (cons (const :tag "Heading when just taking a note" note) string)
2914 (cons (const :tag "Heading when rescheduling" reschedule) string)
2915 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2916 (cons (const :tag "Heading when changing deadline" redeadline) string)
2917 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2918 (cons (const :tag "Heading when refiling" refile) string)
2919 (cons (const :tag "Heading when clocking out" clock-out) string)))
2921 (unless (assq 'note org-log-note-headings)
2922 (push '(note . "%t") org-log-note-headings))
2924 (defcustom org-log-into-drawer nil
2925 "Non-nil means insert state change notes and time stamps into a drawer.
2926 When nil, state changes notes will be inserted after the headline and
2927 any scheduling and clock lines, but not inside a drawer.
2929 The value of this variable should be the name of the drawer to use.
2930 LOGBOOK is proposed as the default drawer for this purpose, you can
2931 also set this to a string to define the drawer of your choice.
2933 A value of t is also allowed, representing \"LOGBOOK\".
2935 A value of t or nil can also be set with on a per-file-basis with
2937 #+STARTUP: logdrawer
2938 #+STARTUP: nologdrawer
2940 If this variable is set, `org-log-state-notes-insert-after-drawers'
2941 will be ignored.
2943 You can set the property LOG_INTO_DRAWER to overrule this setting for
2944 a subtree.
2946 Do not check directly this variable in a Lisp program. Call
2947 function `org-log-into-drawer' instead."
2948 :group 'org-todo
2949 :group 'org-progress
2950 :type '(choice
2951 (const :tag "Not into a drawer" nil)
2952 (const :tag "LOGBOOK" t)
2953 (string :tag "Other")))
2955 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2957 (defun org-log-into-drawer ()
2958 "Name of the log drawer, as a string, or nil.
2959 This is the value of `org-log-into-drawer'. However, if the
2960 current entry has or inherits a LOG_INTO_DRAWER property, it will
2961 be used instead of the default value."
2962 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2963 (cond ((equal p "nil") nil)
2964 ((equal p "t") "LOGBOOK")
2965 ((stringp p) p)
2966 (p "LOGBOOK")
2967 ((stringp org-log-into-drawer) org-log-into-drawer)
2968 (org-log-into-drawer "LOGBOOK"))))
2970 (defcustom org-log-state-notes-insert-after-drawers nil
2971 "Non-nil means insert state change notes after any drawers in entry.
2972 Only the drawers that *immediately* follow the headline and the
2973 deadline/scheduled line are skipped.
2974 When nil, insert notes right after the heading and perhaps the line
2975 with deadline/scheduling if present.
2977 This variable will have no effect if `org-log-into-drawer' is
2978 set."
2979 :group 'org-todo
2980 :group 'org-progress
2981 :type 'boolean)
2983 (defcustom org-log-states-order-reversed t
2984 "Non-nil means the latest state note will be directly after heading.
2985 When nil, the state change notes will be ordered according to time.
2987 This option can also be set with on a per-file-basis with
2989 #+STARTUP: logstatesreversed
2990 #+STARTUP: nologstatesreversed"
2991 :group 'org-todo
2992 :group 'org-progress
2993 :type 'boolean)
2995 (defcustom org-todo-repeat-to-state nil
2996 "The TODO state to which a repeater should return the repeating task.
2997 By default this is the first task in a TODO sequence, or the previous state
2998 in a TODO_TYP set. But you can specify another task here.
2999 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3000 :group 'org-todo
3001 :version "24.1"
3002 :type '(choice (const :tag "Head of sequence" nil)
3003 (string :tag "Specific state")))
3005 (defcustom org-log-repeat 'time
3006 "Non-nil means record moving through the DONE state when triggering repeat.
3007 An auto-repeating task is immediately switched back to TODO when
3008 marked DONE. If you are not logging state changes (by adding \"@\"
3009 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3010 record a closing note, there will be no record of the task moving
3011 through DONE. This variable forces taking a note anyway.
3013 nil Don't force a record
3014 time Record a time stamp
3015 note Prompt for a note and add it with template `org-log-note-headings'
3017 This option can also be set with on a per-file-basis with
3019 #+STARTUP: nologrepeat
3020 #+STARTUP: logrepeat
3021 #+STARTUP: lognoterepeat
3023 You can have local logging settings for a subtree by setting the LOGGING
3024 property to one or more of these keywords."
3025 :group 'org-todo
3026 :group 'org-progress
3027 :type '(choice
3028 (const :tag "Don't force a record" nil)
3029 (const :tag "Force recording the DONE state" time)
3030 (const :tag "Force recording a note with the DONE state" note)))
3033 (defgroup org-priorities nil
3034 "Priorities in Org-mode."
3035 :tag "Org Priorities"
3036 :group 'org-todo)
3038 (defcustom org-enable-priority-commands t
3039 "Non-nil means priority commands are active.
3040 When nil, these commands will be disabled, so that you never accidentally
3041 set a priority."
3042 :group 'org-priorities
3043 :type 'boolean)
3045 (defcustom org-highest-priority ?A
3046 "The highest priority of TODO items. A character like ?A, ?B etc.
3047 Must have a smaller ASCII number than `org-lowest-priority'."
3048 :group 'org-priorities
3049 :type 'character)
3051 (defcustom org-lowest-priority ?C
3052 "The lowest priority of TODO items. A character like ?A, ?B etc.
3053 Must have a larger ASCII number than `org-highest-priority'."
3054 :group 'org-priorities
3055 :type 'character)
3057 (defcustom org-default-priority ?B
3058 "The default priority of TODO items.
3059 This is the priority an item gets if no explicit priority is given.
3060 When starting to cycle on an empty priority the first step in the cycle
3061 depends on `org-priority-start-cycle-with-default'. The resulting first
3062 step priority must not exceed the range from `org-highest-priority' to
3063 `org-lowest-priority' which means that `org-default-priority' has to be
3064 in this range exclusive or inclusive the range boundaries. Else the
3065 first step refuses to set the default and the second will fall back
3066 to (depending on the command used) the highest or lowest priority."
3067 :group 'org-priorities
3068 :type 'character)
3070 (defcustom org-priority-start-cycle-with-default t
3071 "Non-nil means start with default priority when starting to cycle.
3072 When this is nil, the first step in the cycle will be (depending on the
3073 command used) one higher or lower than the default priority.
3074 See also `org-default-priority'."
3075 :group 'org-priorities
3076 :type 'boolean)
3078 (defcustom org-get-priority-function nil
3079 "Function to extract the priority from a string.
3080 The string is normally the headline. If this is nil Org computes the
3081 priority from the priority cookie like [#A] in the headline. It returns
3082 an integer, increasing by 1000 for each priority level.
3083 The user can set a different function here, which should take a string
3084 as an argument and return the numeric priority."
3085 :group 'org-priorities
3086 :version "24.1"
3087 :type '(choice
3088 (const nil)
3089 (function)))
3091 (defgroup org-time nil
3092 "Options concerning time stamps and deadlines in Org-mode."
3093 :tag "Org Time"
3094 :group 'org)
3096 (defcustom org-time-stamp-rounding-minutes '(0 5)
3097 "Number of minutes to round time stamps to.
3098 These are two values, the first applies when first creating a time stamp.
3099 The second applies when changing it with the commands `S-up' and `S-down'.
3100 When changing the time stamp, this means that it will change in steps
3101 of N minutes, as given by the second value.
3103 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3104 numbers should be factors of 60, so for example 5, 10, 15.
3106 When this is larger than 1, you can still force an exact time stamp by using
3107 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3108 and by using a prefix arg to `S-up/down' to specify the exact number
3109 of minutes to shift."
3110 :group 'org-time
3111 :get (lambda (var) ; Make sure both elements are there
3112 (if (integerp (default-value var))
3113 (list (default-value var) 5)
3114 (default-value var)))
3115 :type '(list
3116 (integer :tag "when inserting times")
3117 (integer :tag "when modifying times")))
3119 ;; Normalize old customizations of this variable.
3120 (when (integerp org-time-stamp-rounding-minutes)
3121 (setq org-time-stamp-rounding-minutes
3122 (list org-time-stamp-rounding-minutes
3123 org-time-stamp-rounding-minutes)))
3125 (defcustom org-display-custom-times nil
3126 "Non-nil means overlay custom formats over all time stamps.
3127 The formats are defined through the variable `org-time-stamp-custom-formats'.
3128 To turn this on on a per-file basis, insert anywhere in the file:
3129 #+STARTUP: customtime"
3130 :group 'org-time
3131 :set 'set-default
3132 :type 'sexp)
3133 (make-variable-buffer-local 'org-display-custom-times)
3135 (defcustom org-time-stamp-custom-formats
3136 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3137 "Custom formats for time stamps. See `format-time-string' for the syntax.
3138 These are overlaid over the default ISO format if the variable
3139 `org-display-custom-times' is set. Time like %H:%M should be at the
3140 end of the second format. The custom formats are also honored by export
3141 commands, if custom time display is turned on at the time of export."
3142 :group 'org-time
3143 :type 'sexp)
3145 (defun org-time-stamp-format (&optional long inactive)
3146 "Get the right format for a time string."
3147 (let ((f (if long (cdr org-time-stamp-formats)
3148 (car org-time-stamp-formats))))
3149 (if inactive
3150 (concat "[" (substring f 1 -1) "]")
3151 f)))
3153 (defcustom org-time-clocksum-format
3154 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3155 "The format string used when creating CLOCKSUM lines.
3156 This is also used when Org mode generates a time duration.
3158 The value can be a single format string containing two
3159 %-sequences, which will be filled with the number of hours and
3160 minutes in that order.
3162 Alternatively, the value can be a plist associating any of the
3163 keys :years, :months, :weeks, :days, :hours or :minutes with
3164 format strings. The time duration is formatted using only the
3165 time components that are needed and concatenating the results.
3166 If a time unit in absent, it falls back to the next smallest
3167 unit.
3169 The keys :require-years, :require-months, :require-days,
3170 :require-weeks, :require-hours, :require-minutes are also
3171 meaningful. A non-nil value for these keys indicates that the
3172 corresponding time component should always be included, even if
3173 its value is 0.
3176 For example,
3178 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3179 :require-minutes t)
3181 means durations longer than a day will be expressed in days,
3182 hours and minutes, and durations less than a day will always be
3183 expressed in hours and minutes (even for durations less than an
3184 hour).
3186 The value
3188 \(:days \"%dd\" :minutes \"%dm\")
3190 means durations longer than a day will be expressed in days and
3191 minutes, and durations less than a day will be expressed entirely
3192 in minutes (even for durations longer than an hour)."
3193 :group 'org-time
3194 :group 'org-clock
3195 :version "24.4"
3196 :package-version '(Org . "8.0")
3197 :type '(choice (string :tag "Format string")
3198 (set :tag "Plist"
3199 (group :inline t (const :tag "Years" :years)
3200 (string :tag "Format string"))
3201 (group :inline t
3202 (const :tag "Always show years" :require-years)
3203 (const t))
3204 (group :inline t (const :tag "Months" :months)
3205 (string :tag "Format string"))
3206 (group :inline t
3207 (const :tag "Always show months" :require-months)
3208 (const t))
3209 (group :inline t (const :tag "Weeks" :weeks)
3210 (string :tag "Format string"))
3211 (group :inline t
3212 (const :tag "Always show weeks" :require-weeks)
3213 (const t))
3214 (group :inline t (const :tag "Days" :days)
3215 (string :tag "Format string"))
3216 (group :inline t
3217 (const :tag "Always show days" :require-days)
3218 (const t))
3219 (group :inline t (const :tag "Hours" :hours)
3220 (string :tag "Format string"))
3221 (group :inline t
3222 (const :tag "Always show hours" :require-hours)
3223 (const t))
3224 (group :inline t (const :tag "Minutes" :minutes)
3225 (string :tag "Format string"))
3226 (group :inline t
3227 (const :tag "Always show minutes" :require-minutes)
3228 (const t)))))
3230 (defcustom org-time-clocksum-use-fractional nil
3231 "When non-nil, \\[org-clock-display] uses fractional times.
3232 See `org-time-clocksum-format' for more on time clock formats."
3233 :group 'org-time
3234 :group 'org-clock
3235 :version "24.3"
3236 :type 'boolean)
3238 (defcustom org-time-clocksum-use-effort-durations nil
3239 "When non-nil, \\[org-clock-display] uses effort durations.
3240 E.g. by default, one day is considered to be a 8 hours effort,
3241 so a task that has been clocked for 16 hours will be displayed
3242 as during 2 days in the clock display or in the clocktable.
3244 See `org-effort-durations' on how to set effort durations
3245 and `org-time-clocksum-format' for more on time clock formats."
3246 :group 'org-time
3247 :group 'org-clock
3248 :version "24.4"
3249 :package-version '(Org . "8.0")
3250 :type 'boolean)
3252 (defcustom org-time-clocksum-fractional-format "%.2f"
3253 "The format string used when creating CLOCKSUM lines,
3254 or when Org mode generates a time duration, if
3255 `org-time-clocksum-use-fractional' is enabled.
3257 The value can be a single format string containing one
3258 %-sequence, which will be filled with the number of hours as
3259 a float.
3261 Alternatively, the value can be a plist associating any of the
3262 keys :years, :months, :weeks, :days, :hours or :minutes with
3263 a format string. The time duration is formatted using the
3264 largest time unit which gives a non-zero integer part. If all
3265 specified formats have zero integer part, the smallest time unit
3266 is used."
3267 :group 'org-time
3268 :type '(choice (string :tag "Format string")
3269 (set (group :inline t (const :tag "Years" :years)
3270 (string :tag "Format string"))
3271 (group :inline t (const :tag "Months" :months)
3272 (string :tag "Format string"))
3273 (group :inline t (const :tag "Weeks" :weeks)
3274 (string :tag "Format string"))
3275 (group :inline t (const :tag "Days" :days)
3276 (string :tag "Format string"))
3277 (group :inline t (const :tag "Hours" :hours)
3278 (string :tag "Format string"))
3279 (group :inline t (const :tag "Minutes" :minutes)
3280 (string :tag "Format string")))))
3282 (defcustom org-deadline-warning-days 14
3283 "Number of days before expiration during which a deadline becomes active.
3284 This variable governs the display in sparse trees and in the agenda.
3285 When 0 or negative, it means use this number (the absolute value of it)
3286 even if a deadline has a different individual lead time specified.
3288 Custom commands can set this variable in the options section."
3289 :group 'org-time
3290 :group 'org-agenda-daily/weekly
3291 :type 'integer)
3293 (defcustom org-scheduled-delay-days 0
3294 "Number of days before a scheduled item becomes active.
3295 This variable governs the display in sparse trees and in the agenda.
3296 The default value (i.e. 0) means: don't delay scheduled item.
3297 When negative, it means use this number (the absolute value of it)
3298 even if a scheduled item has a different individual delay time
3299 specified.
3301 Custom commands can set this variable in the options section."
3302 :group 'org-time
3303 :group 'org-agenda-daily/weekly
3304 :version "24.4"
3305 :package-version '(Org . "8.0")
3306 :type 'integer)
3308 (defcustom org-read-date-prefer-future t
3309 "Non-nil means assume future for incomplete date input from user.
3310 This affects the following situations:
3311 1. The user gives a month but not a year.
3312 For example, if it is April and you enter \"feb 2\", this will be read
3313 as Feb 2, *next* year. \"May 5\", however, will be this year.
3314 2. The user gives a day, but no month.
3315 For example, if today is the 15th, and you enter \"3\", Org-mode will
3316 read this as the third of *next* month. However, if you enter \"17\",
3317 it will be considered as *this* month.
3319 If you set this variable to the symbol `time', then also the following
3320 will work:
3322 3. If the user gives a time.
3323 If the time is before now, it will be interpreted as tomorrow.
3325 Currently none of this works for ISO week specifications.
3327 When this option is nil, the current day, month and year will always be
3328 used as defaults.
3330 See also `org-agenda-jump-prefer-future'."
3331 :group 'org-time
3332 :type '(choice
3333 (const :tag "Never" nil)
3334 (const :tag "Check month and day" t)
3335 (const :tag "Check month, day, and time" time)))
3337 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3338 "Should the agenda jump command prefer the future for incomplete dates?
3339 The default is to do the same as configured in `org-read-date-prefer-future'.
3340 But you can also set a deviating value here.
3341 This may t or nil, or the symbol `org-read-date-prefer-future'."
3342 :group 'org-agenda
3343 :group 'org-time
3344 :version "24.1"
3345 :type '(choice
3346 (const :tag "Use org-read-date-prefer-future"
3347 org-read-date-prefer-future)
3348 (const :tag "Never" nil)
3349 (const :tag "Always" t)))
3351 (defcustom org-read-date-force-compatible-dates t
3352 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3354 Depending on the system Emacs is running on, certain dates cannot
3355 be represented with the type used internally to represent time.
3356 Dates between 1970-1-1 and 2038-1-1 can always be represented
3357 correctly. Some systems allow for earlier dates, some for later,
3358 some for both. One way to find out it to insert any date into an
3359 Org buffer, putting the cursor on the year and hitting S-up and
3360 S-down to test the range.
3362 When this variable is set to t, the date/time prompt will not let
3363 you specify dates outside the 1970-2037 range, so it is certain that
3364 these dates will work in whatever version of Emacs you are
3365 running, and also that you can move a file from one Emacs implementation
3366 to another. WHenever Org is forcing the year for you, it will display
3367 a message and beep.
3369 When this variable is nil, Org will check if the date is
3370 representable in the specific Emacs implementation you are using.
3371 If not, it will force a year, usually the current year, and beep
3372 to remind you. Currently this setting is not recommended because
3373 the likelihood that you will open your Org files in an Emacs that
3374 has limited date range is not negligible.
3376 A workaround for this problem is to use diary sexp dates for time
3377 stamps outside of this range."
3378 :group 'org-time
3379 :version "24.1"
3380 :type 'boolean)
3382 (defcustom org-read-date-display-live t
3383 "Non-nil means display current interpretation of date prompt live.
3384 This display will be in an overlay, in the minibuffer."
3385 :group 'org-time
3386 :type 'boolean)
3388 (defcustom org-read-date-popup-calendar t
3389 "Non-nil means pop up a calendar when prompting for a date.
3390 In the calendar, the date can be selected with mouse-1. However, the
3391 minibuffer will also be active, and you can simply enter the date as well.
3392 When nil, only the minibuffer will be available."
3393 :group 'org-time
3394 :type 'boolean)
3395 (org-defvaralias 'org-popup-calendar-for-date-prompt
3396 'org-read-date-popup-calendar)
3398 (make-obsolete-variable
3399 'org-read-date-minibuffer-setup-hook
3400 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3401 (defcustom org-read-date-minibuffer-setup-hook nil
3402 "Hook to be used to set up keys for the date/time interface.
3403 Add key definitions to `minibuffer-local-map', which will be a
3404 temporary copy.
3406 WARNING: This option is obsolete, you should use
3407 `org-read-date-minibuffer-local-map' to set up keys."
3408 :group 'org-time
3409 :type 'hook)
3411 (defcustom org-extend-today-until 0
3412 "The hour when your day really ends. Must be an integer.
3413 This has influence for the following applications:
3414 - When switching the agenda to \"today\". It it is still earlier than
3415 the time given here, the day recognized as TODAY is actually yesterday.
3416 - When a date is read from the user and it is still before the time given
3417 here, the current date and time will be assumed to be yesterday, 23:59.
3418 Also, timestamps inserted in capture templates follow this rule.
3420 IMPORTANT: This is a feature whose implementation is and likely will
3421 remain incomplete. Really, it is only here because past midnight seems to
3422 be the favorite working time of John Wiegley :-)"
3423 :group 'org-time
3424 :type 'integer)
3426 (defcustom org-use-effective-time nil
3427 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3428 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3429 \"effective time\" of any timestamps between midnight and 8am will be
3430 23:59 of the previous day."
3431 :group 'org-time
3432 :version "24.1"
3433 :type 'boolean)
3435 (defcustom org-use-last-clock-out-time-as-effective-time nil
3436 "When non-nil, use the last clock out time for `org-todo'.
3437 Note that this option has precedence over the combined use of
3438 `org-use-effective-time' and `org-extend-today-until'."
3439 :group 'org-time
3440 :version "24.4"
3441 :package-version '(Org . "8.0")
3442 :type 'boolean)
3444 (defcustom org-edit-timestamp-down-means-later nil
3445 "Non-nil means S-down will increase the time in a time stamp.
3446 When nil, S-up will increase."
3447 :group 'org-time
3448 :type 'boolean)
3450 (defcustom org-calendar-follow-timestamp-change t
3451 "Non-nil means make the calendar window follow timestamp changes.
3452 When a timestamp is modified and the calendar window is visible, it will be
3453 moved to the new date."
3454 :group 'org-time
3455 :type 'boolean)
3457 (defgroup org-tags nil
3458 "Options concerning tags in Org-mode."
3459 :tag "Org Tags"
3460 :group 'org)
3462 (defcustom org-tag-alist nil
3463 "List of tags allowed in Org-mode files.
3464 When this list is nil, Org-mode will base TAG input on what is already in the
3465 buffer.
3466 The value of this variable is an alist, the car of each entry must be a
3467 keyword as a string, the cdr may be a character that is used to select
3468 that tag through the fast-tag-selection interface.
3469 See the manual for details."
3470 :group 'org-tags
3471 :type '(repeat
3472 (choice
3473 (cons (string :tag "Tag name")
3474 (character :tag "Access char"))
3475 (list :tag "Start radio group"
3476 (const :startgroup)
3477 (option (string :tag "Group description")))
3478 (list :tag "Start tag group, non distinct"
3479 (const :startgrouptag)
3480 (option (string :tag "Group description")))
3481 (list :tag "Group tags delimiter"
3482 (const :grouptags))
3483 (list :tag "End radio group"
3484 (const :endgroup)
3485 (option (string :tag "Group description")))
3486 (list :tag "End tag group, non distinct"
3487 (const :endgrouptag)
3488 (option (string :tag "Group description")))
3489 (const :tag "New line" (:newline)))))
3491 (defcustom org-tag-persistent-alist nil
3492 "List of tags that will always appear in all Org-mode files.
3493 This is in addition to any in buffer settings or customizations
3494 of `org-tag-alist'.
3495 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3496 The value of this variable is an alist, the car of each entry must be a
3497 keyword as a string, the cdr may be a character that is used to select
3498 that tag through the fast-tag-selection interface.
3499 See the manual for details.
3500 To disable these tags on a per-file basis, insert anywhere in the file:
3501 #+STARTUP: noptag"
3502 :group 'org-tags
3503 :type '(repeat
3504 (choice
3505 (cons (string :tag "Tag name")
3506 (character :tag "Access char"))
3507 (const :tag "Start radio group" (:startgroup))
3508 (const :tag "Group tags delimiter" (:grouptags))
3509 (const :tag "End radio group" (:endgroup))
3510 (const :tag "New line" (:newline)))))
3512 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3513 "If non-nil, always offer completion for all tags of all agenda files.
3514 Instead of customizing this variable directly, you might want to
3515 set it locally for capture buffers, because there no list of
3516 tags in that file can be created dynamically (there are none).
3518 (add-hook 'org-capture-mode-hook
3519 (lambda ()
3520 (set (make-local-variable
3521 'org-complete-tags-always-offer-all-agenda-tags)
3522 t)))"
3523 :group 'org-tags
3524 :version "24.1"
3525 :type 'boolean)
3527 (defvar org-file-tags nil
3528 "List of tags that can be inherited by all entries in the file.
3529 The tags will be inherited if the variable `org-use-tag-inheritance'
3530 says they should be.
3531 This variable is populated from #+FILETAGS lines.")
3533 (defcustom org-use-fast-tag-selection 'auto
3534 "Non-nil means use fast tag selection scheme.
3535 This is a special interface to select and deselect tags with single keys.
3536 When nil, fast selection is never used.
3537 When the symbol `auto', fast selection is used if and only if selection
3538 characters for tags have been configured, either through the variable
3539 `org-tag-alist' or through a #+TAGS line in the buffer.
3540 When t, fast selection is always used and selection keys are assigned
3541 automatically if necessary."
3542 :group 'org-tags
3543 :type '(choice
3544 (const :tag "Always" t)
3545 (const :tag "Never" nil)
3546 (const :tag "When selection characters are configured" auto)))
3548 (defcustom org-fast-tag-selection-single-key nil
3549 "Non-nil means fast tag selection exits after first change.
3550 When nil, you have to press RET to exit it.
3551 During fast tag selection, you can toggle this flag with `C-c'.
3552 This variable can also have the value `expert'. In this case, the window
3553 displaying the tags menu is not even shown, until you press C-c again."
3554 :group 'org-tags
3555 :type '(choice
3556 (const :tag "No" nil)
3557 (const :tag "Yes" t)
3558 (const :tag "Expert" expert)))
3560 (defvar org-fast-tag-selection-include-todo nil
3561 "Non-nil means fast tags selection interface will also offer TODO states.
3562 This is an undocumented feature, you should not rely on it.")
3564 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3565 "The column to which tags should be indented in a headline.
3566 If this number is positive, it specifies the column. If it is negative,
3567 it means that the tags should be flushright to that column. For example,
3568 -80 works well for a normal 80 character screen.
3569 When 0, place tags directly after headline text, with only one space in
3570 between."
3571 :group 'org-tags
3572 :type 'integer)
3574 (defcustom org-auto-align-tags t
3575 "Non-nil keeps tags aligned when modifying headlines.
3576 Some operations (i.e. demoting) change the length of a headline and
3577 therefore shift the tags around. With this option turned on, after
3578 each such operation the tags are again aligned to `org-tags-column'."
3579 :group 'org-tags
3580 :type 'boolean)
3582 (defcustom org-use-tag-inheritance t
3583 "Non-nil means tags in levels apply also for sublevels.
3584 When nil, only the tags directly given in a specific line apply there.
3585 This may also be a list of tags that should be inherited, or a regexp that
3586 matches tags that should be inherited. Additional control is possible
3587 with the variable `org-tags-exclude-from-inheritance' which gives an
3588 explicit list of tags to be excluded from inheritance, even if the value of
3589 `org-use-tag-inheritance' would select it for inheritance.
3591 If this option is t, a match early-on in a tree can lead to a large
3592 number of matches in the subtree when constructing the agenda or creating
3593 a sparse tree. If you only want to see the first match in a tree during
3594 a search, check out the variable `org-tags-match-list-sublevels'."
3595 :group 'org-tags
3596 :type '(choice
3597 (const :tag "Not" nil)
3598 (const :tag "Always" t)
3599 (repeat :tag "Specific tags" (string :tag "Tag"))
3600 (regexp :tag "Tags matched by regexp")))
3602 (defcustom org-tags-exclude-from-inheritance nil
3603 "List of tags that should never be inherited.
3604 This is a way to exclude a few tags from inheritance. For way to do
3605 the opposite, to actively allow inheritance for selected tags,
3606 see the variable `org-use-tag-inheritance'."
3607 :group 'org-tags
3608 :type '(repeat (string :tag "Tag")))
3610 (defun org-tag-inherit-p (tag)
3611 "Check if TAG is one that should be inherited."
3612 (cond
3613 ((member tag org-tags-exclude-from-inheritance) nil)
3614 ((eq org-use-tag-inheritance t) t)
3615 ((not org-use-tag-inheritance) nil)
3616 ((stringp org-use-tag-inheritance)
3617 (string-match org-use-tag-inheritance tag))
3618 ((listp org-use-tag-inheritance)
3619 (member tag org-use-tag-inheritance))
3620 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3622 (defcustom org-tags-match-list-sublevels t
3623 "Non-nil means list also sublevels of headlines matching a search.
3624 This variable applies to tags/property searches, and also to stuck
3625 projects because this search is based on a tags match as well.
3627 When set to the symbol `indented', sublevels are indented with
3628 leading dots.
3630 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3631 the sublevels of a headline matching a tag search often also match
3632 the same search. Listing all of them can create very long lists.
3633 Setting this variable to nil causes subtrees of a match to be skipped.
3635 This variable is semi-obsolete and probably should always be true. It
3636 is better to limit inheritance to certain tags using the variables
3637 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3638 :group 'org-tags
3639 :type '(choice
3640 (const :tag "No, don't list them" nil)
3641 (const :tag "Yes, do list them" t)
3642 (const :tag "List them, indented with leading dots" indented)))
3644 (defcustom org-tags-sort-function nil
3645 "When set, tags are sorted using this function as a comparator."
3646 :group 'org-tags
3647 :type '(choice
3648 (const :tag "No sorting" nil)
3649 (const :tag "Alphabetical" string<)
3650 (const :tag "Reverse alphabetical" string>)
3651 (function :tag "Custom function" nil)))
3653 (defvar org-tags-history nil
3654 "History of minibuffer reads for tags.")
3655 (defvar org-last-tags-completion-table nil
3656 "The last used completion table for tags.")
3657 (defvar org-after-tags-change-hook nil
3658 "Hook that is run after the tags in a line have changed.")
3660 (defgroup org-properties nil
3661 "Options concerning properties in Org-mode."
3662 :tag "Org Properties"
3663 :group 'org)
3665 (defcustom org-property-format "%-10s %s"
3666 "How property key/value pairs should be formatted by `indent-line'.
3667 When `indent-line' hits a property definition, it will format the line
3668 according to this format, mainly to make sure that the values are
3669 lined-up with respect to each other."
3670 :group 'org-properties
3671 :type 'string)
3673 (defcustom org-properties-postprocess-alist nil
3674 "Alist of properties and functions to adjust inserted values.
3675 Elements of this alist must be of the form
3677 ([string] [function])
3679 where [string] must be a property name and [function] must be a
3680 lambda expression: this lambda expression must take one argument,
3681 the value to adjust, and return the new value as a string.
3683 For example, this element will allow the property \"Remaining\"
3684 to be updated wrt the relation between the \"Effort\" property
3685 and the clock summary:
3687 ((\"Remaining\" (lambda(value)
3688 (let ((clocksum (org-clock-sum-current-item))
3689 (effort (org-duration-string-to-minutes
3690 (org-entry-get (point) \"Effort\"))))
3691 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3692 :group 'org-properties
3693 :version "24.1"
3694 :type '(alist :key-type (string :tag "Property")
3695 :value-type (function :tag "Function")))
3697 (defcustom org-use-property-inheritance nil
3698 "Non-nil means properties apply also for sublevels.
3700 This setting is chiefly used during property searches. Turning it on can
3701 cause significant overhead when doing a search, which is why it is not
3702 on by default.
3704 When nil, only the properties directly given in the current entry count.
3705 When t, every property is inherited. The value may also be a list of
3706 properties that should have inheritance, or a regular expression matching
3707 properties that should be inherited.
3709 However, note that some special properties use inheritance under special
3710 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3711 and the properties ending in \"_ALL\" when they are used as descriptor
3712 for valid values of a property.
3714 Note for programmers:
3715 When querying an entry with `org-entry-get', you can control if inheritance
3716 should be used. By default, `org-entry-get' looks only at the local
3717 properties. You can request inheritance by setting the inherit argument
3718 to t (to force inheritance) or to `selective' (to respect the setting
3719 in this variable)."
3720 :group 'org-properties
3721 :type '(choice
3722 (const :tag "Not" nil)
3723 (const :tag "Always" t)
3724 (repeat :tag "Specific properties" (string :tag "Property"))
3725 (regexp :tag "Properties matched by regexp")))
3727 (defun org-property-inherit-p (property)
3728 "Check if PROPERTY is one that should be inherited."
3729 (cond
3730 ((eq org-use-property-inheritance t) t)
3731 ((not org-use-property-inheritance) nil)
3732 ((stringp org-use-property-inheritance)
3733 (string-match org-use-property-inheritance property))
3734 ((listp org-use-property-inheritance)
3735 (member property org-use-property-inheritance))
3736 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3738 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3739 "The default column format, if no other format has been defined.
3740 This variable can be set on the per-file basis by inserting a line
3742 #+COLUMNS: %25ITEM ....."
3743 :group 'org-properties
3744 :type 'string)
3746 (defcustom org-columns-ellipses ".."
3747 "The ellipses to be used when a field in column view is truncated.
3748 When this is the empty string, as many characters as possible are shown,
3749 but then there will be no visual indication that the field has been truncated.
3750 When this is a string of length N, the last N characters of a truncated
3751 field are replaced by this string. If the column is narrower than the
3752 ellipses string, only part of the ellipses string will be shown."
3753 :group 'org-properties
3754 :type 'string)
3756 (defcustom org-columns-modify-value-for-display-function nil
3757 "Function that modifies values for display in column view.
3758 For example, it can be used to cut out a certain part from a time stamp.
3759 The function must take 2 arguments:
3761 column-title The title of the column (*not* the property name)
3762 value The value that should be modified.
3764 The function should return the value that should be displayed,
3765 or nil if the normal value should be used."
3766 :group 'org-properties
3767 :type '(choice (const nil) (function)))
3769 (defconst org-global-properties-fixed
3770 '(("VISIBILITY_ALL" . "folded children content all")
3771 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3772 "List of property/value pairs that can be inherited by any entry.
3774 These are fixed values, for the preset properties. The user variable
3775 that can be used to add to this list is `org-global-properties'.
3777 The entries in this list are cons cells where the car is a property
3778 name and cdr is a string with the value. If the value represents
3779 multiple items like an \"_ALL\" property, separate the items by
3780 spaces.")
3782 (defcustom org-global-properties nil
3783 "List of property/value pairs that can be inherited by any entry.
3785 This list will be combined with the constant `org-global-properties-fixed'.
3787 The entries in this list are cons cells where the car is a property
3788 name and cdr is a string with the value.
3790 You can set buffer-local values for the same purpose in the variable
3791 `org-file-properties' this by adding lines like
3793 #+PROPERTY: NAME VALUE"
3794 :group 'org-properties
3795 :type '(repeat
3796 (cons (string :tag "Property")
3797 (string :tag "Value"))))
3799 (defvar org-file-properties nil
3800 "List of property/value pairs that can be inherited by any entry.
3801 Valid for the current buffer.
3802 This variable is populated from #+PROPERTY lines.")
3803 (make-variable-buffer-local 'org-file-properties)
3805 (defgroup org-agenda nil
3806 "Options concerning agenda views in Org-mode."
3807 :tag "Org Agenda"
3808 :group 'org)
3810 (defvar org-category nil
3811 "Variable used by org files to set a category for agenda display.
3812 Such files should use a file variable to set it, for example
3814 # -*- mode: org; org-category: \"ELisp\"
3816 or contain a special line
3818 #+CATEGORY: ELisp
3820 If the file does not specify a category, then file's base name
3821 is used instead.")
3822 (make-variable-buffer-local 'org-category)
3823 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3825 (defcustom org-agenda-files nil
3826 "The files to be used for agenda display.
3827 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3828 \\[org-remove-file]. You can also use customize to edit the list.
3830 If an entry is a directory, all files in that directory that are matched by
3831 `org-agenda-file-regexp' will be part of the file list.
3833 If the value of the variable is not a list but a single file name, then
3834 the list of agenda files is actually stored and maintained in that file, one
3835 agenda file per line. In this file paths can be given relative to
3836 `org-directory'. Tilde expansion and environment variable substitution
3837 are also made."
3838 :group 'org-agenda
3839 :type '(choice
3840 (repeat :tag "List of files and directories" file)
3841 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3843 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3844 "Regular expression to match files for `org-agenda-files'.
3845 If any element in the list in that variable contains a directory instead
3846 of a normal file, all files in that directory that are matched by this
3847 regular expression will be included."
3848 :group 'org-agenda
3849 :type 'regexp)
3851 (defcustom org-agenda-text-search-extra-files nil
3852 "List of extra files to be searched by text search commands.
3853 These files will be searched in addition to the agenda files by the
3854 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3855 Note that these files will only be searched for text search commands,
3856 not for the other agenda views like todo lists, tag searches or the weekly
3857 agenda. This variable is intended to list notes and possibly archive files
3858 that should also be searched by these two commands.
3859 In fact, if the first element in the list is the symbol `agenda-archives',
3860 then all archive files of all agenda files will be added to the search
3861 scope."
3862 :group 'org-agenda
3863 :type '(set :greedy t
3864 (const :tag "Agenda Archives" agenda-archives)
3865 (repeat :inline t (file))))
3867 (org-defvaralias 'org-agenda-multi-occur-extra-files
3868 'org-agenda-text-search-extra-files)
3870 (defcustom org-agenda-skip-unavailable-files nil
3871 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3872 A nil value means to remove them, after a query, from the list."
3873 :group 'org-agenda
3874 :type 'boolean)
3876 (defcustom org-calendar-to-agenda-key [?c]
3877 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3878 The command `org-calendar-goto-agenda' will be bound to this key. The
3879 default is the character `c' because then `c' can be used to switch back and
3880 forth between agenda and calendar."
3881 :group 'org-agenda
3882 :type 'sexp)
3884 (defcustom org-calendar-insert-diary-entry-key [?i]
3885 "The key to be installed in `calendar-mode-map' for adding diary entries.
3886 This option is irrelevant until `org-agenda-diary-file' has been configured
3887 to point to an Org-mode file. When that is the case, the command
3888 `org-agenda-diary-entry' will be bound to the key given here, by default
3889 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3890 if you want to continue doing this, you need to change this to a different
3891 key."
3892 :group 'org-agenda
3893 :type 'sexp)
3895 (defcustom org-agenda-diary-file 'diary-file
3896 "File to which to add new entries with the `i' key in agenda and calendar.
3897 When this is the symbol `diary-file', the functionality in the Emacs
3898 calendar will be used to add entries to the `diary-file'. But when this
3899 points to a file, `org-agenda-diary-entry' will be used instead."
3900 :group 'org-agenda
3901 :type '(choice
3902 (const :tag "The standard Emacs diary file" diary-file)
3903 (file :tag "Special Org file diary entries")))
3905 (eval-after-load "calendar"
3906 '(progn
3907 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3908 'org-calendar-goto-agenda)
3909 (add-hook 'calendar-mode-hook
3910 (lambda ()
3911 (unless (eq org-agenda-diary-file 'diary-file)
3912 (define-key calendar-mode-map
3913 org-calendar-insert-diary-entry-key
3914 'org-agenda-diary-entry))))))
3916 (defgroup org-latex nil
3917 "Options for embedding LaTeX code into Org-mode."
3918 :tag "Org LaTeX"
3919 :group 'org)
3921 (defcustom org-format-latex-options
3922 '(:foreground default :background default :scale 1.0
3923 :html-foreground "Black" :html-background "Transparent"
3924 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3925 "Options for creating images from LaTeX fragments.
3926 This is a property list with the following properties:
3927 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3928 `default' means use the foreground of the default face.
3929 `auto' means use the foreground from the text face.
3930 :background the background color, or \"Transparent\".
3931 `default' means use the background of the default face.
3932 `auto' means use the background from the text face.
3933 :scale a scaling factor for the size of the images, to get more pixels
3934 :html-foreground, :html-background, :html-scale
3935 the same numbers for HTML export.
3936 :matchers a list indicating which matchers should be used to
3937 find LaTeX fragments. Valid members of this list are:
3938 \"begin\" find environments
3939 \"$1\" find single characters surrounded by $.$
3940 \"$\" find math expressions surrounded by $...$
3941 \"$$\" find math expressions surrounded by $$....$$
3942 \"\\(\" find math expressions surrounded by \\(...\\)
3943 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3944 :group 'org-latex
3945 :type 'plist)
3947 (defcustom org-format-latex-signal-error t
3948 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3949 When nil, just push out a message."
3950 :group 'org-latex
3951 :version "24.1"
3952 :type 'boolean)
3954 (defcustom org-latex-to-mathml-jar-file nil
3955 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3956 Use this to specify additional executable file say a jar file.
3958 When using MathToWeb as the converter, specify the full-path to
3959 your mathtoweb.jar file."
3960 :group 'org-latex
3961 :version "24.1"
3962 :type '(choice
3963 (const :tag "None" nil)
3964 (file :tag "JAR file" :must-match t)))
3966 (defcustom org-latex-to-mathml-convert-command nil
3967 "Command to convert LaTeX fragments to MathML.
3968 Replace format-specifiers in the command as noted below and use
3969 `shell-command' to convert LaTeX to MathML.
3970 %j: Executable file in fully expanded form as specified by
3971 `org-latex-to-mathml-jar-file'.
3972 %I: Input LaTeX file in fully expanded form.
3973 %i: The latex fragment to be converted.
3974 %o: Output MathML file.
3975 This command is used by `org-create-math-formula'.
3977 When using MathToWeb as the converter, set this to
3978 \"java -jar %j -unicode -force -df %o %I\".
3980 When using LaTeXML set this to
3981 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3982 :group 'org-latex
3983 :version "24.1"
3984 :type '(choice
3985 (const :tag "None" nil)
3986 (string :tag "\nShell command")))
3988 (defcustom org-latex-create-formula-image-program 'dvipng
3989 "Program to convert LaTeX fragments with.
3991 dvipng Process the LaTeX fragments to dvi file, then convert
3992 dvi files to png files using dvipng.
3993 This will also include processing of non-math environments.
3994 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3995 to convert pdf files to png files"
3996 :group 'org-latex
3997 :version "24.1"
3998 :type '(choice
3999 (const :tag "dvipng" dvipng)
4000 (const :tag "imagemagick" imagemagick)))
4002 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
4003 "Path to store latex preview images.
4004 A relative path here creates many directories relative to the
4005 processed org files paths. An absolute path puts all preview
4006 images at the same place."
4007 :group 'org-latex
4008 :version "24.3"
4009 :type 'string)
4011 (defun org-format-latex-mathml-available-p ()
4012 "Return t if `org-latex-to-mathml-convert-command' is usable."
4013 (save-match-data
4014 (when (and (boundp 'org-latex-to-mathml-convert-command)
4015 org-latex-to-mathml-convert-command)
4016 (let ((executable (car (split-string
4017 org-latex-to-mathml-convert-command))))
4018 (when (executable-find executable)
4019 (if (string-match
4020 "%j" org-latex-to-mathml-convert-command)
4021 (file-readable-p org-latex-to-mathml-jar-file)
4022 t))))))
4024 (defcustom org-format-latex-header "\\documentclass{article}
4025 \\usepackage[usenames]{color}
4026 \[PACKAGES]
4027 \[DEFAULT-PACKAGES]
4028 \\pagestyle{empty} % do not remove
4029 % The settings below are copied from fullpage.sty
4030 \\setlength{\\textwidth}{\\paperwidth}
4031 \\addtolength{\\textwidth}{-3cm}
4032 \\setlength{\\oddsidemargin}{1.5cm}
4033 \\addtolength{\\oddsidemargin}{-2.54cm}
4034 \\setlength{\\evensidemargin}{\\oddsidemargin}
4035 \\setlength{\\textheight}{\\paperheight}
4036 \\addtolength{\\textheight}{-\\headheight}
4037 \\addtolength{\\textheight}{-\\headsep}
4038 \\addtolength{\\textheight}{-\\footskip}
4039 \\addtolength{\\textheight}{-3cm}
4040 \\setlength{\\topmargin}{1.5cm}
4041 \\addtolength{\\topmargin}{-2.54cm}"
4042 "The document header used for processing LaTeX fragments.
4043 It is imperative that this header make sure that no page number
4044 appears on the page. The package defined in the variables
4045 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4046 will either replace the placeholder \"[PACKAGES]\" in this
4047 header, or they will be appended."
4048 :group 'org-latex
4049 :type 'string)
4051 (defun org-set-packages-alist (var val)
4052 "Set the packages alist and make sure it has 3 elements per entry."
4053 (set var (mapcar (lambda (x)
4054 (if (and (consp x) (= (length x) 2))
4055 (list (car x) (nth 1 x) t)
4057 val)))
4059 (defun org-get-packages-alist (var)
4060 "Get the packages alist and make sure it has 3 elements per entry."
4061 (mapcar (lambda (x)
4062 (if (and (consp x) (= (length x) 2))
4063 (list (car x) (nth 1 x) t)
4065 (default-value var)))
4067 (defcustom org-latex-default-packages-alist
4068 '(("AUTO" "inputenc" t)
4069 ("T1" "fontenc" t)
4070 ("" "fixltx2e" nil)
4071 ("" "graphicx" t)
4072 ("" "grffile" t)
4073 ("" "longtable" nil)
4074 ("" "float" nil)
4075 ("" "wrapfig" nil)
4076 ("" "rotating" nil)
4077 ("normalem" "ulem" t)
4078 ("" "amsmath" t)
4079 ("" "textcomp" t)
4080 ("" "marvosym" t)
4081 ("" "wasysym" t)
4082 ("" "amssymb" t)
4083 ("" "capt-of" nil)
4084 ("" "hyperref" nil)
4085 "\\tolerance=1000")
4086 "Alist of default packages to be inserted in the header.
4088 Change this only if one of the packages here causes an
4089 incompatibility with another package you are using.
4091 The packages in this list are needed by one part or another of
4092 Org mode to function properly:
4094 - inputenc, fontenc: for basic font and character selection
4095 - fixltx2e: Important patches of LaTeX itself
4096 - graphicx: for including images
4097 - grffile: allow periods and spaces in graphics file names
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 "Non-nil when point (or POS) is in #+TBLFM line."
4574 (save-excursion
4575 (goto-char (or pos (point)))
4576 (beginning-of-line)
4577 (and (eq (org-element-type (org-element-at-point)) 'table)
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-heading-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 (:startgrouptag "[")
5221 (:endgrouptag "]")
5222 (:grouptags ":")
5223 (:newline "\\n")
5224 (otherwise (concat (car tag)
5225 (and (characterp (cdr tag))
5226 (format "(%c)" (cdr tag)))))))
5227 org-tag-alist)))
5228 ;; Process the tags.
5229 (org-set-local 'org-tag-groups-alist nil)
5230 (org-set-local 'org-tag-alist nil)
5231 (let (group-flag)
5232 (while tags
5233 (let ((e (car tags)))
5234 (setq tags (cdr tags))
5235 (cond
5236 ((equal e "{")
5237 (push '(:startgroup) org-tag-alist)
5238 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5239 ((equal e "}")
5240 (push '(:endgroup) org-tag-alist)
5241 (setq group-flag nil))
5242 ((equal e "[")
5243 (push '(:startgrouptag) org-tag-alist)
5244 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5245 ((equal e "]")
5246 (push '(:endgrouptag) org-tag-alist)
5247 (setq group-flag nil))
5248 ((equal e ":")
5249 (push '(:grouptags) org-tag-alist)
5250 (setq group-flag 'append))
5251 ((equal e "\\n") (push '(:newline) org-tag-alist))
5252 ((string-match
5253 (org-re (concat "\\`\\([[:alnum:]_@#%]+"
5254 "\\|{.+?}\\)" ; regular expression
5255 "\\(?:(\\(.\\))\\)?\\'")) e)
5256 (let ((tag (match-string 1 e))
5257 (key (and (match-beginning 2)
5258 (string-to-char (match-string 2 e)))))
5259 (cond ((eq group-flag 'append)
5260 (setcar org-tag-groups-alist
5261 (append (car org-tag-groups-alist) (list tag))))
5262 (group-flag (push (list tag) org-tag-groups-alist)))
5263 ;; Push all tags in groups, no matter if they already exist.
5264 (unless (and (not group-flag) (assoc tag org-tag-alist))
5265 (push (cons tag key) org-tag-alist))))))))
5266 (setq org-tag-alist (nreverse org-tag-alist)))
5268 (defun org-file-contents (file &optional noerror)
5269 "Return the contents of FILE, as a string."
5270 (if (and file (file-readable-p file))
5271 (with-temp-buffer
5272 (insert-file-contents file)
5273 (buffer-string))
5274 (funcall (if noerror 'message 'error)
5275 "Cannot read file \"%s\"%s"
5276 file
5277 (let ((from (buffer-file-name (buffer-base-buffer))))
5278 (if from (concat " (referenced in file \"" from "\")") "")))))
5280 (defun org-extract-log-state-settings (x)
5281 "Extract the log state setting from a TODO keyword string.
5282 This will extract info from a string like \"WAIT(w@/!)\"."
5283 (let (kw key log1 log2)
5284 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5285 (setq kw (match-string 1 x)
5286 key (and (match-end 2) (match-string 2 x))
5287 log1 (and (match-end 3) (match-string 3 x))
5288 log2 (and (match-end 4) (match-string 4 x)))
5289 (and (or log1 log2)
5290 (list kw
5291 (and log1 (if (equal log1 "!") 'time 'note))
5292 (and log2 (if (equal log2 "!") 'time 'note)))))))
5294 (defun org-remove-keyword-keys (list)
5295 "Remove a pair of parenthesis at the end of each string in LIST."
5296 (mapcar (lambda (x)
5297 (if (string-match "(.*)$" x)
5298 (substring x 0 (match-beginning 0))
5300 list))
5302 (defun org-assign-fast-keys (alist)
5303 "Assign fast keys to a keyword-key alist.
5304 Respect keys that are already there."
5305 (let (new e (alt ?0))
5306 (while (setq e (pop alist))
5307 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5308 (cdr e)) ;; Key already assigned.
5309 (push e new)
5310 (let ((clist (string-to-list (downcase (car e))))
5311 (used (append new alist)))
5312 (when (= (car clist) ?@)
5313 (pop clist))
5314 (while (and clist (rassoc (car clist) used))
5315 (pop clist))
5316 (unless clist
5317 (while (rassoc alt used)
5318 (incf alt)))
5319 (push (cons (car e) (or (car clist) alt)) new))))
5320 (nreverse new)))
5322 ;;; Some variables used in various places
5324 (defvar org-window-configuration nil
5325 "Used in various places to store a window configuration.")
5326 (defvar org-selected-window nil
5327 "Used in various places to store a window configuration.")
5328 (defvar org-finish-function nil
5329 "Function to be called when `C-c C-c' is used.
5330 This is for getting out of special buffers like capture.")
5333 ;; FIXME: Occasionally check by commenting these, to make sure
5334 ;; no other functions uses these, forgetting to let-bind them.
5335 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5336 (defvar org-last-state)
5337 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5339 ;; Defined somewhere in this file, but used before definition.
5340 (defvar org-entities) ;; defined in org-entities.el
5341 (defvar org-struct-menu)
5342 (defvar org-org-menu)
5343 (defvar org-tbl-menu)
5345 ;;;; Define the Org-mode
5347 ;; We use a before-change function to check if a table might need
5348 ;; an update.
5349 (defvar org-table-may-need-update t
5350 "Indicates that a table might need an update.
5351 This variable is set by `org-before-change-function'.
5352 `org-table-align' sets it back to nil.")
5353 (defun org-before-change-function (beg end)
5354 "Every change indicates that a table might need an update."
5355 (setq org-table-may-need-update t))
5356 (defvar org-mode-map)
5357 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5358 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5359 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5360 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5361 (defvar org-table-buffer-is-an nil)
5363 (defvar bidi-paragraph-direction)
5364 (defvar buffer-face-mode-face)
5366 (require 'outline)
5367 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5368 (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"))
5369 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5371 ;; Other stuff we need.
5372 (require 'time-date)
5373 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5374 (require 'easymenu)
5375 (autoload 'easy-menu-add "easymenu")
5376 (require 'overlay)
5378 ;; (require 'org-macs) moved higher up in the file before it is first used
5379 (require 'org-entities)
5380 ;; (require 'org-compat) moved higher up in the file before it is first used
5381 (require 'org-faces)
5382 (require 'org-list)
5383 (require 'org-pcomplete)
5384 (require 'org-src)
5385 (require 'org-footnote)
5386 (require 'org-macro)
5388 ;; babel
5389 (require 'ob)
5391 ;;;###autoload
5392 (define-derived-mode org-mode outline-mode "Org"
5393 "Outline-based notes management and organizer, alias
5394 \"Carsten's outline-mode for keeping track of everything.\"
5396 Org-mode develops organizational tasks around a NOTES file which
5397 contains information about projects as plain text. Org-mode is
5398 implemented on top of outline-mode, which is ideal to keep the content
5399 of large files well structured. It supports ToDo items, deadlines and
5400 time stamps, which magically appear in the diary listing of the Emacs
5401 calendar. Tables are easily created with a built-in table editor.
5402 Plain text URL-like links connect to websites, emails (VM), Usenet
5403 messages (Gnus), BBDB entries, and any files related to the project.
5404 For printing and sharing of notes, an Org-mode file (or a part of it)
5405 can be exported as a structured ASCII or HTML file.
5407 The following commands are available:
5409 \\{org-mode-map}"
5411 ;; Get rid of Outline menus, they are not needed
5412 ;; Need to do this here because define-derived-mode sets up
5413 ;; the keymap so late. Still, it is a waste to call this each time
5414 ;; we switch another buffer into org-mode.
5415 (if (featurep 'xemacs)
5416 (when (boundp 'outline-mode-menu-heading)
5417 ;; Assume this is Greg's port, it uses easymenu
5418 (easy-menu-remove outline-mode-menu-heading)
5419 (easy-menu-remove outline-mode-menu-show)
5420 (easy-menu-remove outline-mode-menu-hide))
5421 (define-key org-mode-map [menu-bar headings] 'undefined)
5422 (define-key org-mode-map [menu-bar hide] 'undefined)
5423 (define-key org-mode-map [menu-bar show] 'undefined))
5425 (org-load-modules-maybe)
5426 (easy-menu-add org-org-menu)
5427 (easy-menu-add org-tbl-menu)
5428 (org-install-agenda-files-menu)
5429 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5430 (add-to-invisibility-spec '(org-cwidth))
5431 (add-to-invisibility-spec '(org-hide-block . t))
5432 (when (featurep 'xemacs)
5433 (org-set-local 'line-move-ignore-invisible t))
5434 (org-set-local 'outline-regexp org-outline-regexp)
5435 (org-set-local 'outline-level 'org-outline-level)
5436 (setq bidi-paragraph-direction 'left-to-right)
5437 (when (and org-ellipsis
5438 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5439 (fboundp 'make-glyph-code))
5440 (unless org-display-table
5441 (setq org-display-table (make-display-table)))
5442 (set-display-table-slot
5443 org-display-table 4
5444 (vconcat (mapcar
5445 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5446 org-ellipsis)))
5447 (if (stringp org-ellipsis) org-ellipsis "..."))))
5448 (setq buffer-display-table org-display-table))
5449 (org-set-regexps-and-options)
5450 (org-set-font-lock-defaults)
5451 (when (and org-tag-faces (not org-tags-special-faces-re))
5452 ;; tag faces set outside customize.... force initialization.
5453 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5454 ;; Calc embedded
5455 (org-set-local 'calc-embedded-open-mode "# ")
5456 ;; Modify a few syntax entries
5457 (modify-syntax-entry ?@ "w")
5458 (modify-syntax-entry ?\" "\"")
5459 (modify-syntax-entry ?\\ "_")
5460 (modify-syntax-entry ?~ "_")
5461 (if org-startup-truncated (setq truncate-lines t))
5462 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5463 (org-set-local 'font-lock-unfontify-region-function
5464 'org-unfontify-region)
5465 ;; Activate before-change-function
5466 (org-set-local 'org-table-may-need-update t)
5467 (org-add-hook 'before-change-functions 'org-before-change-function nil
5468 'local)
5469 ;; Check for running clock before killing a buffer
5470 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5471 ;; Initialize macros templates.
5472 (org-macro-initialize-templates)
5473 ;; Initialize radio targets.
5474 (org-update-radio-target-regexp)
5475 ;; Indentation.
5476 (org-set-local 'indent-line-function 'org-indent-line)
5477 (org-set-local 'indent-region-function 'org-indent-region)
5478 ;; Filling and auto-filling.
5479 (org-setup-filling)
5480 ;; Comments.
5481 (org-setup-comments-handling)
5482 ;; Initialize cache.
5483 (org-element-cache-reset)
5484 ;; Beginning/end of defun
5485 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5486 (org-set-local 'end-of-defun-function
5487 (lambda ()
5488 (if (not (org-at-heading-p))
5489 (org-forward-element)
5490 (org-forward-element)
5491 (forward-char -1))))
5492 ;; Next error for sparse trees
5493 (org-set-local 'next-error-function 'org-occur-next-match)
5494 ;; Make sure dependence stuff works reliably, even for users who set it
5495 ;; too late :-(
5496 (if org-enforce-todo-dependencies
5497 (add-hook 'org-blocker-hook
5498 'org-block-todo-from-children-or-siblings-or-parent)
5499 (remove-hook 'org-blocker-hook
5500 'org-block-todo-from-children-or-siblings-or-parent))
5501 (if org-enforce-todo-checkbox-dependencies
5502 (add-hook 'org-blocker-hook
5503 'org-block-todo-from-checkboxes)
5504 (remove-hook 'org-blocker-hook
5505 'org-block-todo-from-checkboxes))
5507 ;; Align options lines
5508 (org-set-local
5509 'align-mode-rules-list
5510 '((org-in-buffer-settings
5511 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5512 (modes . '(org-mode)))))
5514 ;; Imenu
5515 (org-set-local 'imenu-create-index-function
5516 'org-imenu-get-tree)
5518 ;; Make isearch reveal context
5519 (if (or (featurep 'xemacs)
5520 (not (boundp 'outline-isearch-open-invisible-function)))
5521 ;; Emacs 21 and XEmacs make use of the hook
5522 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5523 ;; Emacs 22 deals with this through a special variable
5524 (org-set-local 'outline-isearch-open-invisible-function
5525 (lambda (&rest ignore) (org-show-context 'isearch))))
5527 ;; Setup the pcomplete hooks
5528 (set (make-local-variable 'pcomplete-command-completion-function)
5529 'org-pcomplete-initial)
5530 (set (make-local-variable 'pcomplete-command-name-function)
5531 'org-command-at-point)
5532 (set (make-local-variable 'pcomplete-default-completion-function)
5533 'ignore)
5534 (set (make-local-variable 'pcomplete-parse-arguments-function)
5535 'org-parse-arguments)
5536 (set (make-local-variable 'pcomplete-termination-string) "")
5537 (when (>= emacs-major-version 23)
5538 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5540 ;; If empty file that did not turn on org-mode automatically, make it to.
5541 (if (and org-insert-mode-line-in-empty-file
5542 (org-called-interactively-p 'any)
5543 (= (point-min) (point-max)))
5544 (insert "# -*- mode: org -*-\n\n"))
5545 (unless org-inhibit-startup
5546 (org-unmodified
5547 (and org-startup-with-beamer-mode (org-beamer-mode))
5548 (when org-startup-align-all-tables
5549 (org-table-map-tables 'org-table-align 'quietly))
5550 (when org-startup-with-inline-images
5551 (org-display-inline-images))
5552 (when org-startup-with-latex-preview
5553 (org-toggle-latex-fragment))
5554 (unless org-inhibit-startup-visibility-stuff
5555 (org-set-startup-visibility))
5556 (org-refresh-effort-properties)))
5557 ;; Try to set org-hide correctly
5558 (let ((foreground (org-find-invisible-foreground)))
5559 (if foreground
5560 (set-face-foreground 'org-hide foreground))))
5562 ;; Update `customize-package-emacs-version-alist'
5563 (add-to-list 'customize-package-emacs-version-alist
5564 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5565 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5566 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5568 (defvar org-mode-transpose-word-syntax-table
5569 (let ((st (make-syntax-table text-mode-syntax-table)))
5570 (mapc (lambda(c) (modify-syntax-entry
5571 (string-to-char (car c)) "w p" st))
5572 org-emphasis-alist)
5573 st))
5575 (when (fboundp 'abbrev-table-put)
5576 (abbrev-table-put org-mode-abbrev-table
5577 :parents (list text-mode-abbrev-table)))
5579 (defun org-find-invisible-foreground ()
5580 (let ((candidates (remove
5581 "unspecified-bg"
5582 (nconc
5583 (list (face-background 'default)
5584 (face-background 'org-default))
5585 (mapcar
5586 (lambda (alist)
5587 (when (boundp alist)
5588 (cdr (assoc 'background-color (symbol-value alist)))))
5589 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5590 (list (face-foreground 'org-hide))))))
5591 (car (remove nil candidates))))
5593 (defun org-current-time (&optional rounding-minutes past)
5594 "Current time, possibly rounded to ROUNDING-MINUTES.
5595 When ROUNDING-MINUTES is not an integer, fall back on the car of
5596 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5597 the rounding returns a past time."
5598 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5599 (car org-time-stamp-rounding-minutes)))
5600 (time (decode-time)) res)
5601 (if (< r 1)
5602 (current-time)
5603 (setq res
5604 (apply 'encode-time
5605 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5606 (nthcdr 2 time))))
5607 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5608 (seconds-to-time (- (org-float-time res) (* r 60)))
5609 res))))
5611 (defun org-today ()
5612 "Return today date, considering `org-extend-today-until'."
5613 (time-to-days
5614 (time-subtract (current-time)
5615 (list 0 (* 3600 org-extend-today-until) 0))))
5617 ;;;; Font-Lock stuff, including the activators
5619 (defvar org-mouse-map (make-sparse-keymap))
5620 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5621 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5622 (when org-mouse-1-follows-link
5623 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5624 (when org-tab-follows-link
5625 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5626 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5628 (require 'font-lock)
5630 (defconst org-non-link-chars "]\t\n\r<>")
5631 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5632 "file+sys" "news" "shell" "elisp" "doi" "message"
5633 "help"))
5634 (defvar org-link-types-re nil
5635 "Matches a link that has a url-like prefix like \"http:\"")
5636 (defvar org-link-re-with-space nil
5637 "Matches a link with spaces, optional angular brackets around it.")
5638 (defvar org-link-re-with-space2 nil
5639 "Matches a link with spaces, optional angular brackets around it.")
5640 (defvar org-link-re-with-space3 nil
5641 "Matches a link with spaces, only for internal part in bracket links.")
5642 (defvar org-angle-link-re nil
5643 "Matches link with angular brackets, spaces are allowed.")
5644 (defvar org-plain-link-re nil
5645 "Matches plain link, without spaces.")
5646 (defvar org-bracket-link-regexp nil
5647 "Matches a link in double brackets.")
5648 (defvar org-bracket-link-analytic-regexp nil
5649 "Regular expression used to analyze links.
5650 Here is what the match groups contain after a match:
5651 1: http:
5652 2: http
5653 3: path
5654 4: [desc]
5655 5: desc")
5656 (defvar org-bracket-link-analytic-regexp++ nil
5657 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5658 (defvar org-any-link-re nil
5659 "Regular expression matching any link.")
5661 (defconst org-match-sexp-depth 3
5662 "Number of stacked braces for sub/superscript matching.")
5664 (defun org-create-multibrace-regexp (left right n)
5665 "Create a regular expression which will match a balanced sexp.
5666 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5667 as single character strings.
5668 The regexp returned will match the entire expression including the
5669 delimiters. It will also define a single group which contains the
5670 match except for the outermost delimiters. The maximum depth of
5671 stacked delimiters is N. Escaping delimiters is not possible."
5672 (let* ((nothing (concat "[^" left right "]*?"))
5673 (or "\\|")
5674 (re nothing)
5675 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5676 (while (> n 1)
5677 (setq n (1- n)
5678 re (concat re or next)
5679 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5680 (concat left "\\(" re "\\)" right)))
5682 (defconst org-match-substring-regexp
5683 (concat
5684 "\\(\\S-\\)\\([_^]\\)\\("
5685 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5686 "\\|"
5687 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5688 "\\|"
5689 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5690 "The regular expression matching a sub- or superscript.")
5692 (defconst org-match-substring-with-braces-regexp
5693 (concat
5694 "\\(\\S-\\)\\([_^]\\)"
5695 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5696 "The regular expression matching a sub- or superscript, forcing braces.")
5698 (defun org-make-link-regexps ()
5699 "Update the link regular expressions.
5700 This should be called after the variable `org-link-types' has changed."
5701 (let ((types-re (regexp-opt org-link-types t)))
5702 (setq org-link-types-re
5703 (concat "\\`" types-re ":")
5704 org-link-re-with-space
5705 (concat "<?" types-re ":"
5706 "\\([^" org-non-link-chars " ]"
5707 "[^" org-non-link-chars "]*"
5708 "[^" org-non-link-chars " ]\\)>?")
5709 org-link-re-with-space2
5710 (concat "<?" types-re ":"
5711 "\\([^" org-non-link-chars " ]"
5712 "[^\t\n\r]*"
5713 "[^" org-non-link-chars " ]\\)>?")
5714 org-link-re-with-space3
5715 (concat "<?" types-re ":"
5716 "\\([^" org-non-link-chars " ]"
5717 "[^\t\n\r]*\\)")
5718 org-angle-link-re
5719 (concat "<" types-re ":"
5720 "\\([^" org-non-link-chars " ]"
5721 "[^" org-non-link-chars "]*"
5722 "\\)>")
5723 org-plain-link-re
5724 (concat
5725 "\\<" types-re ":"
5726 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5727 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5728 org-bracket-link-regexp
5729 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5730 org-bracket-link-analytic-regexp
5731 (concat
5732 "\\[\\["
5733 "\\(" types-re ":\\)?"
5734 "\\([^]]+\\)"
5735 "\\]"
5736 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5737 "\\]")
5738 org-bracket-link-analytic-regexp++
5739 (concat
5740 "\\[\\["
5741 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5742 "\\([^]]+\\)"
5743 "\\]"
5744 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5745 "\\]")
5746 org-any-link-re
5747 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5748 org-angle-link-re "\\)\\|\\("
5749 org-plain-link-re "\\)"))))
5751 (org-make-link-regexps)
5753 (defvar org-emph-face nil)
5755 (defun org-do-emphasis-faces (limit)
5756 "Run through the buffer and emphasize strings."
5757 (let (rtn a)
5758 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5759 (let* ((border (char-after (match-beginning 3)))
5760 (bre (regexp-quote (char-to-string border))))
5761 (if (and (not (= border (char-after (match-beginning 4))))
5762 (not (save-match-data
5763 (string-match (concat bre ".*" bre)
5764 (replace-regexp-in-string
5765 "\n" " "
5766 (substring (match-string 2) 1 -1))))))
5767 (progn
5768 (setq rtn t)
5769 (setq a (assoc (match-string 3) org-emphasis-alist))
5770 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5771 'face
5772 (nth 1 a))
5773 (and (nth 2 a)
5774 (org-remove-flyspell-overlays-in
5775 (match-beginning 0) (match-end 0)))
5776 (add-text-properties (match-beginning 2) (match-end 2)
5777 '(font-lock-multiline t org-emphasis t))
5778 (when org-hide-emphasis-markers
5779 (add-text-properties (match-end 4) (match-beginning 5)
5780 '(invisible org-link))
5781 (add-text-properties (match-beginning 3) (match-end 3)
5782 '(invisible org-link))))))
5783 (goto-char (1+ (match-beginning 0))))
5784 rtn))
5786 (defun org-emphasize (&optional char)
5787 "Insert or change an emphasis, i.e. a font like bold or italic.
5788 If there is an active region, change that region to a new emphasis.
5789 If there is no region, just insert the marker characters and position
5790 the cursor between them.
5791 CHAR should be the marker character. If it is a space, it means to
5792 remove the emphasis of the selected region.
5793 If CHAR is not given (for example in an interactive call) it will be
5794 prompted for."
5795 (interactive)
5796 (let ((erc org-emphasis-regexp-components)
5797 (prompt "")
5798 (string "") beg end move c s)
5799 (if (org-region-active-p)
5800 (setq beg (region-beginning) end (region-end)
5801 string (buffer-substring beg end))
5802 (setq move t))
5804 (unless char
5805 (message "Emphasis marker or tag: [%s]"
5806 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5807 (setq char (read-char-exclusive)))
5808 (if (equal char ?\ )
5809 (setq s "" move nil)
5810 (unless (assoc (char-to-string char) org-emphasis-alist)
5811 (user-error "No such emphasis marker: \"%c\"" char))
5812 (setq s (char-to-string char)))
5813 (while (and (> (length string) 1)
5814 (equal (substring string 0 1) (substring string -1))
5815 (assoc (substring string 0 1) org-emphasis-alist))
5816 (setq string (substring string 1 -1)))
5817 (setq string (concat s string s))
5818 (if beg (delete-region beg end))
5819 (unless (or (bolp)
5820 (string-match (concat "[" (nth 0 erc) "\n]")
5821 (char-to-string (char-before (point)))))
5822 (insert " "))
5823 (unless (or (eobp)
5824 (string-match (concat "[" (nth 1 erc) "\n]")
5825 (char-to-string (char-after (point)))))
5826 (insert " ") (backward-char 1))
5827 (insert string)
5828 (and move (backward-char 1))))
5830 (defconst org-nonsticky-props
5831 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5833 (defsubst org-rear-nonsticky-at (pos)
5834 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5836 (defun org-activate-plain-links (limit)
5837 "Add link properties for plain links."
5838 (let (f hl)
5839 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5840 (not (member 'org-tag
5841 (get-text-property (1- (match-beginning 0)) 'face)))
5842 (not (org-in-src-block-p)))
5843 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5844 (setq f (get-text-property (match-beginning 0) 'face))
5845 (setq hl (org-match-string-no-properties 0))
5846 (if (or (eq f 'org-tag)
5847 (and (listp f) (memq 'org-tag f)))
5849 (add-text-properties (match-beginning 0) (match-end 0)
5850 (list 'mouse-face 'highlight
5851 'face 'org-link
5852 'htmlize-link `(:uri ,hl)
5853 'keymap org-mouse-map))
5854 (org-rear-nonsticky-at (match-end 0)))
5855 t)))
5857 (defun org-activate-code (limit)
5858 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5859 (progn
5860 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5861 (remove-text-properties (match-beginning 0) (match-end 0)
5862 '(display t invisible t intangible t))
5863 t)))
5865 (defcustom org-src-fontify-natively t
5866 "When non-nil, fontify code in code blocks."
5867 :type 'boolean
5868 :version "24.4"
5869 :package-version '(Org . "8.3")
5870 :group 'org-appearance
5871 :group 'org-babel)
5873 (defcustom org-allow-promoting-top-level-subtree nil
5874 "When non-nil, allow promoting a top level subtree.
5875 The leading star of the top level headline will be replaced
5876 by a #."
5877 :type 'boolean
5878 :version "24.1"
5879 :group 'org-appearance)
5881 (defun org-fontify-meta-lines-and-blocks (limit)
5882 (condition-case nil
5883 (org-fontify-meta-lines-and-blocks-1 limit)
5884 (error (message "org-mode fontification error"))))
5886 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5887 "Fontify #+ lines and blocks."
5888 (let ((case-fold-search t))
5889 (if (re-search-forward
5890 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5891 limit t)
5892 (let ((beg (match-beginning 0))
5893 (block-start (match-end 0))
5894 (block-end nil)
5895 (lang (match-string 7))
5896 (beg1 (line-beginning-position 2))
5897 (dc1 (downcase (match-string 2)))
5898 (dc3 (downcase (match-string 3)))
5899 end end1 quoting block-type ovl)
5900 (cond
5901 ((and (match-end 4) (equal dc3 "+begin"))
5902 ;; Truly a block
5903 (setq block-type (downcase (match-string 5))
5904 quoting (member block-type org-protecting-blocks))
5905 (when (re-search-forward
5906 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5907 nil t) ;; on purpose, we look further than LIMIT
5908 (setq end (min (point-max) (match-end 0))
5909 end1 (min (point-max) (1- (match-beginning 0))))
5910 (setq block-end (match-beginning 0))
5911 (when quoting
5912 (org-remove-flyspell-overlays-in beg1 end1)
5913 (remove-text-properties beg end
5914 '(display t invisible t intangible t)))
5915 (add-text-properties
5916 beg end '(font-lock-fontified t font-lock-multiline t))
5917 (add-text-properties beg beg1 '(face org-meta-line))
5918 (org-remove-flyspell-overlays-in beg beg1)
5919 (add-text-properties ; For end_src
5920 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5921 (org-remove-flyspell-overlays-in end1 end)
5922 (cond
5923 ((and lang (not (string= lang "")) org-src-fontify-natively)
5924 (org-src-font-lock-fontify-block lang block-start block-end)
5925 (add-text-properties beg1 block-end '(src-block t)))
5926 (quoting
5927 (add-text-properties beg1 (min (point-max) (1+ end1))
5928 '(face org-block))) ; end of source block
5929 ((not org-fontify-quote-and-verse-blocks))
5930 ((string= block-type "quote")
5931 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5932 ((string= block-type "verse")
5933 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5934 (add-text-properties beg beg1 '(face org-block-begin-line))
5935 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5936 '(face org-block-end-line))
5938 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5939 (org-remove-flyspell-overlays-in
5940 (match-beginning 0)
5941 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5942 (add-text-properties
5943 beg (match-end 3)
5944 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5945 '(font-lock-fontified t invisible t)
5946 '(font-lock-fontified t face org-document-info-keyword)))
5947 (add-text-properties
5948 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5949 (if (string-equal dc1 "+title:")
5950 '(font-lock-fontified t face org-document-title)
5951 '(font-lock-fontified t face org-document-info))))
5952 ((equal dc1 "+caption:")
5953 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5954 (remove-text-properties (match-beginning 0) (match-end 0)
5955 '(display t invisible t intangible t))
5956 (add-text-properties (match-beginning 1) (match-end 3)
5957 '(font-lock-fontified t face org-meta-line))
5958 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5959 '(font-lock-fontified t face org-block))
5961 ((member dc3 '(" " ""))
5962 (org-remove-flyspell-overlays-in beg (match-end 0))
5963 (add-text-properties
5964 beg (match-end 0)
5965 '(font-lock-fontified t face font-lock-comment-face)))
5966 (t ;; just any other in-buffer setting, but not indented
5967 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5968 (remove-text-properties (match-beginning 0) (match-end 0)
5969 '(display t invisible t intangible t))
5970 (add-text-properties beg (match-end 0)
5971 '(font-lock-fontified t face org-meta-line))
5972 t))))))
5974 (defun org-fontify-drawers (limit)
5975 "Fontify drawers."
5976 (when (re-search-forward org-drawer-regexp limit t)
5977 (add-text-properties
5978 (match-beginning 0) (match-end 0)
5979 '(font-lock-fontified t face org-special-keyword))
5980 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5983 (defun org-fontify-macros (limit)
5984 "Fontify macros."
5985 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5986 (add-text-properties
5987 (match-beginning 0) (match-end 0)
5988 '(font-lock-fontified t face org-macro))
5989 (when org-hide-macro-markers
5990 (add-text-properties (match-end 2) (match-beginning 2)
5991 '(invisible t))
5992 (add-text-properties (match-beginning 1) (match-end 1)
5993 '(invisible t)))
5994 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5997 (defun org-activate-angle-links (limit)
5998 "Add text properties for angle links."
5999 (if (and (re-search-forward org-angle-link-re limit t)
6000 (not (org-in-src-block-p)))
6001 (progn
6002 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6003 (add-text-properties (match-beginning 0) (match-end 0)
6004 (list 'mouse-face 'highlight
6005 'keymap org-mouse-map))
6006 (org-rear-nonsticky-at (match-end 0))
6007 t)))
6009 (defun org-activate-footnote-links (limit)
6010 "Add text properties for footnotes."
6011 (let ((fn (org-footnote-next-reference-or-definition limit)))
6012 (when fn
6013 (let* ((beg (nth 1 fn))
6014 (end (nth 2 fn))
6015 (label (car fn))
6016 (referencep (/= (line-beginning-position) beg)))
6017 (when (and referencep (nth 3 fn))
6018 (save-excursion
6019 (goto-char beg)
6020 (search-forward (or label "fn:"))
6021 (org-remove-flyspell-overlays-in beg (match-end 0))))
6022 (add-text-properties beg end
6023 (list 'mouse-face 'highlight
6024 'keymap org-mouse-map
6025 'help-echo
6026 (if referencep "Footnote reference"
6027 "Footnote definition")
6028 'font-lock-fontified t
6029 'font-lock-multiline t
6030 'face 'org-footnote))))))
6032 (defun org-activate-bracket-links (limit)
6033 "Add text properties for bracketed links."
6034 (if (and (re-search-forward org-bracket-link-regexp limit t)
6035 (not (org-in-src-block-p)))
6036 (let* ((hl (org-match-string-no-properties 1))
6037 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6038 (ip (org-maybe-intangible
6039 (list 'invisible 'org-link
6040 'keymap org-mouse-map 'mouse-face 'highlight
6041 'font-lock-multiline t 'help-echo help
6042 'htmlize-link `(:uri ,hl))))
6043 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6044 'font-lock-multiline t 'help-echo help
6045 'htmlize-link `(:uri ,hl))))
6046 ;; We need to remove the invisible property here. Table narrowing
6047 ;; may have made some of this invisible.
6048 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6049 (remove-text-properties (match-beginning 0) (match-end 0)
6050 '(invisible nil))
6051 (if (match-end 3)
6052 (progn
6053 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6054 (org-rear-nonsticky-at (match-beginning 3))
6055 (add-text-properties (match-beginning 3) (match-end 3) vp)
6056 (org-rear-nonsticky-at (match-end 3))
6057 (add-text-properties (match-end 3) (match-end 0) ip)
6058 (org-rear-nonsticky-at (match-end 0)))
6059 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6060 (org-rear-nonsticky-at (match-beginning 1))
6061 (add-text-properties (match-beginning 1) (match-end 1) vp)
6062 (org-rear-nonsticky-at (match-end 1))
6063 (add-text-properties (match-end 1) (match-end 0) ip)
6064 (org-rear-nonsticky-at (match-end 0)))
6065 t)))
6067 (defun org-activate-dates (limit)
6068 "Add text properties for dates."
6069 (if (and (re-search-forward org-tsr-regexp-both limit t)
6070 (not (equal (char-before (match-beginning 0)) 91)))
6071 (progn
6072 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6073 (add-text-properties (match-beginning 0) (match-end 0)
6074 (list 'mouse-face 'highlight
6075 'keymap org-mouse-map))
6076 (org-rear-nonsticky-at (match-end 0))
6077 (when org-display-custom-times
6078 (if (match-end 3)
6079 (org-display-custom-time (match-beginning 3) (match-end 3)))
6080 (org-display-custom-time (match-beginning 1) (match-end 1)))
6081 t)))
6083 (defvar org-target-link-regexp nil
6084 "Regular expression matching radio targets in plain text.")
6085 (make-variable-buffer-local 'org-target-link-regexp)
6087 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6088 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6089 border border border))
6090 "Regular expression matching a link target.")
6092 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6093 "Regular expression matching a radio target.")
6095 (defconst org-any-target-regexp
6096 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6097 "Regular expression matching any target.")
6099 (defun org-activate-target-links (limit)
6100 "Add text properties for target matches."
6101 (when org-target-link-regexp
6102 (let ((case-fold-search t))
6103 (if (re-search-forward org-target-link-regexp limit t)
6104 (progn
6105 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6106 (add-text-properties (match-beginning 1) (match-end 1)
6107 (list 'mouse-face 'highlight
6108 'keymap org-mouse-map
6109 'help-echo "Radio target link"
6110 'org-linked-text t))
6111 (org-rear-nonsticky-at (match-end 1))
6112 t)))))
6114 (defun org-update-radio-target-regexp ()
6115 "Find all radio targets in this file and update the regular expression.
6116 Also refresh fontification if needed."
6117 (interactive)
6118 (let ((old-regexp org-target-link-regexp)
6119 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6120 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6121 (targets
6122 (org-with-wide-buffer
6123 (goto-char (point-min))
6124 (let (rtn)
6125 (while (re-search-forward org-radio-target-regexp nil t)
6126 ;; Make sure point is really within the object.
6127 (backward-char)
6128 (let ((obj (org-element-context)))
6129 (when (eq (org-element-type obj) 'radio-target)
6130 (add-to-list 'rtn (org-element-property :value obj)))))
6131 rtn))))
6132 (setq org-target-link-regexp
6133 (and targets
6134 (concat before-re
6135 (mapconcat
6136 (lambda (x)
6137 (replace-regexp-in-string
6138 " +" "\\s-+" (regexp-quote x) t t))
6139 targets
6140 "\\|")
6141 after-re)))
6142 (unless (equal old-regexp org-target-link-regexp)
6143 ;; Clean-up cache.
6144 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6145 ((not org-target-link-regexp) old-regexp)
6147 (concat before-re
6148 (mapconcat
6149 (lambda (re)
6150 (substring re (length before-re)
6151 (- (length after-re))))
6152 (list old-regexp org-target-link-regexp)
6153 "\\|")
6154 after-re)))))
6155 (org-with-wide-buffer
6156 (goto-char (point-min))
6157 (while (re-search-forward regexp nil t)
6158 (org-element-cache-refresh (match-beginning 1)))))
6159 ;; Re fontify buffer.
6160 (when (memq 'radio org-highlight-links)
6161 (org-restart-font-lock)))))
6163 (defun org-hide-wide-columns (limit)
6164 (let (s e)
6165 (setq s (text-property-any (point) (or limit (point-max))
6166 'org-cwidth t))
6167 (when s
6168 (setq e (next-single-property-change s 'org-cwidth))
6169 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6170 (goto-char e)
6171 t)))
6173 (defvar org-latex-and-related-regexp nil
6174 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6176 (defun org-compute-latex-and-related-regexp ()
6177 "Compute regular expression for LaTeX, entities and sub/superscript.
6178 Result depends on variable `org-highlight-latex-and-related'."
6179 (org-set-local
6180 'org-latex-and-related-regexp
6181 (let* ((re-sub
6182 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6183 ((eq org-use-sub-superscripts '{})
6184 (list org-match-substring-with-braces-regexp))
6185 (org-use-sub-superscripts (list org-match-substring-regexp))))
6186 (re-latex
6187 (when (memq 'latex org-highlight-latex-and-related)
6188 (let ((matchers (plist-get org-format-latex-options :matchers)))
6189 (delq nil
6190 (mapcar (lambda (x)
6191 (and (member (car x) matchers) (nth 1 x)))
6192 org-latex-regexps)))))
6193 (re-entities
6194 (when (memq 'entities org-highlight-latex-and-related)
6195 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6196 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6198 (defun org-do-latex-and-related (limit)
6199 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6200 LIMIT bounds the search for syntax to highlight. Stop at first
6201 highlighted object, if any. Return t if some highlighting was
6202 done, nil otherwise."
6203 (when (org-string-nw-p org-latex-and-related-regexp)
6204 (catch 'found
6205 (while (re-search-forward org-latex-and-related-regexp limit t)
6206 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6207 'face))
6208 '(org-code org-verbatim underline))
6209 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6210 '(?_ ?^))
6212 0)))
6213 (font-lock-prepend-text-property
6214 (+ offset (match-beginning 0)) (match-end 0)
6215 'face 'org-latex-and-related)
6216 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6217 '(font-lock-multiline t)))
6218 (throw 'found t)))
6219 nil)))
6221 (defun org-restart-font-lock ()
6222 "Restart `font-lock-mode', to force refontification."
6223 (when (and (boundp 'font-lock-mode) font-lock-mode)
6224 (font-lock-mode -1)
6225 (font-lock-mode 1)))
6227 (defun org-activate-tags (limit)
6228 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6229 (progn
6230 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6231 (add-text-properties (match-beginning 1) (match-end 1)
6232 (list 'mouse-face 'highlight
6233 'keymap org-mouse-map))
6234 (org-rear-nonsticky-at (match-end 1))
6235 t)))
6237 (defun org-outline-level ()
6238 "Compute the outline level of the heading at point.
6240 If this is called at a normal headline, the level is the number
6241 of stars. Use `org-reduced-level' to remove the effect of
6242 `org-odd-levels'. Unlike to `org-current-level', this function
6243 takes into consideration inlinetasks."
6244 (org-with-wide-buffer
6245 (end-of-line)
6246 (if (re-search-backward org-outline-regexp-bol nil t)
6247 (1- (- (match-end 0) (match-beginning 0)))
6248 0)))
6250 (defvar org-font-lock-keywords nil)
6252 (defsubst org-re-property (property &optional literal allow-null value)
6253 "Return a regexp matching a PROPERTY line.
6255 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6256 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6257 non-nil, match properties even without a value.
6259 Match group 3 is set to the value when it exists. If there is no
6260 value and ALLOW-NULL is non-nil, it is set to the empty string.
6262 With optional argument VALUE, match only property lines with
6263 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6264 unless LITERAL is non-nil."
6265 (concat
6266 "^\\(?4:[ \t]*\\)"
6267 (format "\\(?1::\\(?2:%s\\):\\)"
6268 (if literal property (regexp-quote property)))
6269 (cond (value
6270 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6271 (if literal value (regexp-quote value))))
6272 (allow-null
6273 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6275 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6277 (defconst org-property-re
6278 (org-re-property "\\S-+" 'literal t)
6279 "Regular expression matching a property line.
6280 There are four matching groups:
6281 1: :PROPKEY: including the leading and trailing colon,
6282 2: PROPKEY without the leading and trailing colon,
6283 3: PROPVAL without leading or trailing spaces,
6284 4: the indentation of the current line,
6285 5: trailing whitespace.")
6287 (defvar org-font-lock-hook nil
6288 "Functions to be called for special font lock stuff.")
6290 (defvar org-font-lock-set-keywords-hook nil
6291 "Functions that can manipulate `org-font-lock-extra-keywords'.
6292 This is called after `org-font-lock-extra-keywords' is defined, but before
6293 it is installed to be used by font lock. This can be useful if something
6294 needs to be inserted at a specific position in the font-lock sequence.")
6296 (defun org-font-lock-hook (limit)
6297 "Run `org-font-lock-hook' within LIMIT."
6298 (run-hook-with-args 'org-font-lock-hook limit))
6300 (defun org-set-font-lock-defaults ()
6301 "Set font lock defaults for the current buffer."
6302 (let* ((em org-fontify-emphasized-text)
6303 (lk org-highlight-links)
6304 (org-font-lock-extra-keywords
6305 (list
6306 ;; Call the hook
6307 '(org-font-lock-hook)
6308 ;; Headlines
6309 `(,(if org-fontify-whole-heading-line
6310 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6311 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6312 (1 (org-get-level-face 1))
6313 (2 (org-get-level-face 2))
6314 (3 (org-get-level-face 3)))
6315 ;; Table lines
6316 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6317 (1 'org-table t))
6318 ;; Table internals
6319 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6320 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6321 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6322 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6323 ;; Drawers
6324 '(org-fontify-drawers)
6325 ;; Properties
6326 (list org-property-re
6327 '(1 'org-special-keyword t)
6328 '(3 'org-property-value t))
6329 ;; Links
6330 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6331 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6332 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6333 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6334 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6335 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6336 (if (memq 'footnote lk) '(org-activate-footnote-links))
6337 ;; Targets.
6338 (list org-any-target-regexp '(0 'org-target t))
6339 ;; Diary sexps.
6340 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6341 ;; Macro
6342 '(org-fontify-macros)
6343 '(org-hide-wide-columns (0 nil append))
6344 ;; TODO keyword
6345 (list (format org-heading-keyword-regexp-format
6346 org-todo-regexp)
6347 '(2 (org-get-todo-face 2) t))
6348 ;; DONE
6349 (if org-fontify-done-headline
6350 (list (format org-heading-keyword-regexp-format
6351 (concat
6352 "\\(?:"
6353 (mapconcat 'regexp-quote org-done-keywords "\\|")
6354 "\\)"))
6355 '(2 'org-headline-done t))
6356 nil)
6357 ;; Priorities
6358 '(org-font-lock-add-priority-faces)
6359 ;; Tags
6360 '(org-font-lock-add-tag-faces)
6361 ;; Tags groups
6362 (if (and org-group-tags org-tag-groups-alist)
6363 (list (concat org-outline-regexp-bol ".+\\(:"
6364 (regexp-opt (mapcar 'car org-tag-groups-alist))
6365 ":\\).*$")
6366 '(1 'org-tag-group prepend)))
6367 ;; Special keywords
6368 (list (concat "\\<" org-comment-string) '(0 'org-special-keyword t))
6369 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6370 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6371 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6372 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6373 ;; Emphasis
6374 (if em
6375 (if (featurep 'xemacs)
6376 '(org-do-emphasis-faces (0 nil append))
6377 '(org-do-emphasis-faces)))
6378 ;; Checkboxes
6379 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6380 1 'org-checkbox prepend)
6381 (if (cdr (assq 'checkbox org-list-automatic-rules))
6382 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6383 (0 (org-get-checkbox-statistics-face) t)))
6384 ;; Description list items
6385 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6386 1 'org-list-dt prepend)
6387 ;; ARCHIVEd headings
6388 (list (concat
6389 org-outline-regexp-bol
6390 "\\(.*:" org-archive-tag ":.*\\)")
6391 '(1 'org-archived prepend))
6392 ;; Specials
6393 '(org-do-latex-and-related)
6394 '(org-fontify-entities)
6395 '(org-raise-scripts)
6396 ;; Code
6397 '(org-activate-code (1 'org-code t))
6398 ;; COMMENT
6399 (list (format
6400 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6401 org-todo-regexp
6402 org-comment-string)
6403 '(9 'org-special-keyword t))
6404 ;; Blocks and meta lines
6405 '(org-fontify-meta-lines-and-blocks))))
6406 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6407 (run-hooks 'org-font-lock-set-keywords-hook)
6408 ;; Now set the full font-lock-keywords
6409 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6410 (org-set-local 'font-lock-defaults
6411 '(org-font-lock-keywords t nil nil backward-paragraph))
6412 (kill-local-variable 'font-lock-keywords) nil))
6414 (defun org-toggle-pretty-entities ()
6415 "Toggle the composition display of entities as UTF8 characters."
6416 (interactive)
6417 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6418 (org-restart-font-lock)
6419 (if org-pretty-entities
6420 (message "Entities are now displayed as UTF8 characters")
6421 (save-restriction
6422 (widen)
6423 (org-decompose-region (point-min) (point-max))
6424 (message "Entities are now displayed as plain text"))))
6426 (defvar org-custom-properties-overlays nil
6427 "List of overlays used for custom properties.")
6428 (make-variable-buffer-local 'org-custom-properties-overlays)
6430 (defun org-toggle-custom-properties-visibility ()
6431 "Display or hide properties in `org-custom-properties'."
6432 (interactive)
6433 (if org-custom-properties-overlays
6434 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6435 (setq org-custom-properties-overlays nil))
6436 (when org-custom-properties
6437 (org-with-wide-buffer
6438 (goto-char (point-min))
6439 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6440 (while (re-search-forward regexp nil t)
6441 (let ((end (cdr (save-match-data (org-get-property-block)))))
6442 (when (and end (< (point) end))
6443 ;; Hide first custom property in current drawer.
6444 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6445 (overlay-put o 'invisible t)
6446 (overlay-put o 'org-custom-property t)
6447 (push o org-custom-properties-overlays))
6448 ;; Hide additional custom properties in the same drawer.
6449 (while (re-search-forward regexp end t)
6450 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6451 (overlay-put o 'invisible t)
6452 (overlay-put o 'org-custom-property t)
6453 (push o org-custom-properties-overlays)))))
6454 ;; Each entry is limited to a single property drawer.
6455 (outline-next-heading)))))))
6457 (defun org-fontify-entities (limit)
6458 "Find an entity to fontify."
6459 (let (ee)
6460 (when org-pretty-entities
6461 (catch 'match
6462 ;; "\_ "-family is left out on purpose. Only the first one,
6463 ;; i.e., "\_ ", could be fontified anyway, and it would be
6464 ;; confusing when adding a second white space character.
6465 (while (re-search-forward
6466 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6467 limit t)
6468 (if (and (not (org-at-comment-p))
6469 (setq ee (org-entity-get (match-string 1)))
6470 (= (length (nth 6 ee)) 1))
6471 (let*
6472 ((end (if (equal (match-string 2) "{}")
6473 (match-end 2)
6474 (match-end 1))))
6475 (add-text-properties
6476 (match-beginning 0) end
6477 (list 'font-lock-fontified t))
6478 (compose-region (match-beginning 0) end
6479 (nth 6 ee) nil)
6480 (backward-char 1)
6481 (throw 'match t))))
6482 nil))))
6484 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6485 "Fontify string S like in Org-mode."
6486 (with-temp-buffer
6487 (insert s)
6488 (let ((org-odd-levels-only odd-levels))
6489 (org-mode)
6490 (font-lock-ensure)
6491 (buffer-string))))
6493 (defvar org-m nil)
6494 (defvar org-l nil)
6495 (defvar org-f nil)
6496 (defun org-get-level-face (n)
6497 "Get the right face for match N in font-lock matching of headlines."
6498 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6499 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6500 (if org-cycle-level-faces
6501 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6502 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6503 (cond
6504 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6505 ((eq n 2) org-f)
6506 (t (if org-level-color-stars-only nil org-f))))
6509 (defun org-get-todo-face (kwd)
6510 "Get the right face for a TODO keyword KWD.
6511 If KWD is a number, get the corresponding match group."
6512 (if (numberp kwd) (setq kwd (match-string kwd)))
6513 (or (org-face-from-face-or-color
6514 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6515 (and (member kwd org-done-keywords) 'org-done)
6516 'org-todo))
6518 (defun org-face-from-face-or-color (context inherit face-or-color)
6519 "Create a face list that inherits INHERIT, but sets the foreground color.
6520 When FACE-OR-COLOR is not a string, just return it."
6521 (if (stringp face-or-color)
6522 (list :inherit inherit
6523 (cdr (assoc context org-faces-easy-properties))
6524 face-or-color)
6525 face-or-color))
6527 (defun org-font-lock-add-tag-faces (limit)
6528 "Add the special tag faces."
6529 (when (and org-tag-faces org-tags-special-faces-re)
6530 (while (re-search-forward org-tags-special-faces-re limit t)
6531 (add-text-properties (match-beginning 1) (match-end 1)
6532 (list 'face (org-get-tag-face 1)
6533 'font-lock-fontified t))
6534 (backward-char 1))))
6536 (defun org-font-lock-add-priority-faces (limit)
6537 "Add the special priority faces."
6538 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6539 (when (save-match-data (org-at-heading-p))
6540 (add-text-properties
6541 (match-beginning 0) (match-end 0)
6542 (list 'face (or (org-face-from-face-or-color
6543 'priority 'org-priority
6544 (cdr (assoc (char-after (match-beginning 1))
6545 org-priority-faces)))
6546 'org-priority)
6547 'font-lock-fontified t)))))
6549 (defun org-get-tag-face (kwd)
6550 "Get the right face for a TODO keyword KWD.
6551 If KWD is a number, get the corresponding match group."
6552 (if (numberp kwd) (setq kwd (match-string kwd)))
6553 (or (org-face-from-face-or-color
6554 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6555 'org-tag))
6557 (defun org-unfontify-region (beg end &optional maybe_loudly)
6558 "Remove fontification and activation overlays from links."
6559 (font-lock-default-unfontify-region beg end)
6560 (let* ((buffer-undo-list t)
6561 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6562 (inhibit-modification-hooks t)
6563 deactivate-mark buffer-file-name buffer-file-truename)
6564 (org-decompose-region beg end)
6565 (remove-text-properties beg end
6566 '(mouse-face t keymap t org-linked-text t
6567 invisible t intangible t
6568 org-emphasis t))
6569 (org-remove-font-lock-display-properties beg end)))
6571 (defconst org-script-display '(((raise -0.3) (height 0.7))
6572 ((raise 0.3) (height 0.7))
6573 ((raise -0.5))
6574 ((raise 0.5)))
6575 "Display properties for showing superscripts and subscripts.")
6577 (defun org-remove-font-lock-display-properties (beg end)
6578 "Remove specific display properties that have been added by font lock.
6579 The will remove the raise properties that are used to show superscripts
6580 and subscripts."
6581 (let (next prop)
6582 (while (< beg end)
6583 (setq next (next-single-property-change beg 'display nil end)
6584 prop (get-text-property beg 'display))
6585 (if (member prop org-script-display)
6586 (put-text-property beg next 'display nil))
6587 (setq beg next))))
6589 (defun org-raise-scripts (limit)
6590 "Add raise properties to sub/superscripts."
6591 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6592 (if (re-search-forward
6593 (if (eq org-use-sub-superscripts t)
6594 org-match-substring-regexp
6595 org-match-substring-with-braces-regexp)
6596 limit t)
6597 (let* ((pos (point)) table-p comment-p
6598 (mpos (match-beginning 3))
6599 (emph-p (get-text-property mpos 'org-emphasis))
6600 (link-p (get-text-property mpos 'mouse-face))
6601 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6602 (goto-char (point-at-bol))
6603 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6604 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6605 (goto-char pos)
6606 ;; Handle a_b^c
6607 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6608 (if (or comment-p emph-p link-p keyw-p)
6610 (put-text-property (match-beginning 3) (match-end 0)
6611 'display
6612 (if (equal (char-after (match-beginning 2)) ?^)
6613 (nth (if table-p 3 1) org-script-display)
6614 (nth (if table-p 2 0) org-script-display)))
6615 (add-text-properties (match-beginning 2) (match-end 2)
6616 (list 'invisible t
6617 'org-dwidth t 'org-dwidth-n 1))
6618 (if (and (eq (char-after (match-beginning 3)) ?{)
6619 (eq (char-before (match-end 3)) ?}))
6620 (progn
6621 (add-text-properties
6622 (match-beginning 3) (1+ (match-beginning 3))
6623 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6624 (add-text-properties
6625 (1- (match-end 3)) (match-end 3)
6626 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6627 t)))))
6629 ;;;; Visibility cycling, including org-goto and indirect buffer
6631 ;;; Cycling
6633 (defvar org-cycle-global-status nil)
6634 (make-variable-buffer-local 'org-cycle-global-status)
6635 (put 'org-cycle-global-status 'org-state t)
6636 (defvar org-cycle-subtree-status nil)
6637 (make-variable-buffer-local 'org-cycle-subtree-status)
6638 (put 'org-cycle-subtree-status 'org-state t)
6640 (defvar org-inlinetask-min-level)
6642 (defun org-unlogged-message (&rest args)
6643 "Display a message, but avoid logging it in the *Messages* buffer."
6644 (let ((message-log-max nil))
6645 (apply 'message args)))
6647 ;;;###autoload
6648 (defun org-cycle (&optional arg)
6649 "TAB-action and visibility cycling for Org-mode.
6651 This is the command invoked in Org-mode by the TAB key. Its main purpose
6652 is outline visibility cycling, but it also invokes other actions
6653 in special contexts.
6655 - When this function is called with a prefix argument, rotate the entire
6656 buffer through 3 states (global cycling)
6657 1. OVERVIEW: Show only top-level headlines.
6658 2. CONTENTS: Show all headlines of all levels, but no body text.
6659 3. SHOW ALL: Show everything.
6660 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6661 determined by the variable `org-startup-folded', and by any VISIBILITY
6662 properties in the buffer.
6663 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6664 including any drawers.
6666 - When inside a table, re-align the table and move to the next field.
6668 - When point is at the beginning of a headline, rotate the subtree started
6669 by this line through 3 different states (local cycling)
6670 1. FOLDED: Only the main headline is shown.
6671 2. CHILDREN: The main headline and the direct children are shown.
6672 From this state, you can move to one of the children
6673 and zoom in further.
6674 3. SUBTREE: Show the entire subtree, including body text.
6675 If there is no subtree, switch directly from CHILDREN to FOLDED.
6677 - When point is at the beginning of an empty headline and the variable
6678 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6679 of the headline by demoting and promoting it to likely levels. This
6680 speeds up creation document structure by pressing TAB once or several
6681 times right after creating a new headline.
6683 - When there is a numeric prefix, go up to a heading with level ARG, do
6684 a `show-subtree' and return to the previous cursor position. If ARG
6685 is negative, go up that many levels.
6687 - When point is not at the beginning of a headline, execute the global
6688 binding for TAB, which is re-indenting the line. See the option
6689 `org-cycle-emulate-tab' for details.
6691 - Special case: if point is at the beginning of the buffer and there is
6692 no headline in line 1, this function will act as if called with prefix arg
6693 (C-u TAB, same as S-TAB) also when called without prefix arg.
6694 But only if also the variable `org-cycle-global-at-bob' is t."
6695 (interactive "P")
6696 (org-load-modules-maybe)
6697 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6698 (and org-cycle-level-after-item/entry-creation
6699 (or (org-cycle-level)
6700 (org-cycle-item-indentation))))
6701 (let* ((limit-level
6702 (or org-cycle-max-level
6703 (and (boundp 'org-inlinetask-min-level)
6704 org-inlinetask-min-level
6705 (1- org-inlinetask-min-level))))
6706 (nstars (and limit-level
6707 (if org-odd-levels-only
6708 (and limit-level (1- (* limit-level 2)))
6709 limit-level)))
6710 (org-outline-regexp
6711 (if (not (derived-mode-p 'org-mode))
6712 outline-regexp
6713 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6714 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6715 (not (looking-at org-outline-regexp))))
6716 (org-cycle-hook
6717 (if bob-special
6718 (delq 'org-optimize-window-after-visibility-change
6719 (copy-sequence org-cycle-hook))
6720 org-cycle-hook))
6721 (pos (point)))
6723 (if (or bob-special (equal arg '(4)))
6724 ;; special case: use global cycling
6725 (setq arg t))
6727 (cond
6729 ((equal arg '(16))
6730 (setq last-command 'dummy)
6731 (org-set-startup-visibility)
6732 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6734 ((equal arg '(64))
6735 (show-all)
6736 (org-unlogged-message "Entire buffer visible, including drawers"))
6738 ;; Try cdlatex TAB completion
6739 ((org-try-cdlatex-tab))
6741 ;; Table: enter it or move to the next field.
6742 ((org-at-table-p 'any)
6743 (if (org-at-table.el-p)
6744 (message "Use C-c ' to edit table.el tables")
6745 (if arg (org-table-edit-field t)
6746 (org-table-justify-field-maybe)
6747 (call-interactively 'org-table-next-field))))
6749 ((run-hook-with-args-until-success
6750 'org-tab-after-check-for-table-hook))
6752 ;; Global cycling: delegate to `org-cycle-internal-global'.
6753 ((eq arg t) (org-cycle-internal-global))
6755 ;; Drawers: delegate to `org-flag-drawer'.
6756 ((save-excursion
6757 (beginning-of-line 1)
6758 (looking-at org-drawer-regexp))
6759 (org-flag-drawer ; toggle block visibility
6760 (not (get-char-property (match-end 0) 'invisible))))
6762 ;; Show-subtree, ARG levels up from here.
6763 ((integerp arg)
6764 (save-excursion
6765 (org-back-to-heading)
6766 (outline-up-heading (if (< arg 0) (- arg)
6767 (- (funcall outline-level) arg)))
6768 (org-show-subtree)))
6770 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6771 ((and (featurep 'org-inlinetask)
6772 (org-inlinetask-at-task-p)
6773 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6774 (org-inlinetask-toggle-visibility))
6776 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6777 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6778 (save-excursion (move-beginning-of-line 1)
6779 (looking-at org-outline-regexp)))
6780 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6781 (org-cycle-internal-local))
6783 ;; From there: TAB emulation and template completion.
6784 (buffer-read-only (org-back-to-heading))
6786 ((run-hook-with-args-until-success
6787 'org-tab-after-check-for-cycling-hook))
6789 ((org-try-structure-completion))
6791 ((run-hook-with-args-until-success
6792 'org-tab-before-tab-emulation-hook))
6794 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6795 (or (not (bolp))
6796 (not (looking-at org-outline-regexp))))
6797 (call-interactively (global-key-binding "\t")))
6799 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6800 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6801 (or (and (eq org-cycle-emulate-tab 'white)
6802 (= (match-end 0) (point-at-eol)))
6803 (and (eq org-cycle-emulate-tab 'whitestart)
6804 (>= (match-end 0) pos))))
6806 (eq org-cycle-emulate-tab t))
6807 (call-interactively (global-key-binding "\t")))
6809 (t (save-excursion
6810 (org-back-to-heading)
6811 (org-cycle)))))))
6813 (defun org-cycle-internal-global ()
6814 "Do the global cycling action."
6815 ;; Hack to avoid display of messages for .org attachments in Gnus
6816 (let ((ga (string-match "\\*fontification" (buffer-name))))
6817 (cond
6818 ((and (eq last-command this-command)
6819 (eq org-cycle-global-status 'overview))
6820 ;; We just created the overview - now do table of contents
6821 ;; This can be slow in very large buffers, so indicate action
6822 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6823 (unless ga (org-unlogged-message "CONTENTS..."))
6824 (org-content)
6825 (unless ga (org-unlogged-message "CONTENTS...done"))
6826 (setq org-cycle-global-status 'contents)
6827 (run-hook-with-args 'org-cycle-hook 'contents))
6829 ((and (eq last-command this-command)
6830 (eq org-cycle-global-status 'contents))
6831 ;; We just showed the table of contents - now show everything
6832 (run-hook-with-args 'org-pre-cycle-hook 'all)
6833 (show-all)
6834 (unless ga (org-unlogged-message "SHOW ALL"))
6835 (setq org-cycle-global-status 'all)
6836 (run-hook-with-args 'org-cycle-hook 'all))
6839 ;; Default action: go to overview
6840 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6841 (org-overview)
6842 (unless ga (org-unlogged-message "OVERVIEW"))
6843 (setq org-cycle-global-status 'overview)
6844 (run-hook-with-args 'org-cycle-hook 'overview)))))
6846 (defvar org-called-with-limited-levels nil
6847 "Non-nil when `org-with-limited-levels' is currently active.")
6849 (defun org-cycle-internal-local ()
6850 "Do the local cycling action."
6851 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6852 ;; First, determine end of headline (EOH), end of subtree or item
6853 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6854 (save-excursion
6855 (if (org-at-item-p)
6856 (progn
6857 (beginning-of-line)
6858 (setq struct (org-list-struct))
6859 (setq eoh (point-at-eol))
6860 (setq eos (org-list-get-item-end-before-blank (point) struct))
6861 (setq has-children (org-list-has-child-p (point) struct)))
6862 (org-back-to-heading)
6863 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6864 (setq eos (save-excursion (org-end-of-subtree t t)
6865 (when (bolp) (backward-char)) (point)))
6866 (setq has-children
6867 (or (save-excursion
6868 (let ((level (funcall outline-level)))
6869 (outline-next-heading)
6870 (and (org-at-heading-p t)
6871 (> (funcall outline-level) level))))
6872 (save-excursion
6873 (org-list-search-forward (org-item-beginning-re) eos t)))))
6874 ;; Determine end invisible part of buffer (EOL)
6875 (beginning-of-line 2)
6876 ;; XEmacs doesn't have `next-single-char-property-change'
6877 (if (featurep 'xemacs)
6878 (while (and (not (eobp)) ;; this is like `next-line'
6879 (get-char-property (1- (point)) 'invisible))
6880 (beginning-of-line 2))
6881 (while (and (not (eobp)) ;; this is like `next-line'
6882 (get-char-property (1- (point)) 'invisible))
6883 (goto-char (next-single-char-property-change (point) 'invisible))
6884 (and (eolp) (beginning-of-line 2))))
6885 (setq eol (point)))
6886 ;; Find out what to do next and set `this-command'
6887 (cond
6888 ((= eos eoh)
6889 ;; Nothing is hidden behind this heading
6890 (unless (org-before-first-heading-p)
6891 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6892 (org-unlogged-message "EMPTY ENTRY")
6893 (setq org-cycle-subtree-status nil)
6894 (save-excursion
6895 (goto-char eos)
6896 (outline-next-heading)
6897 (if (outline-invisible-p) (org-flag-heading nil))))
6898 ((and (or (>= eol eos)
6899 (not (string-match "\\S-" (buffer-substring eol eos))))
6900 (or has-children
6901 (not (setq children-skipped
6902 org-cycle-skip-children-state-if-no-children))))
6903 ;; Entire subtree is hidden in one line: children view
6904 (unless (org-before-first-heading-p)
6905 (run-hook-with-args 'org-pre-cycle-hook 'children))
6906 (if (org-at-item-p)
6907 (org-list-set-item-visibility (point-at-bol) struct 'children)
6908 (org-show-entry)
6909 (org-with-limited-levels (show-children))
6910 ;; FIXME: This slows down the func way too much.
6911 ;; How keep drawers hidden in subtree anyway?
6912 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6913 ;; (org-cycle-hide-drawers 'subtree))
6915 ;; Fold every list in subtree to top-level items.
6916 (when (eq org-cycle-include-plain-lists 'integrate)
6917 (save-excursion
6918 (org-back-to-heading)
6919 (while (org-list-search-forward (org-item-beginning-re) eos t)
6920 (beginning-of-line 1)
6921 (let* ((struct (org-list-struct))
6922 (prevs (org-list-prevs-alist struct))
6923 (end (org-list-get-bottom-point struct)))
6924 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6925 (org-list-get-all-items (point) struct prevs))
6926 (goto-char (if (< end eos) end eos)))))))
6927 (org-unlogged-message "CHILDREN")
6928 (save-excursion
6929 (goto-char eos)
6930 (outline-next-heading)
6931 (if (outline-invisible-p) (org-flag-heading nil)))
6932 (setq org-cycle-subtree-status 'children)
6933 (unless (org-before-first-heading-p)
6934 (run-hook-with-args 'org-cycle-hook 'children)))
6935 ((or children-skipped
6936 (and (eq last-command this-command)
6937 (eq org-cycle-subtree-status 'children)))
6938 ;; We just showed the children, or no children are there,
6939 ;; now show everything.
6940 (unless (org-before-first-heading-p)
6941 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6942 (outline-flag-region eoh eos nil)
6943 (org-unlogged-message
6944 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6945 (setq org-cycle-subtree-status 'subtree)
6946 (unless (org-before-first-heading-p)
6947 (run-hook-with-args 'org-cycle-hook 'subtree)))
6949 ;; Default action: hide the subtree.
6950 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6951 (outline-flag-region eoh eos t)
6952 (org-unlogged-message "FOLDED")
6953 (setq org-cycle-subtree-status 'folded)
6954 (unless (org-before-first-heading-p)
6955 (run-hook-with-args 'org-cycle-hook 'folded))))))
6957 ;;;###autoload
6958 (defun org-global-cycle (&optional arg)
6959 "Cycle the global visibility. For details see `org-cycle'.
6960 With \\[universal-argument] prefix arg, switch to startup visibility.
6961 With a numeric prefix, show all headlines up to that level."
6962 (interactive "P")
6963 (let ((org-cycle-include-plain-lists
6964 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6965 (cond
6966 ((integerp arg)
6967 (show-all)
6968 (hide-sublevels arg)
6969 (setq org-cycle-global-status 'contents))
6970 ((equal arg '(4))
6971 (org-set-startup-visibility)
6972 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6974 (org-cycle '(4))))))
6976 (defun org-set-startup-visibility ()
6977 "Set the visibility required by startup options and properties."
6978 (cond
6979 ((eq org-startup-folded t)
6980 (org-overview))
6981 ((eq org-startup-folded 'content)
6982 (org-content))
6983 ((or (eq org-startup-folded 'showeverything)
6984 (eq org-startup-folded nil))
6985 (show-all)))
6986 (unless (eq org-startup-folded 'showeverything)
6987 (if org-hide-block-startup (org-hide-block-all))
6988 (org-set-visibility-according-to-property 'no-cleanup)
6989 (org-cycle-hide-archived-subtrees 'all)
6990 (org-cycle-hide-drawers 'all)
6991 (org-cycle-show-empty-lines t)))
6993 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6994 "Switch subtree visibilities according to :VISIBILITY: property."
6995 (interactive)
6996 (let (org-show-entry-below)
6997 (org-with-wide-buffer
6998 (goto-char (point-min))
6999 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7000 (if (not (org-at-property-p)) (outline-next-heading)
7001 (let ((state (match-string 3)))
7002 (save-excursion
7003 (org-back-to-heading t)
7004 (hide-subtree)
7005 (org-reveal)
7006 (cond
7007 ((equal state "folded")
7008 (hide-subtree))
7009 ((equal state "children")
7010 (org-show-hidden-entry)
7011 (show-children))
7012 ((equal state "content")
7013 (save-excursion
7014 (save-restriction
7015 (org-narrow-to-subtree)
7016 (org-content))))
7017 ((member state '("all" "showall"))
7018 (show-subtree)))))))
7019 (unless no-cleanup
7020 (org-cycle-hide-archived-subtrees 'all)
7021 (org-cycle-hide-drawers 'all)
7022 (org-cycle-show-empty-lines 'all)))))
7024 ;; This function uses outline-regexp instead of the more fundamental
7025 ;; org-outline-regexp so that org-cycle-global works outside of Org
7026 ;; buffers, where outline-regexp is needed.
7027 (defun org-overview ()
7028 "Switch to overview mode, showing only top-level headlines.
7029 This shows all headlines with a level equal or greater than the level
7030 of the first headline in the buffer. This is important, because if the
7031 first headline is not level one, then (hide-sublevels 1) gives confusing
7032 results."
7033 (interactive)
7034 (save-excursion
7035 (let ((level
7036 (save-excursion
7037 (goto-char (point-min))
7038 (if (re-search-forward (concat "^" outline-regexp) nil t)
7039 (progn
7040 (goto-char (match-beginning 0))
7041 (funcall outline-level))))))
7042 (and level (hide-sublevels level)))))
7044 (defun org-content (&optional arg)
7045 "Show all headlines in the buffer, like a table of contents.
7046 With numerical argument N, show content up to level N."
7047 (interactive "P")
7048 (org-overview)
7049 (save-excursion
7050 ;; Visit all headings and show their offspring
7051 (and (integerp arg) (org-overview))
7052 (goto-char (point-max))
7053 (catch 'exit
7054 (while (and (progn (condition-case nil
7055 (outline-previous-visible-heading 1)
7056 (error (goto-char (point-min))))
7058 (looking-at org-outline-regexp))
7059 (if (integerp arg)
7060 (show-children (1- arg))
7061 (show-branches))
7062 (if (bobp) (throw 'exit nil))))))
7064 (defun org-optimize-window-after-visibility-change (state)
7065 "Adjust the window after a change in outline visibility.
7066 This function is the default value of the hook `org-cycle-hook'."
7067 (when (get-buffer-window (current-buffer))
7068 (cond
7069 ((eq state 'content) nil)
7070 ((eq state 'all) nil)
7071 ((eq state 'folded) nil)
7072 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7073 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7075 (defun org-remove-empty-overlays-at (pos)
7076 "Remove outline overlays that do not contain non-white stuff."
7077 (mapc
7078 (lambda (o)
7079 (and (eq 'outline (overlay-get o 'invisible))
7080 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7081 (overlay-end o))))
7082 (delete-overlay o)))
7083 (overlays-at pos)))
7085 (defun org-clean-visibility-after-subtree-move ()
7086 "Fix visibility issues after moving a subtree."
7087 ;; First, find a reasonable region to look at:
7088 ;; Start two siblings above, end three below
7089 (let* ((beg (save-excursion
7090 (and (org-get-last-sibling)
7091 (org-get-last-sibling))
7092 (point)))
7093 (end (save-excursion
7094 (and (org-get-next-sibling)
7095 (org-get-next-sibling)
7096 (org-get-next-sibling))
7097 (if (org-at-heading-p)
7098 (point-at-eol)
7099 (point))))
7100 (level (looking-at "\\*+"))
7101 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7102 (save-excursion
7103 (save-restriction
7104 (narrow-to-region beg end)
7105 (when re
7106 ;; Properly fold already folded siblings
7107 (goto-char (point-min))
7108 (while (re-search-forward re nil t)
7109 (if (and (not (outline-invisible-p))
7110 (save-excursion
7111 (goto-char (point-at-eol)) (outline-invisible-p)))
7112 (hide-entry))))
7113 (org-cycle-show-empty-lines 'overview)
7114 (org-cycle-hide-drawers 'overview)))))
7116 (defun org-cycle-show-empty-lines (state)
7117 "Show empty lines above all visible headlines.
7118 The region to be covered depends on STATE when called through
7119 `org-cycle-hook'. Lisp program can use t for STATE to get the
7120 entire buffer covered. Note that an empty line is only shown if there
7121 are at least `org-cycle-separator-lines' empty lines before the headline."
7122 (when (/= org-cycle-separator-lines 0)
7123 (save-excursion
7124 (let* ((n (abs org-cycle-separator-lines))
7125 (re (cond
7126 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7127 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7128 (t (let ((ns (number-to-string (- n 2))))
7129 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7130 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7131 beg end)
7132 (cond
7133 ((memq state '(overview contents t))
7134 (setq beg (point-min) end (point-max)))
7135 ((memq state '(children folded))
7136 (setq beg (point)
7137 end (progn (org-end-of-subtree t t)
7138 (line-beginning-position 2)))))
7139 (when beg
7140 (goto-char beg)
7141 (while (re-search-forward re end t)
7142 (unless (get-char-property (match-end 1) 'invisible)
7143 (let ((e (match-end 1))
7144 (b (if (>= org-cycle-separator-lines 0)
7145 (match-beginning 1)
7146 (save-excursion
7147 (goto-char (match-beginning 0))
7148 (skip-chars-backward " \t\n")
7149 (line-end-position)))))
7150 (outline-flag-region b e nil))))))))
7151 ;; Never hide empty lines at the end of the file.
7152 (save-excursion
7153 (goto-char (point-max))
7154 (outline-previous-heading)
7155 (outline-end-of-heading)
7156 (if (and (looking-at "[ \t\n]+")
7157 (= (match-end 0) (point-max)))
7158 (outline-flag-region (point) (match-end 0) nil))))
7160 (defun org-show-empty-lines-in-parent ()
7161 "Move to the parent and re-show empty lines before visible headlines."
7162 (save-excursion
7163 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7164 (org-cycle-show-empty-lines context))))
7166 (defun org-files-list ()
7167 "Return `org-agenda-files' list, plus all open org-mode files.
7168 This is useful for operations that need to scan all of a user's
7169 open and agenda-wise Org files."
7170 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7171 (dolist (buf (buffer-list))
7172 (with-current-buffer buf
7173 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7174 (let ((file (expand-file-name (buffer-file-name))))
7175 (unless (member file files)
7176 (push file files))))))
7177 files))
7179 (defsubst org-entry-beginning-position ()
7180 "Return the beginning position of the current entry."
7181 (save-excursion (outline-back-to-heading t) (point)))
7183 (defsubst org-entry-end-position ()
7184 "Return the end position of the current entry."
7185 (save-excursion (outline-next-heading) (point)))
7187 (defun org-cycle-hide-drawers (state &optional exceptions)
7188 "Re-hide all drawers after a visibility state change.
7189 When non-nil, optional argument EXCEPTIONS is a list of strings
7190 specifying which drawers should not be hidden."
7191 (when (and (derived-mode-p 'org-mode)
7192 (not (memq state '(overview folded contents))))
7193 (save-excursion
7194 (let* ((globalp (memq state '(contents all)))
7195 (beg (if globalp (point-min) (point)))
7196 (end (if globalp (point-max)
7197 (if (eq state 'children)
7198 (save-excursion (outline-next-heading) (point))
7199 (org-end-of-subtree t)))))
7200 (goto-char beg)
7201 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7202 (unless (member-ignore-case (match-string 1) exceptions)
7203 (let ((drawer (org-element-at-point)))
7204 (when (memq (org-element-type drawer) '(drawer property-drawer))
7205 (org-flag-drawer t drawer)
7206 ;; Make sure to skip drawer entirely or we might flag
7207 ;; it another time when matching its ending line with
7208 ;; `org-drawer-regexp'.
7209 (goto-char (org-element-property :end drawer))))))))))
7211 (defun org-flag-drawer (flag &optional element)
7212 "When FLAG is non-nil, hide the drawer we are at.
7213 Otherwise make it visible. When optional argument ELEMENT is
7214 a parsed drawer, as returned by `org-element-at-point', hide or
7215 show that drawer instead."
7216 (when (save-excursion
7217 (beginning-of-line)
7218 (org-looking-at-p org-drawer-regexp))
7219 (let ((drawer (or element (org-element-at-point))))
7220 (when (memq (org-element-type drawer) '(drawer property-drawer))
7221 (let ((post (org-element-property :post-affiliated drawer)))
7222 (save-excursion
7223 (outline-flag-region
7224 (progn (goto-char post) (line-end-position))
7225 (progn (goto-char (org-element-property :end drawer))
7226 (skip-chars-backward " \r\t\n")
7227 (line-end-position))
7228 flag))
7229 ;; When the drawer is hidden away, make sure point lies in
7230 ;; a visible part of the buffer.
7231 (when (and flag (> (line-beginning-position) post))
7232 (goto-char post)))))))
7234 (defun org-subtree-end-visible-p ()
7235 "Is the end of the current subtree visible?"
7236 (pos-visible-in-window-p
7237 (save-excursion (org-end-of-subtree t) (point))))
7239 (defun org-first-headline-recenter ()
7240 "Move cursor to the first headline and recenter the headline."
7241 (goto-char (point-min))
7242 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7243 (set-window-start (selected-window) (point-at-bol))))
7245 ;;; Saving and restoring visibility
7247 (defun org-outline-overlay-data (&optional use-markers)
7248 "Return a list of the locations of all outline overlays.
7249 These are overlays with the `invisible' property value `outline'.
7250 The return value is a list of cons cells, with start and stop
7251 positions for each overlay.
7252 If USE-MARKERS is set, return the positions as markers."
7253 (let (beg end)
7254 (save-excursion
7255 (save-restriction
7256 (widen)
7257 (delq nil
7258 (mapcar (lambda (o)
7259 (when (eq (overlay-get o 'invisible) 'outline)
7260 (setq beg (overlay-start o)
7261 end (overlay-end o))
7262 (and beg end (> end beg)
7263 (if use-markers
7264 (cons (copy-marker beg)
7265 (copy-marker end t))
7266 (cons beg end)))))
7267 (overlays-in (point-min) (point-max))))))))
7269 (defun org-set-outline-overlay-data (data)
7270 "Create visibility overlays for all positions in DATA.
7271 DATA should have been made by `org-outline-overlay-data'."
7272 (let (o)
7273 (save-excursion
7274 (save-restriction
7275 (widen)
7276 (show-all)
7277 (mapc (lambda (c)
7278 (outline-flag-region (car c) (cdr c) t))
7279 data)))))
7281 ;;; Folding of blocks
7283 (defvar org-hide-block-overlays nil
7284 "Overlays hiding blocks.")
7285 (make-variable-buffer-local 'org-hide-block-overlays)
7287 (defun org-block-map (function &optional start end)
7288 "Call FUNCTION at the head of all source blocks in the current buffer.
7289 Optional arguments START and END can be used to limit the range."
7290 (let ((start (or start (point-min)))
7291 (end (or end (point-max))))
7292 (save-excursion
7293 (goto-char start)
7294 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7295 (save-excursion
7296 (save-match-data
7297 (goto-char (match-beginning 0))
7298 (funcall function)))))))
7300 (defun org-hide-block-toggle-all ()
7301 "Toggle the visibility of all blocks in the current buffer."
7302 (org-block-map 'org-hide-block-toggle))
7304 (defun org-hide-block-all ()
7305 "Fold all blocks in the current buffer."
7306 (interactive)
7307 (org-show-block-all)
7308 (org-block-map 'org-hide-block-toggle-maybe))
7310 (defun org-show-block-all ()
7311 "Unfold all blocks in the current buffer."
7312 (interactive)
7313 (mapc 'delete-overlay org-hide-block-overlays)
7314 (setq org-hide-block-overlays nil))
7316 (defun org-hide-block-toggle-maybe ()
7317 "Toggle visibility of block at point.
7318 Unlike to `org-hide-block-toggle', this function does not throw
7319 an error. Return a non-nil value when toggling is successful."
7320 (interactive)
7321 (ignore-errors (org-hide-block-toggle)))
7323 (defun org-hide-block-toggle (&optional force)
7324 "Toggle the visibility of the current block.
7325 When optional argument FORCE is `off', make block visible. If it
7326 is non-nil, hide it unconditionally. Throw an error when not at
7327 a block. Return a non-nil value when toggling is successful."
7328 (interactive)
7329 (let ((element (org-element-at-point)))
7330 (unless (memq (org-element-type element)
7331 '(center-block comment-block dynamic-block example-block
7332 export-block quote-block special-block
7333 src-block verse-block))
7334 (user-error "Not at a block"))
7335 (let* ((start (save-excursion
7336 (goto-char (org-element-property :post-affiliated element))
7337 (line-end-position)))
7338 (end (save-excursion
7339 (goto-char (org-element-property :end element))
7340 (skip-chars-backward " \r\t\n")
7341 (line-end-position)))
7342 (overlays (overlays-at start)))
7343 (cond
7344 ;; Do nothing when not before or at the block opening line or
7345 ;; at the block closing line.
7346 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7347 ((and (not (eq force 'off))
7348 (not (memq t (mapcar
7349 (lambda (o)
7350 (eq (overlay-get o 'invisible) 'org-hide-block))
7351 overlays))))
7352 (let ((ov (make-overlay start end)))
7353 (overlay-put ov 'invisible 'org-hide-block)
7354 ;; Make the block accessible to `isearch'.
7355 (overlay-put
7356 ov 'isearch-open-invisible
7357 (lambda (ov)
7358 (when (memq ov org-hide-block-overlays)
7359 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7360 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7361 (delete-overlay ov))))
7362 (push ov org-hide-block-overlays)
7363 ;; When the block is hidden away, make sure point is left in
7364 ;; a visible part of the buffer.
7365 (when (> (line-beginning-position) start)
7366 (goto-char start)
7367 (beginning-of-line))
7368 ;; Signal successful toggling.
7370 ((or (not force) (eq force 'off))
7371 (dolist (ov overlays t)
7372 (when (memq ov org-hide-block-overlays)
7373 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7374 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7375 (delete-overlay ov))))))))
7377 ;; org-tab-after-check-for-cycling-hook
7378 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7379 ;; Remove overlays when changing major mode
7380 (add-hook 'org-mode-hook
7381 (lambda () (org-add-hook 'change-major-mode-hook
7382 'org-show-block-all 'append 'local)))
7384 ;;; Org-goto
7386 (defvar org-goto-window-configuration nil)
7387 (defvar org-goto-marker nil)
7388 (defvar org-goto-map)
7389 (defun org-goto-map ()
7390 "Set the keymap `org-goto'."
7391 (setq org-goto-map
7392 (let ((map (make-sparse-keymap)))
7393 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7394 mouse-drag-region universal-argument org-occur))
7395 cmd)
7396 (while (setq cmd (pop cmds))
7397 (substitute-key-definition cmd cmd map global-map)))
7398 (suppress-keymap map)
7399 (org-defkey map "\C-m" 'org-goto-ret)
7400 (org-defkey map [(return)] 'org-goto-ret)
7401 (org-defkey map [(left)] 'org-goto-left)
7402 (org-defkey map [(right)] 'org-goto-right)
7403 (org-defkey map [(control ?g)] 'org-goto-quit)
7404 (org-defkey map "\C-i" 'org-cycle)
7405 (org-defkey map [(tab)] 'org-cycle)
7406 (org-defkey map [(down)] 'outline-next-visible-heading)
7407 (org-defkey map [(up)] 'outline-previous-visible-heading)
7408 (if org-goto-auto-isearch
7409 (if (fboundp 'define-key-after)
7410 (define-key-after map [t] 'org-goto-local-auto-isearch)
7411 nil)
7412 (org-defkey map "q" 'org-goto-quit)
7413 (org-defkey map "n" 'outline-next-visible-heading)
7414 (org-defkey map "p" 'outline-previous-visible-heading)
7415 (org-defkey map "f" 'outline-forward-same-level)
7416 (org-defkey map "b" 'outline-backward-same-level)
7417 (org-defkey map "u" 'outline-up-heading))
7418 (org-defkey map "/" 'org-occur)
7419 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7420 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7421 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7422 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7423 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7424 map)))
7426 (defconst org-goto-help
7427 "Browse buffer copy, to find location or copy text.%s
7428 RET=jump to location C-g=quit and return to previous location
7429 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7431 (defvar org-goto-start-pos) ; dynamically scoped parameter
7433 (defun org-goto (&optional alternative-interface)
7434 "Look up a different location in the current file, keeping current visibility.
7436 When you want look-up or go to a different location in a
7437 document, the fastest way is often to fold the entire buffer and
7438 then dive into the tree. This method has the disadvantage, that
7439 the previous location will be folded, which may not be what you
7440 want.
7442 This command works around this by showing a copy of the current
7443 buffer in an indirect buffer, in overview mode. You can dive
7444 into the tree in that copy, use org-occur and incremental search
7445 to find a location. When pressing RET or `Q', the command
7446 returns to the original buffer in which the visibility is still
7447 unchanged. After RET it will also jump to the location selected
7448 in the indirect buffer and expose the headline hierarchy above.
7450 With a prefix argument, use the alternative interface: e.g. if
7451 `org-goto-interface' is 'outline use 'outline-path-completion."
7452 (interactive "P")
7453 (org-goto-map)
7454 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7455 (org-refile-use-outline-path t)
7456 (org-refile-target-verify-function nil)
7457 (interface
7458 (if (not alternative-interface)
7459 org-goto-interface
7460 (if (eq org-goto-interface 'outline)
7461 'outline-path-completion
7462 'outline)))
7463 (org-goto-start-pos (point))
7464 (selected-point
7465 (if (eq interface 'outline)
7466 (car (org-get-location (current-buffer) org-goto-help))
7467 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7468 (org-refile-check-position pa)
7469 (nth 3 pa)))))
7470 (if selected-point
7471 (progn
7472 (org-mark-ring-push org-goto-start-pos)
7473 (goto-char selected-point)
7474 (if (or (outline-invisible-p) (org-invisible-p2))
7475 (org-show-context 'org-goto)))
7476 (message "Quit"))))
7478 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7479 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7480 (defvar org-goto-local-auto-isearch-map) ; defined below
7482 (defun org-get-location (buf help)
7483 "Let the user select a location in the Org-mode buffer BUF.
7484 This function uses a recursive edit. It returns the selected position
7485 or nil."
7486 (org-no-popups
7487 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7488 (isearch-hide-immediately nil)
7489 (isearch-search-fun-function
7490 (lambda () 'org-goto-local-search-headings))
7491 (org-goto-selected-point org-goto-exit-command))
7492 (save-excursion
7493 (save-window-excursion
7494 (delete-other-windows)
7495 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7496 (org-pop-to-buffer-same-window
7497 (condition-case nil
7498 (make-indirect-buffer (current-buffer) "*org-goto*")
7499 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7500 (with-output-to-temp-buffer "*Org Help*"
7501 (princ (format help (if org-goto-auto-isearch
7502 " Just type for auto-isearch."
7503 " n/p/f/b/u to navigate, q to quit."))))
7504 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7505 (setq buffer-read-only nil)
7506 (let ((org-startup-truncated t)
7507 (org-startup-folded nil)
7508 (org-startup-align-all-tables nil))
7509 (org-mode)
7510 (org-overview))
7511 (setq buffer-read-only t)
7512 (if (and (boundp 'org-goto-start-pos)
7513 (integer-or-marker-p org-goto-start-pos))
7514 (progn (goto-char org-goto-start-pos)
7515 (when (outline-invisible-p)
7516 (org-show-set-visibility 'lineage)))
7517 (goto-char (point-min)))
7518 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7519 (message "Select location and press RET")
7520 (use-local-map org-goto-map)
7521 (recursive-edit)))
7522 (kill-buffer "*org-goto*")
7523 (cons org-goto-selected-point org-goto-exit-command))))
7525 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7526 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7527 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7528 (if (fboundp 'isearch-other-control-char)
7529 (progn
7530 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7531 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7532 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7533 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7534 (define-key org-goto-local-auto-isearch-map [return] nil))
7536 (defun org-goto-local-search-headings (string bound noerror)
7537 "Search and make sure that any matches are in headlines."
7538 (catch 'return
7539 (while (if isearch-forward
7540 (search-forward string bound noerror)
7541 (search-backward string bound noerror))
7542 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7543 (and (member :headline context)
7544 (not (member :tags context))))
7545 (throw 'return (point))))))
7547 (defun org-goto-local-auto-isearch ()
7548 "Start isearch."
7549 (interactive)
7550 (goto-char (point-min))
7551 (let ((keys (this-command-keys)))
7552 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7553 (isearch-mode t)
7554 (isearch-process-search-char (string-to-char keys)))))
7556 (defun org-goto-ret (&optional arg)
7557 "Finish `org-goto' by going to the new location."
7558 (interactive "P")
7559 (setq org-goto-selected-point (point)
7560 org-goto-exit-command 'return)
7561 (throw 'exit nil))
7563 (defun org-goto-left ()
7564 "Finish `org-goto' by going to the new location."
7565 (interactive)
7566 (if (org-at-heading-p)
7567 (progn
7568 (beginning-of-line 1)
7569 (setq org-goto-selected-point (point)
7570 org-goto-exit-command 'left)
7571 (throw 'exit nil))
7572 (user-error "Not on a heading")))
7574 (defun org-goto-right ()
7575 "Finish `org-goto' by going to the new location."
7576 (interactive)
7577 (if (org-at-heading-p)
7578 (progn
7579 (setq org-goto-selected-point (point)
7580 org-goto-exit-command 'right)
7581 (throw 'exit nil))
7582 (user-error "Not on a heading")))
7584 (defun org-goto-quit ()
7585 "Finish `org-goto' without cursor motion."
7586 (interactive)
7587 (setq org-goto-selected-point nil)
7588 (setq org-goto-exit-command 'quit)
7589 (throw 'exit nil))
7591 ;;; Indirect buffer display of subtrees
7593 (defvar org-indirect-dedicated-frame nil
7594 "This is the frame being used for indirect tree display.")
7595 (defvar org-last-indirect-buffer nil)
7597 (defun org-tree-to-indirect-buffer (&optional arg)
7598 "Create indirect buffer and narrow it to current subtree.
7599 With a numerical prefix ARG, go up to this level and then take that tree.
7600 If ARG is negative, go up that many levels.
7602 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7603 indirect buffer previously made with this command, to avoid proliferation of
7604 indirect buffers. However, when you call the command with a \
7605 \\[universal-argument] prefix, or
7606 when `org-indirect-buffer-display' is `new-frame', the last buffer
7607 is kept so that you can work with several indirect buffers at the same time.
7608 If `org-indirect-buffer-display' is `dedicated-frame', the \
7609 \\[universal-argument] prefix also
7610 requests that a new frame be made for the new buffer, so that the dedicated
7611 frame is not changed."
7612 (interactive "P")
7613 (let ((cbuf (current-buffer))
7614 (cwin (selected-window))
7615 (pos (point))
7616 beg end level heading ibuf)
7617 (save-excursion
7618 (org-back-to-heading t)
7619 (when (numberp arg)
7620 (setq level (org-outline-level))
7621 (if (< arg 0) (setq arg (+ level arg)))
7622 (while (> (setq level (org-outline-level)) arg)
7623 (org-up-heading-safe)))
7624 (setq beg (point)
7625 heading (org-get-heading))
7626 (org-end-of-subtree t t)
7627 (if (org-at-heading-p) (backward-char 1))
7628 (setq end (point)))
7629 (if (and (buffer-live-p org-last-indirect-buffer)
7630 (not (eq org-indirect-buffer-display 'new-frame))
7631 (not arg))
7632 (kill-buffer org-last-indirect-buffer))
7633 (setq ibuf (org-get-indirect-buffer cbuf heading)
7634 org-last-indirect-buffer ibuf)
7635 (cond
7636 ((or (eq org-indirect-buffer-display 'new-frame)
7637 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7638 (select-frame (make-frame))
7639 (delete-other-windows)
7640 (org-pop-to-buffer-same-window ibuf)
7641 (org-set-frame-title heading))
7642 ((eq org-indirect-buffer-display 'dedicated-frame)
7643 (raise-frame
7644 (select-frame (or (and org-indirect-dedicated-frame
7645 (frame-live-p org-indirect-dedicated-frame)
7646 org-indirect-dedicated-frame)
7647 (setq org-indirect-dedicated-frame (make-frame)))))
7648 (delete-other-windows)
7649 (org-pop-to-buffer-same-window ibuf)
7650 (org-set-frame-title (concat "Indirect: " heading)))
7651 ((eq org-indirect-buffer-display 'current-window)
7652 (org-pop-to-buffer-same-window ibuf))
7653 ((eq org-indirect-buffer-display 'other-window)
7654 (pop-to-buffer ibuf))
7655 (t (error "Invalid value")))
7656 (if (featurep 'xemacs)
7657 (save-excursion (org-mode) (turn-on-font-lock)))
7658 (narrow-to-region beg end)
7659 (show-all)
7660 (goto-char pos)
7661 (run-hook-with-args 'org-cycle-hook 'all)
7662 (and (window-live-p cwin) (select-window cwin))))
7664 (defun org-get-indirect-buffer (&optional buffer heading)
7665 (setq buffer (or buffer (current-buffer)))
7666 (let ((n 1) (base (buffer-name buffer)) bname)
7667 (while (buffer-live-p
7668 (get-buffer
7669 (setq bname
7670 (concat base "-"
7671 (if heading (concat heading "-" (number-to-string n))
7672 (number-to-string n))))))
7673 (setq n (1+ n)))
7674 (condition-case nil
7675 (make-indirect-buffer buffer bname 'clone)
7676 (error (make-indirect-buffer buffer bname)))))
7678 (defun org-set-frame-title (title)
7679 "Set the title of the current frame to the string TITLE."
7680 ;; FIXME: how to name a single frame in XEmacs???
7681 (unless (featurep 'xemacs)
7682 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7684 ;;;; Structure editing
7686 ;;; Inserting headlines
7688 (defun org-previous-line-empty-p (&optional next)
7689 "Is the previous line a blank line?
7690 When NEXT is non-nil, check the next line instead."
7691 (save-excursion
7692 (and (not (bobp))
7693 (or (beginning-of-line (if next 2 0)) t)
7694 (save-match-data
7695 (looking-at "[ \t]*$")))))
7697 (defun org-insert-heading (&optional arg invisible-ok top-level)
7698 "Insert a new heading or an item with the same depth at point.
7700 If point is at the beginning of a heading or a list item, insert
7701 a new heading or a new item above the current one. If point is
7702 at the beginning of a normal line, turn the line into a heading.
7704 If point is in the middle of a headline or a list item, split the
7705 headline or the item and create a new headline/item with the text
7706 in the current line after point \(see `org-M-RET-may-split-line'
7707 on how to modify this behavior).
7709 With one universal prefix argument, set the user option
7710 `org-insert-heading-respect-content' to t for the duration of
7711 the command. This modifies the behavior described above in this
7712 ways: on list items and at the beginning of normal lines, force
7713 the insertion of a heading after the current subtree.
7715 With two universal prefix arguments, insert the heading at the
7716 end of the grandparent subtree. For example, if point is within
7717 a 2nd-level heading, then it will insert a 2nd-level heading at
7718 the end of the 1st-level parent heading.
7720 If point is at the beginning of a headline, insert a sibling
7721 before the current headline. If point is not at the beginning,
7722 split the line and create a new headline with the text in the
7723 current line after point \(see `org-M-RET-may-split-line' on how
7724 to modify this behavior).
7726 If point is at the beginning of a normal line, turn this line
7727 into a heading.
7729 When INVISIBLE-OK is set, stop at invisible headlines when going
7730 back. This is important for non-interactive uses of the
7731 command.
7733 When optional argument TOP-LEVEL is non-nil, insert a level 1
7734 heading, unconditionally."
7735 (interactive "P")
7736 (if (org-called-interactively-p 'any) (org-reveal))
7737 (let ((itemp (and (not top-level) (org-in-item-p)))
7738 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7739 (respect-content (or org-insert-heading-respect-content
7740 (equal arg '(4))))
7741 (initial-content ""))
7743 (cond
7745 ((or (= (buffer-size) 0)
7746 (and (not (save-excursion
7747 (and (ignore-errors (org-back-to-heading invisible-ok))
7748 (org-at-heading-p))))
7749 (or arg (not itemp))))
7750 ;; At beginning of buffer or so high up that only a heading
7751 ;; makes sense.
7752 (cond ((and (bolp) (not respect-content)) (insert "* "))
7753 ((not respect-content)
7754 (unless may-split (end-of-line))
7755 (insert "\n* "))
7756 ((re-search-forward org-outline-regexp-bol nil t)
7757 (beginning-of-line)
7758 (insert "* \n")
7759 (backward-char))
7760 (t (goto-char (point-max))
7761 (insert "\n* ")))
7762 (run-hooks 'org-insert-heading-hook))
7764 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7767 ;; Maybe move at the end of the subtree
7768 (when (equal arg '(16))
7769 (org-up-heading-safe)
7770 (org-end-of-subtree t))
7771 ;; Insert a heading
7772 (save-restriction
7773 (widen)
7774 (let* ((level nil)
7775 (on-heading (org-at-heading-p))
7776 (empty-line-p (if on-heading
7777 (org-previous-line-empty-p)
7778 ;; We will decide later
7779 nil))
7780 ;; Get a level string to fall back on.
7781 (fix-level
7782 (if (org-before-first-heading-p) "*"
7783 (save-excursion
7784 (org-back-to-heading t)
7785 (if (org-previous-line-empty-p) (setq empty-line-p t))
7786 (looking-at org-outline-regexp)
7787 (make-string (1- (length (match-string 0))) ?*))))
7788 (stars
7789 (save-excursion
7790 (condition-case nil
7791 (if top-level "* "
7792 (org-back-to-heading invisible-ok)
7793 (when (and (not on-heading)
7794 (featurep 'org-inlinetask)
7795 (integerp org-inlinetask-min-level)
7796 (>= (length (match-string 0))
7797 org-inlinetask-min-level))
7798 ;; Find a heading level before the inline
7799 ;; task.
7800 (while (and (setq level (org-up-heading-safe))
7801 (>= level org-inlinetask-min-level)))
7802 (if (org-at-heading-p)
7803 (org-back-to-heading invisible-ok)
7804 (error "This should not happen")))
7805 (unless (and (save-excursion
7806 (save-match-data
7807 (org-backward-heading-same-level
7808 1 invisible-ok))
7809 (= (point) (match-beginning 0)))
7810 (not (org-previous-line-empty-p t)))
7811 (setq empty-line-p (or empty-line-p
7812 (org-previous-line-empty-p))))
7813 (match-string 0))
7814 (error (or fix-level "* ")))))
7815 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7816 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7817 pos hide-previous previous-pos)
7819 ;; If we insert after content, move there and clean up
7820 ;; whitespace.
7821 (when (and respect-content
7822 (not (org-looking-at-p org-outline-regexp-bol)))
7823 (if (not (org-before-first-heading-p))
7824 (org-end-of-subtree nil t)
7825 (re-search-forward org-outline-regexp-bol)
7826 (beginning-of-line 0))
7827 (skip-chars-backward " \r\t\n")
7828 (and (not (looking-back "^\\*+"))
7829 (looking-at "[ \t]+") (replace-match ""))
7830 (unless (eobp) (forward-char 1))
7831 (when (looking-at "^\\*")
7832 (unless (bobp) (backward-char 1))
7833 (insert "\n")))
7835 ;; If we are splitting, grab the text that should be moved
7836 ;; to the new headline.
7837 (when may-split
7838 (if (org-on-heading-p)
7839 ;; This is a heading: split intelligently (keeping
7840 ;; tags).
7841 (let ((pos (point)))
7842 (beginning-of-line)
7843 (unless (looking-at org-complex-heading-regexp)
7844 (error "This should not happen"))
7845 (when (and (match-beginning 4)
7846 (> pos (match-beginning 4))
7847 (< pos (match-end 4)))
7848 (setq initial-content (buffer-substring pos (match-end 4)))
7849 (goto-char pos)
7850 (delete-region (point) (match-end 4))
7851 (if (looking-at "[ \t]*$")
7852 (replace-match "")
7853 (insert (make-string (length initial-content) ?\s)))
7854 (setq initial-content (org-trim initial-content)))
7855 (goto-char pos))
7856 ;; A normal line.
7857 (setq initial-content
7858 (org-trim
7859 (delete-and-extract-region (point) (line-end-position))))))
7861 ;; If we are at the beginning of the line, insert before it.
7862 ;; Otherwise, after it.
7863 (cond
7864 ((and (bolp) (looking-at "[ \t]*$")))
7865 ((bolp) (save-excursion (insert "\n")))
7866 (t (end-of-line)
7867 (insert "\n")))
7869 ;; Insert the new heading
7870 (insert stars)
7871 (just-one-space)
7872 (insert initial-content)
7873 (unless (and blank (org-previous-line-empty-p))
7874 (org-N-empty-lines-before-current (if blank 1 0)))
7875 ;; Adjust visibility, which may be messed up if we removed
7876 ;; blank lines while previous entry was hidden.
7877 (let ((bol (line-beginning-position)))
7878 (dolist (o (overlays-at (1- bol)))
7879 (when (and (eq (overlay-get o 'invisible) 'outline)
7880 (eq (overlay-end o) bol))
7881 (move-overlay o (overlay-start o) (1- bol)))))
7882 (run-hooks 'org-insert-heading-hook)))))))
7884 (defun org-N-empty-lines-before-current (N)
7885 "Make the number of empty lines before current exactly N.
7886 So this will delete or add empty lines."
7887 (save-excursion
7888 (beginning-of-line)
7889 (let ((p (point)))
7890 (skip-chars-backward " \r\t\n")
7891 (unless (bolp) (forward-line))
7892 (delete-region (point) p))
7893 (when (> N 0) (insert (make-string N ?\n)))))
7895 (defun org-get-heading (&optional no-tags no-todo)
7896 "Return the heading of the current entry, without the stars.
7897 When NO-TAGS is non-nil, don't include tags.
7898 When NO-TODO is non-nil, don't include TODO keywords."
7899 (save-excursion
7900 (org-back-to-heading t)
7901 (cond
7902 ((and no-tags no-todo)
7903 (looking-at org-complex-heading-regexp)
7904 (match-string 4))
7905 (no-tags
7906 (looking-at (concat org-outline-regexp
7907 "\\(.*?\\)"
7908 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7909 (match-string 1))
7910 (no-todo
7911 (looking-at org-todo-line-regexp)
7912 (match-string 3))
7913 (t (looking-at org-heading-regexp)
7914 (match-string 2)))))
7916 (defvar orgstruct-mode) ; defined below
7918 (defun org-heading-components ()
7919 "Return the components of the current heading.
7920 This is a list with the following elements:
7921 - the level as an integer
7922 - the reduced level, different if `org-odd-levels-only' is set.
7923 - the TODO keyword, or nil
7924 - the priority character, like ?A, or nil if no priority is given
7925 - the headline text itself, or the tags string if no headline text
7926 - the tags string, or nil."
7927 (save-excursion
7928 (org-back-to-heading t)
7929 (if (let (case-fold-search)
7930 (looking-at
7931 (if orgstruct-mode
7932 org-heading-regexp
7933 org-complex-heading-regexp)))
7934 (if orgstruct-mode
7935 (list (length (match-string 1))
7936 (org-reduced-level (length (match-string 1)))
7939 (match-string 2)
7940 nil)
7941 (list (length (match-string 1))
7942 (org-reduced-level (length (match-string 1)))
7943 (org-match-string-no-properties 2)
7944 (and (match-end 3) (aref (match-string 3) 2))
7945 (org-match-string-no-properties 4)
7946 (org-match-string-no-properties 5))))))
7948 (defun org-get-entry ()
7949 "Get the entry text, after heading, entire subtree."
7950 (save-excursion
7951 (org-back-to-heading t)
7952 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7954 (defun org-insert-heading-after-current ()
7955 "Insert a new heading with same level as current, after current subtree."
7956 (interactive)
7957 (org-back-to-heading)
7958 (org-insert-heading)
7959 (org-move-subtree-down)
7960 (end-of-line 1))
7962 (defun org-insert-heading-respect-content (&optional invisible-ok)
7963 "Insert heading with `org-insert-heading-respect-content' set to t."
7964 (interactive)
7965 (org-insert-heading '(4) invisible-ok))
7967 (defun org-insert-todo-heading-respect-content (&optional force-state)
7968 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7969 (interactive)
7970 (org-insert-todo-heading force-state '(4)))
7972 (defun org-insert-todo-heading (arg &optional force-heading)
7973 "Insert a new heading with the same level and TODO state as current heading.
7974 If the heading has no TODO state, or if the state is DONE, use the first
7975 state (TODO by default). Also with one prefix arg, force first state. With
7976 two prefix args, force inserting at the end of the parent subtree."
7977 (interactive "P")
7978 (when (or force-heading (not (org-insert-item 'checkbox)))
7979 (org-insert-heading (or (and (equal arg '(16)) '(16))
7980 force-heading))
7981 (save-excursion
7982 (org-back-to-heading)
7983 (outline-previous-heading)
7984 (looking-at org-todo-line-regexp))
7985 (let*
7986 ((new-mark-x
7987 (if (or (equal arg '(4))
7988 (not (match-beginning 2))
7989 (member (match-string 2) org-done-keywords))
7990 (car org-todo-keywords-1)
7991 (match-string 2)))
7992 (new-mark
7994 (run-hook-with-args-until-success
7995 'org-todo-get-default-hook new-mark-x nil)
7996 new-mark-x)))
7997 (beginning-of-line 1)
7998 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7999 (if org-treat-insert-todo-heading-as-state-change
8000 (org-todo new-mark)
8001 (insert new-mark " "))))
8002 (when org-provide-todo-statistics
8003 (org-update-parent-todo-statistics))))
8005 (defun org-insert-subheading (arg)
8006 "Insert a new subheading and demote it.
8007 Works for outline headings and for plain lists alike."
8008 (interactive "P")
8009 (org-insert-heading arg)
8010 (cond
8011 ((org-at-heading-p) (org-do-demote))
8012 ((org-at-item-p) (org-indent-item))))
8014 (defun org-insert-todo-subheading (arg)
8015 "Insert a new subheading with TODO keyword or checkbox and demote it.
8016 Works for outline headings and for plain lists alike."
8017 (interactive "P")
8018 (org-insert-todo-heading arg)
8019 (cond
8020 ((org-at-heading-p) (org-do-demote))
8021 ((org-at-item-p) (org-indent-item))))
8023 ;;; Promotion and Demotion
8025 (defvar org-after-demote-entry-hook nil
8026 "Hook run after an entry has been demoted.
8027 The cursor will be at the beginning of the entry.
8028 When a subtree is being demoted, the hook will be called for each node.")
8030 (defvar org-after-promote-entry-hook nil
8031 "Hook run after an entry has been promoted.
8032 The cursor will be at the beginning of the entry.
8033 When a subtree is being promoted, the hook will be called for each node.")
8035 (defun org-promote-subtree ()
8036 "Promote the entire subtree.
8037 See also `org-promote'."
8038 (interactive)
8039 (save-excursion
8040 (org-with-limited-levels (org-map-tree 'org-promote)))
8041 (org-fix-position-after-promote))
8043 (defun org-demote-subtree ()
8044 "Demote the entire subtree. See `org-demote'.
8045 See also `org-promote'."
8046 (interactive)
8047 (save-excursion
8048 (org-with-limited-levels (org-map-tree 'org-demote)))
8049 (org-fix-position-after-promote))
8052 (defun org-do-promote ()
8053 "Promote the current heading higher up the tree.
8054 If the region is active in `transient-mark-mode', promote all headings
8055 in the region."
8056 (interactive)
8057 (save-excursion
8058 (if (org-region-active-p)
8059 (org-map-region 'org-promote (region-beginning) (region-end))
8060 (org-promote)))
8061 (org-fix-position-after-promote))
8063 (defun org-do-demote ()
8064 "Demote the current heading lower down the tree.
8065 If the region is active in `transient-mark-mode', demote all headings
8066 in the region."
8067 (interactive)
8068 (save-excursion
8069 (if (org-region-active-p)
8070 (org-map-region 'org-demote (region-beginning) (region-end))
8071 (org-demote)))
8072 (org-fix-position-after-promote))
8074 (defun org-fix-position-after-promote ()
8075 "Make sure that after pro/demotion cursor position is right."
8076 (let ((pos (point)))
8077 (when (save-excursion
8078 (beginning-of-line 1)
8079 (looking-at org-todo-line-regexp)
8080 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8081 (cond ((eobp) (insert " "))
8082 ((eolp) (insert " "))
8083 ((equal (char-after) ?\ ) (forward-char 1))))))
8085 (defun org-current-level ()
8086 "Return the level of the current entry, or nil if before the first headline.
8087 The level is the number of stars at the beginning of the
8088 headline. Use `org-reduced-level' to remove the effect of
8089 `org-odd-levels'. Unlike to `org-outline-level', this function
8090 ignores inlinetasks."
8091 (let ((level (org-with-limited-levels (org-outline-level))))
8092 (and (> level 0) level)))
8094 (defun org-get-previous-line-level ()
8095 "Return the outline depth of the last headline before the current line.
8096 Returns 0 for the first headline in the buffer, and nil if before the
8097 first headline."
8098 (and (org-current-level)
8099 (or (and (/= (line-beginning-position) (point-min))
8100 (save-excursion (beginning-of-line 0) (org-current-level)))
8101 0)))
8103 (defun org-reduced-level (l)
8104 "Compute the effective level of a heading.
8105 This takes into account the setting of `org-odd-levels-only'."
8106 (cond
8107 ((zerop l) 0)
8108 (org-odd-levels-only (1+ (floor (/ l 2))))
8109 (t l)))
8111 (defun org-level-increment ()
8112 "Return the number of stars that will be added or removed at a
8113 time to headlines when structure editing, based on the value of
8114 `org-odd-levels-only'."
8115 (if org-odd-levels-only 2 1))
8117 (defun org-get-valid-level (level &optional change)
8118 "Rectify a level change under the influence of `org-odd-levels-only'
8119 LEVEL is a current level, CHANGE is by how much the level should be
8120 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8121 even level numbers will become the next higher odd number."
8122 (if org-odd-levels-only
8123 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8124 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8125 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8126 (max 1 (+ level (or change 0)))))
8128 (if (boundp 'define-obsolete-function-alias)
8129 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8130 (define-obsolete-function-alias 'org-get-legal-level
8131 'org-get-valid-level)
8132 (define-obsolete-function-alias 'org-get-legal-level
8133 'org-get-valid-level "23.1")))
8135 (defun org-promote ()
8136 "Promote the current heading higher up the tree."
8137 (org-with-wide-buffer
8138 (org-back-to-heading t)
8139 (let* ((after-change-functions (remq 'flyspell-after-change-function
8140 after-change-functions))
8141 (level (save-match-data (funcall outline-level)))
8142 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8143 (diff (abs (- level (length up-head) -1))))
8144 (cond
8145 ((and (= level 1) org-allow-promoting-top-level-subtree)
8146 (replace-match "# " nil t))
8147 ((= level 1)
8148 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8149 (t (replace-match up-head nil t)))
8150 (unless (= level 1)
8151 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8152 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8153 (run-hooks 'org-after-promote-entry-hook))))
8155 (defun org-demote ()
8156 "Demote the current heading lower down the tree."
8157 (org-with-wide-buffer
8158 (org-back-to-heading t)
8159 (let* ((after-change-functions (remq 'flyspell-after-change-function
8160 after-change-functions))
8161 (level (save-match-data (funcall outline-level)))
8162 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8163 (diff (abs (- level (length down-head) -1))))
8164 (replace-match down-head nil t)
8165 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8166 (when org-adapt-indentation (org-fixup-indentation diff))
8167 (run-hooks 'org-after-demote-entry-hook))))
8169 (defun org-cycle-level ()
8170 "Cycle the level of an empty headline through possible states.
8171 This goes first to child, then to parent, level, then up the hierarchy.
8172 After top level, it switches back to sibling level."
8173 (interactive)
8174 (let ((org-adapt-indentation nil))
8175 (when (org-point-at-end-of-empty-headline)
8176 (setq this-command 'org-cycle-level) ; Only needed for caching
8177 (let ((cur-level (org-current-level))
8178 (prev-level (org-get-previous-line-level)))
8179 (cond
8180 ;; If first headline in file, promote to top-level.
8181 ((= prev-level 0)
8182 (loop repeat (/ (- cur-level 1) (org-level-increment))
8183 do (org-do-promote)))
8184 ;; If same level as prev, demote one.
8185 ((= prev-level cur-level)
8186 (org-do-demote))
8187 ;; If parent is top-level, promote to top level if not already.
8188 ((= prev-level 1)
8189 (loop repeat (/ (- cur-level 1) (org-level-increment))
8190 do (org-do-promote)))
8191 ;; If top-level, return to prev-level.
8192 ((= cur-level 1)
8193 (loop repeat (/ (- prev-level 1) (org-level-increment))
8194 do (org-do-demote)))
8195 ;; If less than prev-level, promote one.
8196 ((< cur-level prev-level)
8197 (org-do-promote))
8198 ;; If deeper than prev-level, promote until higher than
8199 ;; prev-level.
8200 ((> cur-level prev-level)
8201 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8202 do (org-do-promote))))
8203 t))))
8205 (defun org-map-tree (fun)
8206 "Call FUN for every heading underneath the current one."
8207 (org-back-to-heading)
8208 (let ((level (funcall outline-level)))
8209 (save-excursion
8210 (funcall fun)
8211 (while (and (progn
8212 (outline-next-heading)
8213 (> (funcall outline-level) level))
8214 (not (eobp)))
8215 (funcall fun)))))
8217 (defun org-map-region (fun beg end)
8218 "Call FUN for every heading between BEG and END."
8219 (let ((org-ignore-region t))
8220 (save-excursion
8221 (setq end (copy-marker end))
8222 (goto-char beg)
8223 (if (and (re-search-forward org-outline-regexp-bol nil t)
8224 (< (point) end))
8225 (funcall fun))
8226 (while (and (progn
8227 (outline-next-heading)
8228 (< (point) end))
8229 (not (eobp)))
8230 (funcall fun)))))
8232 (defun org-fixup-indentation (diff)
8233 "Change the indentation in the current entry by DIFF.
8235 DIFF is an integer. Indentation is done according to the
8236 following rules:
8238 - Planning information and property drawers are always indented
8239 according to the new level of the headline;
8241 - Footnote definitions and their contents are ignored;
8243 - Inlinetasks' boundaries are not shifted;
8245 - Empty lines are ignored;
8247 - Other lines' indentation are shifted by DIFF columns, unless
8248 it would introduce a structural change in the document, in
8249 which case no shifting is done at all.
8251 Assume point is at a heading or an inlinetask beginning."
8252 (org-with-wide-buffer
8253 (narrow-to-region (line-beginning-position)
8254 (save-excursion
8255 (if (org-with-limited-levels (org-at-heading-p))
8256 (org-with-limited-levels (outline-next-heading))
8257 (org-inlinetask-goto-end))
8258 (point)))
8259 (forward-line)
8260 ;; Indent properly planning info and property drawer.
8261 (when (org-looking-at-p org-planning-line-re)
8262 (org-indent-line)
8263 (forward-line))
8264 (when (looking-at org-property-drawer-re)
8265 (goto-char (match-end 0))
8266 (forward-line)
8267 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8268 (catch 'no-shift
8269 (when (zerop diff) (throw 'no-shift nil))
8270 ;; If DIFF is negative, first check if a shift is possible at all
8271 ;; (e.g., it doesn't break structure). This can only happen if
8272 ;; some contents are not properly indented.
8273 (let ((case-fold-search t))
8274 (when (< diff 0)
8275 (let ((diff (- diff))
8276 (forbidden-re (concat org-outline-regexp
8277 "\\|"
8278 (substring org-footnote-definition-re 1))))
8279 (save-excursion
8280 (while (not (eobp))
8281 (cond
8282 ((org-looking-at-p "[ \t]*$") (forward-line))
8283 ((and (org-looking-at-p org-footnote-definition-re)
8284 (let ((e (org-element-at-point)))
8285 (and (eq (org-element-type e) 'footnote-definition)
8286 (goto-char (org-element-property :end e))))))
8287 ((org-looking-at-p org-outline-regexp) (forward-line))
8288 ;; Give up if shifting would move before column 0 or
8289 ;; if it would introduce a headline or a footnote
8290 ;; definition.
8292 (skip-chars-forward " \t")
8293 (let ((ind (current-column)))
8294 (when (or (< ind diff)
8295 (and (= ind diff) (org-looking-at-p forbidden-re)))
8296 (throw 'no-shift nil)))
8297 ;; Ignore contents of example blocks and source
8298 ;; blocks if their indentation is meant to be
8299 ;; preserved. Jump to block's closing line.
8300 (beginning-of-line)
8301 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8302 (let ((e (org-element-at-point)))
8303 (and (memq (org-element-type e)
8304 '(example-block src-block))
8305 (or org-src-preserve-indentation
8306 (org-element-property :preserve-indent e))
8307 (goto-char (org-element-property :end e))
8308 (progn (skip-chars-backward " \r\t\n")
8309 (beginning-of-line)
8310 t))))
8311 (forward-line))))))))
8312 ;; Shift lines but footnote definitions, inlinetasks boundaries
8313 ;; by DIFF. Also skip contents of source or example blocks
8314 ;; when indentation is meant to be preserved.
8315 (while (not (eobp))
8316 (cond
8317 ((and (org-looking-at-p org-footnote-definition-re)
8318 (let ((e (org-element-at-point)))
8319 (and (eq (org-element-type e) 'footnote-definition)
8320 (goto-char (org-element-property :end e))))))
8321 ((org-looking-at-p org-outline-regexp) (forward-line))
8322 ((org-looking-at-p "[ \t]*$") (forward-line))
8324 (org-indent-line-to (+ (org-get-indentation) diff))
8325 (beginning-of-line)
8326 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8327 (let ((e (org-element-at-point)))
8328 (and (memq (org-element-type e)
8329 '(example-block src-block))
8330 (or org-src-preserve-indentation
8331 (org-element-property :preserve-indent e))
8332 (goto-char (org-element-property :end e))
8333 (progn (skip-chars-backward " \r\t\n")
8334 (beginning-of-line)
8335 t))))
8336 (forward-line)))))))))
8338 (defun org-convert-to-odd-levels ()
8339 "Convert an org-mode file with all levels allowed to one with odd levels.
8340 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8341 level 5 etc."
8342 (interactive)
8343 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8344 (let ((outline-level 'org-outline-level)
8345 (org-odd-levels-only nil) n)
8346 (save-excursion
8347 (goto-char (point-min))
8348 (while (re-search-forward "^\\*\\*+ " nil t)
8349 (setq n (- (length (match-string 0)) 2))
8350 (while (>= (setq n (1- n)) 0)
8351 (org-demote))
8352 (end-of-line 1))))))
8354 (defun org-convert-to-oddeven-levels ()
8355 "Convert an org-mode file with only odd levels to one with odd/even levels.
8356 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8357 file contains a section with an even level, conversion would
8358 destroy the structure of the file. An error is signaled in this
8359 case."
8360 (interactive)
8361 (goto-char (point-min))
8362 ;; First check if there are no even levels
8363 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8364 (org-show-set-visibility 'canonical)
8365 (error "Not all levels are odd in this file. Conversion not possible"))
8366 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8367 (let ((outline-regexp org-outline-regexp)
8368 (outline-level 'org-outline-level)
8369 (org-odd-levels-only nil) n)
8370 (save-excursion
8371 (goto-char (point-min))
8372 (while (re-search-forward "^\\*\\*+ " nil t)
8373 (setq n (/ (1- (length (match-string 0))) 2))
8374 (while (>= (setq n (1- n)) 0)
8375 (org-promote))
8376 (end-of-line 1))))))
8378 (defun org-tr-level (n)
8379 "Make N odd if required."
8380 (if org-odd-levels-only (1+ (/ n 2)) n))
8382 ;;; Vertical tree motion, cutting and pasting of subtrees
8384 (defun org-move-subtree-up (&optional arg)
8385 "Move the current subtree up past ARG headlines of the same level."
8386 (interactive "p")
8387 (org-move-subtree-down (- (prefix-numeric-value arg))))
8389 (defun org-move-subtree-down (&optional arg)
8390 "Move the current subtree down past ARG headlines of the same level."
8391 (interactive "p")
8392 (setq arg (prefix-numeric-value arg))
8393 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8394 'org-get-last-sibling))
8395 (ins-point (make-marker))
8396 (cnt (abs arg))
8397 (col (current-column))
8398 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8399 ;; Select the tree
8400 (org-back-to-heading)
8401 (setq beg0 (point))
8402 (save-excursion
8403 (setq ne-beg (org-back-over-empty-lines))
8404 (setq beg (point)))
8405 (save-match-data
8406 (save-excursion (outline-end-of-heading)
8407 (setq folded (outline-invisible-p)))
8408 (progn (org-end-of-subtree nil t)
8409 (unless (eobp) (backward-char))))
8410 (outline-next-heading)
8411 (setq ne-end (org-back-over-empty-lines))
8412 (setq end (point))
8413 (goto-char beg0)
8414 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8415 ;; include less whitespace
8416 (save-excursion
8417 (goto-char beg)
8418 (forward-line (- ne-beg ne-end))
8419 (setq beg (point))))
8420 ;; Find insertion point, with error handling
8421 (while (> cnt 0)
8422 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8423 (progn (goto-char beg0)
8424 (user-error "Cannot move past superior level or buffer limit")))
8425 (setq cnt (1- cnt)))
8426 (if (> arg 0)
8427 ;; Moving forward - still need to move over subtree
8428 (progn (org-end-of-subtree t t)
8429 (save-excursion
8430 (org-back-over-empty-lines)
8431 (or (bolp) (newline)))))
8432 (setq ne-ins (org-back-over-empty-lines))
8433 (move-marker ins-point (point))
8434 (setq txt (buffer-substring beg end))
8435 (org-save-markers-in-region beg end)
8436 (delete-region beg end)
8437 (org-remove-empty-overlays-at beg)
8438 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8439 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8440 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8441 (let ((bbb (point)))
8442 (insert-before-markers txt)
8443 (org-reinstall-markers-in-region bbb)
8444 (move-marker ins-point bbb))
8445 (or (bolp) (insert "\n"))
8446 (setq ins-end (point))
8447 (goto-char ins-point)
8448 (org-skip-whitespace)
8449 (when (and (< arg 0)
8450 (org-first-sibling-p)
8451 (> ne-ins ne-beg))
8452 ;; Move whitespace back to beginning
8453 (save-excursion
8454 (goto-char ins-end)
8455 (let ((kill-whole-line t))
8456 (kill-line (- ne-ins ne-beg)) (point)))
8457 (insert (make-string (- ne-ins ne-beg) ?\n)))
8458 (move-marker ins-point nil)
8459 (if folded
8460 (hide-subtree)
8461 (org-show-entry)
8462 (show-children)
8463 (org-cycle-hide-drawers 'children))
8464 (org-clean-visibility-after-subtree-move)
8465 ;; move back to the initial column we were at
8466 (move-to-column col)))
8468 (defvar org-subtree-clip ""
8469 "Clipboard for cut and paste of subtrees.
8470 This is actually only a copy of the kill, because we use the normal kill
8471 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8473 (defvar org-subtree-clip-folded nil
8474 "Was the last copied subtree folded?
8475 This is used to fold the tree back after pasting.")
8477 (defun org-cut-subtree (&optional n)
8478 "Cut the current subtree into the clipboard.
8479 With prefix arg N, cut this many sequential subtrees.
8480 This is a short-hand for marking the subtree and then cutting it."
8481 (interactive "p")
8482 (org-copy-subtree n 'cut))
8484 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8485 "Copy the current subtree it in the clipboard.
8486 With prefix arg N, copy this many sequential subtrees.
8487 This is a short-hand for marking the subtree and then copying it.
8488 If CUT is non-nil, actually cut the subtree.
8489 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8490 of some markers in the region, even if CUT is non-nil. This is
8491 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8492 (interactive "p")
8493 (let (beg end folded (beg0 (point)))
8494 (if (org-called-interactively-p 'any)
8495 (org-back-to-heading nil) ; take what looks like a subtree
8496 (org-back-to-heading t)) ; take what is really there
8497 (setq beg (point))
8498 (skip-chars-forward " \t\r\n")
8499 (save-match-data
8500 (if nosubtrees
8501 (outline-next-heading)
8502 (save-excursion (outline-end-of-heading)
8503 (setq folded (outline-invisible-p)))
8504 (ignore-errors (org-forward-heading-same-level (1- n) t))
8505 (org-end-of-subtree t t)))
8506 ;; Include the end of an inlinetask
8507 (when (and (featurep 'org-inlinetask)
8508 (looking-at-p (concat (org-inlinetask-outline-regexp)
8509 "END[ \t]*$")))
8510 (end-of-line))
8511 (setq end (point))
8512 (goto-char beg0)
8513 (when (> end beg)
8514 (setq org-subtree-clip-folded folded)
8515 (when (or cut force-store-markers)
8516 (org-save-markers-in-region beg end))
8517 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8518 (setq org-subtree-clip (current-kill 0))
8519 (message "%s: Subtree(s) with %d characters"
8520 (if cut "Cut" "Copied")
8521 (length org-subtree-clip)))))
8523 (defun org-paste-subtree (&optional level tree for-yank remove)
8524 "Paste the clipboard as a subtree, with modification of headline level.
8525 The entire subtree is promoted or demoted in order to match a new headline
8526 level.
8528 If the cursor is at the beginning of a headline, the same level as
8529 that headline is used to paste the tree.
8531 If not, the new level is derived from the *visible* headings
8532 before and after the insertion point, and taken to be the inferior headline
8533 level of the two. So if the previous visible heading is level 3 and the
8534 next is level 4 (or vice versa), level 4 will be used for insertion.
8535 This makes sure that the subtree remains an independent subtree and does
8536 not swallow low level entries.
8538 You can also force a different level, either by using a numeric prefix
8539 argument, or by inserting the heading marker by hand. For example, if the
8540 cursor is after \"*****\", then the tree will be shifted to level 5.
8542 If optional TREE is given, use this text instead of the kill ring.
8544 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8545 move back over whitespace before inserting, and move point to the end of
8546 the inserted text when done.
8548 When REMOVE is non-nil, remove the subtree from the clipboard."
8549 (interactive "P")
8550 (setq tree (or tree (and kill-ring (current-kill 0))))
8551 (unless (org-kill-is-subtree-p tree)
8552 (user-error "%s"
8553 (substitute-command-keys
8554 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8555 (org-with-limited-levels
8556 (let* ((visp (not (outline-invisible-p)))
8557 (txt tree)
8558 (^re_ "\\(\\*+\\)[ \t]*")
8559 (old-level (if (string-match org-outline-regexp-bol txt)
8560 (- (match-end 0) (match-beginning 0) 1)
8561 -1))
8562 (force-level (cond (level (prefix-numeric-value level))
8563 ((and (looking-at "[ \t]*$")
8564 (string-match
8565 "^\\*+$" (buffer-substring
8566 (point-at-bol) (point))))
8567 (- (match-end 0) (match-beginning 0)))
8568 ((and (bolp)
8569 (looking-at org-outline-regexp))
8570 (- (match-end 0) (point) 1))))
8571 (previous-level (save-excursion
8572 (condition-case nil
8573 (progn
8574 (outline-previous-visible-heading 1)
8575 (if (looking-at ^re_)
8576 (- (match-end 0) (match-beginning 0) 1)
8578 (error 1))))
8579 (next-level (save-excursion
8580 (condition-case nil
8581 (progn
8582 (or (looking-at org-outline-regexp)
8583 (outline-next-visible-heading 1))
8584 (if (looking-at ^re_)
8585 (- (match-end 0) (match-beginning 0) 1)
8587 (error 1))))
8588 (new-level (or force-level (max previous-level next-level)))
8589 (shift (if (or (= old-level -1)
8590 (= new-level -1)
8591 (= old-level new-level))
8593 (- new-level old-level)))
8594 (delta (if (> shift 0) -1 1))
8595 (func (if (> shift 0) 'org-demote 'org-promote))
8596 (org-odd-levels-only nil)
8597 beg end newend)
8598 ;; Remove the forced level indicator
8599 (if force-level
8600 (delete-region (point-at-bol) (point)))
8601 ;; Paste
8602 (beginning-of-line (if (bolp) 1 2))
8603 (setq beg (point))
8604 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8605 (insert-before-markers txt)
8606 (unless (string-match "\n\\'" txt) (insert "\n"))
8607 (setq newend (point))
8608 (org-reinstall-markers-in-region beg)
8609 (setq end (point))
8610 (goto-char beg)
8611 (skip-chars-forward " \t\n\r")
8612 (setq beg (point))
8613 (if (and (outline-invisible-p) visp)
8614 (save-excursion (outline-show-heading)))
8615 ;; Shift if necessary
8616 (unless (= shift 0)
8617 (save-restriction
8618 (narrow-to-region beg end)
8619 (while (not (= shift 0))
8620 (org-map-region func (point-min) (point-max))
8621 (setq shift (+ delta shift)))
8622 (goto-char (point-min))
8623 (setq newend (point-max))))
8624 (when (or (org-called-interactively-p 'interactive) for-yank)
8625 (message "Clipboard pasted as level %d subtree" new-level))
8626 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8627 kill-ring
8628 (eq org-subtree-clip (current-kill 0))
8629 org-subtree-clip-folded)
8630 ;; The tree was folded before it was killed/copied
8631 (hide-subtree))
8632 (and for-yank (goto-char newend))
8633 (and remove (setq kill-ring (cdr kill-ring))))))
8635 (defun org-kill-is-subtree-p (&optional txt)
8636 "Check if the current kill is an outline subtree, or a set of trees.
8637 Returns nil if kill does not start with a headline, or if the first
8638 headline level is not the largest headline level in the tree.
8639 So this will actually accept several entries of equal levels as well,
8640 which is OK for `org-paste-subtree'.
8641 If optional TXT is given, check this string instead of the current kill."
8642 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8643 (re (org-get-limited-outline-regexp))
8644 (^re (concat "^" re))
8645 (start-level (and kill
8646 (string-match
8647 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8648 kill)
8649 (- (match-end 2) (match-beginning 2) 1)))
8650 (start (1+ (or (match-beginning 2) -1))))
8651 (if (not start-level)
8652 (progn
8653 nil) ;; does not even start with a heading
8654 (catch 'exit
8655 (while (setq start (string-match ^re kill (1+ start)))
8656 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8657 (throw 'exit nil)))
8658 t))))
8660 (defvar org-markers-to-move nil
8661 "Markers that should be moved with a cut-and-paste operation.
8662 Those markers are stored together with their positions relative to
8663 the start of the region.")
8665 (defun org-save-markers-in-region (beg end)
8666 "Check markers in region.
8667 If these markers are between BEG and END, record their position relative
8668 to BEG, so that after moving the block of text, we can put the markers back
8669 into place.
8670 This function gets called just before an entry or tree gets cut from the
8671 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8672 called immediately, to move the markers with the entries."
8673 (setq org-markers-to-move nil)
8674 (when (featurep 'org-clock)
8675 (org-clock-save-markers-for-cut-and-paste beg end))
8676 (when (featurep 'org-agenda)
8677 (org-agenda-save-markers-for-cut-and-paste beg end)))
8679 (defun org-check-and-save-marker (marker beg end)
8680 "Check if MARKER is between BEG and END.
8681 If yes, remember the marker and the distance to BEG."
8682 (when (and (marker-buffer marker)
8683 (equal (marker-buffer marker) (current-buffer)))
8684 (if (and (>= marker beg) (< marker end))
8685 (push (cons marker (- marker beg)) org-markers-to-move))))
8687 (defun org-reinstall-markers-in-region (beg)
8688 "Move all remembered markers to their position relative to BEG."
8689 (mapc (lambda (x)
8690 (move-marker (car x) (+ beg (cdr x))))
8691 org-markers-to-move)
8692 (setq org-markers-to-move nil))
8694 (defun org-narrow-to-subtree ()
8695 "Narrow buffer to the current subtree."
8696 (interactive)
8697 (save-excursion
8698 (save-match-data
8699 (org-with-limited-levels
8700 (narrow-to-region
8701 (progn (org-back-to-heading t) (point))
8702 (progn (org-end-of-subtree t t)
8703 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8704 (point)))))))
8706 (defun org-narrow-to-block ()
8707 "Narrow buffer to the current block."
8708 (interactive)
8709 (let* ((case-fold-search t)
8710 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8711 "^[ \t]*#\\+end_.*")))
8712 (if blockp
8713 (narrow-to-region (car blockp) (cdr blockp))
8714 (user-error "Not in a block"))))
8716 (defun org-clone-subtree-with-time-shift (n &optional shift)
8717 "Clone the task (subtree) at point N times.
8718 The clones will be inserted as siblings.
8720 In interactive use, the user will be prompted for the number of
8721 clones to be produced. If the entry has a timestamp, the user
8722 will also be prompted for a time shift, which may be a repeater
8723 as used in time stamps, for example `+3d'. To disable this,
8724 you can call the function with a universal prefix argument.
8726 When a valid repeater is given and the entry contains any time
8727 stamps, the clones will become a sequence in time, with time
8728 stamps in the subtree shifted for each clone produced. If SHIFT
8729 is nil or the empty string, time stamps will be left alone. The
8730 ID property of the original subtree is removed.
8732 If the original subtree did contain time stamps with a repeater,
8733 the following will happen:
8734 - the repeater will be removed in each clone
8735 - an additional clone will be produced, with the current, unshifted
8736 date(s) in the entry.
8737 - the original entry will be placed *after* all the clones, with
8738 repeater intact.
8739 - the start days in the repeater in the original entry will be shifted
8740 to past the last clone.
8741 In this way you can spell out a number of instances of a repeating task,
8742 and still retain the repeater to cover future instances of the task."
8743 (interactive "nNumber of clones to produce: ")
8744 (let ((shift
8745 (or shift
8746 (if (and (not (equal current-prefix-arg '(4)))
8747 (save-excursion
8748 (re-search-forward org-ts-regexp-both
8749 (save-excursion
8750 (org-end-of-subtree t)
8751 (point)) t)))
8752 (read-from-minibuffer
8753 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8754 ""))) ;; No time shift
8755 (n-no-remove -1)
8756 (drawer-re org-drawer-regexp)
8757 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8758 beg end template task idprop
8759 shift-n shift-what doshift nmin nmax)
8760 (if (not (and (integerp n) (> n 0)))
8761 (user-error "Invalid number of replications %s" n))
8762 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8763 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8764 shift)))
8765 (user-error "Invalid shift specification %s" shift))
8766 (when doshift
8767 (setq shift-n (string-to-number (match-string 1 shift))
8768 shift-what (cdr (assoc (match-string 2 shift)
8769 '(("d" . day) ("w" . week)
8770 ("m" . month) ("y" . year))))))
8771 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8772 (setq nmin 1 nmax n)
8773 (org-back-to-heading t)
8774 (setq beg (point))
8775 (setq idprop (org-entry-get nil "ID"))
8776 (org-end-of-subtree t t)
8777 (or (bolp) (insert "\n"))
8778 (setq end (point))
8779 (setq template (buffer-substring beg end))
8780 (when (and doshift
8781 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8782 (delete-region beg end)
8783 (setq end beg)
8784 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8785 (goto-char end)
8786 (loop for n from nmin to nmax do
8787 ;; prepare clone
8788 (with-temp-buffer
8789 (insert template)
8790 (org-mode)
8791 (goto-char (point-min))
8792 (org-show-subtree)
8793 (and idprop (if org-clone-delete-id
8794 (org-entry-delete nil "ID")
8795 (org-id-get-create t)))
8796 (unless (= n 0)
8797 (while (re-search-forward org-clock-re nil t)
8798 (kill-whole-line))
8799 (goto-char (point-min))
8800 (while (re-search-forward drawer-re nil t)
8801 (org-remove-empty-drawer-at (point))))
8802 (goto-char (point-min))
8803 (when doshift
8804 (while (re-search-forward org-ts-regexp-both nil t)
8805 (org-timestamp-change (* n shift-n) shift-what))
8806 (unless (= n n-no-remove)
8807 (goto-char (point-min))
8808 (while (re-search-forward org-ts-regexp nil t)
8809 (save-excursion
8810 (goto-char (match-beginning 0))
8811 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8812 (delete-region (match-beginning 1) (match-end 1)))))))
8813 (setq task (buffer-string)))
8814 (insert task))
8815 (goto-char beg)))
8817 ;;; Outline Sorting
8819 (defun org-sort (with-case)
8820 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8821 Optional argument WITH-CASE means sort case-sensitively."
8822 (interactive "P")
8823 (cond
8824 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8825 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8827 (org-call-with-arg 'org-sort-entries with-case))))
8829 (defun org-sort-remove-invisible (s)
8830 "Remove invisible links from string S."
8831 (remove-text-properties 0 (length s) org-rm-props s)
8832 (while (string-match org-bracket-link-regexp s)
8833 (setq s (replace-match (if (match-end 2)
8834 (match-string 3 s)
8835 (match-string 1 s)) t t s)))
8836 (let ((st (format " %s " s)))
8837 (while (string-match org-emph-re st)
8838 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8839 (setq s (substring st 1 -1)))
8842 (defvar org-priority-regexp) ; defined later in the file
8844 (defvar org-after-sorting-entries-or-items-hook nil
8845 "Hook that is run after a bunch of entries or items have been sorted.
8846 When children are sorted, the cursor is in the parent line when this
8847 hook gets called. When a region or a plain list is sorted, the cursor
8848 will be in the first entry of the sorted region/list.")
8850 (defun org-sort-entries
8851 (&optional with-case sorting-type getkey-func compare-func property)
8852 "Sort entries on a certain level of an outline tree.
8853 If there is an active region, the entries in the region are sorted.
8854 Else, if the cursor is before the first entry, sort the top-level items.
8855 Else, the children of the entry at point are sorted.
8857 Sorting can be alphabetically, numerically, by date/time as given by
8858 a time stamp, by a property, by priority order, or by a custom function.
8860 The command prompts for the sorting type unless it has been given to the
8861 function through the SORTING-TYPE argument, which needs to be a character,
8862 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8863 the precise meaning of each character:
8865 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8866 c By creation time, which is assumed to be the first inactive time stamp
8867 at the beginning of a line.
8868 d By deadline date/time.
8869 k By clocking time.
8870 n Numerically, by converting the beginning of the entry/item to a number.
8871 o By order of TODO keywords.
8872 p By priority according to the cookie.
8873 r By the value of a property.
8874 s By scheduled date/time.
8875 t By date/time, either the first active time stamp in the entry, or, if
8876 none exist, by the first inactive one.
8878 Capital letters will reverse the sort order.
8880 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8881 called with point at the beginning of the record. It must return either
8882 a string or a number that should serve as the sorting key for that record.
8884 Comparing entries ignores case by default. However, with an optional argument
8885 WITH-CASE, the sorting considers case as well.
8887 Sorting is done against the visible part of the headlines, it ignores hidden
8888 links.
8890 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8891 (interactive "P")
8892 (let ((case-func (if with-case 'identity 'downcase))
8893 (cmstr
8894 ;; The clock marker is lost when using `sort-subr', let's
8895 ;; store the clocking string.
8896 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8897 (save-excursion
8898 (goto-char org-clock-marker)
8899 (looking-back "^.*") (match-string-no-properties 0))))
8900 start beg end stars re re2
8901 txt what tmp)
8902 ;; Find beginning and end of region to sort
8903 (cond
8904 ((org-region-active-p)
8905 ;; we will sort the region
8906 (setq end (region-end)
8907 what "region")
8908 (goto-char (region-beginning))
8909 (if (not (org-at-heading-p)) (outline-next-heading))
8910 (setq start (point)))
8911 ((or (org-at-heading-p)
8912 (ignore-errors (progn (org-back-to-heading) t)))
8913 ;; we will sort the children of the current headline
8914 (org-back-to-heading)
8915 (setq start (point)
8916 end (progn (org-end-of-subtree t t)
8917 (or (bolp) (insert "\n"))
8918 (when (>= (org-back-over-empty-lines) 1)
8919 (forward-line 1))
8920 (point))
8921 what "children")
8922 (goto-char start)
8923 (show-subtree)
8924 (outline-next-heading))
8926 ;; we will sort the top-level entries in this file
8927 (goto-char (point-min))
8928 (or (org-at-heading-p) (outline-next-heading))
8929 (setq start (point))
8930 (goto-char (point-max))
8931 (beginning-of-line 1)
8932 (when (looking-at ".*?\\S-")
8933 ;; File ends in a non-white line
8934 (end-of-line 1)
8935 (insert "\n"))
8936 (setq end (point-max))
8937 (setq what "top-level")
8938 (goto-char start)
8939 (show-all)))
8941 (setq beg (point))
8942 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8944 (looking-at "\\(\\*+\\)")
8945 (setq stars (match-string 1)
8946 re (concat "^" (regexp-quote stars) " +")
8947 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8948 txt (buffer-substring beg end))
8949 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8950 (if (and (not (equal stars "*")) (string-match re2 txt))
8951 (user-error "Region to sort contains a level above the first entry"))
8953 (unless sorting-type
8954 (message
8955 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8956 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8957 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8958 what)
8959 (setq sorting-type (read-char-exclusive))
8961 (unless getkey-func
8962 (and (= (downcase sorting-type) ?f)
8963 (setq getkey-func
8964 (org-icompleting-read "Sort using function: "
8965 obarray 'fboundp t nil nil))
8966 (setq getkey-func (intern getkey-func))))
8968 (and (= (downcase sorting-type) ?r)
8969 (not property)
8970 (setq property
8971 (org-icompleting-read "Property: "
8972 (mapcar 'list (org-buffer-property-keys t))
8973 nil t))))
8975 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8976 (message "Sorting entries...")
8978 (save-restriction
8979 (narrow-to-region start end)
8980 (let ((dcst (downcase sorting-type))
8981 (case-fold-search nil)
8982 (now (current-time)))
8983 (sort-subr
8984 (/= dcst sorting-type)
8985 ;; This function moves to the beginning character of the "record" to
8986 ;; be sorted.
8987 (lambda nil
8988 (if (re-search-forward re nil t)
8989 (goto-char (match-beginning 0))
8990 (goto-char (point-max))))
8991 ;; This function moves to the last character of the "record" being
8992 ;; sorted.
8993 (lambda nil
8994 (save-match-data
8995 (condition-case nil
8996 (outline-forward-same-level 1)
8997 (error
8998 (goto-char (point-max))))))
8999 ;; This function returns the value that gets sorted against.
9000 (lambda nil
9001 (cond
9002 ((= dcst ?n)
9003 (if (looking-at org-complex-heading-regexp)
9004 (string-to-number (org-sort-remove-invisible (match-string 4)))
9005 nil))
9006 ((= dcst ?a)
9007 (if (looking-at org-complex-heading-regexp)
9008 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9009 nil))
9010 ((= dcst ?k)
9011 (or (get-text-property (point) :org-clock-minutes) 0))
9012 ((= dcst ?t)
9013 (let ((end (save-excursion (outline-next-heading) (point))))
9014 (if (or (re-search-forward org-ts-regexp end t)
9015 (re-search-forward org-ts-regexp-both end t))
9016 (org-time-string-to-seconds (match-string 0))
9017 (org-float-time now))))
9018 ((= dcst ?c)
9019 (let ((end (save-excursion (outline-next-heading) (point))))
9020 (if (re-search-forward
9021 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9022 end t)
9023 (org-time-string-to-seconds (match-string 0))
9024 (org-float-time now))))
9025 ((= dcst ?s)
9026 (let ((end (save-excursion (outline-next-heading) (point))))
9027 (if (re-search-forward org-scheduled-time-regexp end t)
9028 (org-time-string-to-seconds (match-string 1))
9029 (org-float-time now))))
9030 ((= dcst ?d)
9031 (let ((end (save-excursion (outline-next-heading) (point))))
9032 (if (re-search-forward org-deadline-time-regexp end t)
9033 (org-time-string-to-seconds (match-string 1))
9034 (org-float-time now))))
9035 ((= dcst ?p)
9036 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9037 (string-to-char (match-string 2))
9038 org-default-priority))
9039 ((= dcst ?r)
9040 (or (org-entry-get nil property) ""))
9041 ((= dcst ?o)
9042 (if (looking-at org-complex-heading-regexp)
9043 (let* ((m (match-string 2))
9044 (s (if (member m org-done-keywords) '- '+)))
9045 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9046 ((= dcst ?f)
9047 (if getkey-func
9048 (progn
9049 (setq tmp (funcall getkey-func))
9050 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
9051 tmp)
9052 (error "Invalid key function `%s'" getkey-func)))
9053 (t (error "Invalid sorting type `%c'" sorting-type))))
9055 (cond
9056 ((= dcst ?a) 'string<)
9057 ((= dcst ?f) compare-func)
9058 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9059 (run-hooks 'org-after-sorting-entries-or-items-hook)
9060 ;; Reset the clock marker if needed
9061 (when cmstr
9062 (save-excursion
9063 (goto-char start)
9064 (search-forward cmstr nil t)
9065 (move-marker org-clock-marker (point))))
9066 (message "Sorting entries...done")))
9068 ;;; The orgstruct minor mode
9070 ;; Define a minor mode which can be used in other modes in order to
9071 ;; integrate the org-mode structure editing commands.
9073 ;; This is really a hack, because the org-mode structure commands use
9074 ;; keys which normally belong to the major mode. Here is how it
9075 ;; works: The minor mode defines all the keys necessary to operate the
9076 ;; structure commands, but wraps the commands into a function which
9077 ;; tests if the cursor is currently at a headline or a plain list
9078 ;; item. If that is the case, the structure command is used,
9079 ;; temporarily setting many Org-mode variables like regular
9080 ;; expressions for filling etc. However, when any of those keys is
9081 ;; used at a different location, function uses `key-binding' to look
9082 ;; up if the key has an associated command in another currently active
9083 ;; keymap (minor modes, major mode, global), and executes that
9084 ;; command. There might be problems if any of the keys is otherwise
9085 ;; used as a prefix key.
9087 (defcustom orgstruct-heading-prefix-regexp ""
9088 "Regexp that matches the custom prefix of Org headlines in
9089 orgstruct(++)-mode."
9090 :group 'org
9091 :version "24.4"
9092 :package-version '(Org . "8.3")
9093 :type 'regexp)
9094 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9096 (defcustom orgstruct-setup-hook nil
9097 "Hook run after orgstruct-mode-map is filled."
9098 :group 'org
9099 :version "24.4"
9100 :package-version '(Org . "8.0")
9101 :type 'hook)
9103 (defvar orgstruct-initialized nil)
9105 (defvar org-local-vars nil
9106 "List of local variables, for use by `orgstruct-mode'.")
9108 ;;;###autoload
9109 (define-minor-mode orgstruct-mode
9110 "Toggle the minor mode `orgstruct-mode'.
9111 This mode is for using Org-mode structure commands in other
9112 modes. The following keys behave as if Org-mode were active, if
9113 the cursor is on a headline, or on a plain list item (both as
9114 defined by Org-mode)."
9115 nil " OrgStruct" (make-sparse-keymap)
9116 (funcall (if orgstruct-mode
9117 'add-to-invisibility-spec
9118 'remove-from-invisibility-spec)
9119 '(outline . t))
9120 (when orgstruct-mode
9121 (org-load-modules-maybe)
9122 (unless orgstruct-initialized
9123 (orgstruct-setup)
9124 (setq orgstruct-initialized t))))
9126 ;;;###autoload
9127 (defun turn-on-orgstruct ()
9128 "Unconditionally turn on `orgstruct-mode'."
9129 (orgstruct-mode 1))
9131 (defvar org-fb-vars nil)
9132 (make-variable-buffer-local 'org-fb-vars)
9133 (defun orgstruct++-mode (&optional arg)
9134 "Toggle `orgstruct-mode', the enhanced version of it.
9135 In addition to setting orgstruct-mode, this also exports all
9136 indentation and autofilling variables from org-mode into the
9137 buffer. It will also recognize item context in multiline items."
9138 (interactive "P")
9139 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9140 (if (< arg 1)
9141 (progn (orgstruct-mode -1)
9142 (mapc (lambda(v)
9143 (org-set-local (car v)
9144 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9145 org-fb-vars))
9146 (orgstruct-mode 1)
9147 (setq org-fb-vars nil)
9148 (unless org-local-vars
9149 (setq org-local-vars (org-get-local-variables)))
9150 (let (var val)
9151 (mapc
9152 (lambda (x)
9153 (when (string-match
9154 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9155 (symbol-name (car x)))
9156 (setq var (car x) val (nth 1 x))
9157 (push (list var `(quote ,(eval var))) org-fb-vars)
9158 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9159 org-local-vars)
9160 (org-set-local 'orgstruct-is-++ t))))
9162 (defvar orgstruct-is-++ nil
9163 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9164 (make-variable-buffer-local 'orgstruct-is-++)
9166 ;;;###autoload
9167 (defun turn-on-orgstruct++ ()
9168 "Unconditionally turn on `orgstruct++-mode'."
9169 (orgstruct++-mode 1))
9171 (defun orgstruct-error ()
9172 "Error when there is no default binding for a structure key."
9173 (interactive)
9174 (funcall (if (fboundp 'user-error)
9175 'user-error
9176 'error)
9177 "This key has no function outside structure elements"))
9179 (defun orgstruct-setup ()
9180 "Setup orgstruct keymap."
9181 (dolist (cell '((org-demote . t)
9182 (org-metaleft . t)
9183 (org-metaright . t)
9184 (org-promote . t)
9185 (org-shiftmetaleft . t)
9186 (org-shiftmetaright . t)
9187 org-backward-element
9188 org-backward-heading-same-level
9189 org-ctrl-c-ret
9190 org-ctrl-c-minus
9191 org-ctrl-c-star
9192 org-cycle
9193 org-forward-heading-same-level
9194 org-insert-heading
9195 org-insert-heading-respect-content
9196 org-kill-note-or-show-branches
9197 org-mark-subtree
9198 org-meta-return
9199 org-metadown
9200 org-metaup
9201 org-narrow-to-subtree
9202 org-promote-subtree
9203 org-reveal
9204 org-shiftdown
9205 org-shiftleft
9206 org-shiftmetadown
9207 org-shiftmetaup
9208 org-shiftright
9209 org-shifttab
9210 org-shifttab
9211 org-shiftup
9212 org-show-subtree
9213 org-sort
9214 org-up-element
9215 outline-demote
9216 outline-next-visible-heading
9217 outline-previous-visible-heading
9218 outline-promote
9219 outline-up-heading
9220 show-children))
9221 (let ((f (or (car-safe cell) cell))
9222 (disable-when-heading-prefix (cdr-safe cell)))
9223 (when (fboundp f)
9224 (let ((new-bindings))
9225 (dolist (binding (nconc (where-is-internal f org-mode-map)
9226 (where-is-internal f outline-mode-map)))
9227 (push binding new-bindings)
9228 ;; TODO use local-function-key-map
9229 (dolist (rep '(("<tab>" . "TAB")
9230 ("<return>" . "RET")
9231 ("<escape>" . "ESC")
9232 ("<delete>" . "DEL")))
9233 (setq binding (read-kbd-macro
9234 (let ((case-fold-search))
9235 (replace-regexp-in-string
9236 (regexp-quote (cdr rep))
9237 (car rep)
9238 (key-description binding)))))
9239 (pushnew binding new-bindings :test 'equal)))
9240 (dolist (binding new-bindings)
9241 (let ((key (lookup-key orgstruct-mode-map binding)))
9242 (when (or (not key) (numberp key))
9243 (ignore-errors
9244 (org-defkey orgstruct-mode-map
9245 binding
9246 (orgstruct-make-binding
9247 f binding disable-when-heading-prefix))))))))))
9248 (run-hooks 'orgstruct-setup-hook))
9250 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9251 "Create a function for binding in the structure minor mode.
9252 FUN is the command to call inside a table. KEY is the key that
9253 should be checked in for a command to execute outside of tables.
9254 Non-nil `disable-when-heading-prefix' means to disable the command
9255 if `orgstruct-heading-prefix-regexp' is not empty."
9256 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9257 (let ((nname name)
9258 (i 0))
9259 (while (fboundp (intern nname))
9260 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9261 (setq name (intern nname)))
9262 (eval
9263 (let ((bindings '((org-heading-regexp
9264 (concat "^"
9265 orgstruct-heading-prefix-regexp
9266 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9267 (org-outline-regexp
9268 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9269 (org-outline-regexp-bol
9270 (concat "^" org-outline-regexp))
9271 (outline-regexp org-outline-regexp)
9272 (outline-heading-end-regexp "\n")
9273 (outline-level 'org-outline-level)
9274 (outline-heading-alist))))
9275 `(defun ,name (arg)
9276 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9277 "Outside of structure, run the binding of `"
9278 (key-description key) "'."
9279 (when disable-when-heading-prefix
9280 (concat
9281 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9282 "back to the default binding due to limitations of Org's implementation of\n"
9283 "`" (symbol-name fun) "'.")))
9284 (interactive "p")
9285 (let* ((disable
9286 ,(and disable-when-heading-prefix
9287 '(not (string= orgstruct-heading-prefix-regexp ""))))
9288 (fallback
9289 (or disable
9290 (not
9291 (let* ,bindings
9292 (org-context-p 'headline 'item
9293 ,(when (memq fun
9294 '(org-insert-heading
9295 org-insert-heading-respect-content
9296 org-meta-return))
9297 '(when orgstruct-is-++
9298 'item-body))))))))
9299 (if fallback
9300 (let* ((orgstruct-mode)
9301 (binding
9302 (let ((key ,key))
9303 (catch 'exit
9304 (dolist
9305 (rep
9306 '(nil
9307 ("<\\([^>]*\\)tab>" . "\\1TAB")
9308 ("<\\([^>]*\\)return>" . "\\1RET")
9309 ("<\\([^>]*\\)escape>" . "\\1ESC")
9310 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9311 nil)
9312 (when rep
9313 (setq key (read-kbd-macro
9314 (let ((case-fold-search))
9315 (replace-regexp-in-string
9316 (car rep)
9317 (cdr rep)
9318 (key-description key))))))
9319 (when (key-binding key)
9320 (throw 'exit (key-binding key))))))))
9321 (if (keymapp binding)
9322 (org-set-transient-map binding)
9323 (let ((func (or binding
9324 (unless disable
9325 'orgstruct-error))))
9326 (when func
9327 (call-interactively func)))))
9328 (org-run-like-in-org-mode
9329 (lambda ()
9330 (interactive)
9331 (let* ,bindings
9332 (call-interactively ',fun)))))))))
9333 name))
9335 (defun org-contextualize-keys (alist contexts)
9336 "Return valid elements in ALIST depending on CONTEXTS.
9338 `org-agenda-custom-commands' or `org-capture-templates' are the
9339 values used for ALIST, and `org-agenda-custom-commands-contexts'
9340 or `org-capture-templates-contexts' are the associated contexts
9341 definitions."
9342 (let ((contexts
9343 ;; normalize contexts
9344 (mapcar
9345 (lambda(c) (cond ((listp (cadr c))
9346 (list (car c) (car c) (cadr c)))
9347 ((string= "" (cadr c))
9348 (list (car c) (car c) (caddr c)))
9349 (t c))) contexts))
9350 (a alist) c r s)
9351 ;; loop over all commands or templates
9352 (while (setq c (pop a))
9353 (let (vrules repl)
9354 (cond
9355 ((not (assoc (car c) contexts))
9356 (push c r))
9357 ((and (assoc (car c) contexts)
9358 (setq vrules (org-contextualize-validate-key
9359 (car c) contexts)))
9360 (mapc (lambda (vr)
9361 (when (not (equal (car vr) (cadr vr)))
9362 (setq repl vr))) vrules)
9363 (if (not repl) (push c r)
9364 (push (cadr repl) s)
9365 (push
9366 (cons (car c)
9367 (cdr (or (assoc (cadr repl) alist)
9368 (error "Undefined key `%s' as contextual replacement for `%s'"
9369 (cadr repl) (car c)))))
9370 r))))))
9371 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9372 (delq
9374 (delete-dups
9375 (mapcar (lambda (x)
9376 (let ((tpl (car x)))
9377 (when (not (delq
9379 (mapcar (lambda(y)
9380 (equal y tpl)) s))) x)))
9381 (reverse r))))))
9383 (defun org-contextualize-validate-key (key contexts)
9384 "Check CONTEXTS for agenda or capture KEY."
9385 (let (r rr res)
9386 (while (setq r (pop contexts))
9387 (mapc
9388 (lambda (rr)
9389 (when
9390 (and (equal key (car r))
9391 (if (functionp rr) (funcall rr)
9392 (or (and (eq (car rr) 'in-file)
9393 (buffer-file-name)
9394 (string-match (cdr rr) (buffer-file-name)))
9395 (and (eq (car rr) 'in-mode)
9396 (string-match (cdr rr) (symbol-name major-mode)))
9397 (and (eq (car rr) 'in-buffer)
9398 (string-match (cdr rr) (buffer-name)))
9399 (when (and (eq (car rr) 'not-in-file)
9400 (buffer-file-name))
9401 (not (string-match (cdr rr) (buffer-file-name))))
9402 (when (eq (car rr) 'not-in-mode)
9403 (not (string-match (cdr rr) (symbol-name major-mode))))
9404 (when (eq (car rr) 'not-in-buffer)
9405 (not (string-match (cdr rr) (buffer-name)))))))
9406 (push r res)))
9407 (car (last r))))
9408 (delete-dups (delq nil res))))
9410 (defun org-context-p (&rest contexts)
9411 "Check if local context is any of CONTEXTS.
9412 Possible values in the list of contexts are `table', `headline', and `item'."
9413 (let ((pos (point)))
9414 (goto-char (point-at-bol))
9415 (prog1 (or (and (memq 'table contexts)
9416 (looking-at "[ \t]*|"))
9417 (and (memq 'headline contexts)
9418 (looking-at org-outline-regexp))
9419 (and (memq 'item contexts)
9420 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9421 (and (memq 'item-body contexts)
9422 (org-in-item-p)))
9423 (goto-char pos))))
9425 (defun org-get-local-variables ()
9426 "Return a list of all local variables in an Org mode buffer."
9427 (let (varlist)
9428 (with-current-buffer (get-buffer-create "*Org tmp*")
9429 (erase-buffer)
9430 (org-mode)
9431 (setq varlist (buffer-local-variables)))
9432 (kill-buffer "*Org tmp*")
9433 (delq nil
9434 (mapcar
9435 (lambda (x)
9436 (setq x
9437 (if (symbolp x)
9438 (list x)
9439 (list (car x) (cdr x))))
9440 (if (and (not (get (car x) 'org-state))
9441 (string-match
9442 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9443 (symbol-name (car x))))
9444 x nil))
9445 varlist))))
9447 (defun org-clone-local-variables (from-buffer &optional regexp)
9448 "Clone local variables from FROM-BUFFER.
9449 Optional argument REGEXP selects variables to clone."
9450 (mapc
9451 (lambda (pair)
9452 (and (symbolp (car pair))
9453 (or (null regexp)
9454 (string-match regexp (symbol-name (car pair))))
9455 (set (make-local-variable (car pair))
9456 (cdr pair))))
9457 (buffer-local-variables from-buffer)))
9459 ;;;###autoload
9460 (defun org-run-like-in-org-mode (cmd)
9461 "Run a command, pretending that the current buffer is in Org-mode.
9462 This will temporarily bind local variables that are typically bound in
9463 Org-mode to the values they have in Org-mode, and then interactively
9464 call CMD."
9465 (org-load-modules-maybe)
9466 (unless org-local-vars
9467 (setq org-local-vars (org-get-local-variables)))
9468 (let (binds)
9469 (dolist (var org-local-vars)
9470 (when (or (not (boundp (car var)))
9471 (eq (symbol-value (car var))
9472 (default-value (car var))))
9473 (push (list (car var) `(quote ,(cadr var))) binds)))
9474 (eval `(let ,binds
9475 (call-interactively (quote ,cmd))))))
9477 (defun org-get-category (&optional pos force-refresh)
9478 "Get the category applying to position POS."
9479 (save-match-data
9480 (if force-refresh (org-refresh-category-properties))
9481 (let ((pos (or pos (point))))
9482 (or (get-text-property pos 'org-category)
9483 (progn (org-refresh-category-properties)
9484 (get-text-property pos 'org-category))))))
9486 ;;; Refresh properties
9488 (defun org-refresh-properties (dprop tprop)
9489 "Refresh buffer text properties.
9490 DPROP is the drawer property and TPROP is either the
9491 corresponding text property to set, or an alist with each element
9492 being a text property (as a symbol) and a function to apply to
9493 the value of the drawer property."
9494 (let ((case-fold-search t)
9495 (inhibit-read-only t))
9496 (org-with-silent-modifications
9497 (save-excursion
9498 (save-restriction
9499 (widen)
9500 (goto-char (point-min))
9501 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9502 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9504 (defun org-refresh-property (tprop p)
9505 "Refresh the buffer text property TPROP from the drawer property P.
9506 The refresh happens only for the current tree (not subtree)."
9507 (unless (org-before-first-heading-p)
9508 (save-excursion
9509 (org-back-to-heading t)
9510 (if (symbolp tprop)
9511 ;; TPROP is a text property symbol
9512 (put-text-property
9513 (point) (or (outline-next-heading) (point-max)) tprop p)
9514 ;; TPROP is an alist with (properties . function) elements
9515 (dolist (al tprop)
9516 (save-excursion
9517 (put-text-property
9518 (line-beginning-position) (or (outline-next-heading) (point-max))
9519 (car al)
9520 (funcall (cdr al) p))))))))
9522 (defun org-refresh-category-properties ()
9523 "Refresh category text properties in the buffer."
9524 (let ((case-fold-search t)
9525 (inhibit-read-only t)
9526 (default-category
9527 (cond ((null org-category)
9528 (if buffer-file-name
9529 (file-name-sans-extension
9530 (file-name-nondirectory buffer-file-name))
9531 "???"))
9532 ((symbolp org-category) (symbol-name org-category))
9533 (t org-category))))
9534 (org-with-silent-modifications
9535 (org-with-wide-buffer
9536 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9537 ;; This is the default category for the buffer. If none is
9538 ;; found, fall-back to `org-category' or buffer file name.
9539 (put-text-property
9540 (point-min) (point-max)
9541 'org-category
9542 (catch 'buffer-category
9543 (goto-char (point-max))
9544 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9545 (let ((element (org-element-at-point)))
9546 (when (eq (org-element-type element) 'keyword)
9547 (throw 'buffer-category
9548 (org-element-property :value element)))))
9549 default-category))
9550 ;; Set sub-tree specific categories.
9551 (goto-char (point-min))
9552 (let ((regexp (org-re-property "CATEGORY")))
9553 (while (re-search-forward regexp nil t)
9554 (let ((value (org-match-string-no-properties 3)))
9555 (when (org-at-property-p)
9556 (put-text-property
9557 (save-excursion (org-back-to-heading t) (point))
9558 (save-excursion (org-end-of-subtree t t) (point))
9559 'org-category
9560 value)))))))))
9562 (defun org-refresh-stats-properties ()
9563 "Refresh stats text properties in the buffer."
9564 (let (stats)
9565 (org-with-silent-modifications
9566 (save-excursion
9567 (save-restriction
9568 (widen)
9569 (goto-char (point-min))
9570 (while (re-search-forward
9571 (concat org-outline-regexp-bol ".*"
9572 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9573 nil t)
9574 (setq stats (cond ((equal (match-string 3) "0") 0)
9575 ((match-string 2)
9576 (/ (* (string-to-number (match-string 2)) 100)
9577 (string-to-number (match-string 3))))
9578 (t (string-to-number (match-string 1)))))
9579 (org-back-to-heading t)
9580 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9581 'org-stats stats)))))))
9583 (defun org-refresh-effort-properties ()
9584 "Refresh effort properties"
9585 (org-refresh-properties
9586 org-effort-property
9587 '((effort . identity)
9588 (effort-minutes . org-duration-string-to-minutes))))
9590 ;;;; Link Stuff
9592 ;;; Link abbreviations
9594 (defun org-link-expand-abbrev (link)
9595 "Apply replacements as defined in `org-link-abbrev-alist'."
9596 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9597 (let* ((key (match-string 1 link))
9598 (as (or (assoc key org-link-abbrev-alist-local)
9599 (assoc key org-link-abbrev-alist)))
9600 (tag (and (match-end 2) (match-string 3 link)))
9601 rpl)
9602 (if (not as)
9603 link
9604 (setq rpl (cdr as))
9605 (cond
9606 ((symbolp rpl) (funcall rpl tag))
9607 ((string-match "%(\\([^)]+\\))" rpl)
9608 (replace-match
9609 (save-match-data
9610 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9611 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9612 ((string-match "%h" rpl)
9613 (replace-match (url-hexify-string (or tag "")) t t rpl))
9614 (t (concat rpl tag)))))
9615 link))
9617 ;;; Storing and inserting links
9619 (defvar org-insert-link-history nil
9620 "Minibuffer history for links inserted with `org-insert-link'.")
9622 (defvar org-stored-links nil
9623 "Contains the links stored with `org-store-link'.")
9625 (defvar org-store-link-plist nil
9626 "Plist with info about the most recently link created with `org-store-link'.")
9628 (defvar org-link-protocols nil
9629 "Link protocols added to Org-mode using `org-add-link-type'.")
9631 (defvar org-store-link-functions nil
9632 "List of functions that are called to create and store a link.
9633 Each function will be called in turn until one returns a non-nil
9634 value. Each function should check if it is responsible for creating
9635 this link (for example by looking at the major mode).
9636 If not, it must exit and return nil.
9637 If yes, it should return a non-nil value after a calling
9638 `org-store-link-props' with a list of properties and values.
9639 Special properties are:
9641 :type The link prefix, like \"http\". This must be given.
9642 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9643 This is obligatory as well.
9644 :description Optional default description for the second pair
9645 of brackets in an Org-mode link. The user can still change
9646 this when inserting this link into an Org-mode buffer.
9648 In addition to these, any additional properties can be specified
9649 and then used in capture templates.")
9651 (defun org-add-link-type (type &optional follow export)
9652 "Add TYPE to the list of `org-link-types'.
9653 Re-compute all regular expressions depending on `org-link-types'
9655 FOLLOW and EXPORT are two functions.
9657 FOLLOW should take the link path as the single argument and do whatever
9658 is necessary to follow the link, for example find a file or display
9659 a mail message.
9661 EXPORT should format the link path for export to one of the export formats.
9662 It should be a function accepting three arguments:
9664 path the path of the link, the text after the prefix (like \"http:\")
9665 desc the description of the link, if any
9666 format the export format, a symbol like `html' or `latex' or `ascii'.
9668 The function may use the FORMAT information to return different values
9669 depending on the format. The return value will be put literally into
9670 the exported file. If the return value is nil, this means Org should
9671 do what it normally does with links which do not have EXPORT defined.
9673 Org mode has a built-in default for exporting links. If you are happy with
9674 this default, there is no need to define an export function for the link
9675 type. For a simple example of an export function, see `org-bbdb.el'."
9676 (add-to-list 'org-link-types type t)
9677 (org-make-link-regexps)
9678 (org-element-update-syntax)
9679 (if (assoc type org-link-protocols)
9680 (setcdr (assoc type org-link-protocols) (list follow export))
9681 (push (list type follow export) org-link-protocols)))
9683 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9684 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9686 ;;;###autoload
9687 (defun org-store-link (arg)
9688 "\\<org-mode-map>Store an org-link to the current location.
9689 This link is added to `org-stored-links' and can later be inserted
9690 into an Org buffer with \\[org-insert-link].
9692 For some link types, a prefix ARG is interpreted.
9693 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9694 For file links, ARG negates `org-context-in-file-links'.
9696 A double prefix ARG force skipping storing functions that are not
9697 part of Org's core.
9699 A triple prefix ARG force storing a link for each line in the
9700 active region."
9701 (interactive "P")
9702 (org-load-modules-maybe)
9703 (if (and (equal arg '(64)) (org-region-active-p))
9704 (save-excursion
9705 (let ((end (region-end)))
9706 (goto-char (region-beginning))
9707 (set-mark (point))
9708 (while (< (point-at-eol) end)
9709 (move-end-of-line 1) (activate-mark)
9710 (let (current-prefix-arg)
9711 (call-interactively 'org-store-link))
9712 (move-beginning-of-line 2)
9713 (set-mark (point)))))
9714 (org-with-limited-levels
9715 (setq org-store-link-plist nil)
9716 (let (link cpltxt desc description search
9717 txt custom-id agenda-link sfuns sfunsn)
9718 (cond
9720 ;; Store a link using an external link type
9721 ((and (not (equal arg '(16)))
9722 (setq sfuns
9723 (delq
9724 nil (mapcar (lambda (f)
9725 (let (fs) (if (funcall f) (push f fs))))
9726 org-store-link-functions))
9727 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9728 (or (and (cdr sfuns)
9729 (funcall (intern
9730 (completing-read
9731 "Which function for creating the link? "
9732 sfunsn nil t (car sfunsn)))))
9733 (funcall (caar sfuns)))
9734 (setq link (plist-get org-store-link-plist :link)
9735 desc (or (plist-get org-store-link-plist
9736 :description) link))))
9738 ;; Store a link from a source code buffer.
9739 ((org-src-edit-buffer-p)
9740 (cond
9741 ((save-excursion
9742 (beginning-of-line)
9743 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9744 "[ \t]*$")))
9745 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9746 ((org-called-interactively-p 'any)
9747 (let (label)
9748 (while (or (not label)
9749 (org-with-wide-buffer
9750 (goto-char (point-min))
9751 (re-search-forward
9752 (regexp-quote (format org-coderef-label-format label))
9753 nil t)))
9754 (when label (message "Label exists already") (sit-for 2))
9755 (setq label (read-string "Code line label: " label)))
9756 (end-of-line)
9757 (setq link (format org-coderef-label-format label))
9758 (let ((gc (- 79 (length link))))
9759 (if (< (current-column) gc) (org-move-to-column gc t)
9760 (insert " ")))
9761 (insert link)
9762 (setq link (concat "(" label ")") desc nil)))
9763 (t (setq link nil))))
9765 ;; We are in the agenda, link to referenced location
9766 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9767 (let ((m (or (get-text-property (point) 'org-hd-marker)
9768 (get-text-property (point) 'org-marker))))
9769 (when m
9770 (org-with-point-at m
9771 (setq agenda-link
9772 (if (org-called-interactively-p 'any)
9773 (call-interactively 'org-store-link)
9774 (org-store-link nil)))))))
9776 ((eq major-mode 'calendar-mode)
9777 (let ((cd (calendar-cursor-to-date)))
9778 (setq link
9779 (format-time-string
9780 (car org-time-stamp-formats)
9781 (apply 'encode-time
9782 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9783 nil nil nil))))
9784 (org-store-link-props :type "calendar" :date cd)))
9786 ((eq major-mode 'help-mode)
9787 (setq link (concat "help:" (save-excursion
9788 (goto-char (point-min))
9789 (looking-at "^[^ ]+")
9790 (match-string 0))))
9791 (org-store-link-props :type "help"))
9793 ((eq major-mode 'w3-mode)
9794 (setq cpltxt (if (and (buffer-name)
9795 (not (string-match "Untitled" (buffer-name))))
9796 (buffer-name)
9797 (url-view-url t))
9798 link (url-view-url t))
9799 (org-store-link-props :type "w3" :url (url-view-url t)))
9801 ((eq major-mode 'image-mode)
9802 (setq cpltxt (concat "file:"
9803 (abbreviate-file-name buffer-file-name))
9804 link cpltxt)
9805 (org-store-link-props :type "image" :file buffer-file-name))
9807 ;; In dired, store a link to the file of the current line
9808 ((derived-mode-p 'dired-mode)
9809 (let ((file (dired-get-filename nil t)))
9810 (setq file (if file
9811 (abbreviate-file-name
9812 (expand-file-name (dired-get-filename nil t)))
9813 ;; otherwise, no file so use current directory.
9814 default-directory))
9815 (setq cpltxt (concat "file:" file)
9816 link cpltxt)))
9818 ((setq search (run-hook-with-args-until-success
9819 'org-create-file-search-functions))
9820 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9821 "::" search))
9822 (setq cpltxt (or description link)))
9824 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9825 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9826 (cond
9827 ;; Store a link using the target at point
9828 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9829 (setq cpltxt
9830 (concat "file:"
9831 (abbreviate-file-name
9832 (buffer-file-name (buffer-base-buffer)))
9833 "::" (match-string 1))
9834 link cpltxt))
9835 ((and (featurep 'org-id)
9836 (or (eq org-id-link-to-org-use-id t)
9837 (and (org-called-interactively-p 'any)
9838 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9839 (and (eq org-id-link-to-org-use-id
9840 'create-if-interactive-and-no-custom-id)
9841 (not custom-id))))
9842 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9843 ;; Store a link using the ID at point
9844 (setq link (condition-case nil
9845 (prog1 (org-id-store-link)
9846 (setq desc (or (plist-get org-store-link-plist
9847 :description)
9848 "")))
9849 (error
9850 ;; Probably before first headline, link only to file
9851 (concat "file:"
9852 (abbreviate-file-name
9853 (buffer-file-name (buffer-base-buffer))))))))
9855 ;; Just link to current headline
9856 (setq cpltxt (concat "file:"
9857 (abbreviate-file-name
9858 (buffer-file-name (buffer-base-buffer)))))
9859 ;; Add a context search string
9860 (when (org-xor org-context-in-file-links arg)
9861 (let* ((ee (org-element-at-point))
9862 (et (org-element-type ee))
9863 (ev (plist-get (cadr ee) :value))
9864 (ek (plist-get (cadr ee) :key))
9865 (eok (and (stringp ek) (string-match "name" ek))))
9866 (setq txt (cond
9867 ((org-at-heading-p) nil)
9868 ((and (eq et 'keyword) eok) ev)
9869 ((org-region-active-p)
9870 (buffer-substring (region-beginning) (region-end)))))
9871 (when (or (null txt) (string-match "\\S-" txt))
9872 (setq cpltxt
9873 (concat cpltxt "::"
9874 (condition-case nil
9875 (org-make-org-heading-search-string txt)
9876 (error "")))
9877 desc (or (and (eq et 'keyword) eok ev)
9878 (nth 4 (ignore-errors (org-heading-components)))
9879 "NONE")))))
9880 (if (string-match "::\\'" cpltxt)
9881 (setq cpltxt (substring cpltxt 0 -2)))
9882 (setq link cpltxt))))
9884 ((buffer-file-name (buffer-base-buffer))
9885 ;; Just link to this file here.
9886 (setq cpltxt (concat "file:"
9887 (abbreviate-file-name
9888 (buffer-file-name (buffer-base-buffer)))))
9889 ;; Add a context string.
9890 (when (org-xor org-context-in-file-links arg)
9891 (setq txt (if (org-region-active-p)
9892 (buffer-substring (region-beginning) (region-end))
9893 (buffer-substring (point-at-bol) (point-at-eol))))
9894 ;; Only use search option if there is some text.
9895 (when (string-match "\\S-" txt)
9896 (setq cpltxt
9897 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9898 desc "NONE")))
9899 (setq link cpltxt))
9901 ((org-called-interactively-p 'interactive)
9902 (user-error "No method for storing a link from this buffer"))
9904 (t (setq link nil)))
9906 ;; We're done setting link and desc, clean up
9907 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9908 (setq link (or link cpltxt)
9909 desc (or desc cpltxt))
9910 (cond ((equal desc "NONE") (setq desc nil))
9911 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9912 (let ((d0 (match-string 3 desc))
9913 (p0 (match-string 5 desc)))
9914 (setq desc
9915 (replace-regexp-in-string
9916 org-bracket-link-regexp
9917 (concat (or p0 d0)
9918 (if (equal (length (match-string 0 desc))
9919 (length desc)) "*" "")) desc)))))
9921 ;; Return the link
9922 (if (not (and (or (org-called-interactively-p 'any)
9923 executing-kbd-macro) link))
9924 (or agenda-link (and link (org-make-link-string link desc)))
9925 (push (list link desc) org-stored-links)
9926 (message "Stored: %s" (or desc link))
9927 (when custom-id
9928 (setq link (concat "file:" (abbreviate-file-name
9929 (buffer-file-name)) "::#" custom-id))
9930 (push (list link desc) org-stored-links))
9931 (car org-stored-links))))))
9933 (defun org-store-link-props (&rest plist)
9934 "Store link properties, extract names and addresses."
9935 (let (x adr)
9936 (when (setq x (plist-get plist :from))
9937 (setq adr (mail-extract-address-components x))
9938 (setq plist (plist-put plist :fromname (car adr)))
9939 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9940 (when (setq x (plist-get plist :to))
9941 (setq adr (mail-extract-address-components x))
9942 (setq plist (plist-put plist :toname (car adr)))
9943 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9944 (let ((from (plist-get plist :from))
9945 (to (plist-get plist :to)))
9946 (when (and from to org-from-is-user-regexp)
9947 (setq plist
9948 (plist-put plist :fromto
9949 (if (string-match org-from-is-user-regexp from)
9950 (concat "to %t")
9951 (concat "from %f"))))))
9952 (setq org-store-link-plist plist))
9954 (defun org-add-link-props (&rest plist)
9955 "Add these properties to the link property list."
9956 (let (key value)
9957 (while plist
9958 (setq key (pop plist) value (pop plist))
9959 (setq org-store-link-plist
9960 (plist-put org-store-link-plist key value)))))
9962 (defun org-email-link-description (&optional fmt)
9963 "Return the description part of an email link.
9964 This takes information from `org-store-link-plist' and formats it
9965 according to FMT (default from `org-email-link-description-format')."
9966 (setq fmt (or fmt org-email-link-description-format))
9967 (let* ((p org-store-link-plist)
9968 (to (plist-get p :toaddress))
9969 (from (plist-get p :fromaddress))
9970 (table
9971 (list
9972 (cons "%c" (plist-get p :fromto))
9973 (cons "%F" (plist-get p :from))
9974 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9975 (cons "%T" (plist-get p :to))
9976 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9977 (cons "%s" (plist-get p :subject))
9978 (cons "%d" (plist-get p :date))
9979 (cons "%m" (plist-get p :message-id)))))
9980 (when (string-match "%c" fmt)
9981 ;; Check if the user wrote this message
9982 (if (and org-from-is-user-regexp from to
9983 (save-match-data (string-match org-from-is-user-regexp from)))
9984 (setq fmt (replace-match "to %t" t t fmt))
9985 (setq fmt (replace-match "from %f" t t fmt))))
9986 (org-replace-escapes fmt table)))
9988 (defun org-make-org-heading-search-string (&optional string)
9989 "Make search string for the current headline or STRING."
9990 (let ((s (or string
9991 (and (derived-mode-p 'org-mode)
9992 (save-excursion
9993 (org-back-to-heading t)
9994 (org-element-property :raw-value (org-element-at-point))))))
9995 (lines org-context-in-file-links))
9996 (or string (setq s (concat "*" s))) ; Add * for headlines
9997 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9998 (when (and string (integerp lines) (> lines 0))
9999 (let ((slines (org-split-string s "\n")))
10000 (when (< lines (length slines))
10001 (setq s (mapconcat
10002 'identity
10003 (reverse (nthcdr (- (length slines) lines)
10004 (reverse slines))) "\n")))))
10005 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10007 (defun org-make-link-string (link &optional description)
10008 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10009 (unless (org-string-nw-p link) (error "Empty link"))
10010 (let ((uri (cond ((string-match org-link-types-re link)
10011 (concat (match-string 1 link)
10012 (org-link-escape (substring link (match-end 1)))))
10013 ;; For readability, url-encode internal links only
10014 ;; when absolutely needed (i.e, when they contain
10015 ;; square brackets). File links however, are
10016 ;; encoded since, e.g., spaces are significant.
10017 ((or (file-name-absolute-p link)
10018 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
10019 (org-link-escape link))
10020 (t link)))
10021 (description
10022 (and (org-string-nw-p description)
10023 ;; Remove brackets from description, as they are fatal.
10024 (replace-regexp-in-string
10025 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10026 (org-trim description)))))
10027 (format "[[%s]%s]"
10029 (if description (format "[%s]" description) ""))))
10031 (defconst org-link-escape-chars
10032 ;;%20 %5B %5D %25
10033 '(?\s ?\[ ?\] ?%)
10034 "List of characters that should be escaped in a link when stored to Org.
10035 This is the list that is used for internal purposes.")
10037 (defconst org-link-escape-chars-browser
10038 ;;%20 %22
10039 '(?\s ?\")
10040 "List of characters to be escaped before handing over to the browser.
10041 If you consider using this constant then you probably want to use
10042 the function `org-link-escape-browser' instead. See there why
10043 this constant is a candidate to be removed once Org drops support
10044 for Emacs 24.1 and 24.2.")
10046 (defun org-link-escape (text &optional table merge)
10047 "Return percent escaped representation of TEXT.
10048 TEXT is a string with the text to escape.
10049 Optional argument TABLE is a list with characters that should be
10050 escaped. When nil, `org-link-escape-chars' is used.
10051 If optional argument MERGE is set, merge TABLE into
10052 `org-link-escape-chars'."
10053 (let ((characters-to-encode
10054 (cond ((null table) org-link-escape-chars)
10055 (merge (append org-link-escape-chars table))
10056 (t table))))
10057 (mapconcat
10058 (lambda (c)
10059 (if (or (memq c characters-to-encode)
10060 (and org-url-hexify-p (or (< c 32) (> c 126))))
10061 (mapconcat (lambda (e) (format "%%%.2X" e))
10062 (or (encode-coding-char c 'utf-8)
10063 (error "Unable to percent escape character: %c" c))
10065 (char-to-string c)))
10066 text "")))
10068 (defun org-link-escape-browser (text)
10069 "Escape some characters before handing over to the browser.
10070 This function is a candidate to be removed together with the
10071 constant `org-link-escape-chars-browser' once Org drops support
10072 for Emacs 24.1 and 24.2. All calls to this function will have to
10073 be replaced with `url-encode-url' which is available since Emacs
10074 24.3.1."
10075 ;; Example with the Org link
10076 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10077 ;; to open the browser with +subject:"Release 8.2" filled into the
10078 ;; query field: In this case the variable TEXT contains the
10079 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10080 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10081 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10082 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10083 (if (fboundp 'url-encode-url)
10084 (url-encode-url text)
10085 (if (org-string-match-p
10086 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10087 text)
10088 (org-link-escape text org-link-escape-chars-browser)
10089 text)))
10091 (defun org-link-unescape (str)
10092 "Unhex hexified Unicode parts in string STR.
10093 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10094 reciprocal of `org-link-escape', which see."
10095 (if (org-string-nw-p str)
10096 (replace-regexp-in-string
10097 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10098 str))
10100 (defun org-link-unescape-compound (hex)
10101 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10102 Note: this function also decodes single byte encodings like
10103 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10104 (save-match-data
10105 (let* ((bytes (cdr (split-string hex "%")))
10106 (ret "")
10107 (eat 0)
10108 (sum 0))
10109 (while bytes
10110 (let* ((val (string-to-number (pop bytes) 16))
10111 (shift-xor
10112 (if (= 0 eat)
10113 (cond
10114 ((>= val 252) (cons 6 252))
10115 ((>= val 248) (cons 5 248))
10116 ((>= val 240) (cons 4 240))
10117 ((>= val 224) (cons 3 224))
10118 ((>= val 192) (cons 2 192))
10119 (t (cons 0 0)))
10120 (cons 6 128))))
10121 (if (>= val 192) (setq eat (car shift-xor)))
10122 (setq val (logxor val (cdr shift-xor)))
10123 (setq sum (+ (lsh sum (car shift-xor)) val))
10124 (if (> eat 0) (setq eat (- eat 1)))
10125 (cond
10126 ((= 0 eat) ;multi byte
10127 (setq ret (concat ret (org-char-to-string sum)))
10128 (setq sum 0))
10129 ((not bytes) ; single byte(s)
10130 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10131 ret)))
10133 (defun org-link-unescape-single-byte-sequence (hex)
10134 "Unhexify hex-encoded single byte character sequences."
10135 (mapconcat (lambda (byte)
10136 (char-to-string (string-to-number byte 16)))
10137 (cdr (split-string hex "%")) ""))
10139 (defun org-xor (a b)
10140 "Exclusive or."
10141 (if a (not b) b))
10143 (defun org-fixup-message-id-for-http (s)
10144 "Replace special characters in a message id, so it can be used in an http query."
10145 (when (string-match "%" s)
10146 (setq s (mapconcat (lambda (c)
10147 (if (eq c ?%)
10148 "%25"
10149 (char-to-string c)))
10150 s "")))
10151 (while (string-match "<" s)
10152 (setq s (replace-match "%3C" t t s)))
10153 (while (string-match ">" s)
10154 (setq s (replace-match "%3E" t t s)))
10155 (while (string-match "@" s)
10156 (setq s (replace-match "%40" t t s)))
10159 (defun org-link-prettify (link)
10160 "Return a human-readable representation of LINK.
10161 The car of LINK must be a raw link.
10162 The cdr of LINK must be either a link description or nil."
10163 (let ((desc (or (cadr link) "<no description>")))
10164 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10165 "<" (car link) ">")))
10167 ;;;###autoload
10168 (defun org-insert-link-global ()
10169 "Insert a link like Org-mode does.
10170 This command can be called in any mode to insert a link in Org-mode syntax."
10171 (interactive)
10172 (org-load-modules-maybe)
10173 (org-run-like-in-org-mode 'org-insert-link))
10175 (defun org-insert-all-links (arg &optional pre post)
10176 "Insert all links in `org-stored-links'.
10177 When a universal prefix, do not delete the links from `org-stored-links'.
10178 When `ARG' is a number, insert the last N link(s).
10179 `PRE' and `POST' are optional arguments to define a string to
10180 prepend or to append."
10181 (interactive "P")
10182 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10183 (links (copy-seq org-stored-links))
10184 (pr (or pre "- "))
10185 (po (or post "\n"))
10186 (cnt 1) l)
10187 (if (null org-stored-links)
10188 (message "No link to insert")
10189 (while (and (or (listp arg) (>= arg cnt))
10190 (setq l (if (listp arg)
10191 (pop links)
10192 (pop org-stored-links))))
10193 (setq cnt (1+ cnt))
10194 (insert pr)
10195 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10196 (insert po)))))
10198 (defun org-insert-last-stored-link (arg)
10199 "Insert the last link stored in `org-stored-links'."
10200 (interactive "p")
10201 (org-insert-all-links arg "" "\n"))
10203 (defun org-link-fontify-links-to-this-file ()
10204 "Fontify links to the current file in `org-stored-links'."
10205 (let ((f (buffer-file-name)) a b)
10206 (setq a (mapcar (lambda(l)
10207 (let ((ll (car l)))
10208 (when (and (string-match "^file:\\(.+\\)::" ll)
10209 (equal f (expand-file-name (match-string 1 ll))))
10210 ll)))
10211 org-stored-links))
10212 (when (featurep 'org-id)
10213 (setq b (mapcar (lambda(l)
10214 (let ((ll (car l)))
10215 (when (and (string-match "^id:\\(.+\\)$" ll)
10216 (equal f (expand-file-name
10217 (or (org-id-find-id-file
10218 (match-string 1 ll)) ""))))
10219 ll)))
10220 org-stored-links)))
10221 (mapcar (lambda(l)
10222 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10223 (delq nil (append a b)))))
10225 (defvar org-link-links-in-this-file nil)
10226 (defun org-insert-link (&optional complete-file link-location default-description)
10227 "Insert a link. At the prompt, enter the link.
10229 Completion can be used to insert any of the link protocol prefixes like
10230 http or ftp in use.
10232 The history can be used to select a link previously stored with
10233 `org-store-link'. When the empty string is entered (i.e. if you just
10234 press RET at the prompt), the link defaults to the most recently
10235 stored link. As SPC triggers completion in the minibuffer, you need to
10236 use M-SPC or C-q SPC to force the insertion of a space character.
10238 You will also be prompted for a description, and if one is given, it will
10239 be displayed in the buffer instead of the link.
10241 If there is already a link at point, this command will allow you to edit link
10242 and description parts.
10244 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10245 be selected using completion. The path to the file will be relative to the
10246 current directory if the file is in the current directory or a subdirectory.
10247 Otherwise, the link will be the absolute path as completed in the minibuffer
10248 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10249 option `org-link-file-path-type'.
10251 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10252 the current directory or below.
10254 With three \\[universal-argument] prefixes, negate the meaning of
10255 `org-keep-stored-link-after-insertion'.
10257 If `org-make-link-description-function' is non-nil, this function will be
10258 called with the link target, and the result will be the default
10259 link description.
10261 If the LINK-LOCATION parameter is non-nil, this value will be
10262 used as the link location instead of reading one interactively.
10264 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10265 be used as the default description."
10266 (interactive "P")
10267 (let* ((wcf (current-window-configuration))
10268 (origbuf (current-buffer))
10269 (region (if (org-region-active-p)
10270 (buffer-substring (region-beginning) (region-end))))
10271 (remove (and region (list (region-beginning) (region-end))))
10272 (desc region)
10273 tmphist ; byte-compile incorrectly complains about this
10274 (link link-location)
10275 (abbrevs org-link-abbrev-alist-local)
10276 entry file all-prefixes auto-desc)
10277 (cond
10278 (link-location) ; specified by arg, just use it.
10279 ((org-in-regexp org-bracket-link-regexp 1)
10280 ;; We do have a link at point, and we are going to edit it.
10281 (setq remove (list (match-beginning 0) (match-end 0)))
10282 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10283 (setq link (read-string "Link: "
10284 (org-link-unescape
10285 (org-match-string-no-properties 1)))))
10286 ((or (org-in-regexp org-angle-link-re)
10287 (org-in-regexp org-plain-link-re))
10288 ;; Convert to bracket link
10289 (setq remove (list (match-beginning 0) (match-end 0))
10290 link (read-string "Link: "
10291 (org-remove-angle-brackets (match-string 0)))))
10292 ((member complete-file '((4) (16)))
10293 ;; Completing read for file names.
10294 (setq link (org-file-complete-link complete-file)))
10296 ;; Read link, with completion for stored links.
10297 (org-link-fontify-links-to-this-file)
10298 (org-switch-to-buffer-other-window "*Org Links*")
10299 (with-current-buffer "*Org Links*"
10300 (erase-buffer)
10301 (insert "Insert a link.
10302 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10303 (when org-stored-links
10304 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10305 (insert (mapconcat 'org-link-prettify
10306 (reverse org-stored-links) "\n")))
10307 (goto-char (point-min)))
10308 (let ((cw (selected-window)))
10309 (select-window (get-buffer-window "*Org Links*" 'visible))
10310 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10311 (unless (pos-visible-in-window-p (point-max))
10312 (org-fit-window-to-buffer))
10313 (and (window-live-p cw) (select-window cw)))
10314 ;; Fake a link history, containing the stored links.
10315 (setq tmphist (append (mapcar 'car org-stored-links)
10316 org-insert-link-history))
10317 (setq all-prefixes (append (mapcar 'car abbrevs)
10318 (mapcar 'car org-link-abbrev-alist)
10319 org-link-types))
10320 (unwind-protect
10321 (progn
10322 (setq link
10323 (org-completing-read
10324 "Link: "
10325 (append
10326 (mapcar (lambda (x) (concat x ":"))
10327 all-prefixes)
10328 (mapcar 'car org-stored-links))
10329 nil nil nil
10330 'tmphist
10331 (caar org-stored-links)))
10332 (if (not (string-match "\\S-" link))
10333 (user-error "No link selected"))
10334 (mapc (lambda(l)
10335 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10336 org-stored-links)
10337 (if (or (member link all-prefixes)
10338 (and (equal ":" (substring link -1))
10339 (member (substring link 0 -1) all-prefixes)
10340 (setq link (substring link 0 -1))))
10341 (setq link (with-current-buffer origbuf
10342 (org-link-try-special-completion link)))))
10343 (set-window-configuration wcf)
10344 (kill-buffer "*Org Links*"))
10345 (setq entry (assoc link org-stored-links))
10346 (or entry (push link org-insert-link-history))
10347 (setq desc (or desc (nth 1 entry)))))
10349 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10350 (not org-keep-stored-link-after-insertion))
10351 (setq org-stored-links (delq (assoc link org-stored-links)
10352 org-stored-links)))
10354 (if (and (string-match org-plain-link-re link)
10355 (not (string-match org-ts-regexp link)))
10356 ;; URL-like link, normalize the use of angular brackets.
10357 (setq link (org-remove-angle-brackets link)))
10359 ;; Check if we are linking to the current file with a search
10360 ;; option If yes, simplify the link by using only the search
10361 ;; option.
10362 (when (and buffer-file-name
10363 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10364 (let* ((path (match-string 1 link))
10365 (case-fold-search nil)
10366 (search (match-string 2 link)))
10367 (save-match-data
10368 (if (equal (file-truename buffer-file-name) (file-truename path))
10369 ;; We are linking to this same file, with a search option
10370 (setq link search)))))
10372 ;; Check if we can/should use a relative path. If yes, simplify the link
10373 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10374 (let* ((type (match-string 1 link))
10375 (path (match-string 2 link))
10376 (origpath path)
10377 (case-fold-search nil))
10378 (cond
10379 ((or (eq org-link-file-path-type 'absolute)
10380 (equal complete-file '(16)))
10381 (setq path (abbreviate-file-name (expand-file-name path))))
10382 ((eq org-link-file-path-type 'noabbrev)
10383 (setq path (expand-file-name path)))
10384 ((eq org-link-file-path-type 'relative)
10385 (setq path (file-relative-name path)))
10387 (save-match-data
10388 (if (string-match (concat "^" (regexp-quote
10389 (expand-file-name
10390 (file-name-as-directory
10391 default-directory))))
10392 (expand-file-name path))
10393 ;; We are linking a file with relative path name.
10394 (setq path (substring (expand-file-name path)
10395 (match-end 0)))
10396 (setq path (abbreviate-file-name (expand-file-name path)))))))
10397 (setq link (concat type path))
10398 (if (equal desc origpath)
10399 (setq desc path))))
10401 (if org-make-link-description-function
10402 (setq desc
10403 (or (condition-case nil
10404 (funcall org-make-link-description-function link desc)
10405 (error (progn (message "Can't get link description from `%s'"
10406 (symbol-name org-make-link-description-function))
10407 (sit-for 2) nil)))
10408 (read-string "Description: " default-description)))
10409 (if default-description (setq desc default-description)
10410 (setq desc (or (and auto-desc desc)
10411 (read-string "Description: " desc)))))
10413 (unless (string-match "\\S-" desc) (setq desc nil))
10414 (if remove (apply 'delete-region remove))
10415 (insert (org-make-link-string link desc))))
10417 (defun org-link-try-special-completion (type)
10418 "If there is completion support for link type TYPE, offer it."
10419 (let ((fun (intern (concat "org-" type "-complete-link"))))
10420 (if (functionp fun)
10421 (funcall fun)
10422 (read-string "Link (no completion support): " (concat type ":")))))
10424 (defun org-file-complete-link (&optional arg)
10425 "Create a file link using completion."
10426 (let ((file (org-iread-file-name "File: "))
10427 (pwd (file-name-as-directory (expand-file-name ".")))
10428 (pwd1 (file-name-as-directory (abbreviate-file-name
10429 (expand-file-name ".")))))
10430 (cond ((equal arg '(16))
10431 (concat "file:"
10432 (abbreviate-file-name (expand-file-name file))))
10433 ((string-match
10434 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10435 (concat "file:" (match-string 1 file)))
10436 ((string-match
10437 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10438 (expand-file-name file))
10439 (concat "file:"
10440 (match-string 1 (expand-file-name file))))
10441 (t (concat "file:" file)))))
10443 (defun org-iread-file-name (&rest args)
10444 "Read-file-name using `ido-mode' speedup if available.
10445 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10446 See `read-file-name' for a description of parameters."
10447 (org-without-partial-completion
10448 (if (and org-completion-use-ido
10449 (fboundp 'ido-read-file-name)
10450 (org-bound-and-true-p ido-mode)
10451 (listp (nth 1 args)))
10452 (let ((ido-enter-matching-directory nil))
10453 (apply #'ido-read-file-name args))
10454 (apply #'read-file-name args))))
10456 (defun org-completing-read (&rest args)
10457 "Completing-read with SPACE being a normal character."
10458 (let ((enable-recursive-minibuffers t)
10459 (minibuffer-local-completion-map
10460 (copy-keymap minibuffer-local-completion-map)))
10461 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10462 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10463 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10464 (apply 'org-icompleting-read args)))
10466 (defun org-completing-read-no-i (&rest args)
10467 (let (org-completion-use-ido org-completion-use-iswitchb)
10468 (apply 'org-completing-read args)))
10470 (defun org-iswitchb-completing-read (prompt choices &rest args)
10471 "Use iswitch as a completing-read replacement to choose from choices.
10472 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10473 from."
10474 (let* ((iswitchb-use-virtual-buffers nil)
10475 (iswitchb-make-buflist-hook
10476 (lambda ()
10477 (setq iswitchb-temp-buflist choices))))
10478 (iswitchb-read-buffer prompt)))
10480 (defun org-icompleting-read (&rest args)
10481 "Completing-read using `ido-mode' or `iswitchb' speedups if available.
10482 Should be called like `completing-read'."
10483 (org-without-partial-completion
10484 (if (not (listp (nth 1 args)))
10485 ;; Ido only supports lists as the COLLECTION argument. Use
10486 ;; default completion function when second argument is not
10487 ;; a list.
10488 (apply #'completing-read args)
10489 (let ((ido-enter-matching-directory nil))
10490 (apply (cond ((and org-completion-use-ido
10491 (fboundp 'ido-completing-read)
10492 (org-bound-and-true-p ido-mode))
10493 #'ido-completing-read)
10494 ((and org-completion-use-iswitchb
10495 (org-bound-and-true-p iswitchb-mode))
10496 #'org-iswitchb-completing-read)
10497 (t #'completing-read))
10498 args)))))
10500 ;;; Opening/following a link
10502 (defvar org-link-search-failed nil)
10504 (defvar org-open-link-functions nil
10505 "Hook for functions finding a plain text link.
10506 These functions must take a single argument, the link content.
10507 They will be called for links that look like [[link text][description]]
10508 when LINK TEXT does not have a protocol like \"http:\" and does not look
10509 like a filename (e.g. \"./blue.png\").
10511 These functions will be called *before* Org attempts to resolve the
10512 link by doing text searches in the current buffer - so if you want a
10513 link \"[[target]]\" to still find \"<<target>>\", your function should
10514 handle this as a special case.
10516 When the function does handle the link, it must return a non-nil value.
10517 If it decides that it is not responsible for this link, it must return
10518 nil to indicate that that Org-mode can continue with other options
10519 like exact and fuzzy text search.")
10521 (defun org-next-link (&optional search-backward)
10522 "Move forward to the next link.
10523 If the link is in hidden text, expose it."
10524 (interactive "P")
10525 (when (and org-link-search-failed (eq this-command last-command))
10526 (goto-char (point-min))
10527 (message "Link search wrapped back to beginning of buffer"))
10528 (setq org-link-search-failed nil)
10529 (let* ((pos (point))
10530 (ct (org-context))
10531 (a (assoc :link ct))
10532 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10533 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10534 ((looking-at org-any-link-re)
10535 ;; Don't stay stuck at link without an org-link face
10536 (forward-char (if search-backward -1 1))))
10537 (if (funcall srch-fun org-any-link-re nil t)
10538 (progn
10539 (goto-char (match-beginning 0))
10540 (if (outline-invisible-p) (org-show-context)))
10541 (goto-char pos)
10542 (setq org-link-search-failed t)
10543 (message "No further link found"))))
10545 (defun org-previous-link ()
10546 "Move backward to the previous link.
10547 If the link is in hidden text, expose it."
10548 (interactive)
10549 (funcall 'org-next-link t))
10551 (defun org-translate-link (s)
10552 "Translate a link string if a translation function has been defined."
10553 (if (and org-link-translation-function
10554 (fboundp org-link-translation-function)
10555 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10556 (progn
10557 (setq s (funcall org-link-translation-function
10558 (match-string 1 s) (match-string 2 s)))
10559 (concat (car s) ":" (cdr s)))
10562 (defun org-translate-link-from-planner (type path)
10563 "Translate a link from Emacs Planner syntax so that Org can follow it.
10564 This is still an experimental function, your mileage may vary."
10565 (cond
10566 ((member type '("http" "https" "news" "ftp"))
10567 ;; standard Internet links are the same.
10568 nil)
10569 ((and (equal type "irc") (string-match "^//" path))
10570 ;; Planner has two / at the beginning of an irc link, we have 1.
10571 ;; We should have zero, actually....
10572 (setq path (substring path 1)))
10573 ((and (equal type "lisp") (string-match "^/" path))
10574 ;; Planner has a slash, we do not.
10575 (setq type "elisp" path (substring path 1)))
10576 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10577 ;; A typical message link. Planner has the id after the final slash,
10578 ;; we separate it with a hash mark
10579 (setq path (concat (match-string 1 path) "#"
10580 (org-remove-angle-brackets (match-string 2 path))))))
10581 (cons type path))
10583 (defun org-find-file-at-mouse (ev)
10584 "Open file link or URL at mouse."
10585 (interactive "e")
10586 (mouse-set-point ev)
10587 (org-open-at-point 'in-emacs))
10589 (defun org-open-at-mouse (ev)
10590 "Open file link or URL at mouse.
10591 See the docstring of `org-open-file' for details."
10592 (interactive "e")
10593 (mouse-set-point ev)
10594 (if (eq major-mode 'org-agenda-mode)
10595 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10596 (org-open-at-point))
10598 (defvar org-window-config-before-follow-link nil
10599 "The window configuration before following a link.
10600 This is saved in case the need arises to restore it.")
10602 (defvar org-open-link-marker (make-marker)
10603 "Marker pointing to the location where `org-open-at-point' was called.")
10605 ;;;###autoload
10606 (defun org-open-at-point-global ()
10607 "Follow a link like Org-mode does.
10608 This command can be called in any mode to follow a link that has
10609 Org-mode syntax."
10610 (interactive)
10611 (org-run-like-in-org-mode 'org-open-at-point))
10613 ;;;###autoload
10614 (defun org-open-link-from-string (s &optional arg reference-buffer)
10615 "Open a link in the string S, as if it was in Org-mode."
10616 (interactive "sLink: \nP")
10617 (let ((reference-buffer (or reference-buffer (current-buffer))))
10618 (with-temp-buffer
10619 (let ((org-inhibit-startup (not reference-buffer)))
10620 (org-mode)
10621 (insert s)
10622 (goto-char (point-min))
10623 (when reference-buffer
10624 (setq org-link-abbrev-alist-local
10625 (with-current-buffer reference-buffer
10626 org-link-abbrev-alist-local)))
10627 (org-open-at-point arg reference-buffer)))))
10629 (defvar org-open-at-point-functions nil
10630 "Hook that is run when following a link at point.
10632 Functions in this hook must return t if they identify and follow
10633 a link at point. If they don't find anything interesting at point,
10634 they must return nil.")
10636 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10637 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10638 (defun org-open-at-point (&optional arg reference-buffer)
10639 "Open link, timestamp, footnote or tags at point.
10641 When point is on a link, follow it. Normally, files will be
10642 opened by an appropriate application. If the optional prefix
10643 argument ARG is non-nil, Emacs will visit the file. With
10644 a double prefix argument, try to open outside of Emacs, in the
10645 application the system uses for this file type.
10647 When point is on a timestamp, open the agenda at the day
10648 specified.
10650 When point is a footnote definition, move to the first reference
10651 found. If it is on a reference, move to the associated
10652 definition.
10654 When point is on a headline, display a list of every link in the
10655 entry, so it is possible to pick one, or all, of them. If point
10656 is on a tag, call `org-tags-view' instead.
10658 When optional argument REFERENCE-BUFFER is non-nil, it should
10659 specify a buffer from where the link search should happen. This
10660 is used internally by `org-open-link-from-string'.
10662 On top of syntactically correct links, this function will open
10663 the link at point in comments or comment blocks and the first
10664 link in a property drawer line."
10665 (interactive "P")
10666 ;; On a code block, open block's results.
10667 (unless (call-interactively 'org-babel-open-src-block-result)
10668 (org-load-modules-maybe)
10669 (move-marker org-open-link-marker (point))
10670 (setq org-window-config-before-follow-link (current-window-configuration))
10671 (org-remove-occur-highlights nil nil t)
10672 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10673 (let* ((context
10674 ;; Only consider supported types, even if they are not
10675 ;; the closest one.
10676 (org-element-lineage
10677 (org-element-context)
10678 '(comment comment-block footnote-definition footnote-reference
10679 headline inlinetask keyword link node-property
10680 timestamp)
10682 (type (org-element-type context))
10683 (value (org-element-property :value context)))
10684 (cond
10685 ((not context) (user-error "No link found"))
10686 ;; Exception: open timestamps and links in properties
10687 ;; drawers, keywords and comments.
10688 ((memq type '(comment comment-block keyword node-property))
10689 (cond ((org-in-regexp org-any-link-re)
10690 (org-open-link-from-string (match-string-no-properties 0)))
10691 ((or (org-at-timestamp-p t) (org-at-date-range-p t))
10692 (org-follow-timestamp-link))
10693 (t (user-error "No link found"))))
10694 ;; On a headline or an inlinetask, but not on a timestamp,
10695 ;; a link, a footnote reference or on tags.
10696 ((and (memq type '(headline inlinetask))
10697 ;; Not on tags.
10698 (progn (save-excursion (beginning-of-line)
10699 (looking-at org-complex-heading-regexp))
10700 (or (not (match-beginning 5))
10701 (< (point) (match-beginning 5)))))
10702 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10703 (links (car data))
10704 (links-end (cdr data)))
10705 (if links
10706 (dolist (link (if (stringp links) (list links) links))
10707 (search-forward link nil links-end)
10708 (goto-char (match-beginning 0))
10709 (org-open-at-point))
10710 (require 'org-attach)
10711 (org-attach-reveal 'if-exists))))
10712 ;; Do nothing on white spaces after an object, unless point
10713 ;; is right after it.
10714 ((> (point)
10715 (save-excursion
10716 (goto-char (org-element-property :end context))
10717 (skip-chars-backward " \t")
10718 (point)))
10719 (user-error "No link found"))
10720 ((eq type 'timestamp) (org-follow-timestamp-link))
10721 ;; On tags within a headline or an inlinetask.
10722 ((and (memq type '(headline inlinetask))
10723 (progn (save-excursion (beginning-of-line)
10724 (looking-at org-complex-heading-regexp))
10725 (and (match-beginning 5)
10726 (>= (point) (match-beginning 5)))))
10727 (org-tags-view arg (substring (match-string 5) 0 -1)))
10728 ((eq type 'link)
10729 ;; When link is located within the description of another
10730 ;; link (e.g., an inline image), always open the parent
10731 ;; link.
10732 (let*((link (let ((up (org-element-property :parent context)))
10733 (if (eq (org-element-type up) 'link) up context)))
10734 (type (org-element-property :type link))
10735 (path (org-link-unescape (org-element-property :path link))))
10736 ;; Switch back to REFERENCE-BUFFER needed when called in
10737 ;; a temporary buffer through `org-open-link-from-string'.
10738 (with-current-buffer (or reference-buffer (current-buffer))
10739 (cond
10740 ((equal type "file")
10741 (if (string-match "[*?{]" (file-name-nondirectory path))
10742 (dired path)
10743 ;; Look into `org-link-protocols' in order to find
10744 ;; a DEDICATED-FUNCTION to open file. The function
10745 ;; will be applied on raw link instead of parsed
10746 ;; link due to the limitation in `org-add-link-type'
10747 ;; ("open" function called with a single argument).
10748 ;; If no such function is found, fallback to
10749 ;; `org-open-file'.
10751 ;; Note : "file+emacs" and "file+sys" types are
10752 ;; hard-coded in order to escape the previous
10753 ;; limitation.
10754 (let* ((option (org-element-property :search-option link))
10755 (app (org-element-property :application link))
10756 (dedicated-function
10757 (nth 1 (assoc app org-link-protocols))))
10758 (if dedicated-function
10759 (funcall dedicated-function
10760 (concat path
10761 (and option (concat "::" option))))
10762 (apply 'org-open-file
10763 path
10764 (cond (arg)
10765 ((equal app "emacs") 'emacs)
10766 ((equal app "sys") 'system))
10767 (cond ((not option) nil)
10768 ((org-string-match-p "\\`[0-9]+\\'" option)
10769 (list (string-to-number option)))
10770 (t (list nil
10771 (org-link-unescape option)))))))))
10772 ((assoc type org-link-protocols)
10773 (funcall (nth 1 (assoc type org-link-protocols)) path))
10774 ((equal type "help")
10775 (let ((f-or-v (intern path)))
10776 (cond ((fboundp f-or-v) (describe-function f-or-v))
10777 ((boundp f-or-v) (describe-variable f-or-v))
10778 (t (error "Not a known function or variable")))))
10779 ((member type '("http" "https" "ftp" "mailto" "news"))
10780 (browse-url (org-link-escape-browser (concat type ":" path))))
10781 ((equal type "doi")
10782 (browse-url
10783 (org-link-escape-browser (concat org-doi-server-url path))))
10784 ((equal type "message") (browse-url (concat type ":" path)))
10785 ((equal type "shell")
10786 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10787 (cmd path))
10788 (if (or (and (org-string-nw-p
10789 org-confirm-shell-link-not-regexp)
10790 (string-match
10791 org-confirm-shell-link-not-regexp cmd))
10792 (not org-confirm-shell-link-function)
10793 (funcall org-confirm-shell-link-function
10794 (format "Execute \"%s\" in shell? "
10795 (org-add-props cmd nil
10796 'face 'org-warning))))
10797 (progn
10798 (message "Executing %s" cmd)
10799 (shell-command cmd buf)
10800 (when (featurep 'midnight)
10801 (setq clean-buffer-list-kill-buffer-names
10802 (cons (buffer-name buf)
10803 clean-buffer-list-kill-buffer-names))))
10804 (user-error "Abort"))))
10805 ((equal type "elisp")
10806 (let ((cmd path))
10807 (if (or (and (org-string-nw-p
10808 org-confirm-elisp-link-not-regexp)
10809 (org-string-match-p
10810 org-confirm-elisp-link-not-regexp cmd))
10811 (not org-confirm-elisp-link-function)
10812 (funcall org-confirm-elisp-link-function
10813 (format "Execute \"%s\" as elisp? "
10814 (org-add-props cmd nil
10815 'face 'org-warning))))
10816 (message "%s => %s" cmd
10817 (if (eq (string-to-char cmd) ?\()
10818 (eval (read cmd))
10819 (call-interactively (read cmd))))
10820 (user-error "Abort"))))
10821 ((equal type "id")
10822 (require 'ord-id)
10823 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10824 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10825 (unless (run-hook-with-args-until-success
10826 'org-open-link-functions path)
10827 (if (not arg) (org-mark-ring-push)
10828 (switch-to-buffer-other-window
10829 (org-get-buffer-for-internal-link (current-buffer))))
10830 (let ((cmd `(org-link-search
10831 ,(if (member type '("custom-id" "coderef"))
10832 (org-element-property :raw-link link)
10833 path)
10834 ,(cond ((equal arg '(4)) 'occur)
10835 ((equal arg '(16)) 'org-occur))
10836 ,(org-element-property :begin link))))
10837 (condition-case nil
10838 (let ((org-link-search-inhibit-query t))
10839 (eval cmd))
10840 (error (progn (widen) (eval cmd)))))))
10841 (t (browse-url-at-point))))))
10842 ;; On a footnote reference or at a footnote definition's label.
10843 ((or (eq type 'footnote-reference)
10844 (and (eq type 'footnote-definition)
10845 (save-excursion
10846 ;; Do not validate action when point is on the
10847 ;; spaces right after the footnote label, in
10848 ;; order to be on par with behaviour on links.
10849 (skip-chars-forward " \t")
10850 (let ((begin
10851 (org-element-property :contents-begin context)))
10852 (if begin (< (point) begin)
10853 (= (org-element-property :post-affiliated context)
10854 (line-beginning-position)))))))
10855 (org-footnote-action))
10856 (t (user-error "No link found")))))
10857 (move-marker org-open-link-marker nil)
10858 (run-hook-with-args 'org-follow-link-hook)))
10860 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10861 "Offer links in the current entry and return the selected link.
10862 If there is only one link, return it.
10863 If NTH is an integer, return the NTH link found.
10864 If ZERO is a string, check also this string for a link, and if
10865 there is one, return it."
10866 (with-current-buffer buffer
10867 (save-excursion
10868 (save-restriction
10869 (widen)
10870 (goto-char marker)
10871 (let ((cnt ?0)
10872 (in-emacs (if (integerp nth) nil nth))
10873 have-zero end links link c)
10874 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10875 (push (match-string 0 zero) links)
10876 (setq cnt (1- cnt) have-zero t))
10877 (save-excursion
10878 (org-back-to-heading t)
10879 (setq end (save-excursion (outline-next-heading) (point)))
10880 (while (re-search-forward org-any-link-re end t)
10881 (push (match-string 0) links))
10882 (setq links (org-uniquify (reverse links))))
10883 (cond
10884 ((null links)
10885 (message "No links"))
10886 ((equal (length links) 1)
10887 (setq link (car links)))
10888 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10889 (setq link (nth (if have-zero nth (1- nth)) links)))
10890 (t ; we have to select a link
10891 (save-excursion
10892 (save-window-excursion
10893 (delete-other-windows)
10894 (with-output-to-temp-buffer "*Select Link*"
10895 (mapc (lambda (l)
10896 (if (not (string-match org-bracket-link-regexp l))
10897 (princ (format "[%c] %s\n" (incf cnt)
10898 (org-remove-angle-brackets l)))
10899 (if (match-end 3)
10900 (princ (format "[%c] %s (%s)\n" (incf cnt)
10901 (match-string 3 l) (match-string 1 l)))
10902 (princ (format "[%c] %s\n" (incf cnt)
10903 (match-string 1 l))))))
10904 links))
10905 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10906 (message "Select link to open, RET to open all:")
10907 (setq c (read-char-exclusive))
10908 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10909 (when (equal c ?q) (user-error "Abort"))
10910 (if (equal c ?\C-m)
10911 (setq link links)
10912 (setq nth (- c ?0))
10913 (if have-zero (setq nth (1+ nth)))
10914 (unless (and (integerp nth) (>= (length links) nth))
10915 (user-error "Invalid link selection"))
10916 (setq link (nth (1- nth) links)))))
10917 (cons link end))))))
10919 ;; TODO: These functions are deprecated since `org-open-at-point'
10920 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10921 (defun org-open-file-with-system (path)
10922 "Open file at PATH using the system way of opening it."
10923 (org-open-file path 'system))
10924 (defun org-open-file-with-emacs (path)
10925 "Open file at PATH in Emacs."
10926 (org-open-file path 'emacs))
10929 ;;; File search
10931 (defvar org-create-file-search-functions nil
10932 "List of functions to construct the right search string for a file link.
10933 These functions are called in turn with point at the location to
10934 which the link should point.
10936 A function in the hook should first test if it would like to
10937 handle this file type, for example by checking the `major-mode'
10938 or the file extension. If it decides not to handle this file, it
10939 should just return nil to give other functions a chance. If it
10940 does handle the file, it must return the search string to be used
10941 when following the link. The search string will be part of the
10942 file link, given after a double colon, and `org-open-at-point'
10943 will automatically search for it. If special measures must be
10944 taken to make the search successful, another function should be
10945 added to the companion hook `org-execute-file-search-functions',
10946 which see.
10948 A function in this hook may also use `setq' to set the variable
10949 `description' to provide a suggestion for the descriptive text to
10950 be used for this link when it gets inserted into an Org-mode
10951 buffer with \\[org-insert-link].")
10953 (defvar org-execute-file-search-functions nil
10954 "List of functions to execute a file search triggered by a link.
10956 Functions added to this hook must accept a single argument, the
10957 search string that was part of the file link, the part after the
10958 double colon. The function must first check if it would like to
10959 handle this search, for example by checking the `major-mode' or
10960 the file extension. If it decides not to handle this search, it
10961 should just return nil to give other functions a chance. If it
10962 does handle the search, it must return a non-nil value to keep
10963 other functions from trying.
10965 Each function can access the current prefix argument through the
10966 variable `current-prefix-arg'. Note that a single prefix is used
10967 to force opening a link in Emacs, so it may be good to only use a
10968 numeric or double prefix to guide the search function.
10970 In case this is needed, a function in this hook can also restore
10971 the window configuration before `org-open-at-point' was called using:
10973 (set-window-configuration org-window-config-before-follow-link)")
10975 (defun org-link-search (s &optional type avoid-pos stealth)
10976 "Search for a link search option.
10977 If S is surrounded by forward slashes, it is interpreted as a
10978 regular expression. In org-mode files, this will create an `org-occur'
10979 sparse tree. In ordinary files, `occur' will be used to list matches.
10980 If the current buffer is in `dired-mode', grep will be used to search
10981 in all files. If AVOID-POS is given, ignore matches near that position.
10983 When optional argument STEALTH is non-nil, do not modify
10984 visibility around point, thus ignoring `org-show-context-detail'
10985 variable."
10986 (let ((case-fold-search t)
10987 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10988 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10989 (append '(("") (" ") ("\t") ("\n"))
10990 org-emphasis-alist)
10991 "\\|") "\\)"))
10992 (pos (point))
10993 words re0 re2 re4_ re4 re5 re2a re2a_ reall)
10994 (cond
10995 ;; First check if there are any special search functions
10996 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10997 ;; Now try the builtin stuff
10998 ((and (eq (aref s0 0) ?#)
10999 (> (length s0) 1)
11000 (let ((match (org-find-property "CUSTOM_ID" (substring s0 1))))
11001 (and match (goto-char match) (setf type 'dedicated)))))
11002 ((save-excursion
11003 (goto-char (point-min))
11004 (and
11005 (re-search-forward
11006 (concat "<<" (regexp-quote s0) ">>") nil t)
11007 (setq type 'dedicated
11008 pos (match-beginning 0))))
11009 ;; There is an exact target for this
11010 (goto-char pos))
11011 ((save-excursion
11012 (goto-char (point-min))
11013 (and
11014 (re-search-forward
11015 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
11016 (setq type 'dedicated pos (match-beginning 0))))
11017 ;; Found an element with a matching #+name affiliated keyword.
11018 (goto-char pos))
11019 ((and (string-match "^(\\(.*\\))$" s0)
11020 (save-excursion
11021 (goto-char (point-min))
11022 (and
11023 (re-search-forward
11024 (concat "[^[]" (regexp-quote
11025 (format org-coderef-label-format
11026 (match-string 1 s0))))
11027 nil t)
11028 (setq type 'dedicated
11029 pos (1+ (match-beginning 0))))))
11030 ;; There is a coderef target for this
11031 (goto-char pos))
11032 ((string-match "^/\\(.*\\)/$" s)
11033 ;; A regular expression
11034 (cond
11035 ((derived-mode-p 'org-mode)
11036 (org-occur (match-string 1 s)))
11037 (t (org-do-occur (match-string 1 s)))))
11038 ((and (derived-mode-p 'org-mode)
11039 (or (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11040 org-link-search-must-match-exact-headline))
11041 ;; Headline search.
11042 (goto-char (point-min))
11043 (cond
11044 ((let (case-fold-search)
11045 (re-search-forward
11046 (let* ((wspace "[ \t]")
11047 (wspaceopt (concat wspace "*"))
11048 (cookie (concat "\\(?:"
11049 wspaceopt
11050 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11051 wspaceopt
11052 "\\)"))
11053 (sep (concat "\\(?:" wspace "+\\|" cookie "+\\)")))
11054 (concat
11055 org-outline-regexp-bol
11056 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11057 "\\(?:\\[#.\\][ \t]+\\)?"
11058 "\\(?:" org-comment-string "[ \t]+\\)?"
11059 sep "*"
11060 (mapconcat #'identity
11061 (org-split-string (regexp-quote s))
11062 (concat sep "+"))
11063 sep "*"
11064 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11065 "[ \t]*$"))
11066 nil t))
11067 ;; OK, found a match
11068 (setq type 'dedicated)
11069 (goto-char (match-beginning 0)))
11070 ((and (not org-link-search-inhibit-query)
11071 (eq org-link-search-must-match-exact-headline 'query-to-create)
11072 (y-or-n-p "No match - create this as a new heading? "))
11073 (goto-char (point-max))
11074 (unless (bolp) (newline))
11075 (org-insert-heading nil t t)
11076 (insert s "\n")
11077 (beginning-of-line 0))
11079 (goto-char pos)
11080 (error "No match"))))
11082 ;; A normal search string
11083 (remove-text-properties
11084 0 (length s)
11085 '(face nil mouse-face nil keymap nil fontified nil) s)
11086 ;; Make a series of regular expressions to find a match
11087 (setq words (org-split-string s "[ \n\r\t]+")
11089 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11090 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11091 "\\)" markers)
11092 re2a_ (concat "\\(" (mapconcat 'downcase words
11093 "[ \t\r\n]+") "\\)[ \t\r\n]")
11094 re2a (concat "[ \t\r\n]" re2a_)
11095 re4_ (concat "\\(" (mapconcat 'downcase words
11096 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11097 re4 (concat "[^a-zA-Z_]" re4_)
11099 re5 (concat ".*" re4)
11100 reall (concat "\\(" re0 "\\)\\|\\(" re2 "\\)\\|\\(" re4
11101 "\\)\\|\\(" re5 "\\)"))
11102 (cond
11103 ((eq type 'org-occur) (org-occur reall))
11104 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11105 (t (goto-char (point-min))
11106 (setq type 'fuzzy)
11107 (if (or (and (org-search-not-self 1 re0 nil t)
11108 (setq type 'dedicated))
11109 (org-search-not-self 1 re2 nil t)
11110 (org-search-not-self 1 re2a nil t)
11111 (org-search-not-self 1 re4 nil t)
11112 (org-search-not-self 1 re5 nil t))
11113 (goto-char (match-beginning 1))
11114 (goto-char pos)
11115 (error "No match"))))))
11116 (and (derived-mode-p 'org-mode)
11117 (not stealth)
11118 (org-show-context 'link-search))
11119 type))
11121 (defun org-search-not-self (group &rest args)
11122 "Execute `re-search-forward', but only accept matches that do not
11123 enclose the position of `org-open-link-marker'."
11124 (let ((m org-open-link-marker))
11125 (catch 'exit
11126 (while (apply 're-search-forward args)
11127 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11128 (goto-char (match-end group))
11129 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11130 (> (match-beginning 0) (marker-position m))
11131 (< (match-end 0) (marker-position m)))
11132 (save-match-data
11133 (or (not (org-in-regexp
11134 org-bracket-link-analytic-regexp 1))
11135 (not (match-end 4)) ; no description
11136 (and (<= (match-beginning 4) (point))
11137 (>= (match-end 4) (point))))))
11138 (throw 'exit (point))))))))
11140 (defun org-get-buffer-for-internal-link (buffer)
11141 "Return a buffer to be used for displaying the link target of internal links."
11142 (cond
11143 ((not org-display-internal-link-with-indirect-buffer)
11144 buffer)
11145 ((string-match "(Clone)$" (buffer-name buffer))
11146 (message "Buffer is already a clone, not making another one")
11147 ;; we also do not modify visibility in this case
11148 buffer)
11149 (t ; make a new indirect buffer for displaying the link
11150 (let* ((bn (buffer-name buffer))
11151 (ibn (concat bn "(Clone)"))
11152 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11153 (with-current-buffer ib (org-overview))
11154 ib))))
11156 (defun org-do-occur (regexp &optional cleanup)
11157 "Call the Emacs command `occur'.
11158 If CLEANUP is non-nil, remove the printout of the regular expression
11159 in the *Occur* buffer. This is useful if the regex is long and not useful
11160 to read."
11161 (occur regexp)
11162 (when cleanup
11163 (let ((cwin (selected-window)) win beg end)
11164 (when (setq win (get-buffer-window "*Occur*"))
11165 (select-window win))
11166 (goto-char (point-min))
11167 (when (re-search-forward "match[a-z]+" nil t)
11168 (setq beg (match-end 0))
11169 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11170 (setq end (1- (match-beginning 0)))))
11171 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11172 (goto-char (point-min))
11173 (select-window cwin))))
11175 ;;; The mark ring for links jumps
11177 (defvar org-mark-ring nil
11178 "Mark ring for positions before jumps in Org-mode.")
11179 (defvar org-mark-ring-last-goto nil
11180 "Last position in the mark ring used to go back.")
11181 ;; Fill and close the ring
11182 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11183 (loop for i from 1 to org-mark-ring-length do
11184 (push (make-marker) org-mark-ring))
11185 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11186 org-mark-ring)
11188 (defun org-mark-ring-push (&optional pos buffer)
11189 "Put the current position or POS into the mark ring and rotate it."
11190 (interactive)
11191 (setq pos (or pos (point)))
11192 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11193 (move-marker (car org-mark-ring)
11194 (or pos (point))
11195 (or buffer (current-buffer)))
11196 (message "%s"
11197 (substitute-command-keys
11198 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11200 (defun org-mark-ring-goto (&optional n)
11201 "Jump to the previous position in the mark ring.
11202 With prefix arg N, jump back that many stored positions. When
11203 called several times in succession, walk through the entire ring.
11204 Org-mode commands jumping to a different position in the current file,
11205 or to another Org-mode file, automatically push the old position
11206 onto the ring."
11207 (interactive "p")
11208 (let (p m)
11209 (if (eq last-command this-command)
11210 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11211 (setq p org-mark-ring))
11212 (setq org-mark-ring-last-goto p)
11213 (setq m (car p))
11214 (org-pop-to-buffer-same-window (marker-buffer m))
11215 (goto-char m)
11216 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11218 (defun org-remove-angle-brackets (s)
11219 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11220 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11222 (defun org-add-angle-brackets (s)
11223 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11224 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11226 (defun org-remove-double-quotes (s)
11227 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11228 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11231 ;;; Following specific links
11233 (defun org-follow-timestamp-link ()
11234 "Open an agenda view for the time-stamp date/range at point."
11235 (cond
11236 ((org-at-date-range-p t)
11237 (let ((org-agenda-start-on-weekday)
11238 (t1 (match-string 1))
11239 (t2 (match-string 2)) tt1 tt2)
11240 (setq tt1 (time-to-days (org-time-string-to-time t1))
11241 tt2 (time-to-days (org-time-string-to-time t2)))
11242 (let ((org-agenda-buffer-tmp-name
11243 (format "*Org Agenda(a:%s)"
11244 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11245 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11246 ((org-at-timestamp-p t)
11247 (let ((org-agenda-buffer-tmp-name
11248 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11249 (org-agenda-list nil (time-to-days (org-time-string-to-time
11250 (substring (match-string 1) 0 10)))
11251 1)))
11252 (t (error "This should not happen"))))
11255 ;;; Following file links
11256 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11257 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11258 (declare-function mailcap-mime-info
11259 "mailcap" (string &optional request no-decode))
11260 (defvar org-wait nil)
11261 (defun org-open-file (path &optional in-emacs line search)
11262 "Open the file at PATH.
11263 First, this expands any special file name abbreviations. Then the
11264 configuration variable `org-file-apps' is checked if it contains an
11265 entry for this file type, and if yes, the corresponding command is launched.
11267 If no application is found, Emacs simply visits the file.
11269 With optional prefix argument IN-EMACS, Emacs will visit the file.
11270 With a double \\[universal-argument] \\[universal-argument] \
11271 prefix arg, Org tries to avoid opening in Emacs
11272 and to use an external application to visit the file.
11274 Optional LINE specifies a line to go to, optional SEARCH a string
11275 to search for. If LINE or SEARCH is given, the file will be
11276 opened in Emacs, unless an entry from org-file-apps that makes
11277 use of groups in a regexp matches.
11279 If you want to change the way frames are used when following a
11280 link, please customize `org-link-frame-setup'.
11282 If the file does not exist, an error is thrown."
11283 (let* ((file (if (equal path "")
11284 buffer-file-name
11285 (substitute-in-file-name (expand-file-name path))))
11286 (file-apps (append org-file-apps (org-default-apps)))
11287 (apps (org-remove-if
11288 'org-file-apps-entry-match-against-dlink-p file-apps))
11289 (apps-dlink (org-remove-if-not
11290 'org-file-apps-entry-match-against-dlink-p file-apps))
11291 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11292 (dirp (if remp nil (file-directory-p file)))
11293 (file (if (and dirp org-open-directory-means-index-dot-org)
11294 (concat (file-name-as-directory file) "index.org")
11295 file))
11296 (a-m-a-p (assq 'auto-mode apps))
11297 (dfile (downcase file))
11298 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11299 (link (cond ((and (eq line nil)
11300 (eq search nil))
11301 file)
11302 (line
11303 (concat file "::" (number-to-string line)))
11304 (search
11305 (concat file "::" search))))
11306 (dlink (downcase link))
11307 (old-buffer (current-buffer))
11308 (old-pos (point))
11309 (old-mode major-mode)
11310 ext cmd link-match-data)
11311 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11312 (setq ext (match-string 1 dfile))
11313 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11314 (setq ext (match-string 1 dfile))))
11315 (cond
11316 ((member in-emacs '((16) system))
11317 (setq cmd (cdr (assoc 'system apps))))
11318 (in-emacs (setq cmd 'emacs))
11320 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11321 (and dirp (cdr (assoc 'directory apps)))
11322 ; first, try matching against apps-dlink
11323 ; if we get a match here, store the match data for later
11324 (let ((match (assoc-default dlink apps-dlink
11325 'string-match)))
11326 (if match
11327 (progn (setq link-match-data (match-data))
11328 match)
11329 (progn (setq in-emacs (or in-emacs line search))
11330 nil))) ; if we have no match in apps-dlink,
11331 ; always open the file in emacs if line or search
11332 ; is given (for backwards compatibility)
11333 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11334 'string-match)
11335 (cdr (assoc ext apps))
11336 (cdr (assoc t apps))))))
11337 (when (eq cmd 'system)
11338 (setq cmd (cdr (assoc 'system apps))))
11339 (when (eq cmd 'default)
11340 (setq cmd (cdr (assoc t apps))))
11341 (when (eq cmd 'mailcap)
11342 (require 'mailcap)
11343 (mailcap-parse-mailcaps)
11344 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11345 (command (mailcap-mime-info mime-type)))
11346 (if (stringp command)
11347 (setq cmd command)
11348 (setq cmd 'emacs))))
11349 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11350 (not (file-exists-p file))
11351 (not org-open-non-existing-files))
11352 (user-error "No such file: %s" file))
11353 (cond
11354 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11355 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11356 (while (string-match "['\"]%s['\"]" cmd)
11357 (setq cmd (replace-match "%s" t t cmd)))
11358 (while (string-match "%s" cmd)
11359 (setq cmd (replace-match
11360 (save-match-data
11361 (shell-quote-argument
11362 (convert-standard-filename file)))
11363 t t cmd)))
11365 ;; Replace "%1", "%2" etc. in command with group matches from regex
11366 (save-match-data
11367 (let ((match-index 1)
11368 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11369 (set-match-data link-match-data)
11370 (while (<= match-index number-of-groups)
11371 (let ((regex (concat "%" (number-to-string match-index)))
11372 (replace-with (match-string match-index dlink)))
11373 (while (string-match regex cmd)
11374 (setq cmd (replace-match replace-with t t cmd))))
11375 (setq match-index (+ match-index 1)))))
11377 (save-window-excursion
11378 (message "Running %s...done" cmd)
11379 (start-process-shell-command cmd nil cmd)
11380 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11381 ((or (stringp cmd)
11382 (eq cmd 'emacs))
11383 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11384 (widen)
11385 (if line (progn (org-goto-line line)
11386 (if (derived-mode-p 'org-mode)
11387 (org-reveal)))
11388 (if search (org-link-search search))))
11389 ((consp cmd)
11390 (let ((file (convert-standard-filename file)))
11391 (save-match-data
11392 (set-match-data link-match-data)
11393 (eval cmd))))
11394 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11395 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11396 (or (not (equal old-buffer (current-buffer)))
11397 (not (equal old-pos (point))))
11398 (org-mark-ring-push old-pos old-buffer))))
11400 (defun org-file-apps-entry-match-against-dlink-p (entry)
11401 "This function returns non-nil if `entry' uses a regular
11402 expression which should be matched against the whole link by
11403 org-open-file.
11405 It assumes that is the case when the entry uses a regular
11406 expression which has at least one grouping construct and the
11407 action is either a lisp form or a command string containing
11408 '%1', i.e. using at least one subexpression match as a
11409 parameter."
11410 (let ((selector (car entry))
11411 (action (cdr entry)))
11412 (if (stringp selector)
11413 (and (> (regexp-opt-depth selector) 0)
11414 (or (and (stringp action)
11415 (string-match "%[0-9]" action))
11416 (consp action)))
11417 nil)))
11419 (defun org-default-apps ()
11420 "Return the default applications for this operating system."
11421 (cond
11422 ((eq system-type 'darwin)
11423 org-file-apps-defaults-macosx)
11424 ((eq system-type 'windows-nt)
11425 org-file-apps-defaults-windowsnt)
11426 (t org-file-apps-defaults-gnu)))
11428 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11429 "Convert extensions to regular expressions in the cars of LIST.
11430 Also, weed out any non-string entries, because the return value is used
11431 only for regexp matching.
11432 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11433 point to the symbol `emacs', indicating that the file should
11434 be opened in Emacs."
11435 (append
11436 (delq nil
11437 (mapcar (lambda (x)
11438 (if (not (stringp (car x)))
11440 (if (string-match "\\W" (car x))
11442 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11443 list))
11444 (if add-auto-mode
11445 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11447 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11448 (defun org-file-remote-p (file)
11449 "Test whether FILE specifies a location on a remote system.
11450 Return non-nil if the location is indeed remote.
11452 For example, the filename \"/user@host:/foo\" specifies a location
11453 on the system \"/user@host:\"."
11454 (cond ((fboundp 'file-remote-p)
11455 (file-remote-p file))
11456 ((fboundp 'tramp-handle-file-remote-p)
11457 (tramp-handle-file-remote-p file))
11458 ((and (boundp 'ange-ftp-name-format)
11459 (string-match (car ange-ftp-name-format) file))
11460 t)))
11463 ;;;; Refiling
11465 (defun org-get-org-file ()
11466 "Read a filename, with default directory `org-directory'."
11467 (let ((default (or org-default-notes-file remember-data-file)))
11468 (read-file-name (format "File name [%s]: " default)
11469 (file-name-as-directory org-directory)
11470 default)))
11472 (defun org-notes-order-reversed-p ()
11473 "Check if the current file should receive notes in reversed order."
11474 (cond
11475 ((not org-reverse-note-order) nil)
11476 ((eq t org-reverse-note-order) t)
11477 ((not (listp org-reverse-note-order)) nil)
11478 (t (catch 'exit
11479 (let ((all org-reverse-note-order)
11480 entry)
11481 (while (setq entry (pop all))
11482 (if (string-match (car entry) buffer-file-name)
11483 (throw 'exit (cdr entry))))
11484 nil)))))
11486 (defvar org-refile-target-table nil
11487 "The list of refile targets, created by `org-refile'.")
11489 (defvar org-agenda-new-buffers nil
11490 "Buffers created to visit agenda files.")
11492 (defvar org-refile-cache nil
11493 "Cache for refile targets.")
11495 (defvar org-refile-markers nil
11496 "All the markers used for caching refile locations.")
11498 (defun org-refile-marker (pos)
11499 "Get a new refile marker, but only if caching is in use."
11500 (if (not org-refile-use-cache)
11502 (let ((m (make-marker)))
11503 (move-marker m pos)
11504 (push m org-refile-markers)
11505 m)))
11507 (defun org-refile-cache-clear ()
11508 "Clear the refile cache and disable all the markers."
11509 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11510 (setq org-refile-markers nil)
11511 (setq org-refile-cache nil)
11512 (message "Refile cache has been cleared"))
11514 (defun org-refile-cache-check-set (set)
11515 "Check if all the markers in the cache still have live buffers."
11516 (let (marker)
11517 (catch 'exit
11518 (while (and set (setq marker (nth 3 (pop set))))
11519 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11520 (when (and marker (null (marker-buffer marker)))
11521 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11522 (sit-for 3)
11523 (throw 'exit nil)))
11524 t)))
11526 (defun org-refile-cache-put (set &rest identifiers)
11527 "Push the refile targets SET into the cache, under IDENTIFIERS."
11528 (let* ((key (sha1 (prin1-to-string identifiers)))
11529 (entry (assoc key org-refile-cache)))
11530 (if entry
11531 (setcdr entry set)
11532 (push (cons key set) org-refile-cache))))
11534 (defun org-refile-cache-get (&rest identifiers)
11535 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11536 (cond
11537 ((not org-refile-cache) nil)
11538 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11540 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11541 org-refile-cache))))
11542 (and set (org-refile-cache-check-set set) set)))))
11544 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11545 "Produce a table with refile targets."
11546 (let ((case-fold-search nil)
11547 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11548 (entries (or org-refile-targets '((nil . (:level . 1)))))
11549 targets tgs txt re files f desc descre fast-path-p level pos0)
11550 (message "Getting targets...")
11551 (with-current-buffer (or default-buffer (current-buffer))
11552 (while (setq entry (pop entries))
11553 (setq files (car entry) desc (cdr entry))
11554 (setq fast-path-p nil)
11555 (cond
11556 ((null files) (setq files (list (current-buffer))))
11557 ((eq files 'org-agenda-files)
11558 (setq files (org-agenda-files 'unrestricted)))
11559 ((and (symbolp files) (fboundp files))
11560 (setq files (funcall files)))
11561 ((and (symbolp files) (boundp files))
11562 (setq files (symbol-value files))))
11563 (if (stringp files) (setq files (list files)))
11564 (cond
11565 ((eq (car desc) :tag)
11566 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11567 ((eq (car desc) :todo)
11568 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11569 ((eq (car desc) :regexp)
11570 (setq descre (cdr desc)))
11571 ((eq (car desc) :level)
11572 (setq descre (concat "^\\*\\{" (number-to-string
11573 (if org-odd-levels-only
11574 (1- (* 2 (cdr desc)))
11575 (cdr desc)))
11576 "\\}[ \t]")))
11577 ((eq (car desc) :maxlevel)
11578 (setq fast-path-p t)
11579 (setq descre (concat "^\\*\\{1," (number-to-string
11580 (if org-odd-levels-only
11581 (1- (* 2 (cdr desc)))
11582 (cdr desc)))
11583 "\\}[ \t]")))
11584 (t (error "Bad refiling target description %s" desc)))
11585 (while (setq f (pop files))
11586 (with-current-buffer
11587 (if (bufferp f) f (org-get-agenda-file-buffer f))
11589 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11590 (progn
11591 (if (bufferp f) (setq f (buffer-file-name
11592 (buffer-base-buffer f))))
11593 (setq f (and f (expand-file-name f)))
11594 (if (eq org-refile-use-outline-path 'file)
11595 (push (list (file-name-nondirectory f) f nil nil) tgs))
11596 (save-excursion
11597 (save-restriction
11598 (widen)
11599 (goto-char (point-min))
11600 (while (re-search-forward descre nil t)
11601 (goto-char (setq pos0 (point-at-bol)))
11602 (catch 'next
11603 (when org-refile-target-verify-function
11604 (save-match-data
11605 (or (funcall org-refile-target-verify-function)
11606 (throw 'next t))))
11607 (when (and (looking-at org-complex-heading-regexp)
11608 (not (member (match-string 4) excluded-entries))
11609 (match-string 4))
11610 (setq level (org-reduced-level
11611 (- (match-end 1) (match-beginning 1)))
11612 txt (org-link-display-format (match-string 4))
11613 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11614 re (format org-complex-heading-regexp-format
11615 (regexp-quote (match-string 4))))
11616 (when org-refile-use-outline-path
11617 (setq txt (mapconcat
11618 'org-protect-slash
11619 (append
11620 (if (eq org-refile-use-outline-path
11621 'file)
11622 (list (file-name-nondirectory
11623 (buffer-file-name
11624 (buffer-base-buffer))))
11625 (if (eq org-refile-use-outline-path
11626 'full-file-path)
11627 (list (buffer-file-name
11628 (buffer-base-buffer)))))
11629 (org-get-outline-path fast-path-p
11630 level txt)
11631 (list txt))
11632 "/")))
11633 (push (list txt f re (org-refile-marker (point)))
11634 tgs)))
11635 (when (= (point) pos0)
11636 ;; verification function has not moved point
11637 (goto-char (point-at-eol))))))))
11638 (when org-refile-use-cache
11639 (org-refile-cache-put tgs (buffer-file-name) descre))
11640 (setq targets (append tgs targets))))))
11641 (message "Getting targets...done")
11642 (nreverse targets)))
11644 (defun org-protect-slash (s)
11645 (while (string-match "/" s)
11646 (setq s (replace-match "\\" t t s)))
11649 (defvar org-olpa (make-vector 20 nil))
11651 (defun org-get-outline-path (&optional fastp level heading)
11652 "Return the outline path to the current entry, as a list.
11654 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11655 routine which makes outline path derivations for an entire file,
11656 avoiding backtracing. Refile target collection makes use of that."
11657 (if fastp
11658 (progn
11659 (if (> level 19)
11660 (error "Outline path failure, more than 19 levels"))
11661 (loop for i from level upto 19 do
11662 (aset org-olpa i nil))
11663 (prog1
11664 (delq nil (append org-olpa nil))
11665 (aset org-olpa level heading)))
11666 (let (rtn case-fold-search)
11667 (save-excursion
11668 (save-restriction
11669 (widen)
11670 (while (org-up-heading-safe)
11671 (when (looking-at org-complex-heading-regexp)
11672 (push (org-trim
11673 (replace-regexp-in-string
11674 ;; Remove statistical/checkboxes cookies
11675 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11676 (org-match-string-no-properties 4)))
11677 rtn)))
11678 rtn)))))
11680 (defun org-format-outline-path (path &optional width prefix separator)
11681 "Format the outline path PATH for display.
11682 WIDTH is the maximum number of characters that is available.
11683 PREFIX is a prefix to be included in the returned string,
11684 such as the file name.
11685 SEPARATOR is inserted between the different parts of the path,
11686 the default is \"/\"."
11687 (setq width (or width 79))
11688 (if prefix (setq width (- width (length prefix))))
11689 (if (not path)
11690 (or prefix "")
11691 (let* ((nsteps (length path))
11692 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11693 (maxwidth (if (<= total-width width)
11694 10000 ;; everything fits
11695 ;; we need to shorten the level headings
11696 (/ (- width nsteps) nsteps)))
11697 (org-odd-levels-only nil)
11698 (n 0)
11699 (total (1+ (length prefix))))
11700 (setq maxwidth (max maxwidth 10))
11701 (concat prefix
11702 (if prefix (or separator "/"))
11703 (mapconcat
11704 (lambda (h)
11705 (setq n (1+ n))
11706 (if (and (= n nsteps) (< maxwidth 10000))
11707 (setq maxwidth (- total-width total)))
11708 (if (< (length h) maxwidth)
11709 (progn (setq total (+ total (length h) 1)) h)
11710 (setq h (substring h 0 (- maxwidth 2))
11711 total (+ total maxwidth 1))
11712 (if (string-match "[ \t]+\\'" h)
11713 (setq h (substring h 0 (match-beginning 0))))
11714 (setq h (concat h "..")))
11715 (org-add-props h nil 'face
11716 (nth (% (1- n) org-n-level-faces)
11717 org-level-faces))
11719 path (or separator "/"))))))
11721 (defun org-display-outline-path (&optional file current separator just-return-string)
11722 "Display the current outline path in the echo area.
11724 If FILE is non-nil, prepend the output with the file name.
11725 If CURRENT is non-nil, append the current heading to the output.
11726 SEPARATOR is passed through to `org-format-outline-path'. It separates
11727 the different parts of the path and defaults to \"/\".
11728 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11729 (interactive "P")
11730 (let* (case-fold-search
11731 (bfn (buffer-file-name (buffer-base-buffer)))
11732 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11733 res)
11734 (if current (setq path (append path
11735 (save-excursion
11736 (org-back-to-heading t)
11737 (if (looking-at org-complex-heading-regexp)
11738 (list (match-string 4)))))))
11739 (setq res
11740 (org-format-outline-path
11741 path
11742 (1- (frame-width))
11743 (and file bfn (concat (file-name-nondirectory bfn) separator))
11744 separator))
11745 (if just-return-string
11746 (org-no-properties res)
11747 (org-unlogged-message "%s" res))))
11749 (defvar org-refile-history nil
11750 "History for refiling operations.")
11752 (defvar org-after-refile-insert-hook nil
11753 "Hook run after `org-refile' has inserted its stuff at the new location.
11754 Note that this is still *before* the stuff will be removed from
11755 the *old* location.")
11757 (defvar org-capture-last-stored-marker)
11758 (defvar org-refile-keep nil
11759 "Non-nil means `org-refile' will copy instead of refile.")
11761 (defun org-copy ()
11762 "Like `org-refile', but copy."
11763 (interactive)
11764 (let ((org-refile-keep t))
11765 (funcall 'org-refile nil nil nil "Copy")))
11767 (defun org-refile (&optional arg default-buffer rfloc msg)
11768 "Move the entry or entries at point to another heading.
11769 The list of target headings is compiled using the information in
11770 `org-refile-targets', which see.
11772 At the target location, the entry is filed as a subitem of the
11773 target heading. Depending on `org-reverse-note-order', the new
11774 subitem will either be the first or the last subitem.
11776 If there is an active region, all entries in that region will be
11777 refiled. However, the region must fulfill the requirement that
11778 the first heading sets the top-level of the moved text.
11780 With prefix arg ARG, the command will only visit the target
11781 location and not actually move anything.
11783 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11784 refiling operation has put the subtree.
11786 With a numeric prefix argument of `2', refile to the running clock.
11788 With a numeric prefix argument of `3', emulate `org-refile-keep'
11789 being set to `t' and copy to the target location, don't move it.
11790 Beware that keeping refiled entries may result in duplicated ID
11791 properties.
11793 RFLOC can be a refile location obtained in a different way.
11795 MSG is a string to replace \"Refile\" in the default prompt with
11796 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11798 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11800 If you are using target caching (see `org-refile-use-cache'), you
11801 have to clear the target cache in order to find new targets.
11802 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11803 prefix argument (`C-u C-u C-u C-c C-w')."
11804 (interactive "P")
11805 (if (member arg '(0 (64)))
11806 (org-refile-cache-clear)
11807 (let* ((actionmsg (cond (msg msg)
11808 ((equal arg 3) "Refile (and keep)")
11809 (t "Refile")))
11810 (cbuf (current-buffer))
11811 (regionp (org-region-active-p))
11812 (region-start (and regionp (region-beginning)))
11813 (region-end (and regionp (region-end)))
11814 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11815 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11816 pos it nbuf file re level reversed)
11817 (setq last-command nil)
11818 (when regionp
11819 (goto-char region-start)
11820 (or (bolp) (goto-char (point-at-bol)))
11821 (setq region-start (point))
11822 (unless (or (org-kill-is-subtree-p
11823 (buffer-substring region-start region-end))
11824 (prog1 org-refile-active-region-within-subtree
11825 (let ((s (point-at-eol)))
11826 (org-toggle-heading)
11827 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11828 (user-error "The region is not a (sequence of) subtree(s)")))
11829 (if (equal arg '(16))
11830 (org-refile-goto-last-stored)
11831 (when (or
11832 (and (equal arg 2)
11833 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11834 (prog1
11835 (setq it (list (or org-clock-heading "running clock")
11836 (buffer-file-name
11837 (marker-buffer org-clock-hd-marker))
11839 (marker-position org-clock-hd-marker)))
11840 (setq arg nil)))
11841 (setq it (or rfloc
11842 (let (heading-text)
11843 (save-excursion
11844 (unless (and arg (listp arg))
11845 (org-back-to-heading t)
11846 (setq heading-text
11847 (replace-regexp-in-string
11848 org-bracket-link-regexp
11849 "\\3"
11850 (nth 4 (org-heading-components)))))
11851 (org-refile-get-location
11852 (cond ((and arg (listp arg)) "Goto")
11853 (regionp (concat actionmsg " region to"))
11854 (t (concat actionmsg " subtree \""
11855 heading-text "\" to")))
11856 default-buffer
11857 (and (not (equal '(4) arg))
11858 org-refile-allow-creating-parent-nodes)
11859 arg))))))
11860 (setq file (nth 1 it)
11861 re (nth 2 it)
11862 pos (nth 3 it))
11863 (if (and (not arg)
11865 (equal (buffer-file-name) file)
11866 (if regionp
11867 (and (>= pos region-start)
11868 (<= pos region-end))
11869 (and (>= pos (point))
11870 (< pos (save-excursion
11871 (org-end-of-subtree t t))))))
11872 (error "Cannot refile to position inside the tree or region"))
11873 (setq nbuf (or (find-buffer-visiting file)
11874 (find-file-noselect file)))
11875 (if (and arg (not (equal arg 3)))
11876 (progn
11877 (org-pop-to-buffer-same-window nbuf)
11878 (goto-char pos)
11879 (org-show-context 'org-goto))
11880 (if regionp
11881 (progn
11882 (org-kill-new (buffer-substring region-start region-end))
11883 (org-save-markers-in-region region-start region-end))
11884 (org-copy-subtree 1 nil t))
11885 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11886 (find-file-noselect file)))
11887 (setq reversed (org-notes-order-reversed-p))
11888 (save-excursion
11889 (save-restriction
11890 (widen)
11891 (if pos
11892 (progn
11893 (goto-char pos)
11894 (looking-at org-outline-regexp)
11895 (setq level (org-get-valid-level (funcall outline-level) 1))
11896 (goto-char
11897 (if reversed
11898 (or (outline-next-heading) (point-max))
11899 (or (save-excursion (org-get-next-sibling))
11900 (org-end-of-subtree t t)
11901 (point-max)))))
11902 (setq level 1)
11903 (if (not reversed)
11904 (goto-char (point-max))
11905 (goto-char (point-min))
11906 (or (outline-next-heading) (goto-char (point-max)))))
11907 (if (not (bolp)) (newline))
11908 (org-paste-subtree level nil nil t)
11909 (when org-log-refile
11910 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11911 (unless (eq org-log-refile 'note)
11912 (save-excursion (org-add-log-note))))
11913 (and org-auto-align-tags
11914 (let ((org-loop-over-headlines-in-active-region nil))
11915 (org-set-tags nil t)))
11916 (let ((bookmark-name (plist-get org-bookmark-names-plist
11917 :last-refile)))
11918 (when bookmark-name
11919 (with-demoted-errors
11920 (bookmark-set bookmark-name))))
11921 ;; If we are refiling for capture, make sure that the
11922 ;; last-capture pointers point here
11923 (when (org-bound-and-true-p org-refile-for-capture)
11924 (let ((bookmark-name (plist-get org-bookmark-names-plist
11925 :last-capture-marker)))
11926 (when bookmark-name
11927 (with-demoted-errors
11928 (bookmark-set bookmark-name))))
11929 (move-marker org-capture-last-stored-marker (point)))
11930 (if (fboundp 'deactivate-mark) (deactivate-mark))
11931 (run-hooks 'org-after-refile-insert-hook))))
11932 (unless org-refile-keep
11933 (if regionp
11934 (delete-region (point) (+ (point) (- region-end region-start)))
11935 (delete-region
11936 (and (org-back-to-heading t) (point))
11937 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11938 (when (featurep 'org-inlinetask)
11939 (org-inlinetask-remove-END-maybe))
11940 (setq org-markers-to-move nil)
11941 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11943 (defun org-refile-goto-last-stored ()
11944 "Go to the location where the last refile was stored."
11945 (interactive)
11946 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11947 (message "This is the location of the last refile"))
11949 (defun org-refile--get-location (refloc tbl)
11950 "When user refile to REFLOC, find the associated target in TBL.
11951 Also check `org-refile-target-table'."
11952 (car (delq
11954 (mapcar
11955 (lambda (r) (or (assoc r tbl)
11956 (assoc r org-refile-target-table)))
11957 (list (replace-regexp-in-string "/$" "" refloc)
11958 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11960 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11961 no-exclude)
11962 "Prompt the user for a refile location, using PROMPT.
11963 PROMPT should not be suffixed with a colon and a space, because
11964 this function appends the default value from
11965 `org-refile-history' automatically, if that is not empty.
11966 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11967 this is used for the GOTO interface."
11968 (let ((org-refile-targets org-refile-targets)
11969 (org-refile-use-outline-path org-refile-use-outline-path)
11970 excluded-entries)
11971 (when (and (derived-mode-p 'org-mode)
11972 (not org-refile-use-cache)
11973 (not no-exclude))
11974 (org-map-tree
11975 (lambda()
11976 (setq excluded-entries
11977 (append excluded-entries (list (org-get-heading t t)))))))
11978 (setq org-refile-target-table
11979 (org-refile-get-targets default-buffer excluded-entries)))
11980 (unless org-refile-target-table
11981 (user-error "No refile targets"))
11982 (let* ((cbuf (current-buffer))
11983 (partial-completion-mode nil)
11984 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11985 (cfunc (if (and org-refile-use-outline-path
11986 org-outline-path-complete-in-steps)
11987 'org-olpath-completing-read
11988 'org-icompleting-read))
11989 (extra (if org-refile-use-outline-path "/" ""))
11990 (cbnex (concat (buffer-name) extra))
11991 (filename (and cfn (expand-file-name cfn)))
11992 (tbl (mapcar
11993 (lambda (x)
11994 (if (and (not (member org-refile-use-outline-path
11995 '(file full-file-path)))
11996 (not (equal filename (nth 1 x))))
11997 (cons (concat (car x) extra " ("
11998 (file-name-nondirectory (nth 1 x)) ")")
11999 (cdr x))
12000 (cons (concat (car x) extra) (cdr x))))
12001 org-refile-target-table))
12002 (completion-ignore-case t)
12003 cdef
12004 (prompt (concat prompt
12005 (or (and (car org-refile-history)
12006 (concat " (default " (car org-refile-history) ")"))
12007 (and (assoc cbnex tbl) (setq cdef cbnex)
12008 (concat " (default " cbnex ")"))) ": "))
12009 pa answ parent-target child parent old-hist)
12010 (setq old-hist org-refile-history)
12011 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12012 nil 'org-refile-history (or cdef (car org-refile-history))))
12013 (if (setq pa (org-refile--get-location answ tbl))
12014 (progn
12015 (org-refile-check-position pa)
12016 (when (or (not org-refile-history)
12017 (not (eq old-hist org-refile-history))
12018 (not (equal (car pa) (car org-refile-history))))
12019 (setq org-refile-history
12020 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12021 org-refile-history
12022 (cdr org-refile-history))))
12023 (if (equal (car org-refile-history) (nth 1 org-refile-history))
12024 (pop org-refile-history)))
12026 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12027 (progn
12028 (setq parent (match-string 1 answ)
12029 child (match-string 2 answ))
12030 (setq parent-target (org-refile--get-location parent tbl))
12031 (when (and parent-target
12032 (or (eq new-nodes t)
12033 (and (eq new-nodes 'confirm)
12034 (y-or-n-p (format "Create new node \"%s\"? "
12035 child)))))
12036 (org-refile-new-child parent-target child)))
12037 (user-error "Invalid target location")))))
12039 (declare-function org-string-nw-p "org-macs" (s))
12040 (defun org-refile-check-position (refile-pointer)
12041 "Check if the refile pointer matches the headline to which it points."
12042 (let* ((file (nth 1 refile-pointer))
12043 (re (nth 2 refile-pointer))
12044 (pos (nth 3 refile-pointer))
12045 buffer)
12046 (if (and (not (markerp pos)) (not file))
12047 (user-error "Please indicate a target file in the refile path")
12048 (when (org-string-nw-p re)
12049 (setq buffer (if (markerp pos)
12050 (marker-buffer pos)
12051 (or (find-buffer-visiting file)
12052 (find-file-noselect file))))
12053 (with-current-buffer buffer
12054 (save-excursion
12055 (save-restriction
12056 (widen)
12057 (goto-char pos)
12058 (beginning-of-line 1)
12059 (unless (org-looking-at-p re)
12060 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12062 (defun org-refile-new-child (parent-target child)
12063 "Use refile target PARENT-TARGET to add new CHILD below it."
12064 (unless parent-target
12065 (error "Cannot find parent for new node"))
12066 (let ((file (nth 1 parent-target))
12067 (pos (nth 3 parent-target))
12068 level)
12069 (with-current-buffer (or (find-buffer-visiting file)
12070 (find-file-noselect file))
12071 (save-excursion
12072 (save-restriction
12073 (widen)
12074 (if pos
12075 (goto-char pos)
12076 (goto-char (point-max))
12077 (if (not (bolp)) (newline)))
12078 (when (looking-at org-outline-regexp)
12079 (setq level (funcall outline-level))
12080 (org-end-of-subtree t t))
12081 (org-back-over-empty-lines)
12082 (insert "\n" (make-string
12083 (if pos (org-get-valid-level level 1) 1) ?*)
12084 " " child "\n")
12085 (beginning-of-line 0)
12086 (list (concat (car parent-target) "/" child) file "" (point)))))))
12088 (defun org-olpath-completing-read (prompt collection &rest args)
12089 "Read an outline path like a file name."
12090 (let ((thetable collection)
12091 (org-completion-use-ido nil) ; does not work with ido.
12092 (org-completion-use-iswitchb nil)) ; or iswitchb
12093 (apply #'org-icompleting-read
12094 prompt
12095 (lambda (string predicate &optional flag)
12096 (cond
12097 ((eq flag nil) (try-completion string thetable))
12098 ((eq flag t)
12099 (let ((l (length string)))
12100 (mapcar (lambda (x)
12101 (let ((r (substring x l))
12102 (f (if (string-match " ([^)]*)$" x)
12103 (match-string 0 x)
12104 "")))
12105 (if (string-match "/" r)
12106 (concat string (substring r 0 (match-end 0)) f)
12107 x)))
12108 (all-completions string thetable predicate))))
12109 ;; Exact match?
12110 ((eq flag 'lambda) (assoc string thetable))))
12111 args)))
12113 ;;;; Dynamic blocks
12115 (defun org-find-dblock (name)
12116 "Find the first dynamic block with name NAME in the buffer.
12117 If not found, stay at current position and return nil."
12118 (let ((case-fold-search t) pos)
12119 (save-excursion
12120 (goto-char (point-min))
12121 (setq pos (and (re-search-forward
12122 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12123 (match-beginning 0))))
12124 (if pos (goto-char pos))
12125 pos))
12127 (defun org-create-dblock (plist)
12128 "Create a dynamic block section, with parameters taken from PLIST.
12129 PLIST must contain a :name entry which is used as the name of the block."
12130 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12131 (end-of-line 1)
12132 (newline))
12133 (let ((col (current-column))
12134 (name (plist-get plist :name)))
12135 (insert "#+BEGIN: " name)
12136 (while plist
12137 (if (eq (car plist) :name)
12138 (setq plist (cddr plist))
12139 (insert " " (prin1-to-string (pop plist)))))
12140 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12141 (beginning-of-line -2)))
12143 (defun org-prepare-dblock ()
12144 "Prepare dynamic block for refresh.
12145 This empties the block, puts the cursor at the insert position and returns
12146 the property list including an extra property :name with the block name."
12147 (unless (looking-at org-dblock-start-re)
12148 (user-error "Not at a dynamic block"))
12149 (let* ((begdel (1+ (match-end 0)))
12150 (name (org-no-properties (match-string 1)))
12151 (params (append (list :name name)
12152 (read (concat "(" (match-string 3) ")")))))
12153 (save-excursion
12154 (beginning-of-line 1)
12155 (skip-chars-forward " \t")
12156 (setq params (plist-put params :indentation-column (current-column))))
12157 (unless (re-search-forward org-dblock-end-re nil t)
12158 (error "Dynamic block not terminated"))
12159 (setq params
12160 (append params
12161 (list :content (buffer-substring
12162 begdel (match-beginning 0)))))
12163 (delete-region begdel (match-beginning 0))
12164 (goto-char begdel)
12165 (open-line 1)
12166 params))
12168 (defun org-map-dblocks (&optional command)
12169 "Apply COMMAND to all dynamic blocks in the current buffer.
12170 If COMMAND is not given, use `org-update-dblock'."
12171 (let ((cmd (or command 'org-update-dblock)))
12172 (save-excursion
12173 (goto-char (point-min))
12174 (while (re-search-forward org-dblock-start-re nil t)
12175 (goto-char (match-beginning 0))
12176 (save-excursion
12177 (condition-case nil
12178 (funcall cmd)
12179 (error (message "Error during update of dynamic block"))))
12180 (unless (re-search-forward org-dblock-end-re nil t)
12181 (error "Dynamic block not terminated"))))))
12183 (defun org-dblock-update (&optional arg)
12184 "User command for updating dynamic blocks.
12185 Update the dynamic block at point. With prefix ARG, update all dynamic
12186 blocks in the buffer."
12187 (interactive "P")
12188 (if arg
12189 (org-update-all-dblocks)
12190 (or (looking-at org-dblock-start-re)
12191 (org-beginning-of-dblock))
12192 (org-update-dblock)))
12194 (defun org-update-dblock ()
12195 "Update the dynamic block at point.
12196 This means to empty the block, parse for parameters and then call
12197 the correct writing function."
12198 (interactive)
12199 (save-excursion
12200 (let* ((win (selected-window))
12201 (pos (point))
12202 (line (org-current-line))
12203 (params (org-prepare-dblock))
12204 (name (plist-get params :name))
12205 (indent (plist-get params :indentation-column))
12206 (cmd (intern (concat "org-dblock-write:" name))))
12207 (message "Updating dynamic block `%s' at line %d..." name line)
12208 (funcall cmd params)
12209 (message "Updating dynamic block `%s' at line %d...done" name line)
12210 (goto-char pos)
12211 (when (and indent (> indent 0))
12212 (setq indent (make-string indent ?\ ))
12213 (save-excursion
12214 (select-window win)
12215 (org-beginning-of-dblock)
12216 (forward-line 1)
12217 (while (not (looking-at org-dblock-end-re))
12218 (insert indent)
12219 (beginning-of-line 2))
12220 (when (looking-at org-dblock-end-re)
12221 (and (looking-at "[ \t]+")
12222 (replace-match ""))
12223 (insert indent)))))))
12225 (defun org-beginning-of-dblock ()
12226 "Find the beginning of the dynamic block at point.
12227 Error if there is no such block at point."
12228 (let ((pos (point))
12229 beg)
12230 (end-of-line 1)
12231 (if (and (re-search-backward org-dblock-start-re nil t)
12232 (setq beg (match-beginning 0))
12233 (re-search-forward org-dblock-end-re nil t)
12234 (> (match-end 0) pos))
12235 (goto-char beg)
12236 (goto-char pos)
12237 (error "Not in a dynamic block"))))
12239 (defun org-update-all-dblocks ()
12240 "Update all dynamic blocks in the buffer.
12241 This function can be used in a hook."
12242 (interactive)
12243 (when (derived-mode-p 'org-mode)
12244 (org-map-dblocks 'org-update-dblock)))
12247 ;;;; Completion
12249 (declare-function org-export-backend-name "org-export" (cl-x))
12250 (declare-function org-export-backend-options "org-export" (cl-x))
12251 (defun org-get-export-keywords ()
12252 "Return a list of all currently understood export keywords.
12253 Export keywords include options, block names, attributes and
12254 keywords relative to each registered export back-end."
12255 (let (keywords)
12256 (dolist (backend
12257 (org-bound-and-true-p org-export-registered-backends)
12258 (delq nil keywords))
12259 ;; Back-end name (for keywords, like #+LATEX:)
12260 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12261 (dolist (option-entry (org-export-backend-options backend))
12262 ;; Back-end options.
12263 (push (nth 1 option-entry) keywords)))))
12265 (defconst org-options-keywords
12266 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12267 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12268 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12269 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12270 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12272 (defcustom org-structure-template-alist
12273 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12274 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12275 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12276 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12277 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12278 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12279 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12280 ("L" "#+LaTeX: ")
12281 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12282 ("H" "#+HTML: ")
12283 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12284 ("A" "#+ASCII: ")
12285 ("i" "#+INDEX: ?")
12286 ("I" "#+INCLUDE: %file ?"))
12287 "Structure completion elements.
12288 This is a list of abbreviation keys and values. The value gets inserted
12289 if you type `<' followed by the key and then press the completion key,
12290 usually `TAB'. %file will be replaced by a file name after prompting
12291 for the file using completion. The cursor will be placed at the position
12292 of the `?` in the template.
12293 There are two templates for each key, the first uses the original Org syntax,
12294 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12295 the default when the /org-mtags.el/ module has been loaded. See also the
12296 variable `org-mtags-prefer-muse-templates'."
12297 :group 'org-completion
12298 :type '(repeat
12299 (list
12300 (string :tag "Key")
12301 (string :tag "Template")))
12302 :version "25.1"
12303 :package-version '(Org . "8.3"))
12305 (defun org-try-structure-completion ()
12306 "Try to complete a structure template before point.
12307 This looks for strings like \"<e\" on an otherwise empty line and
12308 expands them."
12309 (let ((l (buffer-substring (point-at-bol) (point)))
12311 (when (and (looking-at "[ \t]*$")
12312 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12313 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12314 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12315 (match-beginning 1)) a)
12316 t)))
12318 (defun org-complete-expand-structure-template (start cell)
12319 "Expand a structure template."
12320 (let ((rpl (nth 1 cell))
12321 (ind ""))
12322 (delete-region start (point))
12323 (when (string-match "\\`[ \t]*#\\+" rpl)
12324 (cond
12325 ((bolp))
12326 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12327 (setq ind (buffer-substring (point-at-bol) (point))))
12328 (t (newline))))
12329 (setq start (point))
12330 (if (string-match "%file" rpl)
12331 (setq rpl (replace-match
12332 (concat
12333 "\""
12334 (save-match-data
12335 (abbreviate-file-name (read-file-name "Include file: ")))
12336 "\"")
12337 t t rpl)))
12338 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12339 (concat "\n" ind)))
12340 (insert rpl)
12341 (if (re-search-backward "\\?" start t) (delete-char 1))))
12343 ;;;; TODO, DEADLINE, Comments
12345 (defun org-toggle-comment ()
12346 "Change the COMMENT state of an entry."
12347 (interactive)
12348 (save-excursion
12349 (org-back-to-heading)
12350 (looking-at org-complex-heading-regexp)
12351 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12352 (skip-chars-forward " \t")
12353 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12354 (if (org-in-commented-heading-p t)
12355 (delete-region (point)
12356 (progn (search-forward " " (line-end-position) 'move)
12357 (skip-chars-forward " \t")
12358 (point)))
12359 (insert org-comment-string)
12360 (unless (eolp) (insert " ")))))
12362 (defvar org-last-todo-state-is-todo nil
12363 "This is non-nil when the last TODO state change led to a TODO state.
12364 If the last change removed the TODO tag or switched to DONE, then
12365 this is nil.")
12367 (defvar org-setting-tags nil) ; dynamically skipped
12369 (defvar org-todo-setup-filter-hook nil
12370 "Hook for functions that pre-filter todo specs.
12371 Each function takes a todo spec and returns either nil or the spec
12372 transformed into canonical form." )
12374 (defvar org-todo-get-default-hook nil
12375 "Hook for functions that get a default item for todo.
12376 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12377 nil or a string to be used for the todo mark." )
12379 (defvar org-agenda-headline-snapshot-before-repeat)
12381 (defun org-current-effective-time ()
12382 "Return current time adjusted for `org-extend-today-until' variable."
12383 (let* ((ct (org-current-time))
12384 (dct (decode-time ct))
12385 (ct1
12386 (cond
12387 (org-use-last-clock-out-time-as-effective-time
12388 (or (org-clock-get-last-clock-out-time) ct))
12389 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12390 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12391 (t ct))))
12392 ct1))
12394 (defun org-todo-yesterday (&optional arg)
12395 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12396 (interactive "P")
12397 (if (eq major-mode 'org-agenda-mode)
12398 (apply 'org-agenda-todo-yesterday arg)
12399 (let* ((org-use-effective-time t)
12400 (hour (third (decode-time
12401 (org-current-time))))
12402 (org-extend-today-until (1+ hour)))
12403 (org-todo arg))))
12405 (defvar org-block-entry-blocking ""
12406 "First entry preventing the TODO state change.")
12408 (defun org-cancel-repeater ()
12409 "Cancel a repeater by setting its numeric value to zero."
12410 (interactive)
12411 (save-excursion
12412 (org-back-to-heading t)
12413 (let ((bound1 (point))
12414 (bound0 (save-excursion (outline-next-heading) (point))))
12415 (when (re-search-forward
12416 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12417 org-deadline-time-regexp "\\)\\|\\("
12418 org-ts-regexp "\\)")
12419 bound0 t)
12420 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12421 (replace-match "0" t nil nil 1))))))
12423 (defun org-todo (&optional arg)
12424 "Change the TODO state of an item.
12425 The state of an item is given by a keyword at the start of the heading,
12426 like
12427 *** TODO Write paper
12428 *** DONE Call mom
12430 The different keywords are specified in the variable `org-todo-keywords'.
12431 By default the available states are \"TODO\" and \"DONE\".
12432 So for this example: when the item starts with TODO, it is changed to DONE.
12433 When it starts with DONE, the DONE is removed. And when neither TODO nor
12434 DONE are present, add TODO at the beginning of the heading.
12436 With \\[universal-argument] prefix arg, use completion to determine the new \
12437 state.
12438 With numeric prefix arg, switch to that state.
12439 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12440 keywords (nextset).
12441 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12442 With a numeric prefix arg of 0, inhibit note taking for the change.
12443 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12445 When called through ELisp, arg is also interpreted in the following way:
12446 'none -> empty state
12447 \"\"(empty string) -> switch to empty state
12448 'done -> switch to DONE
12449 'nextset -> switch to the next set of keywords
12450 'previousset -> switch to the previous set of keywords
12451 \"WAITING\" -> switch to the specified keyword, but only if it
12452 really is a member of `org-todo-keywords'."
12453 (interactive "P")
12454 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12455 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12456 'region-start-level 'region))
12457 org-loop-over-headlines-in-active-region)
12458 (org-map-entries
12459 `(org-todo ,arg)
12460 org-loop-over-headlines-in-active-region
12461 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12462 (if (equal arg '(16)) (setq arg 'nextset))
12463 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12464 (let ((org-blocker-hook org-blocker-hook)
12465 commentp
12466 case-fold-search)
12467 (when (equal arg '(64))
12468 (setq arg nil org-blocker-hook nil))
12469 (when (and org-blocker-hook
12470 (or org-inhibit-blocking
12471 (org-entry-get nil "NOBLOCKING")))
12472 (setq org-blocker-hook nil))
12473 (save-excursion
12474 (catch 'exit
12475 (org-back-to-heading t)
12476 (when (org-in-commented-heading-p t)
12477 (org-toggle-comment)
12478 (setq commentp t))
12479 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12480 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12481 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12482 (let* ((match-data (match-data))
12483 (startpos (point-at-bol))
12484 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12485 (org-log-done org-log-done)
12486 (org-log-repeat org-log-repeat)
12487 (org-todo-log-states org-todo-log-states)
12488 (org-inhibit-logging
12489 (if (equal arg 0)
12490 (progn (setq arg nil) 'note) org-inhibit-logging))
12491 (this (match-string 1))
12492 (hl-pos (match-beginning 0))
12493 (head (org-get-todo-sequence-head this))
12494 (ass (assoc head org-todo-kwd-alist))
12495 (interpret (nth 1 ass))
12496 (done-word (nth 3 ass))
12497 (final-done-word (nth 4 ass))
12498 (org-last-state (or this ""))
12499 (completion-ignore-case t)
12500 (member (member this org-todo-keywords-1))
12501 (tail (cdr member))
12502 (org-state (cond
12503 ((and org-todo-key-trigger
12504 (or (and (equal arg '(4))
12505 (eq org-use-fast-todo-selection 'prefix))
12506 (and (not arg) org-use-fast-todo-selection
12507 (not (eq org-use-fast-todo-selection
12508 'prefix)))))
12509 ;; Use fast selection
12510 (org-fast-todo-selection))
12511 ((and (equal arg '(4))
12512 (or (not org-use-fast-todo-selection)
12513 (not org-todo-key-trigger)))
12514 ;; Read a state with completion
12515 (org-icompleting-read
12516 "State: " (mapcar 'list org-todo-keywords-1)
12517 nil t))
12518 ((eq arg 'right)
12519 (if this
12520 (if tail (car tail) nil)
12521 (car org-todo-keywords-1)))
12522 ((eq arg 'left)
12523 (if (equal member org-todo-keywords-1)
12525 (if this
12526 (nth (- (length org-todo-keywords-1)
12527 (length tail) 2)
12528 org-todo-keywords-1)
12529 (org-last org-todo-keywords-1))))
12530 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12531 (setq arg nil))) ; hack to fall back to cycling
12532 (arg
12533 ;; user or caller requests a specific state
12534 (cond
12535 ((equal arg "") nil)
12536 ((eq arg 'none) nil)
12537 ((eq arg 'done) (or done-word (car org-done-keywords)))
12538 ((eq arg 'nextset)
12539 (or (car (cdr (member head org-todo-heads)))
12540 (car org-todo-heads)))
12541 ((eq arg 'previousset)
12542 (let ((org-todo-heads (reverse org-todo-heads)))
12543 (or (car (cdr (member head org-todo-heads)))
12544 (car org-todo-heads))))
12545 ((car (member arg org-todo-keywords-1)))
12546 ((stringp arg)
12547 (user-error "State `%s' not valid in this file" arg))
12548 ((nth (1- (prefix-numeric-value arg))
12549 org-todo-keywords-1))))
12550 ((null member) (or head (car org-todo-keywords-1)))
12551 ((equal this final-done-word) nil) ;; -> make empty
12552 ((null tail) nil) ;; -> first entry
12553 ((memq interpret '(type priority))
12554 (if (eq this-command last-command)
12555 (car tail)
12556 (if (> (length tail) 0)
12557 (or done-word (car org-done-keywords))
12558 nil)))
12560 (car tail))))
12561 (org-state (or
12562 (run-hook-with-args-until-success
12563 'org-todo-get-default-hook org-state org-last-state)
12564 org-state))
12565 (next (if org-state (concat " " org-state " ") " "))
12566 (change-plist (list :type 'todo-state-change :from this :to org-state
12567 :position startpos))
12568 dolog now-done-p)
12569 (when org-blocker-hook
12570 (setq org-last-todo-state-is-todo
12571 (not (member this org-done-keywords)))
12572 (unless (save-excursion
12573 (save-match-data
12574 (org-with-wide-buffer
12575 (run-hook-with-args-until-failure
12576 'org-blocker-hook change-plist))))
12577 (if (org-called-interactively-p 'interactive)
12578 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12579 this org-state org-block-entry-blocking)
12580 ;; fail silently
12581 (message "TODO state change from %s to %s blocked (by \"%s\")"
12582 this org-state org-block-entry-blocking)
12583 (throw 'exit nil))))
12584 (store-match-data match-data)
12585 (replace-match next t t)
12586 (cond ((equal this org-state)
12587 (message "TODO state was already %s" (org-trim next)))
12588 ((pos-visible-in-window-p hl-pos)
12589 (message "TODO state changed to %s" (org-trim next))))
12590 (unless head
12591 (setq head (org-get-todo-sequence-head org-state)
12592 ass (assoc head org-todo-kwd-alist)
12593 interpret (nth 1 ass)
12594 done-word (nth 3 ass)
12595 final-done-word (nth 4 ass)))
12596 (when (memq arg '(nextset previousset))
12597 (message "Keyword-Set %d/%d: %s"
12598 (- (length org-todo-sets) -1
12599 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12600 (length org-todo-sets)
12601 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12602 (setq org-last-todo-state-is-todo
12603 (not (member org-state org-done-keywords)))
12604 (setq now-done-p (and (member org-state org-done-keywords)
12605 (not (member this org-done-keywords))))
12606 (and logging (org-local-logging logging))
12607 (when (and (or org-todo-log-states org-log-done)
12608 (not (eq org-inhibit-logging t))
12609 (not (memq arg '(nextset previousset))))
12610 ;; we need to look at recording a time and note
12611 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12612 (nth 2 (assoc this org-todo-log-states))))
12613 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12614 (setq dolog 'time))
12615 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12616 (and org-state
12617 (member org-state org-not-done-keywords)
12618 (not (member this org-not-done-keywords))))
12619 ;; This is now a todo state and was not one before
12620 ;; If there was a CLOSED time stamp, get rid of it.
12621 (org-add-planning-info nil nil 'closed))
12622 (when (and now-done-p org-log-done)
12623 ;; It is now done, and it was not done before
12624 (org-add-planning-info 'closed (org-current-effective-time))
12625 (if (and (not dolog) (eq 'note org-log-done))
12626 (org-add-log-setup 'done org-state this 'findpos 'note)))
12627 (when (and org-state dolog)
12628 ;; This is a non-nil state, and we need to log it
12629 (org-add-log-setup 'state org-state this 'findpos dolog)))
12630 ;; Fixup tag positioning
12631 (org-todo-trigger-tag-changes org-state)
12632 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12633 (when org-provide-todo-statistics
12634 (org-update-parent-todo-statistics))
12635 (run-hooks 'org-after-todo-state-change-hook)
12636 (if (and arg (not (member org-state org-done-keywords)))
12637 (setq head (org-get-todo-sequence-head org-state)))
12638 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12639 ;; Do we need to trigger a repeat?
12640 (when now-done-p
12641 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12642 ;; This is for the agenda, take a snapshot of the headline.
12643 (save-match-data
12644 (setq org-agenda-headline-snapshot-before-repeat
12645 (org-get-heading))))
12646 (org-auto-repeat-maybe org-state))
12647 ;; Fixup cursor location if close to the keyword
12648 (if (and (outline-on-heading-p)
12649 (not (bolp))
12650 (save-excursion (beginning-of-line 1)
12651 (looking-at org-todo-line-regexp))
12652 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12653 (progn
12654 (goto-char (or (match-end 2) (match-end 1)))
12655 (and (looking-at " ") (just-one-space))))
12656 (when org-trigger-hook
12657 (save-excursion
12658 (run-hook-with-args 'org-trigger-hook change-plist)))
12659 (when commentp (org-toggle-comment))))))))
12661 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12662 "Block turning an entry into a TODO, using the hierarchy.
12663 This checks whether the current task should be blocked from state
12664 changes. Such blocking occurs when:
12666 1. The task has children which are not all in a completed state.
12668 2. A task has a parent with the property :ORDERED:, and there
12669 are siblings prior to the current task with incomplete
12670 status.
12672 3. The parent of the task is blocked because it has siblings that should
12673 be done first, or is child of a block grandparent TODO entry."
12675 (if (not org-enforce-todo-dependencies)
12676 t ; if locally turned off don't block
12677 (catch 'dont-block
12678 ;; If this is not a todo state change, or if this entry is already DONE,
12679 ;; do not block
12680 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12681 (member (plist-get change-plist :from)
12682 (cons 'done org-done-keywords))
12683 (member (plist-get change-plist :to)
12684 (cons 'todo org-not-done-keywords))
12685 (not (plist-get change-plist :to)))
12686 (throw 'dont-block t))
12687 ;; If this task has children, and any are undone, it's blocked
12688 (save-excursion
12689 (org-back-to-heading t)
12690 (let ((this-level (funcall outline-level)))
12691 (outline-next-heading)
12692 (let ((child-level (funcall outline-level)))
12693 (while (and (not (eobp))
12694 (> child-level this-level))
12695 ;; this todo has children, check whether they are all
12696 ;; completed
12697 (if (and (not (org-entry-is-done-p))
12698 (org-entry-is-todo-p))
12699 (progn (setq org-block-entry-blocking (org-get-heading))
12700 (throw 'dont-block nil)))
12701 (outline-next-heading)
12702 (setq child-level (funcall outline-level))))))
12703 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12704 ;; any previous siblings are undone, it's blocked
12705 (save-excursion
12706 (org-back-to-heading t)
12707 (let* ((pos (point))
12708 (parent-pos (and (org-up-heading-safe) (point))))
12709 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12710 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12711 (forward-line 1)
12712 (re-search-forward org-not-done-heading-regexp pos t))
12713 (setq org-block-entry-blocking (match-string 0))
12714 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12715 ;; Search further up the hierarchy, to see if an ancestor is blocked
12716 (while t
12717 (goto-char parent-pos)
12718 (if (not (looking-at org-not-done-heading-regexp))
12719 (throw 'dont-block t)) ; do not block, parent is not a TODO
12720 (setq pos (point))
12721 (setq parent-pos (and (org-up-heading-safe) (point)))
12722 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12723 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12724 (forward-line 1)
12725 (re-search-forward org-not-done-heading-regexp pos t)
12726 (setq org-block-entry-blocking (org-get-heading)))
12727 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12729 (defcustom org-track-ordered-property-with-tag nil
12730 "Should the ORDERED property also be shown as a tag?
12731 The ORDERED property decides if an entry should require subtasks to be
12732 completed in sequence. Since a property is not very visible, setting
12733 this option means that toggling the ORDERED property with the command
12734 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12735 not relevant for the behavior, but it makes things more visible.
12737 Note that toggling the tag with tags commands will not change the property
12738 and therefore not influence behavior!
12740 This can be t, meaning the tag ORDERED should be used, It can also be a
12741 string to select a different tag for this task."
12742 :group 'org-todo
12743 :type '(choice
12744 (const :tag "No tracking" nil)
12745 (const :tag "Track with ORDERED tag" t)
12746 (string :tag "Use other tag")))
12748 (defun org-toggle-ordered-property ()
12749 "Toggle the ORDERED property of the current entry.
12750 For better visibility, you can track the value of this property with a tag.
12751 See variable `org-track-ordered-property-with-tag'."
12752 (interactive)
12753 (let* ((t1 org-track-ordered-property-with-tag)
12754 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12755 (save-excursion
12756 (org-back-to-heading)
12757 (if (org-entry-get nil "ORDERED")
12758 (progn
12759 (org-delete-property "ORDERED")
12760 (and tag (org-toggle-tag tag 'off))
12761 (message "Subtasks can be completed in arbitrary order"))
12762 (org-entry-put nil "ORDERED" "t")
12763 (and tag (org-toggle-tag tag 'on))
12764 (message "Subtasks must be completed in sequence")))))
12766 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12767 (defun org-block-todo-from-checkboxes (change-plist)
12768 "Block turning an entry into a TODO, using checkboxes.
12769 This checks whether the current task should be blocked from state
12770 changes because there are unchecked boxes in this entry."
12771 (if (not org-enforce-todo-checkbox-dependencies)
12772 t ; if locally turned off don't block
12773 (catch 'dont-block
12774 ;; If this is not a todo state change, or if this entry is already DONE,
12775 ;; do not block
12776 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12777 (member (plist-get change-plist :from)
12778 (cons 'done org-done-keywords))
12779 (member (plist-get change-plist :to)
12780 (cons 'todo org-not-done-keywords))
12781 (not (plist-get change-plist :to)))
12782 (throw 'dont-block t))
12783 ;; If this task has checkboxes that are not checked, it's blocked
12784 (save-excursion
12785 (org-back-to-heading t)
12786 (let ((beg (point)) end)
12787 (outline-next-heading)
12788 (setq end (point))
12789 (goto-char beg)
12790 (if (org-list-search-forward
12791 (concat (org-item-beginning-re)
12792 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12793 "\\[[- ]\\]")
12794 end t)
12795 (progn
12796 (if (boundp 'org-blocked-by-checkboxes)
12797 (setq org-blocked-by-checkboxes t))
12798 (throw 'dont-block nil)))))
12799 t))) ; do not block
12801 (defun org-entry-blocked-p ()
12802 "Is the current entry blocked?"
12803 (org-with-silent-modifications
12804 (if (org-entry-get nil "NOBLOCKING")
12805 nil ;; Never block this entry
12806 (not (run-hook-with-args-until-failure
12807 'org-blocker-hook
12808 (list :type 'todo-state-change
12809 :position (point)
12810 :from 'todo
12811 :to 'done))))))
12813 (defun org-update-statistics-cookies (all)
12814 "Update the statistics cookie, either from TODO or from checkboxes.
12815 This should be called with the cursor in a line with a statistics cookie."
12816 (interactive "P")
12817 (if all
12818 (progn
12819 (org-update-checkbox-count 'all)
12820 (org-map-entries 'org-update-parent-todo-statistics))
12821 (if (not (org-at-heading-p))
12822 (org-update-checkbox-count)
12823 (let ((pos (point-marker))
12824 end l1 l2)
12825 (ignore-errors (org-back-to-heading t))
12826 (if (not (org-at-heading-p))
12827 (org-update-checkbox-count)
12828 (setq l1 (org-outline-level))
12829 (setq end (save-excursion
12830 (outline-next-heading)
12831 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12832 (point)))
12833 (if (and (save-excursion
12834 (re-search-forward
12835 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12836 (not (save-excursion (re-search-forward
12837 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12838 (org-update-checkbox-count)
12839 (if (and l2 (> l2 l1))
12840 (progn
12841 (goto-char end)
12842 (org-update-parent-todo-statistics))
12843 (goto-char pos)
12844 (beginning-of-line 1)
12845 (while (re-search-forward
12846 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12847 (point-at-eol) t)
12848 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12849 (goto-char pos)
12850 (move-marker pos nil)))))
12852 (defvar org-entry-property-inherited-from) ;; defined below
12853 (defun org-update-parent-todo-statistics ()
12854 "Update any statistics cookie in the parent of the current headline.
12855 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12856 the entire subtree and this will travel up the hierarchy and update
12857 statistics everywhere."
12858 (let* ((prop (save-excursion (org-up-heading-safe)
12859 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12860 (recursive (or (not org-hierarchical-todo-statistics)
12861 (and prop (string-match "\\<recursive\\>" prop))))
12862 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12864 (first t)
12865 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12866 level ltoggle l1 new ndel
12867 (cnt-all 0) (cnt-done 0) is-percent kwd
12868 checkbox-beg ov ovs ove cookie-present)
12869 (catch 'exit
12870 (save-excursion
12871 (beginning-of-line 1)
12872 (setq ltoggle (funcall outline-level))
12873 ;; Three situations are to consider:
12875 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12876 ;; to the top-level ancestor on the headline;
12878 ;; 2. If parent has "recursive" property, repeat up to the
12879 ;; headline setting that property, taking inheritance into
12880 ;; account;
12882 ;; 3. Else, move up to direct parent and proceed only once.
12883 (while (and (setq level (org-up-heading-safe))
12884 (or recursive first)
12885 (>= (point) lim))
12886 (setq first nil cookie-present nil)
12887 (unless (and level
12888 (not (string-match
12889 "\\<checkbox\\>"
12890 (downcase (or (org-entry-get nil "COOKIE_DATA")
12891 "")))))
12892 (throw 'exit nil))
12893 (while (re-search-forward box-re (point-at-eol) t)
12894 (setq cnt-all 0 cnt-done 0 cookie-present t)
12895 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12896 (save-match-data
12897 (unless (outline-next-heading) (throw 'exit nil))
12898 (while (and (looking-at org-complex-heading-regexp)
12899 (> (setq l1 (length (match-string 1))) level))
12900 (setq kwd (and (or recursive (= l1 ltoggle))
12901 (match-string 2)))
12902 (if (or (eq org-provide-todo-statistics 'all-headlines)
12903 (and (eq org-provide-todo-statistics t)
12904 (or (member kwd org-done-keywords)))
12905 (and (listp org-provide-todo-statistics)
12906 (stringp (car org-provide-todo-statistics))
12907 (or (member kwd org-provide-todo-statistics)
12908 (member kwd org-done-keywords)))
12909 (and (listp org-provide-todo-statistics)
12910 (listp (car org-provide-todo-statistics))
12911 (or (member kwd (car org-provide-todo-statistics))
12912 (and (member kwd org-done-keywords)
12913 (member kwd (cadr org-provide-todo-statistics))))))
12914 (setq cnt-all (1+ cnt-all))
12915 (if (eq org-provide-todo-statistics t)
12916 (and kwd (setq cnt-all (1+ cnt-all)))))
12917 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12918 (member kwd org-done-keywords))
12919 (and (listp org-provide-todo-statistics)
12920 (listp (car org-provide-todo-statistics))
12921 (member kwd org-done-keywords)
12922 (member kwd (cadr org-provide-todo-statistics)))
12923 (and (listp org-provide-todo-statistics)
12924 (stringp (car org-provide-todo-statistics))
12925 (member kwd org-done-keywords)))
12926 (setq cnt-done (1+ cnt-done)))
12927 (outline-next-heading)))
12928 (setq new
12929 (if is-percent
12930 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12931 (format "[%d/%d]" cnt-done cnt-all))
12932 ndel (- (match-end 0) checkbox-beg))
12933 ;; handle overlays when updating cookie from column view
12934 (when (setq ov (car (overlays-at checkbox-beg)))
12935 (setq ovs (overlay-start ov) ove (overlay-end ov))
12936 (delete-overlay ov))
12937 (goto-char checkbox-beg)
12938 (insert new)
12939 (delete-region (point) (+ (point) ndel))
12940 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12941 (when ov (move-overlay ov ovs ove)))
12942 (when cookie-present
12943 (run-hook-with-args 'org-after-todo-statistics-hook
12944 cnt-done (- cnt-all cnt-done))))))
12945 (run-hooks 'org-todo-statistics-hook)))
12947 (defvar org-after-todo-statistics-hook nil
12948 "Hook that is called after a TODO statistics cookie has been updated.
12949 Each function is called with two arguments: the number of not-done entries
12950 and the number of done entries.
12952 For example, the following function, when added to this hook, will switch
12953 an entry to DONE when all children are done, and back to TODO when new
12954 entries are set to a TODO status. Note that this hook is only called
12955 when there is a statistics cookie in the headline!
12957 (defun org-summary-todo (n-done n-not-done)
12958 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12959 (let (org-log-done org-log-states) ; turn off logging
12960 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12963 (defvar org-todo-statistics-hook nil
12964 "Hook that is run whenever Org thinks TODO statistics should be updated.
12965 This hook runs even if there is no statistics cookie present, in which case
12966 `org-after-todo-statistics-hook' would not run.")
12968 (defun org-todo-trigger-tag-changes (state)
12969 "Apply the changes defined in `org-todo-state-tags-triggers'."
12970 (let ((l org-todo-state-tags-triggers)
12971 changes)
12972 (when (or (not state) (equal state ""))
12973 (setq changes (append changes (cdr (assoc "" l)))))
12974 (when (and (stringp state) (> (length state) 0))
12975 (setq changes (append changes (cdr (assoc state l)))))
12976 (when (member state org-not-done-keywords)
12977 (setq changes (append changes (cdr (assoc 'todo l)))))
12978 (when (member state org-done-keywords)
12979 (setq changes (append changes (cdr (assoc 'done l)))))
12980 (dolist (c changes)
12981 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12983 (defun org-local-logging (value)
12984 "Get logging settings from a property VALUE."
12985 (let* (words w a)
12986 ;; directly set the variables, they are already local.
12987 (setq org-log-done nil
12988 org-log-repeat nil
12989 org-todo-log-states nil)
12990 (setq words (org-split-string value))
12991 (while (setq w (pop words))
12992 (cond
12993 ((setq a (assoc w org-startup-options))
12994 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12995 (set (nth 1 a) (nth 2 a))))
12996 ((setq a (org-extract-log-state-settings w))
12997 (and (member (car a) org-todo-keywords-1)
12998 (push a org-todo-log-states)))))))
13000 (defun org-get-todo-sequence-head (kwd)
13001 "Return the head of the TODO sequence to which KWD belongs.
13002 If KWD is not set, check if there is a text property remembering the
13003 right sequence."
13004 (let (p)
13005 (cond
13006 ((not kwd)
13007 (or (get-text-property (point-at-bol) 'org-todo-head)
13008 (progn
13009 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13010 nil (point-at-eol)))
13011 (get-text-property p 'org-todo-head))))
13012 ((not (member kwd org-todo-keywords-1))
13013 (car org-todo-keywords-1))
13014 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13016 (defun org-fast-todo-selection ()
13017 "Fast TODO keyword selection with single keys.
13018 Returns the new TODO keyword, or nil if no state change should occur."
13019 (let* ((fulltable org-todo-key-alist)
13020 (done-keywords org-done-keywords) ;; needed for the faces.
13021 (maxlen (apply 'max (mapcar
13022 (lambda (x)
13023 (if (stringp (car x)) (string-width (car x)) 0))
13024 fulltable)))
13025 (expert nil)
13026 (fwidth (+ maxlen 3 1 3))
13027 (ncol (/ (- (window-width) 4) fwidth))
13028 tg cnt e c tbl
13029 groups ingroup)
13030 (save-excursion
13031 (save-window-excursion
13032 (if expert
13033 (set-buffer (get-buffer-create " *Org todo*"))
13034 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13035 (erase-buffer)
13036 (org-set-local 'org-done-keywords done-keywords)
13037 (setq tbl fulltable cnt 0)
13038 (while (setq e (pop tbl))
13039 (cond
13040 ((equal e '(:startgroup))
13041 (push '() groups) (setq ingroup t)
13042 (when (not (= cnt 0))
13043 (setq cnt 0)
13044 (insert "\n"))
13045 (insert "{ "))
13046 ((equal e '(:endgroup))
13047 (setq ingroup nil cnt 0)
13048 (insert "}\n"))
13049 ((equal e '(:newline))
13050 (when (not (= cnt 0))
13051 (setq cnt 0)
13052 (insert "\n")
13053 (setq e (car tbl))
13054 (while (equal (car tbl) '(:newline))
13055 (insert "\n")
13056 (setq tbl (cdr tbl)))))
13058 (setq tg (car e) c (cdr e))
13059 (if ingroup (push tg (car groups)))
13060 (setq tg (org-add-props tg nil 'face
13061 (org-get-todo-face tg)))
13062 (if (and (= cnt 0) (not ingroup)) (insert " "))
13063 (insert "[" c "] " tg (make-string
13064 (- fwidth 4 (length tg)) ?\ ))
13065 (when (= (setq cnt (1+ cnt)) ncol)
13066 (insert "\n")
13067 (if ingroup (insert " "))
13068 (setq cnt 0)))))
13069 (insert "\n")
13070 (goto-char (point-min))
13071 (if (not expert) (org-fit-window-to-buffer))
13072 (message "[a-z..]:Set [SPC]:clear")
13073 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13074 (cond
13075 ((or (= c ?\C-g)
13076 (and (= c ?q) (not (rassoc c fulltable))))
13077 (setq quit-flag t))
13078 ((= c ?\ ) nil)
13079 ((setq e (rassoc c fulltable) tg (car e))
13081 (t (setq quit-flag t)))))))
13083 (defun org-entry-is-todo-p ()
13084 (member (org-get-todo-state) org-not-done-keywords))
13086 (defun org-entry-is-done-p ()
13087 (member (org-get-todo-state) org-done-keywords))
13089 (defun org-get-todo-state ()
13090 "Return the TODO keyword of the current subtree."
13091 (save-excursion
13092 (org-back-to-heading t)
13093 (and (looking-at org-todo-line-regexp)
13094 (match-end 2)
13095 (match-string 2))))
13097 (defun org-at-date-range-p (&optional inactive-ok)
13098 "Is the cursor inside a date range?"
13099 (interactive)
13100 (save-excursion
13101 (catch 'exit
13102 (let ((pos (point)))
13103 (skip-chars-backward "^[<\r\n")
13104 (skip-chars-backward "<[")
13105 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13106 (>= (match-end 0) pos)
13107 (throw 'exit t))
13108 (skip-chars-backward "^<[\r\n")
13109 (skip-chars-backward "<[")
13110 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13111 (>= (match-end 0) pos)
13112 (throw 'exit t)))
13113 nil)))
13115 (defun org-get-repeat (&optional tagline)
13116 "Check if there is a deadline/schedule with repeater in this entry."
13117 (save-match-data
13118 (save-excursion
13119 (org-back-to-heading t)
13120 (and (re-search-forward (if tagline
13121 (concat tagline "\\s-*" org-repeat-re)
13122 org-repeat-re)
13123 (org-entry-end-position) t)
13124 (match-string-no-properties 1)))))
13126 (defvar org-last-changed-timestamp)
13127 (defvar org-last-inserted-timestamp)
13128 (defvar org-log-post-message)
13129 (defvar org-log-note-purpose)
13130 (defvar org-log-note-how nil)
13131 (defvar org-log-note-extra)
13132 (defun org-auto-repeat-maybe (done-word)
13133 "Check if the current headline contains a repeated deadline/schedule.
13134 If yes, set TODO state back to what it was and change the base date
13135 of repeating deadline/scheduled time stamps to new date.
13136 This function is run automatically after each state change to a DONE state."
13137 ;; last-state is dynamically scoped into this function
13138 (let* ((repeat (org-get-repeat))
13139 (aa (assoc org-last-state org-todo-kwd-alist))
13140 (interpret (nth 1 aa))
13141 (head (nth 2 aa))
13142 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13143 (msg "Entry repeats: ")
13144 (org-log-done nil)
13145 (org-todo-log-states nil)
13146 re type n what ts time to-state)
13147 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13148 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13149 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13150 org-todo-repeat-to-state))
13151 (unless (and to-state (member to-state org-todo-keywords-1))
13152 (setq to-state (if (eq interpret 'type) org-last-state head)))
13153 (org-todo to-state)
13154 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13155 (org-entry-put nil "LAST_REPEAT" (format-time-string
13156 (org-time-stamp-format t t))))
13157 (when org-log-repeat
13158 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13159 (memq 'org-add-log-note post-command-hook))
13160 ;; OK, we are already setup for some record
13161 (if (eq org-log-repeat 'note)
13162 ;; make sure we take a note, not only a time stamp
13163 (setq org-log-note-how 'note))
13164 ;; Set up for taking a record
13165 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13166 org-last-state
13167 'findpos org-log-repeat)))
13168 (org-back-to-heading t)
13169 (org-add-planning-info nil nil 'closed)
13170 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13171 org-deadline-time-regexp "\\)\\|\\("
13172 org-ts-regexp "\\)"))
13173 (while (re-search-forward
13174 re (save-excursion (outline-next-heading) (point)) t)
13175 (setq type (if (match-end 1) org-scheduled-string
13176 (if (match-end 3) org-deadline-string "Plain:"))
13177 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13178 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13179 (setq n (string-to-number (match-string 2 ts))
13180 what (match-string 3 ts))
13181 (if (equal what "w") (setq n (* n 7) what "d"))
13182 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13183 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13184 ;; Preparation, see if we need to modify the start date for the change
13185 (when (match-end 1)
13186 (setq time (save-match-data (org-time-string-to-time ts)))
13187 (cond
13188 ((equal (match-string 1 ts) ".")
13189 ;; Shift starting date to today
13190 (org-timestamp-change
13191 (- (org-today) (time-to-days time))
13192 'day))
13193 ((equal (match-string 1 ts) "+")
13194 (let ((nshiftmax 10) (nshift 0))
13195 (while (or (= nshift 0)
13196 (<= (time-to-days time)
13197 (time-to-days (current-time))))
13198 (when (= (incf nshift) nshiftmax)
13199 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13200 (user-error "Abort")))
13201 (org-timestamp-change n (cdr (assoc what whata)))
13202 (org-at-timestamp-p t)
13203 (setq ts (match-string 1))
13204 (setq time (save-match-data (org-time-string-to-time ts)))))
13205 (org-timestamp-change (- n) (cdr (assoc what whata)))
13206 ;; rematch, so that we have everything in place for the real shift
13207 (org-at-timestamp-p t)
13208 (setq ts (match-string 1))
13209 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13210 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13211 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13212 (setq org-log-post-message msg)
13213 (message "%s" msg))))
13215 (defun org-show-todo-tree (arg)
13216 "Make a compact tree which shows all headlines marked with TODO.
13217 The tree will show the lines where the regexp matches, and all higher
13218 headlines above the match.
13219 With a \\[universal-argument] prefix, prompt for a regexp to match.
13220 With a numeric prefix N, construct a sparse tree for the Nth element
13221 of `org-todo-keywords-1'."
13222 (interactive "P")
13223 (let ((case-fold-search nil)
13224 (kwd-re
13225 (cond ((null arg) org-not-done-regexp)
13226 ((equal arg '(4))
13227 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13228 (mapcar 'list org-todo-keywords-1))))
13229 (concat "\\("
13230 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13231 "\\)\\>")))
13232 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13233 (regexp-quote (nth (1- (prefix-numeric-value arg))
13234 org-todo-keywords-1)))
13235 (t (user-error "Invalid prefix argument: %s" arg)))))
13236 (message "%d TODO entries found"
13237 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13239 (defun org-deadline (arg &optional time)
13240 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13241 With one universal prefix argument, remove any deadline from the item.
13242 With two universal prefix arguments, prompt for a warning delay.
13243 With argument TIME, set the deadline at the corresponding date. TIME
13244 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13245 (interactive "P")
13246 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13247 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13248 'region-start-level 'region))
13249 org-loop-over-headlines-in-active-region)
13250 (org-map-entries
13251 `(org-deadline ',arg ,time)
13252 org-loop-over-headlines-in-active-region
13253 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13254 (let* ((old-date (org-entry-get nil "DEADLINE"))
13255 (old-date-time (if old-date (org-time-string-to-time old-date)))
13256 (repeater (and old-date
13257 (string-match
13258 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13259 old-date)
13260 (match-string 1 old-date))))
13261 (cond
13262 ((equal arg '(4))
13263 (when (and old-date org-log-redeadline)
13264 (org-add-log-setup 'deldeadline nil old-date 'findpos
13265 org-log-redeadline))
13266 (org-remove-timestamp-with-keyword org-deadline-string)
13267 (message "Item no longer has a deadline."))
13268 ((equal arg '(16))
13269 (save-excursion
13270 (org-back-to-heading t)
13271 (if (re-search-forward
13272 org-deadline-time-regexp
13273 (save-excursion (outline-next-heading) (point)) t)
13274 (let* ((rpl0 (match-string 1))
13275 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13276 (replace-match
13277 (concat org-deadline-string
13278 " <" rpl
13279 (format " -%dd"
13280 (abs
13281 (- (time-to-days
13282 (save-match-data
13283 (org-read-date nil t nil "Warn starting from" old-date-time)))
13284 (time-to-days old-date-time))))
13285 ">") t t))
13286 (user-error "No deadline information to update"))))
13288 (org-add-planning-info 'deadline time 'closed)
13289 (when (and old-date org-log-redeadline
13290 (not (equal old-date
13291 (substring org-last-inserted-timestamp 1 -1))))
13292 (org-add-log-setup 'redeadline nil old-date 'findpos
13293 org-log-redeadline))
13294 (when repeater
13295 (save-excursion
13296 (org-back-to-heading t)
13297 (when (re-search-forward (concat org-deadline-string " "
13298 org-last-inserted-timestamp)
13299 (save-excursion
13300 (outline-next-heading) (point)) t)
13301 (goto-char (1- (match-end 0)))
13302 (insert " " repeater)
13303 (setq org-last-inserted-timestamp
13304 (concat (substring org-last-inserted-timestamp 0 -1)
13305 " " repeater
13306 (substring org-last-inserted-timestamp -1))))))
13307 (message "Deadline on %s" org-last-inserted-timestamp))))))
13309 (defun org-schedule (arg &optional time)
13310 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13311 With one universal prefix argument, remove any scheduling date from the item.
13312 With two universal prefix arguments, prompt for a delay cookie.
13313 With argument TIME, scheduled at the corresponding date. TIME can
13314 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13315 (interactive "P")
13316 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13317 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13318 'region-start-level 'region))
13319 org-loop-over-headlines-in-active-region)
13320 (org-map-entries
13321 `(org-schedule ',arg ,time)
13322 org-loop-over-headlines-in-active-region
13323 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13324 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13325 (old-date-time (if old-date (org-time-string-to-time old-date)))
13326 (repeater (and old-date
13327 (string-match
13328 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13329 old-date)
13330 (match-string 1 old-date))))
13331 (cond
13332 ((equal arg '(4))
13333 (progn
13334 (when (and old-date org-log-reschedule)
13335 (org-add-log-setup 'delschedule nil old-date 'findpos
13336 org-log-reschedule))
13337 (org-remove-timestamp-with-keyword org-scheduled-string)
13338 (message "Item is no longer scheduled.")))
13339 ((equal arg '(16))
13340 (save-excursion
13341 (org-back-to-heading t)
13342 (if (re-search-forward
13343 org-scheduled-time-regexp
13344 (save-excursion (outline-next-heading) (point)) t)
13345 (let* ((rpl0 (match-string 1))
13346 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13347 (replace-match
13348 (concat org-scheduled-string
13349 " <" rpl
13350 (format " -%dd"
13351 (abs
13352 (- (time-to-days
13353 (save-match-data
13354 (org-read-date nil t nil "Delay until" old-date-time)))
13355 (time-to-days old-date-time))))
13356 ">") t t))
13357 (user-error "No scheduled information to update"))))
13359 (org-add-planning-info 'scheduled time 'closed)
13360 (when (and old-date org-log-reschedule
13361 (not (equal old-date
13362 (substring org-last-inserted-timestamp 1 -1))))
13363 (org-add-log-setup 'reschedule nil old-date 'findpos
13364 org-log-reschedule))
13365 (when repeater
13366 (save-excursion
13367 (org-back-to-heading t)
13368 (when (re-search-forward (concat org-scheduled-string " "
13369 org-last-inserted-timestamp)
13370 (save-excursion
13371 (outline-next-heading) (point)) t)
13372 (goto-char (1- (match-end 0)))
13373 (insert " " repeater)
13374 (setq org-last-inserted-timestamp
13375 (concat (substring org-last-inserted-timestamp 0 -1)
13376 " " repeater
13377 (substring org-last-inserted-timestamp -1))))))
13378 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13380 (defun org-get-scheduled-time (pom &optional inherit)
13381 "Get the scheduled time as a time tuple, of a format suitable
13382 for calling org-schedule with, or if there is no scheduling,
13383 returns nil."
13384 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13385 (when time
13386 (apply 'encode-time (org-parse-time-string time)))))
13388 (defun org-get-deadline-time (pom &optional inherit)
13389 "Get the deadline as a time tuple, of a format suitable for
13390 calling org-deadline with, or if there is no scheduling, returns
13391 nil."
13392 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13393 (when time
13394 (apply 'encode-time (org-parse-time-string time)))))
13396 (defun org-remove-timestamp-with-keyword (keyword)
13397 "Remove all time stamps with KEYWORD in the current entry."
13398 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13399 beg)
13400 (save-excursion
13401 (org-back-to-heading t)
13402 (setq beg (point))
13403 (outline-next-heading)
13404 (while (re-search-backward re beg t)
13405 (replace-match "")
13406 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13407 (equal (char-before) ?\ ))
13408 (backward-delete-char 1)
13409 (if (string-match "^[ \t]*$" (buffer-substring
13410 (point-at-bol) (point-at-eol)))
13411 (delete-region (point-at-bol)
13412 (min (point-max) (1+ (point-at-eol))))))))))
13414 (defvar org-time-was-given) ; dynamically scoped parameter
13415 (defvar org-end-time-was-given) ; dynamically scoped parameter
13417 (defun org-at-planning-p ()
13418 "Non-nil when point is on a planning info line."
13419 ;; This is as accurate and faster than `org-element-at-point' since
13420 ;; planning info location is fixed in the section.
13421 (org-with-wide-buffer
13422 (beginning-of-line)
13423 (and (org-looking-at-p org-planning-line-re)
13424 (eq (point)
13425 (ignore-errors
13426 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13427 (org-back-to-heading t)
13428 (org-with-limited-levels (org-back-to-heading t)))
13429 (line-beginning-position 2))))))
13431 (defun org-add-planning-info (what &optional time &rest remove)
13432 "Insert new timestamp with keyword in the planning line.
13433 WHAT indicates what kind of time stamp to add. It is a symbol
13434 among `closed', `deadline', `scheduled' and nil. TIME indicates
13435 the time to use. If none is given, the user is prompted for
13436 a date. REMOVE indicates what kind of entries to remove. An old
13437 WHAT entry will also be removed."
13438 (let (org-time-was-given org-end-time-was-given default-time default-input)
13439 (catch 'exit
13440 (when (and (memq what '(scheduled deadline))
13441 (or (not time)
13442 (and (stringp time)
13443 (string-match "^[-+]+[0-9]" time))))
13444 ;; Try to get a default date/time from existing timestamp
13445 (save-excursion
13446 (org-back-to-heading t)
13447 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13448 (when (re-search-forward (if (eq what 'scheduled)
13449 org-scheduled-time-regexp
13450 org-deadline-time-regexp)
13451 end t)
13452 (setq ts (match-string 1)
13453 default-time (apply 'encode-time (org-parse-time-string ts))
13454 default-input (and ts (org-get-compact-tod ts)))))))
13455 (when what
13456 (setq time
13457 (if (stringp time)
13458 ;; This is a string (relative or absolute), set
13459 ;; proper date.
13460 (apply #'encode-time
13461 (org-read-date-analyze
13462 time default-time (decode-time default-time)))
13463 ;; If necessary, get the time from the user
13464 (or time (org-read-date nil 'to-time nil nil
13465 default-time default-input)))))
13467 (org-with-wide-buffer
13468 (org-back-to-heading t)
13469 (forward-line)
13470 (unless (bolp) (insert "\n"))
13471 (cond ((org-looking-at-p org-planning-line-re)
13472 ;; Move to current indentation.
13473 (skip-chars-forward " \t")
13474 ;; Check if we have to remove something.
13475 (dolist (type (if what (cons what remove) remove))
13476 (when (save-excursion
13477 (re-search-forward
13478 (case type
13479 (closed org-closed-time-regexp)
13480 (deadline org-deadline-time-regexp)
13481 (scheduled org-scheduled-time-regexp)
13482 (otherwise (error "Invalid planning type: %s" type)))
13483 (line-end-position) t))
13484 (replace-match "")
13485 (when (looking-at "--+<[^>]+>") (replace-match ""))
13486 (when (and (not what) (eq type 'closed))
13487 (save-excursion
13488 (beginning-of-line)
13489 (if (looking-at "[ \t]*$")
13490 (delete-region (point) (1+ (point-at-eol)))))))
13491 ;; Remove leading white spaces.
13492 (when (and (not (bolp)) (looking-at "[ \t]+")) (replace-match ""))))
13493 ((not what) (throw 'exit nil)) ; Nothing to do.
13494 (t (insert-before-markers "\n")
13495 (backward-char 1)
13496 (when org-adapt-indentation
13497 (org-indent-to-column (1+ (org-outline-level))))))
13498 (when what
13499 ;; Insert planning keyword.
13500 (insert (case what
13501 (closed org-closed-string)
13502 (deadline org-deadline-string)
13503 (scheduled org-scheduled-string)
13504 (otherwise (error "Invalid planning type: %s" what)))
13505 " ")
13506 ;; Insert associated timestamp.
13507 (let ((ts (org-insert-time-stamp
13508 time
13509 (or org-time-was-given
13510 (and (eq what 'closed) org-log-done-with-time))
13511 (eq what 'closed)
13512 nil nil (list org-end-time-was-given))))
13513 (unless (eolp) (insert " "))
13514 ts))))))
13516 (defvar org-log-note-marker (make-marker))
13517 (defvar org-log-note-purpose nil)
13518 (defvar org-log-note-state nil)
13519 (defvar org-log-note-previous-state nil)
13520 (defvar org-log-note-extra nil)
13521 (defvar org-log-note-window-configuration nil)
13522 (defvar org-log-note-return-to (make-marker))
13523 (defvar org-log-note-effective-time nil
13524 "Remembered current time so that dynamically scoped
13525 `org-extend-today-until' affects tha timestamps in state change
13526 log")
13528 (defvar org-log-post-message nil
13529 "Message to be displayed after a log note has been stored.
13530 The auto-repeater uses this.")
13532 (defun org-add-note ()
13533 "Add a note to the current entry.
13534 This is done in the same way as adding a state change note."
13535 (interactive)
13536 (org-add-log-setup 'note nil nil 'findpos nil))
13538 (defun org-log-beginning (&optional create)
13539 "Return expected start of log notes in current entry.
13540 When optional argument CREATE is non-nil, the function creates
13541 a drawer to store notes, if necessary. Returned position ignores
13542 narrowing."
13543 (org-with-wide-buffer
13544 (org-end-of-meta-data)
13545 (let ((end (if (org-at-heading-p) (point)
13546 (save-excursion (outline-next-heading) (point))))
13547 (drawer (org-log-into-drawer)))
13548 (cond
13549 (drawer
13550 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13551 (case-fold-search t))
13552 (catch 'exit
13553 ;; Try to find existing drawer.
13554 (while (re-search-forward regexp end t)
13555 (let ((element (org-element-at-point)))
13556 (when (eq (org-element-type element) 'drawer)
13557 (let ((cend (org-element-property :contents-end element)))
13558 (when (and (not org-log-states-order-reversed) cend)
13559 (goto-char cend)))
13560 (throw 'exit nil))))
13561 ;; No drawer found. Create one, if permitted.
13562 (when create
13563 (unless (bolp) (insert "\n"))
13564 (let ((beg (point)))
13565 (insert ":" drawer ":\n:END:\n")
13566 (org-indent-region beg (point)))
13567 (end-of-line -1)))))
13568 (org-log-state-notes-insert-after-drawers
13569 (while (and (looking-at org-drawer-regexp)
13570 (progn (goto-char (match-end 0))
13571 (re-search-forward org-property-end-re end t)))
13572 (forward-line)))))
13573 (if (bolp) (point) (line-beginning-position 2))))
13575 (defun org-add-log-setup (&optional purpose state prev-state findpos how extra)
13576 "Set up the post command hook to take a note.
13577 If this is about to TODO state change, the new state is expected in STATE.
13578 When FINDPOS is non-nil, find the correct position for the note in
13579 the current entry. If not, assume that it can be inserted at point.
13580 HOW is an indicator what kind of note should be created.
13581 EXTRA is additional text that will be inserted into the notes buffer."
13582 (org-with-wide-buffer
13583 (when findpos
13584 (goto-char (org-log-beginning t))
13585 (unless org-log-states-order-reversed
13586 (org-skip-over-state-notes)
13587 (skip-chars-backward " \t\n\r")
13588 (forward-line)))
13589 (move-marker org-log-note-marker (point))
13590 ;; Preserve position even if a property drawer is inserted in the
13591 ;; process.
13592 (set-marker-insertion-type org-log-note-marker t)
13593 (setq org-log-note-purpose purpose
13594 org-log-note-state state
13595 org-log-note-previous-state prev-state
13596 org-log-note-how how
13597 org-log-note-extra extra
13598 org-log-note-effective-time (org-current-effective-time))
13599 (add-hook 'post-command-hook 'org-add-log-note 'append)))
13601 (defun org-skip-over-state-notes ()
13602 "Skip past the list of State notes in an entry."
13603 (when (ignore-errors (goto-char (org-in-item-p)))
13604 (let* ((struct (org-list-struct))
13605 (prevs (org-list-prevs-alist struct))
13606 (regexp
13607 (concat "[ \t]*- +"
13608 (replace-regexp-in-string
13609 " +" " +"
13610 (org-replace-escapes
13611 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13612 `(("%d" . ,org-ts-regexp-inactive)
13613 ("%D" . ,org-ts-regexp)
13614 ("%s" . "\"\\S-+\"")
13615 ("%S" . "\"\\S-+\"")
13616 ("%t" . ,org-ts-regexp-inactive)
13617 ("%T" . ,org-ts-regexp)
13618 ("%u" . ".*?")
13619 ("%U" . ".*?")))))))
13620 (while (org-looking-at-p regexp)
13621 (goto-char (or (org-list-get-next-item (point) struct prevs)
13622 (org-list-get-item-end (point) struct)))))))
13624 (defun org-add-log-note (&optional purpose)
13625 "Pop up a window for taking a note, and add this note later at point."
13626 (remove-hook 'post-command-hook 'org-add-log-note)
13627 (setq org-log-note-window-configuration (current-window-configuration))
13628 (delete-other-windows)
13629 (move-marker org-log-note-return-to (point))
13630 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13631 (goto-char org-log-note-marker)
13632 (org-switch-to-buffer-other-window "*Org Note*")
13633 (erase-buffer)
13634 (if (memq org-log-note-how '(time state))
13635 (let (current-prefix-arg) (org-store-log-note))
13636 (let ((org-inhibit-startup t)) (org-mode))
13637 (insert (format "# Insert note for %s.
13638 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13639 (cond
13640 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13641 ((eq org-log-note-purpose 'done) "closed todo item")
13642 ((eq org-log-note-purpose 'state)
13643 (format "state change from \"%s\" to \"%s\""
13644 (or org-log-note-previous-state "")
13645 (or org-log-note-state "")))
13646 ((eq org-log-note-purpose 'reschedule)
13647 "rescheduling")
13648 ((eq org-log-note-purpose 'delschedule)
13649 "no longer scheduled")
13650 ((eq org-log-note-purpose 'redeadline)
13651 "changing deadline")
13652 ((eq org-log-note-purpose 'deldeadline)
13653 "removing deadline")
13654 ((eq org-log-note-purpose 'refile)
13655 "refiling")
13656 ((eq org-log-note-purpose 'note)
13657 "this entry")
13658 (t (error "This should not happen")))))
13659 (if org-log-note-extra (insert org-log-note-extra))
13660 (org-set-local 'org-finish-function 'org-store-log-note)
13661 (run-hooks 'org-log-buffer-setup-hook)))
13663 (defvar org-note-abort nil) ; dynamically scoped
13664 (defun org-store-log-note ()
13665 "Finish taking a log note, and insert it to where it belongs."
13666 (let ((txt (buffer-string)))
13667 (kill-buffer (current-buffer))
13668 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings))) lines)
13669 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13670 (setq txt (replace-match "" t t txt)))
13671 (if (string-match "\\s-+\\'" txt)
13672 (setq txt (replace-match "" t t txt)))
13673 (setq lines (org-split-string txt "\n"))
13674 (when (and note (string-match "\\S-" note))
13675 (setq note
13676 (org-replace-escapes
13677 note
13678 (list (cons "%u" (user-login-name))
13679 (cons "%U" user-full-name)
13680 (cons "%t" (format-time-string
13681 (org-time-stamp-format 'long 'inactive)
13682 org-log-note-effective-time))
13683 (cons "%T" (format-time-string
13684 (org-time-stamp-format 'long nil)
13685 org-log-note-effective-time))
13686 (cons "%d" (format-time-string
13687 (org-time-stamp-format nil 'inactive)
13688 org-log-note-effective-time))
13689 (cons "%D" (format-time-string
13690 (org-time-stamp-format nil nil)
13691 org-log-note-effective-time))
13692 (cons "%s" (if org-log-note-state
13693 (concat "\"" org-log-note-state "\"")
13694 ""))
13695 (cons "%S" (if org-log-note-previous-state
13696 (concat "\"" org-log-note-previous-state "\"")
13697 "\"\"")))))
13698 (when lines (setq note (concat note " \\\\")))
13699 (push note lines))
13700 (when (or current-prefix-arg org-note-abort)
13701 (when (org-log-into-drawer)
13702 (org-remove-empty-drawer-at org-log-note-marker))
13703 (setq lines nil))
13704 (when lines
13705 (with-current-buffer (marker-buffer org-log-note-marker)
13706 (org-with-wide-buffer
13707 (goto-char org-log-note-marker)
13708 (move-marker org-log-note-marker nil)
13709 ;; Make sure point is at the beginning of an empty line.
13710 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13711 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13712 ;; In an existing list, add a new item at the top level.
13713 ;; Otherwise, indent line like a regular one.
13714 (let ((itemp (org-in-item-p)))
13715 (if itemp
13716 (org-indent-line-to
13717 (let ((struct (save-excursion
13718 (goto-char itemp) (org-list-struct))))
13719 (org-list-get-ind (org-list-get-top-point struct) struct)))
13720 (org-indent-line)))
13721 (insert (org-list-bullet-string "-") (pop lines))
13722 (let ((ind (org-list-item-body-column (line-beginning-position))))
13723 (dolist (line lines)
13724 (insert "\n")
13725 (org-indent-line-to ind)
13726 (insert line)))
13727 (message "Note stored")
13728 (org-back-to-heading t)
13729 (org-cycle-hide-drawers 'children))
13730 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13731 ;; from within `org-add-log-note' because `buffer-undo-list'
13732 ;; is then modified outside of `org-with-remote-undo'.
13733 (when (eq this-command 'org-agenda-todo)
13734 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13735 ;; Don't add undo information when called from `org-agenda-todo'
13736 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13737 (set-window-configuration org-log-note-window-configuration)
13738 (with-current-buffer (marker-buffer org-log-note-return-to)
13739 (goto-char org-log-note-return-to))
13740 (move-marker org-log-note-return-to nil)
13741 (and org-log-post-message (message "%s" org-log-post-message))))
13743 (defun org-remove-empty-drawer-at (pos)
13744 "Remove an empty drawer at position POS.
13745 POS may also be a marker."
13746 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13747 (org-with-wide-buffer
13748 (goto-char pos)
13749 (let ((drawer (org-element-at-point)))
13750 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13751 (not (org-element-property :contents-begin drawer)))
13752 (delete-region (org-element-property :begin drawer)
13753 (progn (goto-char (org-element-property :end drawer))
13754 (skip-chars-backward " \r\t\n")
13755 (forward-line)
13756 (point))))))))
13758 (defvar org-ts-type nil)
13759 (defun org-sparse-tree (&optional arg type)
13760 "Create a sparse tree, prompt for the details.
13761 This command can create sparse trees. You first need to select the type
13762 of match used to create the tree:
13764 t Show all TODO entries.
13765 T Show entries with a specific TODO keyword.
13766 m Show entries selected by a tags/property match.
13767 p Enter a property name and its value (both with completion on existing
13768 names/values) and show entries with that property.
13769 r Show entries matching a regular expression (`/' can be used as well).
13770 b Show deadlines and scheduled items before a date.
13771 a Show deadlines and scheduled items after a date.
13772 d Show deadlines due within `org-deadline-warning-days'.
13773 D Show deadlines and scheduled items between a date range."
13774 (interactive "P")
13775 (setq type (or type org-sparse-tree-default-date-type))
13776 (setq org-ts-type type)
13777 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13778 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13779 [c]ycle through date types: %s"
13780 (case type
13781 (all "all timestamps")
13782 (scheduled "only scheduled")
13783 (deadline "only deadline")
13784 (active "only active timestamps")
13785 (inactive "only inactive timestamps")
13786 (closed "with a closed time-stamp")
13787 (otherwise "scheduled/deadline")))
13788 (let ((answer (read-char-exclusive)))
13789 (case answer
13791 (org-sparse-tree
13793 (cadr
13794 (memq type '(nil all scheduled deadline active inactive closed)))))
13795 (?d (call-interactively 'org-check-deadlines))
13796 (?b (call-interactively 'org-check-before-date))
13797 (?a (call-interactively 'org-check-after-date))
13798 (?D (call-interactively 'org-check-dates-range))
13799 (?t (call-interactively 'org-show-todo-tree))
13800 (?T (org-show-todo-tree '(4)))
13801 (?m (call-interactively 'org-match-sparse-tree))
13802 ((?p ?P)
13803 (let* ((kwd (org-icompleting-read
13804 "Property: " (mapcar 'list (org-buffer-property-keys))))
13805 (value (org-icompleting-read
13806 "Value: " (mapcar 'list (org-property-values kwd)))))
13807 (unless (string-match "\\`{.*}\\'" value)
13808 (setq value (concat "\"" value "\"")))
13809 (org-match-sparse-tree arg (concat kwd "=" value))))
13810 ((?r ?R ?/) (call-interactively 'org-occur))
13811 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13813 (defvar org-occur-highlights nil
13814 "List of overlays used for occur matches.")
13815 (make-variable-buffer-local 'org-occur-highlights)
13816 (defvar org-occur-parameters nil
13817 "Parameters of the active org-occur calls.
13818 This is a list, each call to org-occur pushes as cons cell,
13819 containing the regular expression and the callback, onto the list.
13820 The list can contain several entries if `org-occur' has been called
13821 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13822 will only contain one set of parameters. When the highlights are
13823 removed (for example with `C-c C-c', or with the next edit (depending
13824 on `org-remove-highlights-with-change'), this variable is emptied
13825 as well.")
13826 (make-variable-buffer-local 'org-occur-parameters)
13828 (defun org-occur (regexp &optional keep-previous callback)
13829 "Make a compact tree which shows all matches of REGEXP.
13830 The tree will show the lines where the regexp matches, and all higher
13831 headlines above the match. It will also show the heading after the match,
13832 to make sure editing the matching entry is easy.
13833 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13834 call to `org-occur' will be kept, to allow stacking of calls to this
13835 command.
13836 If CALLBACK is non-nil, it is a function which is called to confirm
13837 that the match should indeed be shown."
13838 (interactive "sRegexp: \nP")
13839 (when (equal regexp "")
13840 (user-error "Regexp cannot be empty"))
13841 (unless keep-previous
13842 (org-remove-occur-highlights nil nil t))
13843 (push (cons regexp callback) org-occur-parameters)
13844 (let ((cnt 0))
13845 (save-excursion
13846 (goto-char (point-min))
13847 (if (or (not keep-previous) ; do not want to keep
13848 (not org-occur-highlights)) ; no previous matches
13849 ;; hide everything
13850 (org-overview))
13851 (while (re-search-forward regexp nil t)
13852 (when (or (not callback)
13853 (save-match-data (funcall callback)))
13854 (setq cnt (1+ cnt))
13855 (when org-highlight-sparse-tree-matches
13856 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13857 (org-show-context 'occur-tree))))
13858 (when org-remove-highlights-with-change
13859 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13860 nil 'local))
13861 (unless org-sparse-tree-open-archived-trees
13862 (org-hide-archived-subtrees (point-min) (point-max)))
13863 (run-hooks 'org-occur-hook)
13864 (if (org-called-interactively-p 'interactive)
13865 (message "%d match(es) for regexp %s" cnt regexp))
13866 cnt))
13868 (defun org-occur-next-match (&optional n reset)
13869 "Function for `next-error-function' to find sparse tree matches.
13870 N is the number of matches to move, when negative move backwards.
13871 RESET is entirely ignored - this function always goes back to the
13872 starting point when no match is found."
13873 (let* ((limit (if (< n 0) (point-min) (point-max)))
13874 (search-func (if (< n 0)
13875 'previous-single-char-property-change
13876 'next-single-char-property-change))
13877 (n (abs n))
13878 (pos (point))
13880 (catch 'exit
13881 (while (setq p1 (funcall search-func (point) 'org-type))
13882 (when (equal p1 limit)
13883 (goto-char pos)
13884 (user-error "No more matches"))
13885 (when (equal (get-char-property p1 'org-type) 'org-occur)
13886 (setq n (1- n))
13887 (when (= n 0)
13888 (goto-char p1)
13889 (throw 'exit (point))))
13890 (goto-char p1))
13891 (goto-char p1)
13892 (user-error "No more matches"))))
13894 (defun org-show-context (&optional key)
13895 "Make sure point and context are visible.
13896 Optional argument KEY, when non-nil, is a symbol. See
13897 `org-show-context-detail' for allowed values and how much is to
13898 be shown."
13899 (org-show-set-visibility
13900 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13901 ((cdr (assq key org-show-context-detail)))
13902 (t (cdr (assq 'default org-show-context-detail))))))
13904 (defun org-show-set-visibility (detail)
13905 "Set visibility around point according to DETAIL.
13906 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13907 `tree', `canonical' or t. See `org-show-context-detail' for more
13908 information."
13909 (unless (org-before-first-heading-p)
13910 ;; Show current heading and possibly its entry, following headline
13911 ;; or all children.
13912 (if (and (org-at-heading-p) (not (eq detail 'local)))
13913 (org-flag-heading nil)
13914 (org-show-entry)
13915 (org-with-limited-levels
13916 (case detail
13917 ((tree canonical t) (show-children))
13918 ((nil minimal ancestors))
13919 (t (save-excursion
13920 (outline-next-heading)
13921 (org-flag-heading nil))))))
13922 ;; Show all siblings.
13923 (when (eq detail 'lineage) (org-show-siblings))
13924 ;; Show ancestors, possibly with their children.
13925 (when (memq detail '(ancestors lineage tree canonical t))
13926 (save-excursion
13927 (while (org-up-heading-safe)
13928 (org-flag-heading nil)
13929 (when (memq detail '(canonical t)) (org-show-entry))
13930 (when (memq detail '(tree canonical t)) (show-children)))))))
13932 (defvar org-reveal-start-hook nil
13933 "Hook run before revealing a location.")
13935 (defun org-reveal (&optional siblings)
13936 "Show current entry, hierarchy above it, and the following headline.
13938 This can be used to show a consistent set of context around
13939 locations exposed with `org-show-context'.
13941 With optional argument SIBLINGS, on each level of the hierarchy all
13942 siblings are shown. This repairs the tree structure to what it would
13943 look like when opened with hierarchical calls to `org-cycle'.
13945 With double optional argument \\[universal-argument] \\[universal-argument], \
13946 go to the parent and show the
13947 entire tree."
13948 (interactive "P")
13949 (run-hooks 'org-reveal-start-hook)
13950 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13951 ((equal siblings '(16))
13952 (save-excursion
13953 (when (org-up-heading-safe)
13954 (org-show-subtree)
13955 (run-hook-with-args 'org-cycle-hook 'subtree))))
13956 (t (org-show-set-visibility 'lineage))))
13958 (defun org-highlight-new-match (beg end)
13959 "Highlight from BEG to END and mark the highlight is an occur headline."
13960 (let ((ov (make-overlay beg end)))
13961 (overlay-put ov 'face 'secondary-selection)
13962 (overlay-put ov 'org-type 'org-occur)
13963 (push ov org-occur-highlights)))
13965 (defun org-remove-occur-highlights (&optional beg end noremove)
13966 "Remove the occur highlights from the buffer.
13967 BEG and END are ignored. If NOREMOVE is nil, remove this function
13968 from the `before-change-functions' in the current buffer."
13969 (interactive)
13970 (unless org-inhibit-highlight-removal
13971 (mapc 'delete-overlay org-occur-highlights)
13972 (setq org-occur-highlights nil)
13973 (setq org-occur-parameters nil)
13974 (unless noremove
13975 (remove-hook 'before-change-functions
13976 'org-remove-occur-highlights 'local))))
13978 ;;;; Priorities
13980 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13981 "Regular expression matching the priority indicator.")
13983 (defvar org-remove-priority-next-time nil)
13985 (defun org-priority-up ()
13986 "Increase the priority of the current item."
13987 (interactive)
13988 (org-priority 'up))
13990 (defun org-priority-down ()
13991 "Decrease the priority of the current item."
13992 (interactive)
13993 (org-priority 'down))
13995 (defun org-priority (&optional action show)
13996 "Change the priority of an item.
13997 ACTION can be `set', `up', `down', or a character."
13998 (interactive "P")
13999 (if (equal action '(4))
14000 (org-show-priority)
14001 (unless org-enable-priority-commands
14002 (user-error "Priority commands are disabled"))
14003 (setq action (or action 'set))
14004 (let (current new news have remove)
14005 (save-excursion
14006 (org-back-to-heading t)
14007 (if (looking-at org-priority-regexp)
14008 (setq current (string-to-char (match-string 2))
14009 have t))
14010 (cond
14011 ((eq action 'remove)
14012 (setq remove t new ?\ ))
14013 ((or (eq action 'set)
14014 (if (featurep 'xemacs) (characterp action) (integerp action)))
14015 (if (not (eq action 'set))
14016 (setq new action)
14017 (message "Priority %c-%c, SPC to remove: "
14018 org-highest-priority org-lowest-priority)
14019 (save-match-data
14020 (setq new (read-char-exclusive))))
14021 (if (and (= (upcase org-highest-priority) org-highest-priority)
14022 (= (upcase org-lowest-priority) org-lowest-priority))
14023 (setq new (upcase new)))
14024 (cond ((equal new ?\ ) (setq remove t))
14025 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14026 (user-error "Priority must be between `%c' and `%c'"
14027 org-highest-priority org-lowest-priority))))
14028 ((eq action 'up)
14029 (setq new (if have
14030 (1- current) ; normal cycling
14031 ;; last priority was empty
14032 (if (eq last-command this-command)
14033 org-lowest-priority ; wrap around empty to lowest
14034 ;; default
14035 (if org-priority-start-cycle-with-default
14036 org-default-priority
14037 (1- org-default-priority))))))
14038 ((eq action 'down)
14039 (setq new (if have
14040 (1+ current) ; normal cycling
14041 ;; last priority was empty
14042 (if (eq last-command this-command)
14043 org-highest-priority ; wrap around empty to highest
14044 ;; default
14045 (if org-priority-start-cycle-with-default
14046 org-default-priority
14047 (1+ org-default-priority))))))
14048 (t (user-error "Invalid action")))
14049 (if (or (< (upcase new) org-highest-priority)
14050 (> (upcase new) org-lowest-priority))
14051 (if (and (memq action '(up down))
14052 (not have) (not (eq last-command this-command)))
14053 ;; `new' is from default priority
14054 (error
14055 "The default can not be set, see `org-default-priority' why")
14056 ;; normal cycling: `new' is beyond highest/lowest priority
14057 ;; and is wrapped around to the empty priority
14058 (setq remove t)))
14059 (setq news (format "%c" new))
14060 (if have
14061 (if remove
14062 (replace-match "" t t nil 1)
14063 (replace-match news t t nil 2))
14064 (if remove
14065 (user-error "No priority cookie found in line")
14066 (let ((case-fold-search nil))
14067 (looking-at org-todo-line-regexp))
14068 (if (match-end 2)
14069 (progn
14070 (goto-char (match-end 2))
14071 (insert " [#" news "]"))
14072 (goto-char (match-beginning 3))
14073 (insert "[#" news "] "))))
14074 (org-set-tags nil 'align))
14075 (if remove
14076 (message "Priority removed")
14077 (message "Priority of current item set to %s" news)))))
14079 (defun org-show-priority ()
14080 "Show the priority of the current item.
14081 This priority is composed of the main priority given with the [#A] cookies,
14082 and by additional input from the age of a schedules or deadline entry."
14083 (interactive)
14084 (let ((pri (if (eq major-mode 'org-agenda-mode)
14085 (org-get-at-bol 'priority)
14086 (save-excursion
14087 (save-match-data
14088 (beginning-of-line)
14089 (and (looking-at org-heading-regexp)
14090 (org-get-priority (match-string 0))))))))
14091 (message "Priority is %d" (if pri pri -1000))))
14093 (defun org-get-priority (s)
14094 "Find priority cookie and return priority."
14095 (save-match-data
14096 (if (functionp org-get-priority-function)
14097 (funcall org-get-priority-function)
14098 (if (not (string-match org-priority-regexp s))
14099 (* 1000 (- org-lowest-priority org-default-priority))
14100 (* 1000 (- org-lowest-priority
14101 (string-to-char (match-string 2 s))))))))
14103 ;;;; Tags
14105 (defvar org-agenda-archives-mode)
14106 (defvar org-map-continue-from nil
14107 "Position from where mapping should continue.
14108 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14110 (defvar org-scanner-tags nil
14111 "The current tag list while the tags scanner is running.")
14112 (defvar org-trust-scanner-tags nil
14113 "Should `org-get-tags-at' use the tags for the scanner.
14114 This is for internal dynamical scoping only.
14115 When this is non-nil, the function `org-get-tags-at' will return the value
14116 of `org-scanner-tags' instead of building the list by itself. This
14117 can lead to large speed-ups when the tags scanner is used in a file with
14118 many entries, and when the list of tags is retrieved, for example to
14119 obtain a list of properties. Building the tags list for each entry in such
14120 a file becomes an N^2 operation - but with this variable set, it scales
14121 as N.")
14123 (defun org-scan-tags (action matcher todo-only &optional start-level)
14124 "Scan headline tags with inheritance and produce output ACTION.
14126 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14127 or `agenda' to produce an entry list for an agenda view. It can also be
14128 a Lisp form or a function that should be called at each matched headline, in
14129 this case the return value is a list of all return values from these calls.
14131 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14132 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14133 only lines with a not-done TODO keyword are included in the output.
14134 This should be the same variable that was scoped into
14135 and set by `org-make-tags-matcher' when it constructed MATCHER.
14137 START-LEVEL can be a string with asterisks, reducing the scope to
14138 headlines matching this string."
14139 (require 'org-agenda)
14140 (let* ((re (concat "^"
14141 (if start-level
14142 ;; Get the correct level to match
14143 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14144 org-outline-regexp)
14145 " *\\(\\<\\("
14146 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14147 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14148 (props (list 'face 'default
14149 'done-face 'org-agenda-done
14150 'undone-face 'default
14151 'mouse-face 'highlight
14152 'org-not-done-regexp org-not-done-regexp
14153 'org-todo-regexp org-todo-regexp
14154 'org-complex-heading-regexp org-complex-heading-regexp
14155 'help-echo
14156 (format "mouse-2 or RET jump to org file %s"
14157 (abbreviate-file-name
14158 (or (buffer-file-name (buffer-base-buffer))
14159 (buffer-name (buffer-base-buffer)))))))
14160 (org-map-continue-from nil)
14161 lspos tags tags-list
14162 (tags-alist (list (cons 0 org-file-tags)))
14163 (llast 0) rtn rtn1 level category i txt
14164 todo marker entry priority
14165 ts-date ts-date-type ts-date-pair)
14166 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14167 (setq action (list 'lambda nil action)))
14168 (save-excursion
14169 (goto-char (point-min))
14170 (when (eq action 'sparse-tree)
14171 (org-overview)
14172 (org-remove-occur-highlights))
14173 (while (let (case-fold-search)
14174 (re-search-forward re nil t))
14175 (setq org-map-continue-from nil)
14176 (catch :skip
14177 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14178 tags (if (match-end 4) (org-match-string-no-properties 4)))
14179 (goto-char (setq lspos (match-beginning 0)))
14180 (setq level (org-reduced-level (org-outline-level))
14181 category (org-get-category))
14182 (when (eq action 'agenda)
14183 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14184 ts-date (car ts-date-pair)
14185 ts-date-type (cdr ts-date-pair)))
14186 (setq i llast llast level)
14187 ;; remove tag lists from same and sublevels
14188 (while (>= i level)
14189 (when (setq entry (assoc i tags-alist))
14190 (setq tags-alist (delete entry tags-alist)))
14191 (setq i (1- i)))
14192 ;; add the next tags
14193 (when tags
14194 (setq tags (org-split-string tags ":")
14195 tags-alist
14196 (cons (cons level tags) tags-alist)))
14197 ;; compile tags for current headline
14198 (setq tags-list
14199 (if org-use-tag-inheritance
14200 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14201 tags)
14202 org-scanner-tags tags-list)
14203 (when org-use-tag-inheritance
14204 (setcdr (car tags-alist)
14205 (mapcar (lambda (x)
14206 (setq x (copy-sequence x))
14207 (org-add-prop-inherited x))
14208 (cdar tags-alist))))
14209 (when (and tags org-use-tag-inheritance
14210 (or (not (eq t org-use-tag-inheritance))
14211 org-tags-exclude-from-inheritance))
14212 ;; selective inheritance, remove uninherited ones
14213 (setcdr (car tags-alist)
14214 (org-remove-uninherited-tags (cdar tags-alist))))
14215 (when (and
14217 ;; eval matcher only when the todo condition is OK
14218 (and (or (not todo-only) (member todo org-not-done-keywords))
14219 (let ((case-fold-search t) (org-trust-scanner-tags t))
14220 (eval matcher)))
14222 ;; Call the skipper, but return t if it does not skip,
14223 ;; so that the `and' form continues evaluating
14224 (progn
14225 (unless (eq action 'sparse-tree) (org-agenda-skip))
14228 ;; Check if timestamps are deselecting this entry
14229 (or (not todo-only)
14230 (and (member todo org-not-done-keywords)
14231 (or (not org-agenda-tags-todo-honor-ignore-options)
14232 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14234 ;; select this headline
14235 (cond
14236 ((eq action 'sparse-tree)
14237 (and org-highlight-sparse-tree-matches
14238 (org-get-heading) (match-end 0)
14239 (org-highlight-new-match
14240 (match-beginning 1) (match-end 1)))
14241 (org-show-context 'tags-tree))
14242 ((eq action 'agenda)
14243 (setq txt (org-agenda-format-item
14245 (concat
14246 (if (eq org-tags-match-list-sublevels 'indented)
14247 (make-string (1- level) ?.) "")
14248 (org-get-heading))
14249 (make-string level ?\s)
14250 category
14251 tags-list)
14252 priority (org-get-priority txt))
14253 (goto-char lspos)
14254 (setq marker (org-agenda-new-marker))
14255 (org-add-props txt props
14256 'org-marker marker 'org-hd-marker marker 'org-category category
14257 'todo-state todo
14258 'ts-date ts-date
14259 'priority priority
14260 'type (concat "tagsmatch" ts-date-type))
14261 (push txt rtn))
14262 ((functionp action)
14263 (setq org-map-continue-from nil)
14264 (save-excursion
14265 (setq rtn1 (funcall action))
14266 (push rtn1 rtn)))
14267 (t (user-error "Invalid action")))
14269 ;; if we are to skip sublevels, jump to end of subtree
14270 (unless org-tags-match-list-sublevels
14271 (org-end-of-subtree t)
14272 (backward-char 1))))
14273 ;; Get the correct position from where to continue
14274 (if org-map-continue-from
14275 (goto-char org-map-continue-from)
14276 (and (= (point) lspos) (end-of-line 1)))))
14277 (when (and (eq action 'sparse-tree)
14278 (not org-sparse-tree-open-archived-trees))
14279 (org-hide-archived-subtrees (point-min) (point-max)))
14280 (nreverse rtn)))
14282 (defun org-remove-uninherited-tags (tags)
14283 "Remove all tags that are not inherited from the list TAGS."
14284 (cond
14285 ((eq org-use-tag-inheritance t)
14286 (if org-tags-exclude-from-inheritance
14287 (org-delete-all org-tags-exclude-from-inheritance tags)
14288 tags))
14289 ((not org-use-tag-inheritance) nil)
14290 ((stringp org-use-tag-inheritance)
14291 (delq nil (mapcar
14292 (lambda (x)
14293 (if (and (string-match org-use-tag-inheritance x)
14294 (not (member x org-tags-exclude-from-inheritance)))
14295 x nil))
14296 tags)))
14297 ((listp org-use-tag-inheritance)
14298 (delq nil (mapcar
14299 (lambda (x)
14300 (if (member x org-use-tag-inheritance) x nil))
14301 tags)))))
14303 (defun org-match-sparse-tree (&optional todo-only match)
14304 "Create a sparse tree according to tags string MATCH.
14305 MATCH can contain positive and negative selection of tags, like
14306 \"+WORK+URGENT-WITHBOSS\".
14307 If optional argument TODO-ONLY is non-nil, only select lines that are
14308 also TODO lines."
14309 (interactive "P")
14310 (org-agenda-prepare-buffers (list (current-buffer)))
14311 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14313 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14315 (defvar org-cached-props nil)
14316 (defun org-cached-entry-get (pom property)
14317 (if (or (eq t org-use-property-inheritance)
14318 (and (stringp org-use-property-inheritance)
14319 (let ((case-fold-search t))
14320 (org-string-match-p org-use-property-inheritance property)))
14321 (and (listp org-use-property-inheritance)
14322 (member-ignore-case property org-use-property-inheritance)))
14323 ;; Caching is not possible, check it directly.
14324 (org-entry-get pom property 'inherit)
14325 ;; Get all properties, so we can do complicated checks easily.
14326 (cdr (assoc-string property
14327 (or org-cached-props
14328 (setq org-cached-props (org-entry-properties pom)))
14329 t))))
14331 (defun org-global-tags-completion-table (&optional files)
14332 "Return the list of all tags in all agenda buffer/files.
14333 Optional FILES argument is a list of files which can be used
14334 instead of the agenda files."
14335 (save-excursion
14336 (org-uniquify
14337 (delq nil
14338 (apply 'append
14339 (mapcar
14340 (lambda (file)
14341 (set-buffer (find-file-noselect file))
14342 (append (org-get-buffer-tags)
14343 (mapcar (lambda (x) (if (stringp (car-safe x))
14344 (list (car-safe x)) nil))
14345 org-tag-alist)))
14346 (if (and files (car files))
14347 files
14348 (org-agenda-files))))))))
14350 (defun org-make-tags-matcher (match)
14351 "Create the TAGS/TODO matcher form for the selection string MATCH.
14353 The variable `todo-only' is scoped dynamically into this function.
14354 It will be set to t if the matcher restricts matching to TODO entries,
14355 otherwise will not be touched.
14357 Returns a cons of the selection string MATCH and the constructed
14358 lisp form implementing the matcher. The matcher is to be evaluated
14359 at an Org entry, with point on the headline, and returns t if the
14360 entry matches the selection string MATCH. The returned lisp form
14361 references two variables with information about the entry, which
14362 must be bound around the form's evaluation: todo, the TODO keyword
14363 at the entry (or nil of none); and tags-list, the list of all tags
14364 at the entry including inherited ones. Additionally, the category
14365 of the entry (if any) must be specified as the text property
14366 'org-category on the headline.
14368 See also `org-scan-tags'.
14370 (declare (special todo-only))
14371 (unless (boundp 'todo-only)
14372 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14373 (unless match
14374 ;; Get a new match request, with completion against the global
14375 ;; tags table and the local tags in current buffer
14376 (let ((org-last-tags-completion-table
14377 (org-uniquify
14378 (delq nil (append (org-get-buffer-tags)
14379 (org-global-tags-completion-table))))))
14380 (setq match (org-completing-read-no-i
14381 "Match: " 'org-tags-completion-function nil nil nil
14382 'org-tags-history))))
14384 ;; Parse the string and create a lisp form
14385 (let ((match0 match)
14386 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14387 minus tag mm
14388 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14389 orterms term orlist re-p str-p level-p level-op time-p
14390 prop-p pn pv po gv rest (start 0) (ss 0))
14391 ;; Expand group tags
14392 (setq match (org-tags-expand match))
14394 ;; Check if there is a TODO part of this match, which would be the
14395 ;; part after a "/". TO make sure that this slash is not part of
14396 ;; a property value to be matched against, we also check that there
14397 ;; is no " after that slash.
14398 ;; First, find the last slash
14399 (while (string-match "/+" match ss)
14400 (setq start (match-beginning 0) ss (match-end 0)))
14401 (if (and (string-match "/+" match start)
14402 (not (save-match-data (string-match "\"" match start))))
14403 ;; match contains also a todo-matching request
14404 (progn
14405 (setq tagsmatch (substring match 0 (match-beginning 0))
14406 todomatch (substring match (match-end 0)))
14407 (if (string-match "^!" todomatch)
14408 (setq todo-only t todomatch (substring todomatch 1)))
14409 (if (string-match "^\\s-*$" todomatch)
14410 (setq todomatch nil)))
14411 ;; only matching tags
14412 (setq tagsmatch match todomatch nil))
14414 ;; Make the tags matcher
14415 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14416 (setq tagsmatcher t)
14417 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14418 (while (setq term (pop orterms))
14419 (while (and (equal (substring term -1) "\\") orterms)
14420 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14421 (while (string-match re term)
14422 (setq rest (substring term (match-end 0))
14423 minus (and (match-end 1)
14424 (equal (match-string 1 term) "-"))
14425 tag (save-match-data (replace-regexp-in-string
14426 "\\\\-" "-"
14427 (match-string 2 term)))
14428 re-p (equal (string-to-char tag) ?{)
14429 level-p (match-end 4)
14430 prop-p (match-end 5)
14431 mm (cond
14432 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14433 (level-p
14434 (setq level-op (org-op-to-function (match-string 3 term)))
14435 `(,level-op level ,(string-to-number
14436 (match-string 4 term))))
14437 (prop-p
14438 (setq pn (match-string 5 term)
14439 po (match-string 6 term)
14440 pv (match-string 7 term)
14441 re-p (equal (string-to-char pv) ?{)
14442 str-p (equal (string-to-char pv) ?\")
14443 time-p (save-match-data
14444 (string-match "^\"[[<].*[]>]\"$" pv))
14445 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14446 (if time-p (setq pv (org-matcher-time pv)))
14447 (setq po (org-op-to-function po (if time-p 'time str-p)))
14448 (cond
14449 ((equal pn "CATEGORY")
14450 (setq gv '(get-text-property (point) 'org-category)))
14451 ((equal pn "TODO")
14452 (setq gv 'todo))
14454 (setq gv `(org-cached-entry-get nil ,pn))))
14455 (if re-p
14456 (if (eq po 'org<>)
14457 `(not (string-match ,pv (or ,gv "")))
14458 `(string-match ,pv (or ,gv "")))
14459 (if str-p
14460 `(,po (or ,gv "") ,pv)
14461 `(,po (string-to-number (or ,gv ""))
14462 ,(string-to-number pv) ))))
14463 (t `(member ,tag tags-list)))
14464 mm (if minus (list 'not mm) mm)
14465 term rest)
14466 (push mm tagsmatcher))
14467 (push (if (> (length tagsmatcher) 1)
14468 (cons 'and tagsmatcher)
14469 (car tagsmatcher))
14470 orlist)
14471 (setq tagsmatcher nil))
14472 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14473 (setq tagsmatcher
14474 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14475 ;; Make the todo matcher
14476 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14477 (setq todomatcher t)
14478 (setq orterms (org-split-string todomatch "|") orlist nil)
14479 (while (setq term (pop orterms))
14480 (while (string-match re term)
14481 (setq minus (and (match-end 1)
14482 (equal (match-string 1 term) "-"))
14483 kwd (match-string 2 term)
14484 re-p (equal (string-to-char kwd) ?{)
14485 term (substring term (match-end 0))
14486 mm (if re-p
14487 `(string-match ,(substring kwd 1 -1) todo)
14488 (list 'equal 'todo kwd))
14489 mm (if minus (list 'not mm) mm))
14490 (push mm todomatcher))
14491 (push (if (> (length todomatcher) 1)
14492 (cons 'and todomatcher)
14493 (car todomatcher))
14494 orlist)
14495 (setq todomatcher nil))
14496 (setq todomatcher (if (> (length orlist) 1)
14497 (cons 'or orlist) (car orlist))))
14499 ;; Return the string and lisp forms of the matcher
14500 (setq matcher (if todomatcher
14501 (list 'and tagsmatcher todomatcher)
14502 tagsmatcher))
14503 (when todo-only
14504 (setq matcher (list 'and '(member todo org-not-done-keywords)
14505 matcher)))
14506 (cons match0 matcher)))
14508 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14509 "Expand group tags in MATCH.
14511 This replaces every group tag in MATCH with a regexp tag search.
14512 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14513 will be replaced like this:
14515 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14516 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14517 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14519 Replacing by a regexp preserves the structure of the match.
14520 E.g., this expansion
14522 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14524 will match anything tagged with \"Lab\" and \"Home\", or tagged
14525 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14527 A group tag in MATCH can contain regular expressions of its own.
14528 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14529 will be replaced like this:
14531 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14533 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14534 assumed to be a single group tag, and the function will return
14535 the list of tags in this group.
14537 When DOWNCASE is non-nil, expand downcased TAGS."
14538 (if org-group-tags
14539 (let* ((case-fold-search t)
14540 (stable org-mode-syntax-table)
14541 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14542 (taggroups (if downcased
14543 (mapcar (lambda (tg) (mapcar #'downcase tg))
14544 taggroups)
14545 taggroups))
14546 (taggroups-keys (mapcar #'car taggroups))
14547 (return-match (if downcased (downcase match) match))
14548 (count 0)
14549 (work-already-expanded tags-already-expanded)
14550 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14551 ;; @ and _ are allowed as word-components in tags.
14552 (modify-syntax-entry ?@ "w" stable)
14553 (modify-syntax-entry ?_ "w" stable)
14554 ;; Temporarily replace regexp-expressions in the match-expression.
14555 (while (string-match "{.+?}" return-match)
14556 (incf count)
14557 (push (match-string 0 return-match) regexps-in-match)
14558 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14559 (while (and taggroups-keys
14560 (with-syntax-table stable
14561 (string-match
14562 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14563 (regexp-opt taggroups-keys) "\\>\\)") return-match)))
14564 (let* ((dir (match-string 1 return-match))
14565 (tag (match-string 2 return-match))
14566 (tag (if downcased (downcase tag) tag)))
14567 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14568 (member tag work-already-expanded))
14569 (setq tags-in-group (assoc tag taggroups))
14570 (push tag work-already-expanded)
14571 ;; Recursively expand each tag in the group, if the tag hasn't
14572 ;; already been expanded. Restore the match-data after all recursive calls.
14573 (save-match-data
14574 (let (tags-expanded)
14575 (dolist (x (cdr tags-in-group))
14576 (if (and (member x taggroups-keys)
14577 (not (member x work-already-expanded)))
14578 (setq tags-expanded
14579 (delete-dups
14580 (append
14581 (org-tags-expand x t downcased
14582 work-already-expanded)
14583 tags-expanded)))
14584 (setq tags-expanded
14585 (append (list x) tags-expanded)))
14586 (setq work-already-expanded
14587 (delete-dups
14588 (append tags-expanded
14589 work-already-expanded))))
14590 (setq tags-in-group
14591 (delete-dups (cons (car tags-in-group)
14592 tags-expanded)))))
14593 ;; Filter tag-regexps from tags.
14594 (setq regexp-in-group-escaped
14595 (delq nil (mapcar (lambda (x)
14596 (if (stringp x)
14597 (and (equal "{" (substring x 0 1))
14598 (equal "}" (substring x -1))
14601 tags-in-group))
14602 regexp-in-group
14603 (mapcar (lambda (x)
14604 (substring x 1 -1))
14605 regexp-in-group-escaped)
14606 tags-in-group
14607 (delq nil (mapcar (lambda (x)
14608 (if (stringp x)
14609 (and (not (equal "{" (substring x 0 1)))
14610 (not (equal "}" (substring x -1)))
14613 tags-in-group)))
14614 ;; If single-as-list, do no more in the while-loop.
14615 (if (not single-as-list)
14616 (progn
14617 (when regexp-in-group
14618 (setq regexp-in-group
14619 (concat "\\|"
14620 (mapconcat 'identity regexp-in-group
14621 "\\|"))))
14622 (setq tags-in-group
14623 (concat dir
14624 "{\\<"
14625 (regexp-opt tags-in-group)
14626 "\\>"
14627 regexp-in-group
14628 "}"))
14629 (when (stringp tags-in-group)
14630 (org-add-props tags-in-group '(grouptag t)))
14631 (setq return-match
14632 (replace-match tags-in-group t t return-match)))
14633 (setq tags-in-group
14634 (append regexp-in-group-escaped tags-in-group))))
14635 (setq taggroups-keys (delete tag taggroups-keys))))
14636 ;; Add the regular expressions back into the match-expression again.
14637 (while regexps-in-match
14638 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14639 (pop regexps-in-match)
14640 return-match t t))
14641 (decf count))
14642 (if single-as-list
14643 (if tags-in-group tags-in-group (list return-match))
14644 return-match))
14645 (if single-as-list
14646 (list (if downcased (downcase match) match))
14647 match)))
14649 (defun org-op-to-function (op &optional stringp)
14650 "Turn an operator into the appropriate function."
14651 (setq op
14652 (cond
14653 ((equal op "<" ) '(< string< org-time<))
14654 ((equal op ">" ) '(> org-string> org-time>))
14655 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14656 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14657 ((member op '("=" "==")) '(= string= org-time=))
14658 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14659 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14661 (defun org<> (a b) (not (= a b)))
14662 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14663 (defun org-string>= (a b) (not (string< a b)))
14664 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14665 (defun org-string<> (a b) (not (string= a b)))
14666 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14667 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14668 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14669 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14670 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14671 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14672 (defun org-2ft (s)
14673 "Convert S to a floating point time.
14674 If S is already a number, just return it. If it is a string, parse
14675 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14676 (cond
14677 ((numberp s) s)
14678 ((stringp s)
14679 (condition-case nil
14680 (float-time (apply 'encode-time (org-parse-time-string s)))
14681 (error 0.)))
14682 (t 0.)))
14684 (defun org-time-today ()
14685 "Time in seconds today at 0:00.
14686 Returns the float number of seconds since the beginning of the
14687 epoch to the beginning of today (00:00)."
14688 (float-time (apply 'encode-time
14689 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14691 (defun org-matcher-time (s)
14692 "Interpret a time comparison value."
14693 (save-match-data
14694 (cond
14695 ((string= s "<now>") (float-time))
14696 ((string= s "<today>") (org-time-today))
14697 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14698 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14699 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14700 (+ (org-time-today)
14701 (* (string-to-number (match-string 1 s))
14702 (cdr (assoc (match-string 2 s)
14703 '(("d" . 86400.0) ("w" . 604800.0)
14704 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14705 (t (org-2ft s)))))
14707 (defun org-match-any-p (re list)
14708 "Does re match any element of list?"
14709 (setq list (mapcar (lambda (x) (string-match re x)) list))
14710 (delq nil list))
14712 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14713 (defvar org-tags-overlay (make-overlay 1 1))
14714 (org-detach-overlay org-tags-overlay)
14716 (defun org-get-local-tags-at (&optional pos)
14717 "Get a list of tags defined in the current headline."
14718 (org-get-tags-at pos 'local))
14720 (defun org-get-local-tags ()
14721 "Get a list of tags defined in the current headline."
14722 (org-get-tags-at nil 'local))
14724 (defun org-get-tags-at (&optional pos local)
14725 "Get a list of all headline tags applicable at POS.
14726 POS defaults to point. If tags are inherited, the list contains
14727 the targets in the same sequence as the headlines appear, i.e.
14728 the tags of the current headline come last.
14729 When LOCAL is non-nil, only return tags from the current headline,
14730 ignore inherited ones."
14731 (interactive)
14732 (if (and org-trust-scanner-tags
14733 (or (not pos) (equal pos (point)))
14734 (not local))
14735 org-scanner-tags
14736 (let (tags ltags lastpos parent)
14737 (save-excursion
14738 (save-restriction
14739 (widen)
14740 (goto-char (or pos (point)))
14741 (save-match-data
14742 (catch 'done
14743 (condition-case nil
14744 (progn
14745 (org-back-to-heading t)
14746 (while (not (equal lastpos (point)))
14747 (setq lastpos (point))
14748 (when (looking-at
14749 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14750 (setq ltags (org-split-string
14751 (org-match-string-no-properties 1) ":"))
14752 (when parent
14753 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14754 (setq tags (append
14755 (if parent
14756 (org-remove-uninherited-tags ltags)
14757 ltags)
14758 tags)))
14759 (or org-use-tag-inheritance (throw 'done t))
14760 (if local (throw 'done t))
14761 (or (org-up-heading-safe) (error nil))
14762 (setq parent t)))
14763 (error nil)))))
14764 (if local
14765 tags
14766 (reverse (delete-dups
14767 (reverse (append
14768 (org-remove-uninherited-tags
14769 org-file-tags) tags)))))))))
14771 (defun org-add-prop-inherited (s)
14772 (add-text-properties 0 (length s) '(inherited t) s)
14775 (defun org-toggle-tag (tag &optional onoff)
14776 "Toggle the tag TAG for the current line.
14777 If ONOFF is `on' or `off', don't toggle but set to this state."
14778 (let (res current)
14779 (save-excursion
14780 (org-back-to-heading t)
14781 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14782 (point-at-eol) t)
14783 (progn
14784 (setq current (match-string 1))
14785 (replace-match ""))
14786 (setq current ""))
14787 (setq current (nreverse (org-split-string current ":")))
14788 (cond
14789 ((eq onoff 'on)
14790 (setq res t)
14791 (or (member tag current) (push tag current)))
14792 ((eq onoff 'off)
14793 (or (not (member tag current)) (setq current (delete tag current))))
14794 (t (if (member tag current)
14795 (setq current (delete tag current))
14796 (setq res t)
14797 (push tag current))))
14798 (end-of-line 1)
14799 (if current
14800 (progn
14801 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14802 (org-set-tags nil t))
14803 (delete-horizontal-space))
14804 (run-hooks 'org-after-tags-change-hook))
14805 res))
14807 (defun org-align-tags-here (to-col)
14808 ;; Assumes that this is a headline
14809 "Align tags on the current headline to TO-COL."
14810 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14811 (beginning-of-line 1)
14812 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14813 (< pos (match-beginning 2)))
14814 (progn
14815 (setq tags-l (- (match-end 2) (match-beginning 2)))
14816 (goto-char (match-beginning 1))
14817 (insert " ")
14818 (delete-region (point) (1+ (match-beginning 2)))
14819 (setq ncol (max (current-column)
14820 (1+ col)
14821 (if (> to-col 0)
14822 to-col
14823 (- (abs to-col) tags-l))))
14824 (setq p (point))
14825 (insert (make-string (- ncol (current-column)) ?\ ))
14826 (setq ncol (current-column))
14827 (when indent-tabs-mode (tabify p (point-at-eol)))
14828 (org-move-to-column (min ncol col)))
14829 (goto-char pos))))
14831 (defun org-set-tags-command (&optional arg just-align)
14832 "Call the set-tags command for the current entry."
14833 (interactive "P")
14834 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14835 (org-set-tags arg just-align)
14836 (save-excursion
14837 (unless (and (org-region-active-p)
14838 org-loop-over-headlines-in-active-region)
14839 (org-back-to-heading t))
14840 (org-set-tags arg just-align))))
14842 (defun org-set-tags-to (data)
14843 "Set the tags of the current entry to DATA, replacing the current tags.
14844 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14845 If DATA is nil or the empty string, any tags will be removed."
14846 (interactive "sTags: ")
14847 (setq data
14848 (cond
14849 ((eq data nil) "")
14850 ((equal data "") "")
14851 ((stringp data)
14852 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14853 ":"))
14854 ((listp data)
14855 (concat ":" (mapconcat 'identity data ":") ":"))))
14856 (when data
14857 (save-excursion
14858 (org-back-to-heading t)
14859 (when (looking-at org-complex-heading-regexp)
14860 (if (match-end 5)
14861 (progn
14862 (goto-char (match-beginning 5))
14863 (insert data)
14864 (delete-region (point) (point-at-eol))
14865 (org-set-tags nil 'align))
14866 (goto-char (point-at-eol))
14867 (insert " " data)
14868 (org-set-tags nil 'align)))
14869 (beginning-of-line 1)
14870 (if (looking-at ".*?\\([ \t]+\\)$")
14871 (delete-region (match-beginning 1) (match-end 1))))))
14873 (defun org-align-all-tags ()
14874 "Align the tags i all headings."
14875 (interactive)
14876 (save-excursion
14877 (or (ignore-errors (org-back-to-heading t))
14878 (outline-next-heading))
14879 (if (org-at-heading-p)
14880 (org-set-tags t)
14881 (message "No headings"))))
14883 (defvar org-indent-indentation-per-level)
14884 (defun org-set-tags (&optional arg just-align)
14885 "Set the tags for the current headline.
14886 With prefix ARG, realign all tags in headings in the current buffer.
14887 When JUST-ALIGN is non-nil, only align tags."
14888 (interactive "P")
14889 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14890 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14891 'region-start-level 'region))
14892 org-loop-over-headlines-in-active-region)
14893 (org-map-entries
14894 ;; We don't use ARG and JUST-ALIGN here because these args
14895 ;; are not useful when looping over headlines.
14896 `(org-set-tags)
14897 org-loop-over-headlines-in-active-region
14898 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14899 (let* ((re org-outline-regexp-bol)
14900 (current (unless arg (org-get-tags-string)))
14901 (col (current-column))
14902 (org-setting-tags t)
14903 table current-tags inherited-tags ; computed below when needed
14904 tags p0 c0 c1 rpl di tc level)
14905 (if arg
14906 (save-excursion
14907 (goto-char (point-min))
14908 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14909 (while (re-search-forward re nil t)
14910 (org-set-tags nil t)
14911 (end-of-line 1)))
14912 (message "All tags realigned to column %d" org-tags-column))
14913 (if just-align
14914 (setq tags current)
14915 ;; Get a new set of tags from the user
14916 (save-excursion
14917 (setq table (append org-tag-persistent-alist
14918 (or org-tag-alist (org-get-buffer-tags))
14919 (and
14920 org-complete-tags-always-offer-all-agenda-tags
14921 (org-global-tags-completion-table
14922 (org-agenda-files))))
14923 org-last-tags-completion-table table
14924 current-tags (org-split-string current ":")
14925 inherited-tags (nreverse
14926 (nthcdr (length current-tags)
14927 (nreverse (org-get-tags-at))))
14928 tags
14929 (if (or (eq t org-use-fast-tag-selection)
14930 (and org-use-fast-tag-selection
14931 (delq nil (mapcar 'cdr table))))
14932 (org-fast-tag-selection
14933 current-tags inherited-tags table
14934 (if org-fast-tag-selection-include-todo
14935 org-todo-key-alist))
14936 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14937 (org-trim
14938 (org-icompleting-read "Tags: "
14939 'org-tags-completion-function
14940 nil nil current 'org-tags-history))))))
14941 (while (string-match "[-+&]+" tags)
14942 ;; No boolean logic, just a list
14943 (setq tags (replace-match ":" t t tags))))
14945 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14947 (if org-tags-sort-function
14948 (setq tags (mapconcat 'identity
14949 (sort (org-split-string
14950 tags (org-re "[^[:alnum:]_@#%]+"))
14951 org-tags-sort-function) ":")))
14953 (if (string-match "\\`[\t ]*\\'" tags)
14954 (setq tags "")
14955 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14956 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14958 ;; Insert new tags at the correct column
14959 (beginning-of-line 1)
14960 (setq level (or (and (looking-at org-outline-regexp)
14961 (- (match-end 0) (point) 1))
14963 (cond
14964 ((and (equal current "") (equal tags "")))
14965 ((re-search-forward
14966 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14967 (point-at-eol) t)
14968 (if (equal tags "")
14969 (setq rpl "")
14970 (goto-char (match-beginning 0))
14971 (setq c0 (current-column)
14972 ;; compute offset for the case of org-indent-mode active
14973 di (if (org-bound-and-true-p org-indent-mode)
14974 (* (1- org-indent-indentation-per-level) (1- level))
14976 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14977 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14978 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14979 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14980 (replace-match rpl t t)
14981 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14982 tags)
14983 (t (error "Tags alignment failed")))
14984 (org-move-to-column col)
14985 (unless just-align
14986 (run-hooks 'org-after-tags-change-hook))))))
14988 (defun org-change-tag-in-region (beg end tag off)
14989 "Add or remove TAG for each entry in the region.
14990 This works in the agenda, and also in an org-mode buffer."
14991 (interactive
14992 (list (region-beginning) (region-end)
14993 (let ((org-last-tags-completion-table
14994 (if (derived-mode-p 'org-mode)
14995 (org-uniquify
14996 (delq nil (append (org-get-buffer-tags)
14997 (org-global-tags-completion-table))))
14998 (org-global-tags-completion-table))))
14999 (org-icompleting-read
15000 "Tag: " 'org-tags-completion-function nil nil nil
15001 'org-tags-history))
15002 (progn
15003 (message "[s]et or [r]emove? ")
15004 (equal (read-char-exclusive) ?r))))
15005 (if (fboundp 'deactivate-mark) (deactivate-mark))
15006 (let ((agendap (equal major-mode 'org-agenda-mode))
15007 l1 l2 m buf pos newhead (cnt 0))
15008 (goto-char end)
15009 (setq l2 (1- (org-current-line)))
15010 (goto-char beg)
15011 (setq l1 (org-current-line))
15012 (loop for l from l1 to l2 do
15013 (org-goto-line l)
15014 (setq m (get-text-property (point) 'org-hd-marker))
15015 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15016 (and agendap m))
15017 (setq buf (if agendap (marker-buffer m) (current-buffer))
15018 pos (if agendap m (point)))
15019 (with-current-buffer buf
15020 (save-excursion
15021 (save-restriction
15022 (goto-char pos)
15023 (setq cnt (1+ cnt))
15024 (org-toggle-tag tag (if off 'off 'on))
15025 (setq newhead (org-get-heading)))))
15026 (and agendap (org-agenda-change-all-lines newhead m))))
15027 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15029 (defun org-tags-completion-function (string predicate &optional flag)
15030 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15031 (confirm (lambda (x) (stringp (car x)))))
15032 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15033 (setq s1 (match-string 1 string)
15034 s2 (match-string 2 string))
15035 (setq s1 "" s2 string))
15036 (cond
15037 ((eq flag nil)
15038 ;; try completion
15039 (setq rtn (try-completion s2 ctable confirm))
15040 (if (stringp rtn)
15041 (setq rtn
15042 (concat s1 s2 (substring rtn (length s2))
15043 (if (and org-add-colon-after-tag-completion
15044 (assoc rtn ctable))
15045 ":" ""))))
15046 rtn)
15047 ((eq flag t)
15048 ;; all-completions
15049 (all-completions s2 ctable confirm))
15050 ((eq flag 'lambda)
15051 ;; exact match?
15052 (assoc s2 ctable)))))
15054 (defun org-fast-tag-insert (kwd tags face &optional end)
15055 "Insert KDW, and the TAGS, the latter with face FACE.
15056 Also insert END."
15057 (insert (format "%-12s" (concat kwd ":"))
15058 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15059 (or end "")))
15061 (defun org-fast-tag-show-exit (flag)
15062 (save-excursion
15063 (org-goto-line 3)
15064 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15065 (replace-match ""))
15066 (when flag
15067 (end-of-line 1)
15068 (org-move-to-column (- (window-width) 19) t)
15069 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15071 (defun org-set-current-tags-overlay (current prefix)
15072 "Add an overlay to CURRENT tag with PREFIX."
15073 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15074 (if (featurep 'xemacs)
15075 (org-overlay-display org-tags-overlay (concat prefix s)
15076 'secondary-selection)
15077 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15078 (org-overlay-display org-tags-overlay (concat prefix s)))))
15080 (defvar org-last-tag-selection-key nil)
15081 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15082 "Fast tag selection with single keys.
15083 CURRENT is the current list of tags in the headline, INHERITED is the
15084 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15085 possibly with grouping information. TODO-TABLE is a similar table with
15086 TODO keywords, should these have keys assigned to them.
15087 If the keys are nil, a-z are automatically assigned.
15088 Returns the new tags string, or nil to not change the current settings."
15089 (let* ((fulltable (append table todo-table))
15090 (maxlen (apply 'max (mapcar
15091 (lambda (x)
15092 (if (stringp (car x)) (string-width (car x)) 0))
15093 fulltable)))
15094 (buf (current-buffer))
15095 (expert (eq org-fast-tag-selection-single-key 'expert))
15096 (buffer-tags nil)
15097 (fwidth (+ maxlen 3 1 3))
15098 (ncol (/ (- (window-width) 4) fwidth))
15099 (i-face 'org-done)
15100 (c-face 'org-todo)
15101 tg cnt e c char c1 c2 ntable tbl rtn
15102 ov-start ov-end ov-prefix
15103 (exit-after-next org-fast-tag-selection-single-key)
15104 (done-keywords org-done-keywords)
15105 groups ingroup intaggroup)
15106 (save-excursion
15107 (beginning-of-line 1)
15108 (if (looking-at
15109 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15110 (setq ov-start (match-beginning 1)
15111 ov-end (match-end 1)
15112 ov-prefix "")
15113 (setq ov-start (1- (point-at-eol))
15114 ov-end (1+ ov-start))
15115 (skip-chars-forward "^\n\r")
15116 (setq ov-prefix
15117 (concat
15118 (buffer-substring (1- (point)) (point))
15119 (if (> (current-column) org-tags-column)
15121 (make-string (- org-tags-column (current-column)) ?\ ))))))
15122 (move-overlay org-tags-overlay ov-start ov-end)
15123 (save-window-excursion
15124 (if expert
15125 (set-buffer (get-buffer-create " *Org tags*"))
15126 (delete-other-windows)
15127 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15128 (org-switch-to-buffer-other-window " *Org tags*"))
15129 (erase-buffer)
15130 (org-set-local 'org-done-keywords done-keywords)
15131 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15132 (org-fast-tag-insert "Current" current c-face "\n\n")
15133 (org-fast-tag-show-exit exit-after-next)
15134 (org-set-current-tags-overlay current ov-prefix)
15135 (setq tbl fulltable char ?a cnt 0)
15136 (while (setq e (pop tbl))
15137 (cond
15138 ((eq (car e) :startgroup)
15139 (push '() groups) (setq ingroup t)
15140 (unless (zerop cnt)
15141 (setq cnt 0)
15142 (insert "\n"))
15143 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15144 ((eq (car e) :endgroup)
15145 (setq ingroup nil cnt 0)
15146 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15147 ((eq (car e) :startgrouptag)
15148 (setq intaggroup t)
15149 (unless (zerop cnt)
15150 (setq cnt 0)
15151 (insert "\n"))
15152 (insert "[ "))
15153 ((eq (car e) :endgrouptag)
15154 (setq intaggroup nil cnt 0)
15155 (insert "]\n"))
15156 ((equal e '(:newline))
15157 (unless (zerop cnt)
15158 (setq cnt 0)
15159 (insert "\n")
15160 (setq e (car tbl))
15161 (while (equal (car tbl) '(:newline))
15162 (insert "\n")
15163 (setq tbl (cdr tbl)))))
15164 ((equal e '(:grouptags)) (insert " : "))
15166 (setq tg (copy-sequence (car e)) c2 nil)
15167 (if (cdr e)
15168 (setq c (cdr e))
15169 ;; automatically assign a character.
15170 (setq c1 (string-to-char
15171 (downcase (substring
15172 tg (if (= (string-to-char tg) ?@) 1 0)))))
15173 (if (or (rassoc c1 ntable) (rassoc c1 table))
15174 (while (or (rassoc char ntable) (rassoc char table))
15175 (setq char (1+ char)))
15176 (setq c2 c1))
15177 (setq c (or c2 char)))
15178 (when ingroup (push tg (car groups)))
15179 (setq tg (org-add-props tg nil 'face
15180 (cond
15181 ((not (assoc tg table))
15182 (org-get-todo-face tg))
15183 ((member tg current) c-face)
15184 ((member tg inherited) i-face))))
15185 (when (equal (caar tbl) :grouptags)
15186 (org-add-props tg nil 'face 'org-tag-group))
15187 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15188 (insert "[" c "] " tg (make-string
15189 (- fwidth 4 (length tg)) ?\ ))
15190 (push (cons tg c) ntable)
15191 (when (= (incf cnt) ncol)
15192 (insert "\n")
15193 (when (or ingroup intaggroup) (insert " "))
15194 (setq cnt 0)))))
15195 (setq ntable (nreverse ntable))
15196 (insert "\n")
15197 (goto-char (point-min))
15198 (unless expert (org-fit-window-to-buffer))
15199 (setq rtn
15200 (catch 'exit
15201 (while t
15202 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15203 (if (not groups) "no " "")
15204 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15205 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15206 (setq org-last-tag-selection-key c)
15207 (cond
15208 ((= c ?\r) (throw 'exit t))
15209 ((= c ?!)
15210 (setq groups (not groups))
15211 (goto-char (point-min))
15212 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15213 ((= c ?\C-c)
15214 (if (not expert)
15215 (org-fast-tag-show-exit
15216 (setq exit-after-next (not exit-after-next)))
15217 (setq expert nil)
15218 (delete-other-windows)
15219 (set-window-buffer (split-window-vertically) " *Org tags*")
15220 (org-switch-to-buffer-other-window " *Org tags*")
15221 (org-fit-window-to-buffer)))
15222 ((or (= c ?\C-g)
15223 (and (= c ?q) (not (rassoc c ntable))))
15224 (org-detach-overlay org-tags-overlay)
15225 (setq quit-flag t))
15226 ((= c ?\ )
15227 (setq current nil)
15228 (when exit-after-next (setq exit-after-next 'now)))
15229 ((= c ?\t)
15230 (condition-case nil
15231 (setq tg (org-icompleting-read
15232 "Tag: "
15233 (or buffer-tags
15234 (with-current-buffer buf
15235 (org-get-buffer-tags)))))
15236 (quit (setq tg "")))
15237 (when (string-match "\\S-" tg)
15238 (add-to-list 'buffer-tags (list tg))
15239 (if (member tg current)
15240 (setq current (delete tg current))
15241 (push tg current)))
15242 (when exit-after-next (setq exit-after-next 'now)))
15243 ((setq e (rassoc c todo-table) tg (car e))
15244 (with-current-buffer buf
15245 (save-excursion (org-todo tg)))
15246 (when exit-after-next (setq exit-after-next 'now)))
15247 ((setq e (rassoc c ntable) tg (car e))
15248 (if (member tg current)
15249 (setq current (delete tg current))
15250 (loop for g in groups do
15251 (when (member tg g)
15252 (dolist (x g) (setq current (delete x current)))))
15253 (push tg current))
15254 (when exit-after-next (setq exit-after-next 'now))))
15256 ;; Create a sorted list
15257 (setq current
15258 (sort current
15259 (lambda (a b)
15260 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15261 (when (eq exit-after-next 'now) (throw 'exit t))
15262 (goto-char (point-min))
15263 (beginning-of-line 2)
15264 (delete-region (point) (point-at-eol))
15265 (org-fast-tag-insert "Current" current c-face)
15266 (org-set-current-tags-overlay current ov-prefix)
15267 (while (re-search-forward
15268 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15269 (setq tg (match-string 1))
15270 (add-text-properties
15271 (match-beginning 1) (match-end 1)
15272 (list 'face
15273 (cond
15274 ((member tg current) c-face)
15275 ((member tg inherited) i-face)
15276 (t (get-text-property (match-beginning 1) 'face))))))
15277 (goto-char (point-min)))))
15278 (org-detach-overlay org-tags-overlay)
15279 (if rtn
15280 (mapconcat 'identity current ":")
15281 nil))))
15283 (defun org-get-tags-string ()
15284 "Get the TAGS string in the current headline."
15285 (unless (org-at-heading-p t)
15286 (user-error "Not on a heading"))
15287 (save-excursion
15288 (beginning-of-line 1)
15289 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15290 (org-match-string-no-properties 1)
15291 "")))
15293 (defun org-get-tags ()
15294 "Get the list of tags specified in the current headline."
15295 (org-split-string (org-get-tags-string) ":"))
15297 (defun org-get-buffer-tags ()
15298 "Get a table of all tags used in the buffer, for completion."
15299 (org-with-wide-buffer
15300 (goto-char (point-min))
15301 (let ((tag-re (concat org-outline-regexp-bol
15302 "\\(?:.*?[ \t]\\)?"
15303 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15304 tags)
15305 (while (re-search-forward tag-re nil t)
15306 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15307 (push tag tags)))
15308 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15310 ;;;; The mapping API
15312 (defun org-map-entries (func &optional match scope &rest skip)
15313 "Call FUNC at each headline selected by MATCH in SCOPE.
15315 FUNC is a function or a lisp form. The function will be called without
15316 arguments, with the cursor positioned at the beginning of the headline.
15317 The return values of all calls to the function will be collected and
15318 returned as a list.
15320 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15321 does not need to preserve point. After evaluation, the cursor will be
15322 moved to the end of the line (presumably of the headline of the
15323 processed entry) and search continues from there. Under some
15324 circumstances, this may not produce the wanted results. For example,
15325 if you have removed (e.g. archived) the current (sub)tree it could
15326 mean that the next entry will be skipped entirely. In such cases, you
15327 can specify the position from where search should continue by making
15328 FUNC set the variable `org-map-continue-from' to the desired buffer
15329 position.
15331 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15332 Only headlines that are matched by this query will be considered during
15333 the iteration. When MATCH is nil or t, all headlines will be
15334 visited by the iteration.
15336 SCOPE determines the scope of this command. It can be any of:
15338 nil The current buffer, respecting the restriction if any
15339 tree The subtree started with the entry at point
15340 region The entries within the active region, if any
15341 region-start-level
15342 The entries within the active region, but only those at
15343 the same level than the first one.
15344 file The current buffer, without restriction
15345 file-with-archives
15346 The current buffer, and any archives associated with it
15347 agenda All agenda files
15348 agenda-with-archives
15349 All agenda files with any archive files associated with them
15350 \(file1 file2 ...)
15351 If this is a list, all files in the list will be scanned
15353 The remaining args are treated as settings for the skipping facilities of
15354 the scanner. The following items can be given here:
15356 archive skip trees with the archive tag
15357 comment skip trees with the COMMENT keyword
15358 function or Emacs Lisp form:
15359 will be used as value for `org-agenda-skip-function', so
15360 whenever the function returns a position, FUNC will not be
15361 called for that entry and search will continue from the
15362 position returned
15364 If your function needs to retrieve the tags including inherited tags
15365 at the *current* entry, you can use the value of the variable
15366 `org-scanner-tags' which will be much faster than getting the value
15367 with `org-get-tags-at'. If your function gets properties with
15368 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15369 to t around the call to `org-entry-properties' to get the same speedup.
15370 Note that if your function moves around to retrieve tags and properties at
15371 a *different* entry, you cannot use these techniques."
15372 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15373 (not (org-region-active-p)))
15374 (let* ((org-agenda-archives-mode nil) ; just to make sure
15375 (org-agenda-skip-archived-trees (memq 'archive skip))
15376 (org-agenda-skip-comment-trees (memq 'comment skip))
15377 (org-agenda-skip-function
15378 (car (org-delete-all '(comment archive) skip)))
15379 (org-tags-match-list-sublevels t)
15380 (start-level (eq scope 'region-start-level))
15381 matcher file res
15382 org-todo-keywords-for-agenda
15383 org-done-keywords-for-agenda
15384 org-todo-keyword-alist-for-agenda
15385 org-tag-alist-for-agenda
15386 todo-only)
15388 (cond
15389 ((eq match t) (setq matcher t))
15390 ((eq match nil) (setq matcher t))
15391 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15393 (save-excursion
15394 (save-restriction
15395 (cond ((eq scope 'tree)
15396 (org-back-to-heading t)
15397 (org-narrow-to-subtree)
15398 (setq scope nil))
15399 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15400 (org-region-active-p))
15401 ;; If needed, set start-level to a string like "2"
15402 (when start-level
15403 (save-excursion
15404 (goto-char (region-beginning))
15405 (unless (org-at-heading-p) (outline-next-heading))
15406 (setq start-level (org-current-level))))
15407 (narrow-to-region (region-beginning)
15408 (save-excursion
15409 (goto-char (region-end))
15410 (unless (and (bolp) (org-at-heading-p))
15411 (outline-next-heading))
15412 (point)))
15413 (setq scope nil)))
15415 (if (not scope)
15416 (progn
15417 (org-agenda-prepare-buffers
15418 (list (buffer-file-name (current-buffer))))
15419 (setq res (org-scan-tags func matcher todo-only start-level)))
15420 ;; Get the right scope
15421 (cond
15422 ((and scope (listp scope) (symbolp (car scope)))
15423 (setq scope (eval scope)))
15424 ((eq scope 'agenda)
15425 (setq scope (org-agenda-files t)))
15426 ((eq scope 'agenda-with-archives)
15427 (setq scope (org-agenda-files t))
15428 (setq scope (org-add-archive-files scope)))
15429 ((eq scope 'file)
15430 (setq scope (list (buffer-file-name))))
15431 ((eq scope 'file-with-archives)
15432 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15433 (org-agenda-prepare-buffers scope)
15434 (while (setq file (pop scope))
15435 (with-current-buffer (org-find-base-buffer-visiting file)
15436 (save-excursion
15437 (save-restriction
15438 (widen)
15439 (goto-char (point-min))
15440 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15441 res)))
15443 ;;; Properties API
15445 (defconst org-special-properties
15446 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15447 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15448 "The special properties valid in Org mode.
15449 These are properties that are not defined in the property drawer,
15450 but in some other way.")
15452 (defconst org-default-properties
15453 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15454 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15455 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15456 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15457 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15458 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15459 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15460 "Some properties that are used by Org mode for various purposes.
15461 Being in this list makes sure that they are offered for completion.")
15463 (defun org--update-property-plist (key val props)
15464 "Associate KEY to VAL in alist PROPS.
15465 Modifications are made by side-effect. Return new alist."
15466 (let* ((appending (string= (substring key -1) "+"))
15467 (key (if appending (substring key 0 -1) key))
15468 (old (assoc-string key props t)))
15469 (if (not old) (cons (cons key val) props)
15470 (setcdr old (if appending (concat (cdr old) " " val) val))
15471 props)))
15473 (defun org-get-property-block (&optional beg force)
15474 "Return the (beg . end) range of the body of the property drawer.
15475 BEG is the beginning of the current subtree, or of the part
15476 before the first headline. If it is not given, it will be found.
15477 If the drawer does not exist, create it if FORCE is non-nil, or
15478 return nil."
15479 (org-with-wide-buffer
15480 (when beg (goto-char beg))
15481 (unless (org-before-first-heading-p)
15482 (let ((beg (cond (beg)
15483 ((or (not (featurep 'org-inlinetask))
15484 (org-inlinetask-in-task-p))
15485 (org-back-to-heading t))
15486 (t (org-with-limited-levels (org-back-to-heading t))))))
15487 (forward-line)
15488 (when (org-looking-at-p org-planning-line-re) (forward-line))
15489 (cond ((looking-at org-property-drawer-re)
15490 (forward-line)
15491 (cons (point) (progn (goto-char (match-end 0))
15492 (line-beginning-position))))
15493 (force
15494 (goto-char beg)
15495 (org-insert-property-drawer)
15496 (let ((pos (save-excursion (search-forward ":END:")
15497 (line-beginning-position))))
15498 (cons pos pos))))))))
15500 (defun org-at-property-p ()
15501 "Non-nil when point is inside a property drawer.
15502 See `org-property-re' for match data, if applicable."
15503 (save-excursion
15504 (beginning-of-line)
15505 (and (looking-at org-property-re)
15506 (let ((property-drawer (save-match-data (org-get-property-block))))
15507 (and property-drawer
15508 (>= (point) (car property-drawer))
15509 (< (point) (cdr property-drawer)))))))
15511 (defun org-property-action ()
15512 "Do an action on properties."
15513 (interactive)
15514 (unless (org-at-property-p) (user-error "Not at a property"))
15515 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15516 (let ((c (read-char-exclusive)))
15517 (case c
15518 (?s (call-interactively #'org-set-property))
15519 (?d (call-interactively #'org-delete-property))
15520 (?D (call-interactively #'org-delete-property-globally))
15521 (?c (call-interactively #'org-compute-property-at-point))
15522 (otherwise (user-error "No such property action %c" c)))))
15524 (defun org-inc-effort ()
15525 "Increment the value of the effort property in the current entry."
15526 (interactive)
15527 (org-set-effort nil t))
15529 (defvar org-clock-effort) ; Defined in org-clock.el.
15530 (defvar org-clock-current-task) ; Defined in org-clock.el.
15531 (defun org-set-effort (&optional value increment)
15532 "Set the effort property of the current entry.
15533 With numerical prefix arg, use the nth allowed value, 0 stands for the
15534 10th allowed value.
15536 When INCREMENT is non-nil, set the property to the next allowed value."
15537 (interactive "P")
15538 (if (equal value 0) (setq value 10))
15539 (let* ((completion-ignore-case t)
15540 (prop org-effort-property)
15541 (cur (org-entry-get nil prop))
15542 (allowed (org-property-get-allowed-values nil prop 'table))
15543 (existing (mapcar 'list (org-property-values prop)))
15544 (heading (nth 4 (org-heading-components)))
15546 (val (cond
15547 ((stringp value) value)
15548 ((and allowed (integerp value))
15549 (or (car (nth (1- value) allowed))
15550 (car (org-last allowed))))
15551 ((and allowed increment)
15552 (or (caadr (member (list cur) allowed))
15553 (user-error "Allowed effort values are not set")))
15554 (allowed
15555 (message "Select 1-9,0, [RET%s]: %s"
15556 (if cur (concat "=" cur) "")
15557 (mapconcat 'car allowed " "))
15558 (setq rpl (read-char-exclusive))
15559 (if (equal rpl ?\r)
15561 (setq rpl (- rpl ?0))
15562 (if (equal rpl 0) (setq rpl 10))
15563 (if (and (> rpl 0) (<= rpl (length allowed)))
15564 (car (nth (1- rpl) allowed))
15565 (org-completing-read "Effort: " allowed nil))))
15567 (let (org-completion-use-ido org-completion-use-iswitchb)
15568 (org-completing-read
15569 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15570 (concat "[" cur "]") "")
15571 ": ")
15572 existing nil nil "" nil cur))))))
15573 (unless (equal (org-entry-get nil prop) val)
15574 (org-entry-put nil prop val))
15575 (org-refresh-property
15576 '((effort . identity)
15577 (effort-minutes . org-duration-string-to-minutes))
15578 val)
15579 (when (string= heading org-clock-current-task)
15580 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15581 (org-clock-update-mode-line))
15582 (message "%s is now %s" prop val)))
15584 (defun org-entry-properties (&optional pom which)
15585 "Get all properties of the current entry.
15587 When POM is a buffer position, get all properties from the entry
15588 there instead.
15590 This includes the TODO keyword, the tags, time strings for
15591 deadline, scheduled, and clocking, and any additional properties
15592 defined in the entry.
15594 If WHICH is nil or `all', get all properties. If WHICH is
15595 `special' or `standard', only get that subclass. If WHICH is
15596 a string, only get that property.
15598 Return value is an alist. Keys are properties, as upcased
15599 strings."
15600 (org-with-point-at pom
15601 (when (and (derived-mode-p 'org-mode)
15602 (ignore-errors (org-back-to-heading t)))
15603 (catch 'exit
15604 (let* ((beg (point))
15605 (specific (and (stringp which) (upcase which)))
15606 (which (cond ((not specific) which)
15607 ((member specific org-special-properties) 'special)
15608 (t 'standard)))
15609 props)
15610 ;; Get the special properties, like TODO and TAGS.
15611 (when (memq which '(nil all special))
15612 (when (or (not specific) (string= specific "CLOCKSUM"))
15613 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15614 (when clocksum
15615 (push (cons "CLOCKSUM"
15616 (org-columns-number-to-string
15617 (/ (float clocksum) 60.) 'add_times))
15618 props)))
15619 (when specific (throw 'exit props)))
15620 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15621 (let ((clocksumt (get-text-property (point)
15622 :org-clock-minutes-today)))
15623 (when clocksumt
15624 (push (cons "CLOCKSUM_T"
15625 (org-columns-number-to-string
15626 (/ (float clocksumt) 60.) 'add_times))
15627 props)))
15628 (when specific (throw 'exit props)))
15629 (when (or (not specific) (string= specific "ITEM"))
15630 (when (looking-at org-complex-heading-regexp)
15631 (push (cons "ITEM"
15632 (concat
15633 (org-match-string-no-properties 1)
15634 (let ((title (org-match-string-no-properties 4)))
15635 (when (org-string-nw-p title)
15636 (concat " " (org-remove-tabs title))))))
15637 props))
15638 (when specific (throw 'exit props)))
15639 (when (or (not specific) (string= specific "TODO"))
15640 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15641 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15642 (when specific (throw 'exit props)))
15643 (when (or (not specific) (string= specific "PRIORITY"))
15644 (when (looking-at org-priority-regexp)
15645 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15646 (when specific (throw 'exit props)))
15647 (when (or (not specific) (string= specific "FILE"))
15648 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15649 props)
15650 (when specific (throw 'exit props)))
15651 (when (or (not specific) (string= specific "TAGS"))
15652 (let ((value (org-string-nw-p (org-get-tags-string))))
15653 (when value (push (cons "TAGS" value) props)))
15654 (when specific (throw 'exit props)))
15655 (when (or (not specific) (string= specific "ALLTAGS"))
15656 (let ((value (org-get-tags-at)))
15657 (when value
15658 (push (cons "ALLTAGS"
15659 (format ":%s:" (mapconcat #'identity value ":")))
15660 props)))
15661 (when specific (throw 'exit props)))
15662 (when (or (not specific) (string= specific "BLOCKED"))
15663 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15664 (when specific (throw 'exit props)))
15665 (when (or (not specific)
15666 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15667 (forward-line)
15668 (when (org-looking-at-p org-planning-line-re)
15669 (end-of-line)
15670 (let ((bol (line-beginning-position))
15671 ;; Backward compatibility: time keywords used to
15672 ;; be configurable (before 8.3). Make sure we
15673 ;; get the correct keyword.
15674 (key-assoc `(("CLOSED" . ,org-closed-string)
15675 ("DEADLINE" . ,org-deadline-string)
15676 ("SCHEDULED" . ,org-scheduled-string))))
15677 (dolist (pair (if specific (list (assoc specific key-assoc))
15678 key-assoc))
15679 (save-excursion
15680 (when (search-backward (cdr pair) bol t)
15681 (goto-char (match-end 0))
15682 (skip-chars-forward " \t")
15683 (and (looking-at org-ts-regexp-both)
15684 (push (cons (car pair)
15685 (org-match-string-no-properties 0))
15686 props)))))))
15687 (when specific (throw 'exit props)))
15688 (when (or (not specific)
15689 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15690 (let ((find-ts
15691 (lambda (end ts)
15692 (let ((regexp (if (or (string= specific "TIMESTAMP")
15693 (assoc "TIMESTAMP_IA" ts))
15694 org-ts-regexp
15695 org-ts-regexp-both)))
15696 (catch 'next
15697 (while (re-search-forward regexp end t)
15698 (backward-char)
15699 (let ((object (org-element-context)))
15700 ;; Accept to match timestamps in node
15701 ;; properties, too.
15702 (when (memq (org-element-type object)
15703 '(node-property timestamp))
15704 (let ((type
15705 (org-element-property :type object)))
15706 (cond
15707 ((and (memq type '(active active-range))
15708 (not (equal specific "TIMESTAMP_IA")))
15709 (unless (assoc "TIMESTAMP" ts)
15710 (push (cons "TIMESTAMP"
15711 (org-element-property
15712 :raw-value object))
15714 (when specific (throw 'exit ts))))
15715 ((and (memq type '(inactive inactive-range))
15716 (not (string= specific "TIMESTAMP")))
15717 (unless (assoc "TIMESTAMP_IA" ts)
15718 (push (cons "TIMESTAMP_IA"
15719 (org-element-property
15720 :raw-value object))
15722 (when specific (throw 'exit ts))))))
15723 ;; Both timestamp types are found,
15724 ;; move to next part.
15725 (when (= (length ts) 2) (throw 'next ts)))))
15726 ts)))))
15727 (goto-char beg)
15728 ;; First look for timestamps within headline.
15729 (let ((ts (funcall find-ts (line-end-position) nil)))
15730 (if (= (length ts) 2) (setq props (nconc ts props))
15731 (forward-line)
15732 ;; Then find timestamps in the section, skipping
15733 ;; planning line.
15734 (when (org-looking-at-p org-planning-line-re)
15735 (forward-line))
15736 (let ((end (save-excursion (outline-next-heading))))
15737 (setq props (nconc (funcall find-ts end ts) props))))))))
15738 ;; Get the standard properties, like :PROP:.
15739 (when (memq which '(nil all standard))
15740 ;; If we are looking after a specific property, delegate
15741 ;; to `org-entry-get', which is faster. However, make an
15742 ;; exception for "CATEGORY", since it can be also set
15743 ;; through keywords (i.e. #+CATEGORY).
15744 (if (and specific (not (equal specific "CATEGORY")))
15745 (let ((value (org-entry-get beg specific nil t)))
15746 (throw 'exit (and value (list (cons specific value)))))
15747 (let ((range (org-get-property-block beg)))
15748 (when range
15749 (let ((end (cdr range)) seen-base)
15750 (goto-char (car range))
15751 ;; Unlike to `org--update-property-plist', we
15752 ;; handle the case where base values is found
15753 ;; after its extension. We also forbid standard
15754 ;; properties to be named as special properties.
15755 (while (re-search-forward org-property-re end t)
15756 (let* ((key (upcase (org-match-string-no-properties 2)))
15757 (extendp (org-string-match-p "\\+\\'" key))
15758 (key-base (if extendp (substring key 0 -1) key))
15759 (value (org-match-string-no-properties 3)))
15760 (cond
15761 ((member-ignore-case key-base org-special-properties))
15762 (extendp
15763 (setq props
15764 (org--update-property-plist key value props)))
15765 ((member key seen-base))
15766 (t (push key seen-base)
15767 (let ((p (assoc-string key props t)))
15768 (if p (setcdr p (concat value " " (cdr p)))
15769 (push (cons key value) props))))))))))))
15770 (unless (assoc "CATEGORY" props)
15771 (push (cons "CATEGORY" (org-get-category beg)) props)
15772 (when (string= specific "CATEGORY") (throw 'exit props)))
15773 ;; Return value.
15774 (append (get-text-property beg 'org-summaries) props))))))
15776 (defun org-entry-get (pom property &optional inherit literal-nil)
15777 "Get value of PROPERTY for entry or content at point-or-marker POM.
15779 If INHERIT is non-nil and the entry does not have the property,
15780 then also check higher levels of the hierarchy. If INHERIT is
15781 the symbol `selective', use inheritance only if the setting in
15782 `org-use-property-inheritance' selects PROPERTY for inheritance.
15784 If the property is present but empty, the return value is the
15785 empty string. If the property is not present at all, nil is
15786 returned. In any other case, return the value as a string.
15787 Search is case-insensitive.
15789 If LITERAL-NIL is set, return the string value \"nil\" as
15790 a string, do not interpret it as the list atom nil. This is used
15791 for inheritance when a \"nil\" value can supersede a non-nil
15792 value higher up the hierarchy."
15793 (org-with-point-at pom
15794 (cond
15795 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15796 ;; We need a special property. Use `org-entry-properties' to
15797 ;; retrieve it, but specify the wanted property.
15798 (cdr (assoc-string property (org-entry-properties nil property))))
15799 ((and inherit
15800 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15801 (org-entry-get-with-inheritance property literal-nil))
15803 (let ((range (org-get-property-block)))
15804 (when range
15805 (let* ((case-fold-search t)
15806 (end (cdr range))
15807 (props
15808 (let ((global
15809 (or (assoc-string property org-file-properties t)
15810 (assoc-string property org-global-properties t)
15811 (assoc-string
15812 property org-global-properties-fixed t))))
15813 ;; Make sure to not re-use GLOBAL as
15814 ;; `org--update-property-plist' would alter it by
15815 ;; side-effect.
15816 (and global (list (cons property (cdr global))))))
15817 (find-value
15818 (lambda (key)
15819 (when (re-search-forward (org-re-property key nil t) end t)
15820 (setq props
15821 (org--update-property-plist
15822 key (org-match-string-no-properties 3) props))))))
15823 (goto-char (car range))
15824 ;; Find base value.
15825 (save-excursion (funcall find-value property))
15826 ;; Find additional values.
15827 (let ((property+ (concat property "+")))
15828 (while (funcall find-value property+)))
15829 ;; Return final value.
15830 (let ((val (cdr (assoc-string property props t))))
15831 (if literal-nil val (org-not-nil val))))))))))
15833 (defun org-property-or-variable-value (var &optional inherit)
15834 "Check if there is a property fixing the value of VAR.
15835 If yes, return this value. If not, return the current value of the variable."
15836 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15837 (if (and prop (stringp prop) (string-match "\\S-" prop))
15838 (read prop)
15839 (symbol-value var))))
15841 (defun org-entry-delete (pom property)
15842 "Delete PROPERTY from entry at point-or-marker POM.
15843 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15844 non-nil when a property was removed."
15845 (unless (member property org-special-properties)
15846 (org-with-point-at pom
15847 (let ((range (org-get-property-block)))
15848 (when range
15849 (let* ((begin (car range))
15850 (origin (cdr range))
15851 (end (copy-marker origin))
15852 (re (org-re-property
15853 (concat (regexp-quote property) "\\+?") t t)))
15854 (goto-char begin)
15855 (while (re-search-forward re end t)
15856 (delete-region (match-beginning 0) (line-beginning-position 2)))
15857 ;; If drawer is empty, remove it altogether.
15858 (when (= begin end)
15859 (delete-region (line-beginning-position 0)
15860 (line-beginning-position 2)))
15861 ;; Return non-nil if some property was removed.
15862 (prog1 (/= end origin) (set-marker end nil))))))))
15864 ;; Multi-values properties are properties that contain multiple values
15865 ;; These values are assumed to be single words, separated by whitespace.
15866 (defun org-entry-add-to-multivalued-property (pom property value)
15867 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15868 (let* ((old (org-entry-get pom property))
15869 (values (and old (org-split-string old "[ \t]"))))
15870 (setq value (org-entry-protect-space value))
15871 (unless (member value values)
15872 (setq values (append values (list value)))
15873 (org-entry-put pom property
15874 (mapconcat 'identity values " ")))))
15876 (defun org-entry-remove-from-multivalued-property (pom property value)
15877 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15878 (let* ((old (org-entry-get pom property))
15879 (values (and old (org-split-string old "[ \t]"))))
15880 (setq value (org-entry-protect-space value))
15881 (when (member value values)
15882 (setq values (delete value values))
15883 (org-entry-put pom property
15884 (mapconcat 'identity values " ")))))
15886 (defun org-entry-member-in-multivalued-property (pom property value)
15887 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15888 (let* ((old (org-entry-get pom property))
15889 (values (and old (org-split-string old "[ \t]"))))
15890 (setq value (org-entry-protect-space value))
15891 (member value values)))
15893 (defun org-entry-get-multivalued-property (pom property)
15894 "Return a list of values in a multivalued property."
15895 (let* ((value (org-entry-get pom property))
15896 (values (and value (org-split-string value "[ \t]"))))
15897 (mapcar 'org-entry-restore-space values)))
15899 (defun org-entry-put-multivalued-property (pom property &rest values)
15900 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15901 VALUES should be a list of strings. Spaces will be protected."
15902 (org-entry-put pom property
15903 (mapconcat 'org-entry-protect-space values " "))
15904 (let* ((value (org-entry-get pom property))
15905 (values (and value (org-split-string value "[ \t]"))))
15906 (mapcar 'org-entry-restore-space values)))
15908 (defun org-entry-protect-space (s)
15909 "Protect spaces and newline in string S."
15910 (while (string-match " " s)
15911 (setq s (replace-match "%20" t t s)))
15912 (while (string-match "\n" s)
15913 (setq s (replace-match "%0A" t t s)))
15916 (defun org-entry-restore-space (s)
15917 "Restore spaces and newline in string S."
15918 (while (string-match "%20" s)
15919 (setq s (replace-match " " t t s)))
15920 (while (string-match "%0A" s)
15921 (setq s (replace-match "\n" t t s)))
15924 (defvar org-entry-property-inherited-from (make-marker)
15925 "Marker pointing to the entry from where a property was inherited.
15926 Each call to `org-entry-get-with-inheritance' will set this marker to the
15927 location of the entry where the inheritance search matched. If there was
15928 no match, the marker will point nowhere.
15929 Note that also `org-entry-get' calls this function, if the INHERIT flag
15930 is set.")
15932 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15933 "Get PROPERTY of entry or content at point, search higher levels if needed.
15934 The search will stop at the first ancestor which has the property defined.
15935 If the value found is \"nil\", return nil to show that the property
15936 should be considered as undefined (this is the meaning of nil here).
15937 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15938 (move-marker org-entry-property-inherited-from nil)
15939 (let (value)
15940 (org-with-wide-buffer
15941 (catch 'exit
15942 (while t
15943 (when (setq value (org-entry-get nil property nil literal-nil))
15944 (org-back-to-heading t)
15945 (move-marker org-entry-property-inherited-from (point))
15946 (throw 'exit nil))
15947 (or (org-up-heading-safe) (throw 'exit nil)))))
15948 (unless value
15949 (setq value
15950 (cdr (or (assoc-string property org-file-properties t)
15951 (assoc-string property org-global-properties t)
15952 (assoc-string property org-global-properties-fixed t)))))
15953 (if literal-nil value (org-not-nil value))))
15955 (defvar org-property-changed-functions nil
15956 "Hook called when the value of a property has changed.
15957 Each hook function should accept two arguments, the name of the property
15958 and the new value.")
15960 (defun org-entry-put (pom property value)
15961 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15963 If the value is `nil', it is converted to the empty string. If
15964 it is not a string, an error is raised.
15966 PROPERTY can be any regular property (see
15967 `org-special-properties'). It can also be \"TODO\",
15968 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15970 For the last two properties, VALUE may have any of the special
15971 values \"earlier\" and \"later\". The function then increases or
15972 decreases scheduled or deadline date by one day."
15973 (cond ((null value) (setq value ""))
15974 ((not (stringp value)) (error "Properties values should be strings")))
15975 (org-with-point-at pom
15976 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15977 (org-back-to-heading t)
15978 (org-with-limited-levels (org-back-to-heading t)))
15979 (let ((beg (point)))
15980 (cond
15981 ((equal property "TODO")
15982 (cond ((not (org-string-nw-p value)) (setq value 'none))
15983 ((not (member value org-todo-keywords-1))
15984 (user-error "\"%s\" is not a valid TODO state" value)))
15985 (org-todo value)
15986 (org-set-tags nil 'align))
15987 ((equal property "PRIORITY")
15988 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15989 (org-set-tags nil 'align))
15990 ((equal property "SCHEDULED")
15991 (forward-line)
15992 (if (and (org-looking-at-p org-planning-line-re)
15993 (re-search-forward
15994 org-scheduled-time-regexp (line-end-position) t))
15995 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15996 ((string= value "later") (org-timestamp-change 1 'day))
15997 ((string= value "") (org-schedule '(4)))
15998 (t (org-schedule nil value)))
15999 (if (member value '("earlier" "later" ""))
16000 (call-interactively #'org-schedule)
16001 (org-schedule nil value))))
16002 ((equal property "DEADLINE")
16003 (forward-line)
16004 (if (and (org-looking-at-p org-planning-line-re)
16005 (re-search-forward
16006 org-deadline-time-regexp (line-end-position) t))
16007 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16008 ((string= value "later") (org-timestamp-change 1 'day))
16009 ((string= value "") (org-deadline '(4)))
16010 (t (org-deadline nil value)))
16011 (if (member value '("earlier" "later" ""))
16012 (call-interactively #'org-deadline)
16013 (org-deadline nil value))))
16014 ((member property org-special-properties)
16015 (error "The %s property cannot be set with `org-entry-put'" property))
16017 (let* ((range (org-get-property-block beg 'force))
16018 (end (cdr range))
16019 (case-fold-search t))
16020 (goto-char (car range))
16021 (if (re-search-forward (org-re-property property nil t) end t)
16022 (progn (delete-region (match-beginning 0) (match-end 0))
16023 (goto-char (match-beginning 0)))
16024 (goto-char end)
16025 (insert "\n")
16026 (backward-char))
16027 (insert ":" property ":")
16028 (when value (insert " " value))
16029 (org-indent-line)))))
16030 (run-hook-with-args 'org-property-changed-functions property value)))
16032 (defun org-buffer-property-keys (&optional specials defaults columns)
16033 "Get all property keys in the current buffer.
16035 When SPECIALS is non-nil, also list the special properties that
16036 reflect things like tags and TODO state.
16038 When DEFAULTS is non-nil, also include properties that has
16039 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16040 DESCRIPTION, LOCATION, and LOGGING and others.
16042 When COLUMNS in non-nil, also include property names given in
16043 COLUMN formats in the current buffer."
16044 (let ((case-fold-search t)
16045 (props (append
16046 (and specials org-special-properties)
16047 (and defaults (cons org-effort-property org-default-properties))
16048 nil)))
16049 (org-with-wide-buffer
16050 (goto-char (point-min))
16051 (while (re-search-forward org-property-start-re nil t)
16052 (let ((range (org-get-property-block)))
16053 (catch 'skip
16054 (unless range
16055 (when (and (not (org-before-first-heading-p))
16056 (y-or-n-p (format "Malformed drawer at %d, repair?"
16057 (line-beginning-position))))
16058 (org-get-property-block nil t))
16059 (throw 'skip nil))
16060 (goto-char (car range))
16061 (let ((begin (car range))
16062 (end (cdr range)))
16063 ;; Make sure that found property block is not located
16064 ;; before current point, as it would generate an infloop.
16065 ;; It can happen, for example, in the following
16066 ;; situation:
16068 ;; * Headline
16069 ;; :PROPERTIES:
16070 ;; ...
16071 ;; :END:
16072 ;; *************** Inlinetask
16073 ;; #+BEGIN_EXAMPLE
16074 ;; :PROPERTIES:
16075 ;; #+END_EXAMPLE
16077 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16078 (while (< (point) end)
16079 (let ((p (progn (looking-at org-property-re)
16080 (org-match-string-no-properties 2))))
16081 ;; Only add true property name, not extension symbol.
16082 (add-to-list 'props
16083 (if (not (org-string-match-p "\\+\\'" p)) p
16084 (substring p 0 -1))))
16085 (forward-line))))
16086 (outline-next-heading)))
16087 (when columns
16088 (goto-char (point-min))
16089 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16090 (let ((element (org-element-at-point)))
16091 (when (memq (org-element-type element) '(keyword node-property))
16092 (let ((value (org-element-property :value element))
16093 (start 0))
16094 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16095 (setq start (match-end 0))
16096 (let ((p (org-match-string-no-properties 1 value)))
16097 (unless (member-ignore-case p org-special-properties)
16098 (add-to-list 'props p))))))))))
16099 (sort props (lambda (a b) (string< (upcase a) (upcase b))))))
16101 (defun org-property-values (key)
16102 "List all non-nil values of property KEY in current buffer."
16103 (org-with-wide-buffer
16104 (goto-char (point-min))
16105 (let ((case-fold-search t)
16106 (re (org-re-property key))
16107 values)
16108 (while (re-search-forward re nil t)
16109 (add-to-list 'values (org-entry-get (point) key)))
16110 values)))
16112 (defun org-insert-property-drawer ()
16113 "Insert a property drawer into the current entry."
16114 (org-with-wide-buffer
16115 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16116 (org-back-to-heading t)
16117 (org-with-limited-levels (org-back-to-heading t)))
16118 (forward-line)
16119 (when (org-looking-at-p org-planning-line-re) (forward-line))
16120 (unless (org-looking-at-p org-property-drawer-re)
16121 (let ((inhibit-read-only t))
16122 (unless (bolp) (insert "\n"))
16123 (let ((begin (point)))
16124 (insert ":PROPERTIES:\n:END:\n")
16125 (org-indent-region begin (point)))))))
16127 (defun org-insert-drawer (&optional arg drawer)
16128 "Insert a drawer at point.
16130 When optional argument ARG is non-nil, insert a property drawer.
16132 Optional argument DRAWER, when non-nil, is a string representing
16133 drawer's name. Otherwise, the user is prompted for a name.
16135 If a region is active, insert the drawer around that region
16136 instead.
16138 Point is left between drawer's boundaries."
16139 (interactive "P")
16140 (let* ((drawer (if arg "PROPERTIES"
16141 (or drawer (read-from-minibuffer "Drawer: ")))))
16142 (cond
16143 ;; With C-u, fall back on `org-insert-property-drawer'
16144 (arg (org-insert-property-drawer))
16145 ;; Check validity of suggested drawer's name.
16146 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16147 (user-error "Invalid drawer name"))
16148 ;; With an active region, insert a drawer at point.
16149 ((not (org-region-active-p))
16150 (progn
16151 (unless (bolp) (insert "\n"))
16152 (insert (format ":%s:\n\n:END:\n" drawer))
16153 (forward-line -2)))
16154 ;; Otherwise, insert the drawer at point
16156 (let ((rbeg (region-beginning))
16157 (rend (copy-marker (region-end))))
16158 (unwind-protect
16159 (progn
16160 (goto-char rbeg)
16161 (beginning-of-line)
16162 (when (save-excursion
16163 (re-search-forward org-outline-regexp-bol rend t))
16164 (user-error "Drawers cannot contain headlines"))
16165 ;; Position point at the beginning of the first
16166 ;; non-blank line in region. Insert drawer's opening
16167 ;; there, then indent it.
16168 (org-skip-whitespace)
16169 (beginning-of-line)
16170 (insert ":" drawer ":\n")
16171 (forward-line -1)
16172 (indent-for-tab-command)
16173 ;; Move point to the beginning of the first blank line
16174 ;; after the last non-blank line in region. Insert
16175 ;; drawer's closing, then indent it.
16176 (goto-char rend)
16177 (skip-chars-backward " \r\t\n")
16178 (insert "\n:END:")
16179 (deactivate-mark t)
16180 (indent-for-tab-command)
16181 (unless (eolp) (insert "\n")))
16182 ;; Clear marker, whatever the outcome of insertion is.
16183 (set-marker rend nil)))))))
16185 (defvar org-property-set-functions-alist nil
16186 "Property set function alist.
16187 Each entry should have the following format:
16189 (PROPERTY . READ-FUNCTION)
16191 The read function will be called with the same argument as
16192 `org-completing-read'.")
16194 (defun org-set-property-function (property)
16195 "Get the function that should be used to set PROPERTY.
16196 This is computed according to `org-property-set-functions-alist'."
16197 (or (cdr (assoc property org-property-set-functions-alist))
16198 'org-completing-read))
16200 (defun org-read-property-value (property)
16201 "Read PROPERTY value from user."
16202 (let* ((completion-ignore-case t)
16203 (allowed (org-property-get-allowed-values nil property 'table))
16204 (cur (org-entry-get nil property))
16205 (prompt (concat property " value"
16206 (if (and cur (string-match "\\S-" cur))
16207 (concat " [" cur "]") "") ": "))
16208 (set-function (org-set-property-function property))
16209 (val (if allowed
16210 (funcall set-function prompt allowed nil
16211 (not (get-text-property 0 'org-unrestricted
16212 (caar allowed))))
16213 (let (org-completion-use-ido org-completion-use-iswitchb)
16214 (funcall set-function prompt
16215 (mapcar 'list (org-property-values property))
16216 nil nil "" nil cur)))))
16217 (org-trim val)))
16219 (defvar org-last-set-property nil)
16220 (defvar org-last-set-property-value nil)
16221 (defun org-read-property-name ()
16222 "Read a property name."
16223 (let ((completion-ignore-case t)
16224 (default-prop (or (and (org-at-property-p)
16225 (org-match-string-no-properties 2))
16226 org-last-set-property)))
16227 (org-completing-read
16228 (concat "Property"
16229 (if default-prop (concat " [" default-prop "]") "")
16230 ": ")
16231 (mapcar #'list (org-buffer-property-keys nil t t))
16232 nil nil nil nil default-prop)))
16234 (defun org-set-property-and-value (use-last)
16235 "Allow to set [PROPERTY]: [value] direction from prompt.
16236 When use-default, don't even ask, just use the last
16237 \"[PROPERTY]: [value]\" string from the history."
16238 (interactive "P")
16239 (let* ((completion-ignore-case t)
16240 (pv (or (and use-last org-last-set-property-value)
16241 (org-completing-read
16242 "Enter a \"[Property]: [value]\" pair: "
16243 nil nil nil nil nil
16244 org-last-set-property-value)))
16245 prop val)
16246 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16247 (setq prop (match-string 1 pv)
16248 val (match-string 2 pv))
16249 (org-set-property prop val))))
16251 (defun org-set-property (property value)
16252 "In the current entry, set PROPERTY to VALUE.
16253 When called interactively, this will prompt for a property name, offering
16254 completion on existing and default properties. And then it will prompt
16255 for a value, offering completion either on allowed values (via an inherited
16256 xxx_ALL property) or on existing values in other instances of this property
16257 in the current file."
16258 (interactive (list nil nil))
16259 (let* ((property (or property (org-read-property-name)))
16260 (value (or value (org-read-property-value property)))
16261 (fn (cdr (assoc property org-properties-postprocess-alist))))
16262 (setq org-last-set-property property)
16263 (setq org-last-set-property-value (concat property ": " value))
16264 ;; Possibly postprocess the inserted value:
16265 (when fn (setq value (funcall fn value)))
16266 (unless (equal (org-entry-get nil property) value)
16267 (org-entry-put nil property value))))
16269 (defun org-find-property (property &optional value)
16270 "Find first entry in buffer that sets PROPERTY.
16272 When optional argument VALUE is non-nil, only consider an entry
16273 if it contains PROPERTY set to this value. If PROPERTY should be
16274 explicitly set to nil, use string \"nil\" for VALUE.
16276 Return position where the entry begins, or nil if there is no
16277 such entry. If narrowing is in effect, only search the visible
16278 part of the buffer."
16279 (save-excursion
16280 (goto-char (point-min))
16281 (let ((case-fold-search t)
16282 (re (org-re-property property nil (not value) value)))
16283 (catch 'exit
16284 (while (re-search-forward re nil t)
16285 (when (if value (org-at-property-p)
16286 (org-entry-get (point) property nil t))
16287 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16289 (defun org-delete-property (property)
16290 "In the current entry, delete PROPERTY."
16291 (interactive
16292 (let* ((completion-ignore-case t)
16293 (cat (org-entry-get (point) "CATEGORY"))
16294 (props0 (org-entry-properties nil 'standard))
16295 (props (if cat props0
16296 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16297 (prop (if (< 1 (length props))
16298 (org-icompleting-read "Property: " props nil t)
16299 (caar props))))
16300 (list prop)))
16301 (if (not property)
16302 (message "No property to delete in this entry")
16303 (org-entry-delete nil property)
16304 (message "Property \"%s\" deleted" property)))
16306 (defun org-delete-property-globally (property)
16307 "Remove PROPERTY globally, from all entries.
16308 This function ignores narrowing, if any."
16309 (interactive
16310 (let* ((completion-ignore-case t)
16311 (prop (org-icompleting-read
16312 "Globally remove property: "
16313 (mapcar #'list (org-buffer-property-keys)))))
16314 (list prop)))
16315 (org-with-wide-buffer
16316 (goto-char (point-min))
16317 (let ((count 0)
16318 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16319 (while (re-search-forward re nil t)
16320 (when (org-entry-delete (point) property) (incf count)))
16321 (message "Property \"%s\" removed from %d entries" property count))))
16323 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16325 (defun org-compute-property-at-point ()
16326 "Compute the property at point.
16327 This looks for an enclosing column format, extracts the operator and
16328 then applies it to the property in the column format's scope."
16329 (interactive)
16330 (unless (org-at-property-p)
16331 (user-error "Not at a property"))
16332 (let ((prop (org-match-string-no-properties 2)))
16333 (org-columns-get-format-and-top-level)
16334 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16335 (user-error "No operator defined for property %s" prop))
16336 (org-columns-compute prop)))
16338 (defvar org-property-allowed-value-functions nil
16339 "Hook for functions supplying allowed values for a specific property.
16340 The functions must take a single argument, the name of the property, and
16341 return a flat list of allowed values. If \":ETC\" is one of
16342 the values, this means that these values are intended as defaults for
16343 completion, but that other values should be allowed too.
16344 The functions must return nil if they are not responsible for this
16345 property.")
16347 (defun org-property-get-allowed-values (pom property &optional table)
16348 "Get allowed values for the property PROPERTY.
16349 When TABLE is non-nil, return an alist that can directly be used for
16350 completion."
16351 (let (vals)
16352 (cond
16353 ((equal property "TODO")
16354 (setq vals (org-with-point-at pom
16355 (append org-todo-keywords-1 '("")))))
16356 ((equal property "PRIORITY")
16357 (let ((n org-lowest-priority))
16358 (while (>= n org-highest-priority)
16359 (push (char-to-string n) vals)
16360 (setq n (1- n)))))
16361 ((equal property "CATEGORY"))
16362 ((member property org-special-properties))
16363 ((setq vals (run-hook-with-args-until-success
16364 'org-property-allowed-value-functions property)))
16366 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16367 (when (and vals (string-match "\\S-" vals))
16368 (setq vals (car (read-from-string (concat "(" vals ")"))))
16369 (setq vals (mapcar (lambda (x)
16370 (cond ((stringp x) x)
16371 ((numberp x) (number-to-string x))
16372 ((symbolp x) (symbol-name x))
16373 (t "???")))
16374 vals)))))
16375 (when (member ":ETC" vals)
16376 (setq vals (remove ":ETC" vals))
16377 (org-add-props (car vals) '(org-unrestricted t)))
16378 (if table (mapcar 'list vals) vals)))
16380 (defun org-property-previous-allowed-value (&optional previous)
16381 "Switch to the next allowed value for this property."
16382 (interactive)
16383 (org-property-next-allowed-value t))
16385 (defun org-property-next-allowed-value (&optional previous)
16386 "Switch to the next allowed value for this property."
16387 (interactive)
16388 (unless (org-at-property-p)
16389 (user-error "Not at a property"))
16390 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16391 (key (match-string 2))
16392 (value (match-string 3))
16393 (allowed (or (org-property-get-allowed-values (point) key)
16394 (and (member value '("[ ]" "[-]" "[X]"))
16395 '("[ ]" "[X]"))))
16396 (heading (save-match-data (nth 4 (org-heading-components))))
16397 nval)
16398 (unless allowed
16399 (user-error "Allowed values for this property have not been defined"))
16400 (if previous (setq allowed (reverse allowed)))
16401 (if (member value allowed)
16402 (setq nval (car (cdr (member value allowed)))))
16403 (setq nval (or nval (car allowed)))
16404 (if (equal nval value)
16405 (user-error "Only one allowed value for this property"))
16406 (org-at-property-p)
16407 (replace-match (concat " :" key ": " nval) t t)
16408 (org-indent-line)
16409 (beginning-of-line 1)
16410 (skip-chars-forward " \t")
16411 (when (equal prop org-effort-property)
16412 (org-refresh-property
16413 '((effort . identity)
16414 (effort-minutes . org-duration-string-to-minutes))
16415 nval)
16416 (when (string= org-clock-current-task heading)
16417 (setq org-clock-effort nval)
16418 (org-clock-update-mode-line)))
16419 (run-hook-with-args 'org-property-changed-functions key nval)))
16421 (defun org-find-olp (path &optional this-buffer)
16422 "Return a marker pointing to the entry at outline path OLP.
16423 If anything goes wrong, throw an error.
16424 You can wrap this call to catch the error like this:
16426 (condition-case msg
16427 (org-mobile-locate-entry (match-string 4))
16428 (error (nth 1 msg)))
16430 The return value will then be either a string with the error message,
16431 or a marker if everything is OK.
16433 If THIS-BUFFER is set, the outline path does not contain a file,
16434 only headings."
16435 (let* ((file (if this-buffer buffer-file-name (pop path)))
16436 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16437 (level 1)
16438 (lmin 1)
16439 (lmax 1)
16440 limit re end found pos heading cnt flevel)
16441 (unless buffer (error "File not found :%s" file))
16442 (with-current-buffer buffer
16443 (save-excursion
16444 (save-restriction
16445 (widen)
16446 (setq limit (point-max))
16447 (goto-char (point-min))
16448 (while (setq heading (pop path))
16449 (setq re (format org-complex-heading-regexp-format
16450 (regexp-quote heading)))
16451 (setq cnt 0 pos (point))
16452 (while (re-search-forward re end t)
16453 (setq level (- (match-end 1) (match-beginning 1)))
16454 (if (and (>= level lmin) (<= level lmax))
16455 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16456 (when (= cnt 0) (error "Heading not found on level %d: %s"
16457 lmax heading))
16458 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16459 lmax heading))
16460 (goto-char found)
16461 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16462 (setq end (save-excursion (org-end-of-subtree t t))))
16463 (when (org-at-heading-p)
16464 (point-marker)))))))
16466 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16467 "Find node HEADING in BUFFER.
16468 Return a marker to the heading if it was found, or nil if not.
16469 If POS-ONLY is set, return just the position instead of a marker.
16471 The heading text must match exact, but it may have a TODO keyword,
16472 a priority cookie and tags in the standard locations."
16473 (with-current-buffer (or buffer (current-buffer))
16474 (save-excursion
16475 (save-restriction
16476 (widen)
16477 (goto-char (point-min))
16478 (let (case-fold-search)
16479 (if (re-search-forward
16480 (format org-complex-heading-regexp-format
16481 (regexp-quote heading)) nil t)
16482 (if pos-only
16483 (match-beginning 0)
16484 (move-marker (make-marker) (match-beginning 0)))))))))
16486 (defun org-find-exact-heading-in-directory (heading &optional dir)
16487 "Find Org node headline HEADING in all .org files in directory DIR.
16488 When the target headline is found, return a marker to this location."
16489 (let ((files (directory-files (or dir default-directory)
16490 t "\\`[^.#].*\\.org\\'"))
16491 file visiting m buffer)
16492 (catch 'found
16493 (while (setq file (pop files))
16494 (message "trying %s" file)
16495 (setq visiting (org-find-base-buffer-visiting file))
16496 (setq buffer (or visiting (find-file-noselect file)))
16497 (setq m (org-find-exact-headline-in-buffer
16498 heading buffer))
16499 (when (and (not m) (not visiting)) (kill-buffer buffer))
16500 (and m (throw 'found m))))))
16502 (defun org-find-entry-with-id (ident)
16503 "Locate the entry that contains the ID property with exact value IDENT.
16504 IDENT can be a string, a symbol or a number, this function will search for
16505 the string representation of it.
16506 Return the position where this entry starts, or nil if there is no such entry."
16507 (interactive "sID: ")
16508 (let ((id (cond
16509 ((stringp ident) ident)
16510 ((symbolp ident) (symbol-name ident))
16511 ((numberp ident) (number-to-string ident))
16512 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16513 (org-with-wide-buffer (org-find-property "ID" id))))
16515 ;;;; Timestamps
16517 (defvar org-last-changed-timestamp nil)
16518 (defvar org-last-inserted-timestamp nil
16519 "The last time stamp inserted with `org-insert-time-stamp'.")
16520 (defvar org-ts-what) ; dynamically scoped parameter
16522 (defun org-time-stamp (arg &optional inactive)
16523 "Prompt for a date/time and insert a time stamp.
16525 If the user specifies a time like HH:MM or if this command is
16526 called with at least one prefix argument, the time stamp contains
16527 the date and the time. Otherwise, only the date is included.
16529 All parts of a date not specified by the user are filled in from
16530 the timestamp at point, if any, or the current date/time
16531 otherwise.
16533 If there is already a timestamp at the cursor, it is replaced.
16535 With two universal prefix arguments, insert an active timestamp
16536 with the current time without prompting the user.
16538 When called from lisp, the timestamp is inactive if INACTIVE is
16539 non-nil."
16540 (interactive "P")
16541 (let* ((ts
16542 (cond ((org-at-date-range-p t)
16543 (save-excursion
16544 (goto-char (match-beginning 0))
16545 (looking-at (if inactive org-ts-regexp-both org-ts-regexp)))
16546 (match-string 0))
16547 ((org-at-timestamp-p t) (match-string 0))))
16548 ;; Default time is either the timestamp at point or today.
16549 ;; When entering a range, only the range start is considered.
16550 (default-time (if (not ts) (current-time)
16551 (apply #'encode-time (org-parse-time-string ts))))
16552 (default-input (and ts (org-get-compact-tod ts)))
16553 (repeater (and ts
16554 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16555 (match-string 0 ts)))
16556 org-time-was-given
16557 org-end-time-was-given
16558 (time
16559 (and (if (equal arg '(16)) (current-time)
16560 ;; Preserve `this-command' and `last-command'.
16561 (let ((this-command this-command)
16562 (last-command last-command))
16563 (org-read-date
16564 arg 'totime nil nil default-time default-input
16565 inactive))))))
16566 (cond
16567 ((and ts
16568 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16569 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16570 (insert "--")
16571 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16573 ;; Make sure we're on a timestamp. When in the middle of a date
16574 ;; range, move arbitrarily to range end.
16575 (unless (org-at-timestamp-p t)
16576 (skip-chars-forward "-")
16577 (org-at-timestamp-p t))
16578 (replace-match "")
16579 (setq org-last-changed-timestamp
16580 (org-insert-time-stamp
16581 time (or org-time-was-given arg)
16582 inactive nil nil (list org-end-time-was-given)))
16583 (when repeater
16584 (backward-char)
16585 (insert " " repeater)
16586 (setq org-last-changed-timestamp
16587 (concat (substring org-last-inserted-timestamp 0 -1)
16588 " " repeater ">")))
16589 (message "Timestamp updated"))
16590 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16591 (t (org-insert-time-stamp
16592 time (or org-time-was-given arg) inactive nil nil
16593 (list org-end-time-was-given))))))
16595 ;; FIXME: can we use this for something else, like computing time differences?
16596 (defun org-get-compact-tod (s)
16597 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16598 (let* ((t1 (match-string 1 s))
16599 (h1 (string-to-number (match-string 2 s)))
16600 (m1 (string-to-number (match-string 3 s)))
16601 (t2 (and (match-end 4) (match-string 5 s)))
16602 (h2 (and t2 (string-to-number (match-string 6 s))))
16603 (m2 (and t2 (string-to-number (match-string 7 s))))
16604 dh dm)
16605 (if (not t2)
16607 (setq dh (- h2 h1) dm (- m2 m1))
16608 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16609 (concat t1 "+" (number-to-string dh)
16610 (and (/= 0 dm) (format ":%02d" dm)))))))
16612 (defun org-time-stamp-inactive (&optional arg)
16613 "Insert an inactive time stamp.
16614 An inactive time stamp is enclosed in square brackets instead of angle
16615 brackets. It is inactive in the sense that it does not trigger agenda entries,
16616 does not link to the calendar and cannot be changed with the S-cursor keys.
16617 So these are more for recording a certain time/date."
16618 (interactive "P")
16619 (org-time-stamp arg 'inactive))
16621 (defvar org-date-ovl (make-overlay 1 1))
16622 (overlay-put org-date-ovl 'face 'org-date-selected)
16623 (org-detach-overlay org-date-ovl)
16625 (defvar org-ans1) ; dynamically scoped parameter
16626 (defvar org-ans2) ; dynamically scoped parameter
16628 (defvar org-plain-time-of-day-regexp) ; defined below
16630 (defvar org-overriding-default-time nil) ; dynamically scoped
16631 (defvar org-read-date-overlay nil)
16632 (defvar org-dcst nil) ; dynamically scoped
16633 (defvar org-read-date-history nil)
16634 (defvar org-read-date-final-answer nil)
16635 (defvar org-read-date-analyze-futurep nil)
16636 (defvar org-read-date-analyze-forced-year nil)
16637 (defvar org-read-date-inactive)
16639 (defvar org-read-date-minibuffer-local-map
16640 (let* ((map (make-sparse-keymap)))
16641 (set-keymap-parent map minibuffer-local-map)
16642 (org-defkey map (kbd ".")
16643 (lambda () (interactive)
16644 ;; Are we at the beginning of the prompt?
16645 (if (looking-back "^[^:]+: ")
16646 (org-eval-in-calendar '(calendar-goto-today))
16647 (insert "."))))
16648 (org-defkey map (kbd "C-.")
16649 (lambda () (interactive)
16650 (org-eval-in-calendar '(calendar-goto-today))))
16651 (org-defkey map [(meta shift left)]
16652 (lambda () (interactive)
16653 (org-eval-in-calendar '(calendar-backward-month 1))))
16654 (org-defkey map [(meta shift right)]
16655 (lambda () (interactive)
16656 (org-eval-in-calendar '(calendar-forward-month 1))))
16657 (org-defkey map [(meta shift up)]
16658 (lambda () (interactive)
16659 (org-eval-in-calendar '(calendar-backward-year 1))))
16660 (org-defkey map [(meta shift down)]
16661 (lambda () (interactive)
16662 (org-eval-in-calendar '(calendar-forward-year 1))))
16663 (org-defkey map [?\e (shift left)]
16664 (lambda () (interactive)
16665 (org-eval-in-calendar '(calendar-backward-month 1))))
16666 (org-defkey map [?\e (shift right)]
16667 (lambda () (interactive)
16668 (org-eval-in-calendar '(calendar-forward-month 1))))
16669 (org-defkey map [?\e (shift up)]
16670 (lambda () (interactive)
16671 (org-eval-in-calendar '(calendar-backward-year 1))))
16672 (org-defkey map [?\e (shift down)]
16673 (lambda () (interactive)
16674 (org-eval-in-calendar '(calendar-forward-year 1))))
16675 (org-defkey map [(shift up)]
16676 (lambda () (interactive)
16677 (org-eval-in-calendar '(calendar-backward-week 1))))
16678 (org-defkey map [(shift down)]
16679 (lambda () (interactive)
16680 (org-eval-in-calendar '(calendar-forward-week 1))))
16681 (org-defkey map [(shift left)]
16682 (lambda () (interactive)
16683 (org-eval-in-calendar '(calendar-backward-day 1))))
16684 (org-defkey map [(shift right)]
16685 (lambda () (interactive)
16686 (org-eval-in-calendar '(calendar-forward-day 1))))
16687 (org-defkey map "!"
16688 (lambda () (interactive)
16689 (org-eval-in-calendar '(diary-view-entries))
16690 (message "")))
16691 (org-defkey map ">"
16692 (lambda () (interactive)
16693 (org-eval-in-calendar '(calendar-scroll-left 1))))
16694 (org-defkey map "<"
16695 (lambda () (interactive)
16696 (org-eval-in-calendar '(calendar-scroll-right 1))))
16697 (org-defkey map "\C-v"
16698 (lambda () (interactive)
16699 (org-eval-in-calendar
16700 '(calendar-scroll-left-three-months 1))))
16701 (org-defkey map "\M-v"
16702 (lambda () (interactive)
16703 (org-eval-in-calendar
16704 '(calendar-scroll-right-three-months 1))))
16705 map)
16706 "Keymap for minibuffer commands when using `org-read-date'.")
16708 (defvar org-def)
16709 (defvar org-defdecode)
16710 (defvar org-with-time)
16712 (defun org-read-date (&optional org-with-time to-time from-string prompt
16713 default-time default-input inactive)
16714 "Read a date, possibly a time, and make things smooth for the user.
16715 The prompt will suggest to enter an ISO date, but you can also enter anything
16716 which will at least partially be understood by `parse-time-string'.
16717 Unrecognized parts of the date will default to the current day, month, year,
16718 hour and minute. If this command is called to replace a timestamp at point,
16719 or to enter the second timestamp of a range, the default time is taken
16720 from the existing stamp. Furthermore, the command prefers the future,
16721 so if you are giving a date where the year is not given, and the day-month
16722 combination is already past in the current year, it will assume you
16723 mean next year. For details, see the manual. A few examples:
16725 3-2-5 --> 2003-02-05
16726 feb 15 --> currentyear-02-15
16727 2/15 --> currentyear-02-15
16728 sep 12 9 --> 2009-09-12
16729 12:45 --> today 12:45
16730 22 sept 0:34 --> currentyear-09-22 0:34
16731 12 --> currentyear-currentmonth-12
16732 Fri --> nearest Friday after today
16733 -Tue --> last Tuesday
16734 etc.
16736 Furthermore you can specify a relative date by giving, as the *first* thing
16737 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16738 change in days weeks, months, years.
16739 With a single plus or minus, the date is relative to today. With a double
16740 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16741 +4d --> four days from today
16742 +4 --> same as above
16743 +2w --> two weeks from today
16744 ++5 --> five days from default date
16746 The function understands only English month and weekday abbreviations.
16748 While prompting, a calendar is popped up - you can also select the
16749 date with the mouse (button 1). The calendar shows a period of three
16750 months. To scroll it to other months, use the keys `>' and `<'.
16751 If you don't like the calendar, turn it off with
16752 \(setq org-read-date-popup-calendar nil)
16754 With optional argument TO-TIME, the date will immediately be converted
16755 to an internal time.
16756 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16757 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16758 still enter a time, and this function will inform the calling routine
16759 about this change. The calling routine may then choose to change the
16760 format used to insert the time stamp into the buffer to include the time.
16761 With optional argument FROM-STRING, read from this string instead from
16762 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16763 the time/date that is used for everything that is not specified by the
16764 user."
16765 (require 'parse-time)
16766 (let* ((org-time-stamp-rounding-minutes
16767 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16768 (org-dcst org-display-custom-times)
16769 (ct (org-current-time))
16770 (org-def (or org-overriding-default-time default-time ct))
16771 (org-defdecode (decode-time org-def))
16772 (dummy (progn
16773 (when (< (nth 2 org-defdecode) org-extend-today-until)
16774 (setcar (nthcdr 2 org-defdecode) -1)
16775 (setcar (nthcdr 1 org-defdecode) 59)
16776 (setq org-def (apply 'encode-time org-defdecode)
16777 org-defdecode (decode-time org-def)))))
16778 (cur-frame (selected-frame))
16779 (mouse-autoselect-window nil) ; Don't let the mouse jump
16780 (calendar-frame-setup nil)
16781 (calendar-setup (when (eq calendar-setup 'calendar-only) 'calendar-only))
16782 (calendar-move-hook nil)
16783 (calendar-view-diary-initially-flag nil)
16784 (calendar-view-holidays-initially-flag nil)
16785 (timestr (format-time-string
16786 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16787 (prompt (concat (if prompt (concat prompt " ") "")
16788 (format "Date+time [%s]: " timestr)))
16789 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16791 (cond
16792 (from-string (setq ans from-string))
16793 (org-read-date-popup-calendar
16794 (save-excursion
16795 (save-window-excursion
16796 (calendar)
16797 (when (eq calendar-setup 'calendar-only)
16798 (setq cal-frame
16799 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16800 (select-frame cal-frame))
16801 (org-eval-in-calendar '(setq cursor-type nil) t)
16802 (unwind-protect
16803 (progn
16804 (calendar-forward-day (- (time-to-days org-def)
16805 (calendar-absolute-from-gregorian
16806 (calendar-current-date))))
16807 (org-eval-in-calendar nil t)
16808 (let* ((old-map (current-local-map))
16809 (map (copy-keymap calendar-mode-map))
16810 (minibuffer-local-map
16811 (copy-keymap org-read-date-minibuffer-local-map)))
16812 (org-defkey map (kbd "RET") 'org-calendar-select)
16813 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16814 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16815 (unwind-protect
16816 (progn
16817 (use-local-map map)
16818 (setq org-read-date-inactive inactive)
16819 (add-hook 'post-command-hook 'org-read-date-display)
16820 (setq org-ans0 (read-string prompt default-input
16821 'org-read-date-history nil))
16822 ;; org-ans0: from prompt
16823 ;; org-ans1: from mouse click
16824 ;; org-ans2: from calendar motion
16825 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16826 (remove-hook 'post-command-hook 'org-read-date-display)
16827 (use-local-map old-map)
16828 (when org-read-date-overlay
16829 (delete-overlay org-read-date-overlay)
16830 (setq org-read-date-overlay nil)))))
16831 (bury-buffer "*Calendar*")
16832 (when cal-frame
16833 (delete-frame cal-frame)
16834 (select-frame-set-input-focus cur-frame))))))
16836 (t ; Naked prompt only
16837 (unwind-protect
16838 (setq ans (read-string prompt default-input
16839 'org-read-date-history timestr))
16840 (when org-read-date-overlay
16841 (delete-overlay org-read-date-overlay)
16842 (setq org-read-date-overlay nil)))))
16844 (setq final (org-read-date-analyze ans org-def org-defdecode))
16846 (when org-read-date-analyze-forced-year
16847 (message "Year was forced into %s"
16848 (if org-read-date-force-compatible-dates
16849 "compatible range (1970-2037)"
16850 "range representable on this machine"))
16851 (ding))
16853 ;; One round trip to get rid of 34th of August and stuff like that....
16854 (setq final (decode-time (apply 'encode-time final)))
16856 (setq org-read-date-final-answer ans)
16858 (if to-time
16859 (apply 'encode-time final)
16860 (if (and (boundp 'org-time-was-given) org-time-was-given)
16861 (format "%04d-%02d-%02d %02d:%02d"
16862 (nth 5 final) (nth 4 final) (nth 3 final)
16863 (nth 2 final) (nth 1 final))
16864 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16866 (defun org-read-date-display ()
16867 "Display the current date prompt interpretation in the minibuffer."
16868 (when org-read-date-display-live
16869 (when org-read-date-overlay
16870 (delete-overlay org-read-date-overlay))
16871 (when (minibufferp (current-buffer))
16872 (save-excursion
16873 (end-of-line 1)
16874 (while (not (equal (buffer-substring
16875 (max (point-min) (- (point) 4)) (point))
16876 " "))
16877 (insert " ")))
16878 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16879 " " (or org-ans1 org-ans2)))
16880 (org-end-time-was-given nil)
16881 (f (org-read-date-analyze ans org-def org-defdecode))
16882 (fmts (if org-dcst
16883 org-time-stamp-custom-formats
16884 org-time-stamp-formats))
16885 (fmt (if (or org-with-time
16886 (and (boundp 'org-time-was-given) org-time-was-given))
16887 (cdr fmts)
16888 (car fmts)))
16889 (txt (format-time-string fmt (apply 'encode-time f)))
16890 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16891 (txt (concat "=> " txt)))
16892 (when (and org-end-time-was-given
16893 (string-match org-plain-time-of-day-regexp txt))
16894 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16895 org-end-time-was-given
16896 (substring txt (match-end 0)))))
16897 (when org-read-date-analyze-futurep
16898 (setq txt (concat txt " (=>F)")))
16899 (setq org-read-date-overlay
16900 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16901 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16903 (defun org-read-date-analyze (ans org-def org-defdecode)
16904 "Analyze the combined answer of the date prompt."
16905 ;; FIXME: cleanup and comment
16906 (let ((nowdecode (decode-time (current-time)))
16907 delta deltan deltaw deltadef year month day
16908 hour minute second wday pm h2 m2 tl wday1
16909 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16910 (setq org-read-date-analyze-futurep nil
16911 org-read-date-analyze-forced-year nil)
16912 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16913 (setq ans "+0"))
16915 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16916 (setq ans (replace-match "" t t ans)
16917 deltan (car delta)
16918 deltaw (nth 1 delta)
16919 deltadef (nth 2 delta)))
16921 ;; Check if there is an iso week date in there. If yes, store the
16922 ;; info and postpone interpreting it until the rest of the parsing
16923 ;; is done.
16924 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16925 (setq iso-year (if (match-end 1)
16926 (org-small-year-to-year
16927 (string-to-number (match-string 1 ans))))
16928 iso-weekday (if (match-end 3)
16929 (string-to-number (match-string 3 ans)))
16930 iso-week (string-to-number (match-string 2 ans)))
16931 (setq ans (replace-match "" t t ans)))
16933 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16934 (when (string-match
16935 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16936 (setq year (if (match-end 2)
16937 (string-to-number (match-string 2 ans))
16938 (progn (setq kill-year t)
16939 (string-to-number (format-time-string "%Y"))))
16940 month (string-to-number (match-string 3 ans))
16941 day (string-to-number (match-string 4 ans)))
16942 (if (< year 100) (setq year (+ 2000 year)))
16943 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16944 t nil ans)))
16946 ;; Help matching dotted european dates
16947 (when (string-match
16948 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16949 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16950 (setq kill-year t)
16951 (string-to-number (format-time-string "%Y")))
16952 day (string-to-number (match-string 1 ans))
16953 month (string-to-number (match-string 2 ans))
16954 ans (replace-match (format "%04d-%02d-%02d" year month day)
16955 t nil ans)))
16957 ;; Help matching american dates, like 5/30 or 5/30/7
16958 (when (string-match
16959 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16960 (setq year (if (match-end 4)
16961 (string-to-number (match-string 4 ans))
16962 (progn (setq kill-year t)
16963 (string-to-number (format-time-string "%Y"))))
16964 month (string-to-number (match-string 1 ans))
16965 day (string-to-number (match-string 2 ans)))
16966 (if (< year 100) (setq year (+ 2000 year)))
16967 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16968 t nil ans)))
16969 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16970 ;; If there is a time with am/pm, and *no* time without it, we convert
16971 ;; so that matching will be successful.
16972 (loop for i from 1 to 2 do ; twice, for end time as well
16973 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16974 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16975 (setq hour (string-to-number (match-string 1 ans))
16976 minute (if (match-end 3)
16977 (string-to-number (match-string 3 ans))
16979 pm (equal ?p
16980 (string-to-char (downcase (match-string 4 ans)))))
16981 (if (and (= hour 12) (not pm))
16982 (setq hour 0)
16983 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16984 (setq ans (replace-match (format "%02d:%02d" hour minute)
16985 t t ans))))
16987 ;; Check if a time range is given as a duration
16988 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16989 (setq hour (string-to-number (match-string 1 ans))
16990 h2 (+ hour (string-to-number (match-string 3 ans)))
16991 minute (string-to-number (match-string 2 ans))
16992 m2 (+ minute (if (match-end 5) (string-to-number
16993 (match-string 5 ans))0)))
16994 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16995 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16996 t t ans)))
16998 ;; Check if there is a time range
16999 (when (boundp 'org-end-time-was-given)
17000 (setq org-time-was-given nil)
17001 (when (and (string-match org-plain-time-of-day-regexp ans)
17002 (match-end 8))
17003 (setq org-end-time-was-given (match-string 8 ans))
17004 (setq ans (concat (substring ans 0 (match-beginning 7))
17005 (substring ans (match-end 7))))))
17007 (setq tl (parse-time-string ans)
17008 day (or (nth 3 tl) (nth 3 org-defdecode))
17009 month
17010 (cond ((nth 4 tl))
17011 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17012 ;; Day was specified. Make sure DAY+MONTH
17013 ;; combination happens in the future.
17014 ((nth 3 tl)
17015 (setq futurep t)
17016 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17017 (nth 4 nowdecode)))
17018 (t (nth 4 org-defdecode)))
17019 year
17020 (cond ((and (not kill-year) (nth 5 tl)))
17021 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17022 ;; Month was guessed in the future and is at least
17023 ;; equal to NOWDECODE's. Fix year accordingly.
17024 (futurep
17025 (if (or (> month (nth 4 nowdecode))
17026 (>= day (nth 3 nowdecode)))
17027 (nth 5 nowdecode)
17028 (1+ (nth 5 nowdecode))))
17029 ;; Month was specified. Make sure MONTH+YEAR
17030 ;; combination happens in the future.
17031 ((nth 4 tl)
17032 (setq futurep t)
17033 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17034 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17035 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17036 (t (nth 5 nowdecode))))
17037 (t (nth 5 org-defdecode)))
17038 hour (or (nth 2 tl) (nth 2 org-defdecode))
17039 minute (or (nth 1 tl) (nth 1 org-defdecode))
17040 second (or (nth 0 tl) 0)
17041 wday (nth 6 tl))
17043 (when (and (eq org-read-date-prefer-future 'time)
17044 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17045 (equal day (nth 3 nowdecode))
17046 (equal month (nth 4 nowdecode))
17047 (equal year (nth 5 nowdecode))
17048 (nth 2 tl)
17049 (or (< (nth 2 tl) (nth 2 nowdecode))
17050 (and (= (nth 2 tl) (nth 2 nowdecode))
17051 (nth 1 tl)
17052 (< (nth 1 tl) (nth 1 nowdecode)))))
17053 (setq day (1+ day)
17054 futurep t))
17056 ;; Special date definitions below
17057 (cond
17058 (iso-week
17059 ;; There was an iso week
17060 (require 'cal-iso)
17061 (setq futurep nil)
17062 (setq year (or iso-year year)
17063 day (or iso-weekday wday 1)
17064 wday nil ; to make sure that the trigger below does not match
17065 iso-date (calendar-gregorian-from-absolute
17066 (calendar-iso-to-absolute
17067 (list iso-week day year))))
17068 ; FIXME: Should we also push ISO weeks into the future?
17069 ; (when (and org-read-date-prefer-future
17070 ; (not iso-year)
17071 ; (< (calendar-absolute-from-gregorian iso-date)
17072 ; (time-to-days (current-time))))
17073 ; (setq year (1+ year)
17074 ; iso-date (calendar-gregorian-from-absolute
17075 ; (calendar-iso-to-absolute
17076 ; (list iso-week day year)))))
17077 (setq month (car iso-date)
17078 year (nth 2 iso-date)
17079 day (nth 1 iso-date)))
17080 (deltan
17081 (setq futurep nil)
17082 (unless deltadef
17083 (let ((now (decode-time (current-time))))
17084 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17085 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17086 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17087 ((equal deltaw "m") (setq month (+ month deltan)))
17088 ((equal deltaw "y") (setq year (+ year deltan)))))
17089 ((and wday (not (nth 3 tl)))
17090 ;; Weekday was given, but no day, so pick that day in the week
17091 ;; on or after the derived date.
17092 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17093 (unless (equal wday wday1)
17094 (setq day (+ day (% (- wday wday1 -7) 7))))))
17095 (if (and (boundp 'org-time-was-given)
17096 (nth 2 tl))
17097 (setq org-time-was-given t))
17098 (if (< year 100) (setq year (+ 2000 year)))
17099 ;; Check of the date is representable
17100 (if org-read-date-force-compatible-dates
17101 (progn
17102 (if (< year 1970)
17103 (setq year 1970 org-read-date-analyze-forced-year t))
17104 (if (> year 2037)
17105 (setq year 2037 org-read-date-analyze-forced-year t)))
17106 (condition-case nil
17107 (ignore (encode-time second minute hour day month year))
17108 (error
17109 (setq year (nth 5 org-defdecode))
17110 (setq org-read-date-analyze-forced-year t))))
17111 (setq org-read-date-analyze-futurep futurep)
17112 (list second minute hour day month year)))
17114 (defvar parse-time-weekdays)
17115 (defun org-read-date-get-relative (s today default)
17116 "Check string S for special relative date string.
17117 TODAY and DEFAULT are internal times, for today and for a default.
17118 Return shift list (N what def-flag)
17119 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17120 N is the number of WHATs to shift.
17121 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17122 the DEFAULT date rather than TODAY."
17123 (require 'parse-time)
17124 (when (and
17125 (string-match
17126 (concat
17127 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17128 "\\([0-9]+\\)?"
17129 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17130 "\\([ \t]\\|$\\)") s)
17131 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17132 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17133 (string-to-char (substring (match-string 1 s) -1))
17134 ?+))
17135 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17136 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17137 (what (if (match-end 3) (match-string 3 s) "d"))
17138 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17139 (date (if rel default today))
17140 (wday (nth 6 (decode-time date)))
17141 delta)
17142 (if wday1
17143 (progn
17144 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17145 (if (= delta 0) (setq delta 7))
17146 (if (= dir ?-)
17147 (progn
17148 (setq delta (- delta 7))
17149 (if (= delta 0) (setq delta -7))))
17150 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17151 (list delta "d" rel))
17152 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17154 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17155 "Turn a user-specified date into the internal representation.
17156 The internal representation needed by the calendar is (month day year).
17157 This is a wrapper to handle the brain-dead convention in calendar that
17158 user function argument order change dependent on argument order."
17159 (if (boundp 'calendar-date-style)
17160 (cond
17161 ((eq calendar-date-style 'american)
17162 (list arg1 arg2 arg3))
17163 ((eq calendar-date-style 'european)
17164 (list arg2 arg1 arg3))
17165 ((eq calendar-date-style 'iso)
17166 (list arg2 arg3 arg1)))
17167 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17168 (if (org-bound-and-true-p european-calendar-style)
17169 (list arg2 arg1 arg3)
17170 (list arg1 arg2 arg3)))))
17172 (defun org-eval-in-calendar (form &optional keepdate)
17173 "Eval FORM in the calendar window and return to current window.
17174 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17175 otherwise stick to the current value of `org-ans2'."
17176 (let ((sf (selected-frame))
17177 (sw (selected-window)))
17178 (select-window (get-buffer-window "*Calendar*" t))
17179 (eval form)
17180 (when (and (not keepdate) (calendar-cursor-to-date))
17181 (let* ((date (calendar-cursor-to-date))
17182 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17183 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17184 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17185 (select-window sw)
17186 (org-select-frame-set-input-focus sf)))
17188 (defun org-calendar-select ()
17189 "Return to `org-read-date' with the date currently selected.
17190 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17191 (interactive)
17192 (when (calendar-cursor-to-date)
17193 (let* ((date (calendar-cursor-to-date))
17194 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17195 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17196 (if (active-minibuffer-window) (exit-minibuffer))))
17198 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17199 "Insert a date stamp for the date given by the internal TIME.
17200 See `format-time-string' for the format of TIME.
17201 WITH-HM means use the stamp format that includes the time of the day.
17202 INACTIVE means use square brackets instead of angular ones, so that the
17203 stamp will not contribute to the agenda.
17204 PRE and POST are optional strings to be inserted before and after the
17205 stamp.
17206 The command returns the inserted time stamp."
17207 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17208 stamp)
17209 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17210 (insert-before-markers (or pre ""))
17211 (when (listp extra)
17212 (setq extra (car extra))
17213 (if (and (stringp extra)
17214 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17215 (setq extra (format "-%02d:%02d"
17216 (string-to-number (match-string 1 extra))
17217 (string-to-number (match-string 2 extra))))
17218 (setq extra nil)))
17219 (when extra
17220 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17221 (insert-before-markers (setq stamp (format-time-string fmt time)))
17222 (insert-before-markers (or post ""))
17223 (setq org-last-inserted-timestamp stamp)))
17225 (defun org-toggle-time-stamp-overlays ()
17226 "Toggle the use of custom time stamp formats."
17227 (interactive)
17228 (setq org-display-custom-times (not org-display-custom-times))
17229 (unless org-display-custom-times
17230 (let ((p (point-min)) (bmp (buffer-modified-p)))
17231 (while (setq p (next-single-property-change p 'display))
17232 (if (and (get-text-property p 'display)
17233 (eq (get-text-property p 'face) 'org-date))
17234 (remove-text-properties
17235 p (setq p (next-single-property-change p 'display))
17236 '(display t))))
17237 (set-buffer-modified-p bmp)))
17238 (if (featurep 'xemacs)
17239 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17240 (org-restart-font-lock)
17241 (setq org-table-may-need-update t)
17242 (if org-display-custom-times
17243 (message "Time stamps are overlaid with custom format")
17244 (message "Time stamp overlays removed")))
17246 (defun org-display-custom-time (beg end)
17247 "Overlay modified time stamp format over timestamp between BEG and END."
17248 (let* ((ts (buffer-substring beg end))
17249 t1 w1 with-hm tf time str w2 (off 0))
17250 (save-match-data
17251 (setq t1 (org-parse-time-string ts t))
17252 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17253 (setq off (- (match-end 0) (match-beginning 0)))))
17254 (setq end (- end off))
17255 (setq w1 (- end beg)
17256 with-hm (and (nth 1 t1) (nth 2 t1))
17257 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17258 time (org-fix-decoded-time t1)
17259 str (org-add-props
17260 (format-time-string
17261 (substring tf 1 -1) (apply 'encode-time time))
17262 nil 'mouse-face 'highlight)
17263 w2 (length str))
17264 (if (not (= w2 w1))
17265 (add-text-properties (1+ beg) (+ 2 beg)
17266 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17267 (if (featurep 'xemacs)
17268 (progn
17269 (put-text-property beg end 'invisible t)
17270 (put-text-property beg end 'end-glyph (make-glyph str)))
17271 (put-text-property beg end 'display str))))
17273 (defun org-fix-decoded-time (time)
17274 "Set 0 instead of nil for the first 6 elements of time.
17275 Don't touch the rest."
17276 (let ((n 0))
17277 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17279 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17281 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17282 "Difference between TIMESTAMP-STRING and now in days.
17283 If SECONDS is non-nil, return the difference in seconds."
17284 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17285 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17286 (funcall fdiff (current-time)))))
17288 (defun org-deadline-close (timestamp-string &optional ndays)
17289 "Is the time in TIMESTAMP-STRING close to the current date?"
17290 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17291 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17292 (not (org-entry-is-done-p))))
17294 (defun org-get-wdays (ts &optional delay zero-delay)
17295 "Get the deadline lead time appropriate for timestring TS.
17296 When DELAY is non-nil, get the delay time for scheduled items
17297 instead of the deadline lead time. When ZERO-DELAY is non-nil
17298 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17299 don't try to find the delay cookie in the scheduled timestamp."
17300 (let ((tv (if delay org-scheduled-delay-days
17301 org-deadline-warning-days)))
17302 (cond
17303 ((or (and delay (< tv 0))
17304 (and delay zero-delay (<= tv 0))
17305 (and (not delay) (<= tv 0)))
17306 ;; Enforce this value no matter what
17307 (- tv))
17308 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17309 ;; lead time is specified.
17310 (floor (* (string-to-number (match-string 1 ts))
17311 (cdr (assoc (match-string 2 ts)
17312 '(("d" . 1) ("w" . 7)
17313 ("m" . 30.4) ("y" . 365.25)
17314 ("h" . 0.041667)))))))
17315 ;; go for the default.
17316 (t tv))))
17318 (defun org-calendar-select-mouse (ev)
17319 "Return to `org-read-date' with the date currently selected.
17320 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17321 (interactive "e")
17322 (mouse-set-point ev)
17323 (when (calendar-cursor-to-date)
17324 (let* ((date (calendar-cursor-to-date))
17325 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17326 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17327 (if (active-minibuffer-window) (exit-minibuffer))))
17329 (defun org-check-deadlines (ndays)
17330 "Check if there are any deadlines due or past due.
17331 A deadline is considered due if it happens within `org-deadline-warning-days'
17332 days from today's date. If the deadline appears in an entry marked DONE,
17333 it is not shown. The prefix arg NDAYS can be used to test that many
17334 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17335 (interactive "P")
17336 (let* ((org-warn-days
17337 (cond
17338 ((equal ndays '(4)) 100000)
17339 (ndays (prefix-numeric-value ndays))
17340 (t (abs org-deadline-warning-days))))
17341 (case-fold-search nil)
17342 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17343 (callback
17344 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17346 (message "%d deadlines past-due or due within %d days"
17347 (org-occur regexp nil callback)
17348 org-warn-days)))
17350 (defsubst org-re-timestamp (type)
17351 "Return a regexp for timestamp TYPE.
17352 Allowed values for TYPE are:
17354 all: all timestamps
17355 active: only active timestamps (<...>)
17356 inactive: only inactive timestamps ([...])
17357 scheduled: only scheduled timestamps
17358 deadline: only deadline timestamps
17359 closed: only closed time-stamps
17361 When TYPE is nil, fall back on returning a regexp that matches
17362 both scheduled and deadline timestamps."
17363 (case type
17364 (all org-ts-regexp-both)
17365 (active org-ts-regexp)
17366 (inactive org-ts-regexp-inactive)
17367 (scheduled org-scheduled-time-regexp)
17368 (deadline org-deadline-time-regexp)
17369 (closed org-closed-time-regexp)
17370 (otherwise
17371 (concat "\\<"
17372 (regexp-opt (list org-deadline-string org-scheduled-string))
17373 " *<\\([^>]+\\)>"))))
17375 (defun org-check-before-date (date)
17376 "Check if there are deadlines or scheduled entries before DATE."
17377 (interactive (list (org-read-date)))
17378 (let ((case-fold-search nil)
17379 (regexp (org-re-timestamp org-ts-type))
17380 (callback
17381 `(lambda ()
17382 (and ,(if (memq org-ts-type '(active inactive all))
17383 '(eq (org-element-type (org-element-context)) 'timestamp)
17384 '(org-at-planning-p))
17385 (time-less-p
17386 (org-time-string-to-time (match-string 1))
17387 (org-time-string-to-time date))))))
17388 (message "%d entries before %s"
17389 (org-occur regexp nil callback) date)))
17391 (defun org-check-after-date (date)
17392 "Check if there are deadlines or scheduled entries after DATE."
17393 (interactive (list (org-read-date)))
17394 (let ((case-fold-search nil)
17395 (regexp (org-re-timestamp org-ts-type))
17396 (callback
17397 `(lambda ()
17398 (and ,(if (memq org-ts-type '(active inactive all))
17399 '(eq (org-element-type (org-element-context)) 'timestamp)
17400 '(org-at-planning-p))
17401 (not (time-less-p
17402 (org-time-string-to-time (match-string 1))
17403 (org-time-string-to-time date)))))))
17404 (message "%d entries after %s"
17405 (org-occur regexp nil callback) date)))
17407 (defun org-check-dates-range (start-date end-date)
17408 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17409 (interactive (list (org-read-date nil nil nil "Range starts")
17410 (org-read-date nil nil nil "Range end")))
17411 (let ((case-fold-search nil)
17412 (regexp (org-re-timestamp org-ts-type))
17413 (callback
17414 `(lambda ()
17415 (let ((match (match-string 1)))
17416 (and
17417 ,(if (memq org-ts-type '(active inactive all))
17418 '(eq (org-element-type (org-element-context)) 'timestamp)
17419 '(org-at-planning-p))
17420 (not (time-less-p
17421 (org-time-string-to-time match)
17422 (org-time-string-to-time start-date)))
17423 (time-less-p
17424 (org-time-string-to-time match)
17425 (org-time-string-to-time end-date)))))))
17426 (message "%d entries between %s and %s"
17427 (org-occur regexp nil callback) start-date end-date)))
17429 (defun org-evaluate-time-range (&optional to-buffer)
17430 "Evaluate a time range by computing the difference between start and end.
17431 Normally the result is just printed in the echo area, but with prefix arg
17432 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17433 If the time range is actually in a table, the result is inserted into the
17434 next column.
17435 For time difference computation, a year is assumed to be exactly 365
17436 days in order to avoid rounding problems."
17437 (interactive "P")
17439 (org-clock-update-time-maybe)
17440 (save-excursion
17441 (unless (org-at-date-range-p t)
17442 (goto-char (point-at-bol))
17443 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17444 (if (not (org-at-date-range-p t))
17445 (user-error "Not at a time-stamp range, and none found in current line")))
17446 (let* ((ts1 (match-string 1))
17447 (ts2 (match-string 2))
17448 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17449 (match-end (match-end 0))
17450 (time1 (org-time-string-to-time ts1))
17451 (time2 (org-time-string-to-time ts2))
17452 (t1 (org-float-time time1))
17453 (t2 (org-float-time time2))
17454 (diff (abs (- t2 t1)))
17455 (negative (< (- t2 t1) 0))
17456 ;; (ys (floor (* 365 24 60 60)))
17457 (ds (* 24 60 60))
17458 (hs (* 60 60))
17459 (fy "%dy %dd %02d:%02d")
17460 (fy1 "%dy %dd")
17461 (fd "%dd %02d:%02d")
17462 (fd1 "%dd")
17463 (fh "%02d:%02d")
17464 y d h m align)
17465 (if havetime
17466 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17468 d (floor (/ diff ds)) diff (mod diff ds)
17469 h (floor (/ diff hs)) diff (mod diff hs)
17470 m (floor (/ diff 60)))
17471 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17473 d (floor (+ (/ diff ds) 0.5))
17474 h 0 m 0))
17475 (if (not to-buffer)
17476 (message "%s" (org-make-tdiff-string y d h m))
17477 (if (org-at-table-p)
17478 (progn
17479 (goto-char match-end)
17480 (setq align t)
17481 (and (looking-at " *|") (goto-char (match-end 0))))
17482 (goto-char match-end))
17483 (if (looking-at
17484 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17485 (replace-match ""))
17486 (if negative (insert " -"))
17487 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17488 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17489 (insert " " (format fh h m))))
17490 (if align (org-table-align))
17491 (message "Time difference inserted")))))
17493 (defun org-make-tdiff-string (y d h m)
17494 (let ((fmt "")
17495 (l nil))
17496 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17497 l (push y l)))
17498 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17499 l (push d l)))
17500 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17501 l (push h l)))
17502 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17503 l (push m l)))
17504 (apply 'format fmt (nreverse l))))
17506 (defun org-time-string-to-time (s &optional buffer pos)
17507 "Convert a timestamp string into internal time."
17508 (condition-case errdata
17509 (apply 'encode-time (org-parse-time-string s))
17510 (error (error "Bad timestamp `%s'%s\nError was: %s"
17511 s (if (not (and buffer pos))
17513 (format " at %d in buffer `%s'" pos buffer))
17514 (cdr errdata)))))
17516 (defun org-time-string-to-seconds (s)
17517 "Convert a timestamp string to a number of seconds."
17518 (org-float-time (org-time-string-to-time s)))
17520 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17521 "Convert a time stamp to an absolute day number.
17522 If there is a specifier for a cyclic time stamp, get the closest
17523 date to DAYNR.
17524 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17525 The variable `date' is bound by the calendar when this is called."
17526 (cond
17527 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17528 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17529 daynr
17530 (+ daynr 1000)))
17531 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17532 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17533 (time-to-days (current-time))) (match-string 0 s)
17534 prefer show-all))
17535 (t (time-to-days
17536 (condition-case errdata
17537 (apply 'encode-time (org-parse-time-string s))
17538 (error (error "Bad timestamp `%s'%s\nError was: %s"
17539 s (if (not (and buffer pos))
17541 (format " at %d in buffer `%s'" pos buffer))
17542 (cdr errdata))))))))
17544 (defun org-days-to-iso-week (days)
17545 "Return the iso week number."
17546 (require 'cal-iso)
17547 (car (calendar-iso-from-absolute days)))
17549 (defun org-small-year-to-year (year)
17550 "Convert 2-digit years into 4-digit years.
17551 YEAR is expanded into one of the 30 next years, if possible, or
17552 into a past one. Any year larger than 99 is returned unchanged."
17553 (if (>= year 100) year
17554 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17555 (century (/ current 100))
17556 (offset (- year (% current 100))))
17557 (cond ((> offset 30) (+ (* (1- century) 100) year))
17558 ((> offset -70) (+ (* century 100) year))
17559 (t (+ (* (1+ century) 100) year))))))
17561 (defun org-time-from-absolute (d)
17562 "Return the time corresponding to date D.
17563 D may be an absolute day number, or a calendar-type list (month day year)."
17564 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17565 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17567 (defun org-calendar-holiday ()
17568 "List of holidays, for Diary display in Org-mode."
17569 (require 'holidays)
17570 (let ((hl (funcall
17571 (if (fboundp 'calendar-check-holidays)
17572 'calendar-check-holidays 'check-calendar-holidays) date)))
17573 (if hl (mapconcat 'identity hl "; "))))
17575 (defun org-diary-sexp-entry (sexp entry date)
17576 "Process a SEXP diary ENTRY for DATE."
17577 (require 'diary-lib)
17578 (let ((result (if calendar-debug-sexp
17579 (let ((stack-trace-on-error t))
17580 (eval (car (read-from-string sexp))))
17581 (condition-case nil
17582 (eval (car (read-from-string sexp)))
17583 (error
17584 (beep)
17585 (message "Bad sexp at line %d in %s: %s"
17586 (org-current-line)
17587 (buffer-file-name) sexp)
17588 (sleep-for 2))))))
17589 (cond ((stringp result) (split-string result "; "))
17590 ((and (consp result)
17591 (not (consp (cdr result)))
17592 (stringp (cdr result))) (cdr result))
17593 ((and (consp result)
17594 (stringp (car result))) result)
17595 (result entry))))
17597 (defun org-diary-to-ical-string (frombuf)
17598 "Get iCalendar entries from diary entries in buffer FROMBUF.
17599 This uses the icalendar.el library."
17600 (let* ((tmpdir (if (featurep 'xemacs)
17601 (temp-directory)
17602 temporary-file-directory))
17603 (tmpfile (make-temp-name
17604 (expand-file-name "orgics" tmpdir)))
17605 buf rtn b e)
17606 (with-current-buffer frombuf
17607 (icalendar-export-region (point-min) (point-max) tmpfile)
17608 (setq buf (find-buffer-visiting tmpfile))
17609 (set-buffer buf)
17610 (goto-char (point-min))
17611 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17612 (setq b (match-beginning 0)))
17613 (goto-char (point-max))
17614 (if (re-search-backward "^END:VEVENT" nil t)
17615 (setq e (match-end 0)))
17616 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17617 (kill-buffer buf)
17618 (delete-file tmpfile)
17619 rtn))
17621 (defun org-closest-date (start current change prefer show-all)
17622 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17623 When PREFER is `past', return a date that is either CURRENT or past.
17624 When PREFER is `future', return a date that is either CURRENT or future.
17625 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17626 ;; Make the proper lists from the dates
17627 (catch 'exit
17628 (let ((a1 '(("h" . hour)
17629 ("d" . day)
17630 ("w" . week)
17631 ("m" . month)
17632 ("y" . year)))
17633 (shour (nth 2 (org-parse-time-string start)))
17634 dn dw sday cday n1 n2 n0
17635 d m y y1 y2 date1 date2 nmonths nm ny m2)
17637 (setq start (org-date-to-gregorian start)
17638 current (org-date-to-gregorian
17639 (if show-all
17640 current
17641 (time-to-days (current-time))))
17642 sday (calendar-absolute-from-gregorian start)
17643 cday (calendar-absolute-from-gregorian current))
17645 (if (<= cday sday) (throw 'exit sday))
17647 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17648 (setq dn (string-to-number (match-string 1 change))
17649 dw (cdr (assoc (match-string 2 change) a1)))
17650 (user-error "Invalid change specifier: %s" change))
17651 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17652 (cond
17653 ((eq dw 'hour)
17654 (let ((missing-hours
17655 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17656 dn)))
17657 (setq n1 (if (zerop missing-hours) cday
17658 (- cday (1+ (floor (/ missing-hours 24)))))
17659 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17660 ((eq dw 'day)
17661 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17662 n2 (+ n1 dn)))
17663 ((eq dw 'year)
17664 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17665 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17666 (setq date1 (list m d y1)
17667 n1 (calendar-absolute-from-gregorian date1)
17668 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17669 n2 (calendar-absolute-from-gregorian date2)))
17670 ((eq dw 'month)
17671 ;; approx number of month between the two dates
17672 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17673 ;; How often does dn fit in there?
17674 (setq d (nth 1 start) m (car start) y (nth 2 start)
17675 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17676 m (+ m nm)
17677 ny (floor (/ m 12))
17678 y (+ y ny)
17679 m (- m (* ny 12)))
17680 (while (> m 12) (setq m (- m 12) y (1+ y)))
17681 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17682 (setq m2 (+ m dn) y2 y)
17683 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17684 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17685 (while (<= n2 cday)
17686 (setq n1 n2 m m2 y y2)
17687 (setq m2 (+ m dn) y2 y)
17688 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17689 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17690 ;; Make sure n1 is the earlier date
17691 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17692 (if show-all
17693 (cond
17694 ((eq prefer 'past) (if (= cday n2) n2 n1))
17695 ((eq prefer 'future) (if (= cday n1) n1 n2))
17696 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17697 (cond
17698 ((eq prefer 'past) (if (= cday n2) n2 n1))
17699 ((eq prefer 'future) (if (= cday n1) n1 n2))
17700 (t (if (= cday n1) n1 n2)))))))
17702 (defun org-date-to-gregorian (date)
17703 "Turn any specification of DATE into a Gregorian date for the calendar."
17704 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17705 ((and (listp date) (= (length date) 3)) date)
17706 ((stringp date)
17707 (setq date (org-parse-time-string date))
17708 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17709 ((listp date)
17710 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17712 (defun org-parse-time-string (s &optional nodefault)
17713 "Parse the standard Org-mode time string.
17714 This should be a lot faster than the normal `parse-time-string'.
17715 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17716 hour and minute fields will be nil if not given."
17717 (cond ((string-match org-ts-regexp0 s)
17718 (list 0
17719 (if (or (match-beginning 8) (not nodefault))
17720 (string-to-number (or (match-string 8 s) "0")))
17721 (if (or (match-beginning 7) (not nodefault))
17722 (string-to-number (or (match-string 7 s) "0")))
17723 (string-to-number (match-string 4 s))
17724 (string-to-number (match-string 3 s))
17725 (string-to-number (match-string 2 s))
17726 nil nil nil))
17727 ((string-match "^<[^>]+>$" s)
17728 (decode-time (seconds-to-time (org-matcher-time s))))
17729 (t (error "Not a standard Org-mode time string: %s" s))))
17731 (defun org-timestamp-up (&optional arg)
17732 "Increase the date item at the cursor by one.
17733 If the cursor is on the year, change the year. If it is on the month,
17734 the day or the time, change that.
17735 With prefix ARG, change by that many units."
17736 (interactive "p")
17737 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17739 (defun org-timestamp-down (&optional arg)
17740 "Decrease the date item at the cursor by one.
17741 If the cursor is on the year, change the year. If it is on the month,
17742 the day or the time, change that.
17743 With prefix ARG, change by that many units."
17744 (interactive "p")
17745 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17747 (defun org-timestamp-up-day (&optional arg)
17748 "Increase the date in the time stamp by one day.
17749 With prefix ARG, change that many days."
17750 (interactive "p")
17751 (if (and (not (org-at-timestamp-p t))
17752 (org-at-heading-p))
17753 (org-todo 'up)
17754 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17756 (defun org-timestamp-down-day (&optional arg)
17757 "Decrease the date in the time stamp by one day.
17758 With prefix ARG, change that many days."
17759 (interactive "p")
17760 (if (and (not (org-at-timestamp-p t))
17761 (org-at-heading-p))
17762 (org-todo 'down)
17763 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17765 (defun org-at-timestamp-p (&optional inactive-ok)
17766 "Determine if the cursor is in or at a timestamp."
17767 (interactive)
17768 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17769 (pos (point))
17770 (ans (or (looking-at tsr)
17771 (save-excursion
17772 (skip-chars-backward "^[<\n\r\t")
17773 (if (> (point) (point-min)) (backward-char 1))
17774 (and (looking-at tsr)
17775 (> (- (match-end 0) pos) -1))))))
17776 (and ans
17777 (boundp 'org-ts-what)
17778 (setq org-ts-what
17779 (cond
17780 ((= pos (match-beginning 0)) 'bracket)
17781 ;; Point is considered to be "on the bracket" whether
17782 ;; it's really on it or right after it.
17783 ((= pos (1- (match-end 0))) 'bracket)
17784 ((= pos (match-end 0)) 'after)
17785 ((org-pos-in-match-range pos 2) 'year)
17786 ((org-pos-in-match-range pos 3) 'month)
17787 ((org-pos-in-match-range pos 7) 'hour)
17788 ((org-pos-in-match-range pos 8) 'minute)
17789 ((or (org-pos-in-match-range pos 4)
17790 (org-pos-in-match-range pos 5)) 'day)
17791 ((and (> pos (or (match-end 8) (match-end 5)))
17792 (< pos (match-end 0)))
17793 (- pos (or (match-end 8) (match-end 5))))
17794 (t 'day))))
17795 ans))
17797 (defun org-toggle-timestamp-type ()
17798 "Toggle the type (<active> or [inactive]) of a time stamp."
17799 (interactive)
17800 (when (org-at-timestamp-p t)
17801 (let ((beg (match-beginning 0)) (end (match-end 0))
17802 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17803 (save-excursion
17804 (goto-char beg)
17805 (while (re-search-forward "[][<>]" end t)
17806 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17807 t t)))
17808 (message "Timestamp is now %sactive"
17809 (if (equal (char-after beg) ?<) "" "in")))))
17811 (defun org-at-clock-log-p nil
17812 "Is the cursor on the clock log line?"
17813 (save-excursion
17814 (move-beginning-of-line 1)
17815 (looking-at org-clock-line-re)))
17817 (defvar org-clock-history) ; defined in org-clock.el
17818 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17819 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17820 "Change the date in the time stamp at point.
17821 The date will be changed by N times WHAT. WHAT can be `day', `month',
17822 `year', `minute', `second'. If WHAT is not given, the cursor position
17823 in the timestamp determines what will be changed.
17824 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17825 (let ((origin (point)) origin-cat
17826 with-hm inactive
17827 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17828 org-ts-what
17829 extra rem
17830 ts time time0 fixnext clrgx)
17831 (if (not (org-at-timestamp-p t))
17832 (user-error "Not at a timestamp"))
17833 (if (and (not what) (eq org-ts-what 'bracket))
17834 (org-toggle-timestamp-type)
17835 ;; Point isn't on brackets. Remember the part of the time-stamp
17836 ;; the point was in. Indeed, size of time-stamps may change,
17837 ;; but point must be kept in the same category nonetheless.
17838 (setq origin-cat org-ts-what)
17839 (if (and (not what) (not (eq org-ts-what 'day))
17840 org-display-custom-times
17841 (get-text-property (point) 'display)
17842 (not (get-text-property (1- (point)) 'display)))
17843 (setq org-ts-what 'day))
17844 (setq org-ts-what (or what org-ts-what)
17845 inactive (= (char-after (match-beginning 0)) ?\[)
17846 ts (match-string 0))
17847 (replace-match "")
17848 (when (string-match
17849 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17851 (setq extra (match-string 1 ts))
17852 (if suppress-tmp-delay
17853 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17854 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17855 (setq with-hm t))
17856 (setq time0 (org-parse-time-string ts))
17857 (when (and updown
17858 (eq org-ts-what 'minute)
17859 (not current-prefix-arg))
17860 ;; This looks like s-up and s-down. Change by one rounding step.
17861 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17862 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17863 (setcar (cdr time0) (+ (nth 1 time0)
17864 (if (> n 0) (- rem) (- dm rem))))))
17865 (setq time
17866 (encode-time (or (car time0) 0)
17867 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17868 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17869 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17870 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17871 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17872 (nthcdr 6 time0)))
17873 (when (and (member org-ts-what '(hour minute))
17874 extra
17875 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17876 (setq extra (org-modify-ts-extra
17877 extra
17878 (if (eq org-ts-what 'hour) 2 5)
17879 n dm)))
17880 (when (integerp org-ts-what)
17881 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17882 (if (eq what 'calendar)
17883 (let ((cal-date (org-get-date-from-calendar)))
17884 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17885 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17886 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17887 (setcar time0 (or (car time0) 0))
17888 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17889 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17890 (setq time (apply 'encode-time time0))))
17891 ;; Insert the new time-stamp, and ensure point stays in the same
17892 ;; category as before (i.e. not after the last position in that
17893 ;; category).
17894 (let ((pos (point)))
17895 ;; Stay before inserted string. `save-excursion' is of no use.
17896 (setq org-last-changed-timestamp
17897 (org-insert-time-stamp time with-hm inactive nil nil extra))
17898 (goto-char pos))
17899 (save-match-data
17900 (looking-at org-ts-regexp3)
17901 (goto-char (cond
17902 ;; `day' category ends before `hour' if any, or at
17903 ;; the end of the day name.
17904 ((eq origin-cat 'day)
17905 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17906 ((eq origin-cat 'hour) (min (match-end 7) origin))
17907 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17908 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17909 ;; `year' and `month' have both fixed size: point
17910 ;; couldn't have moved into another part.
17911 (t origin))))
17912 ;; Update clock if on a CLOCK line.
17913 (org-clock-update-time-maybe)
17914 ;; Maybe adjust the closest clock in `org-clock-history'
17915 (when org-clock-adjust-closest
17916 (if (not (and (org-at-clock-log-p)
17917 (< 1 (length (delq nil (mapcar 'marker-position
17918 org-clock-history))))))
17919 (message "No clock to adjust")
17920 (cond ((save-excursion ; fix previous clock?
17921 (re-search-backward org-ts-regexp0 nil t)
17922 (org-looking-back (concat org-clock-string " \\[")))
17923 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17924 ((save-excursion ; fix next clock?
17925 (re-search-backward org-ts-regexp0 nil t)
17926 (looking-at (concat org-ts-regexp0 "\\] =>")))
17927 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17928 (save-window-excursion
17929 ;; Find closest clock to point, adjust the previous/next one in history
17930 (let* ((p (save-excursion (org-back-to-heading t)))
17931 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17932 (clfixnth
17933 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17934 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17935 (if (not clfixpos)
17936 (message "No clock to adjust")
17937 (save-excursion
17938 (org-goto-marker-or-bmk clfixpos)
17939 (org-show-subtree)
17940 (when (re-search-forward clrgx nil t)
17941 (goto-char (match-beginning 1))
17942 (let (org-clock-adjust-closest)
17943 (org-timestamp-change n org-ts-what updown))
17944 (message "Clock adjusted in %s for heading: %s"
17945 (file-name-nondirectory (buffer-file-name))
17946 (org-get-heading t t)))))))))
17947 ;; Try to recenter the calendar window, if any.
17948 (if (and org-calendar-follow-timestamp-change
17949 (get-buffer-window "*Calendar*" t)
17950 (memq org-ts-what '(day month year)))
17951 (org-recenter-calendar (time-to-days time))))))
17953 (defun org-modify-ts-extra (s pos n dm)
17954 "Change the different parts of the lead-time and repeat fields in timestamp."
17955 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17956 ng h m new rem)
17957 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17958 (cond
17959 ((or (org-pos-in-match-range pos 2)
17960 (org-pos-in-match-range pos 3))
17961 (setq m (string-to-number (match-string 3 s))
17962 h (string-to-number (match-string 2 s)))
17963 (if (org-pos-in-match-range pos 2)
17964 (setq h (+ h n))
17965 (setq n (* dm (org-no-warnings (signum n))))
17966 (when (not (= 0 (setq rem (% m dm))))
17967 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17968 (setq m (+ m n)))
17969 (if (< m 0) (setq m (+ m 60) h (1- h)))
17970 (if (> m 59) (setq m (- m 60) h (1+ h)))
17971 (setq h (min 24 (max 0 h)))
17972 (setq ng 1 new (format "-%02d:%02d" h m)))
17973 ((org-pos-in-match-range pos 6)
17974 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17975 ((org-pos-in-match-range pos 5)
17976 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17978 ((org-pos-in-match-range pos 9)
17979 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17980 ((org-pos-in-match-range pos 8)
17981 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17983 (when ng
17984 (setq s (concat
17985 (substring s 0 (match-beginning ng))
17987 (substring s (match-end ng))))))
17990 (defun org-recenter-calendar (date)
17991 "If the calendar is visible, recenter it to DATE."
17992 (let ((cwin (get-buffer-window "*Calendar*" t)))
17993 (when cwin
17994 (let ((calendar-move-hook nil))
17995 (with-selected-window cwin
17996 (calendar-goto-date (if (listp date) date
17997 (calendar-gregorian-from-absolute date))))))))
17999 (defun org-goto-calendar (&optional arg)
18000 "Go to the Emacs calendar at the current date.
18001 If there is a time stamp in the current line, go to that date.
18002 A prefix ARG can be used to force the current date."
18003 (interactive "P")
18004 (let ((tsr org-ts-regexp) diff
18005 (calendar-move-hook nil)
18006 (calendar-view-holidays-initially-flag nil)
18007 (calendar-view-diary-initially-flag nil))
18008 (if (or (org-at-timestamp-p)
18009 (save-excursion
18010 (beginning-of-line 1)
18011 (looking-at (concat ".*" tsr))))
18012 (let ((d1 (time-to-days (current-time)))
18013 (d2 (time-to-days
18014 (org-time-string-to-time (match-string 1)))))
18015 (setq diff (- d2 d1))))
18016 (calendar)
18017 (calendar-goto-today)
18018 (if (and diff (not arg)) (calendar-forward-day diff))))
18020 (defun org-get-date-from-calendar ()
18021 "Return a list (month day year) of date at point in calendar."
18022 (with-current-buffer "*Calendar*"
18023 (save-match-data
18024 (calendar-cursor-to-date))))
18026 (defun org-date-from-calendar ()
18027 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18028 If there is already a time stamp at the cursor position, update it."
18029 (interactive)
18030 (if (org-at-timestamp-p t)
18031 (org-timestamp-change 0 'calendar)
18032 (let ((cal-date (org-get-date-from-calendar)))
18033 (org-insert-time-stamp
18034 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18036 (defcustom org-effort-durations
18037 `(("min" . 1)
18038 ("h" . 60)
18039 ("d" . ,(* 60 8))
18040 ("w" . ,(* 60 8 5))
18041 ("m" . ,(* 60 8 5 4))
18042 ("y" . ,(* 60 8 5 40)))
18043 "Conversion factor to minutes for an effort modifier.
18045 Each entry has the form (MODIFIER . MINUTES).
18047 In an effort string, a number followed by MODIFIER is multiplied
18048 by the specified number of MINUTES to obtain an effort in
18049 minutes.
18051 For example, if the value of this variable is ((\"hours\" . 60)), then an
18052 effort string \"2hours\" is equivalent to 120 minutes."
18053 :group 'org-agenda
18054 :version "25.1"
18055 :package-version '(Org . "8.3")
18056 :type '(alist :key-type (string :tag "Modifier")
18057 :value-type (number :tag "Minutes")))
18059 (defun org-minutes-to-clocksum-string (m)
18060 "Format number of minutes as a clocksum string.
18061 The format is determined by `org-time-clocksum-format',
18062 `org-time-clocksum-use-fractional' and
18063 `org-time-clocksum-fractional-format' and
18064 `org-time-clocksum-use-effort-durations'."
18065 (let ((clocksum "")
18066 (m (round m)) ; Don't allow fractions of minutes
18067 h d w mo y fmt n)
18068 (setq h (if org-time-clocksum-use-effort-durations
18069 (cdr (assoc "h" org-effort-durations)) 60)
18070 d (if org-time-clocksum-use-effort-durations
18071 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18072 w (if org-time-clocksum-use-effort-durations
18073 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18074 mo (if org-time-clocksum-use-effort-durations
18075 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18076 y (if org-time-clocksum-use-effort-durations
18077 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18078 ;; fractional format
18079 (if org-time-clocksum-use-fractional
18080 (cond
18081 ;; single format string
18082 ((stringp org-time-clocksum-fractional-format)
18083 (format org-time-clocksum-fractional-format (/ m (float h))))
18084 ;; choice of fractional formats for different time units
18085 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18086 (> (/ (truncate m) (* y d h)) 0))
18087 (format fmt (/ m (* y d (float h)))))
18088 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18089 (> (/ (truncate m) (* mo d h)) 0))
18090 (format fmt (/ m (* mo d (float h)))))
18091 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18092 (> (/ (truncate m) (* w d h)) 0))
18093 (format fmt (/ m (* w d (float h)))))
18094 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18095 (> (/ (truncate m) (* d h)) 0))
18096 (format fmt (/ m (* d (float h)))))
18097 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18098 (> (/ (truncate m) h) 0))
18099 (format fmt (/ m (float h))))
18100 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18101 (format fmt m))
18102 ;; fall back to smallest time unit with a format
18103 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18104 (format fmt (/ m (float h))))
18105 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18106 (format fmt (/ m (* d (float h)))))
18107 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18108 (format fmt (/ m (* w d (float h)))))
18109 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18110 (format fmt (/ m (* mo d (float h)))))
18111 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18112 (format fmt (/ m (* y d (float h))))))
18113 ;; standard (non-fractional) format, with single format string
18114 (if (stringp org-time-clocksum-format)
18115 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18116 ;; separate formats components
18117 (and (setq fmt (plist-get org-time-clocksum-format :years))
18118 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18119 (plist-get org-time-clocksum-format :require-years))
18120 (setq clocksum (concat clocksum (format fmt n))
18121 m (- m (* n y d h))))
18122 (and (setq fmt (plist-get org-time-clocksum-format :months))
18123 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18124 (plist-get org-time-clocksum-format :require-months))
18125 (setq clocksum (concat clocksum (format fmt n))
18126 m (- m (* n mo d h))))
18127 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18128 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18129 (plist-get org-time-clocksum-format :require-weeks))
18130 (setq clocksum (concat clocksum (format fmt n))
18131 m (- m (* n w d h))))
18132 (and (setq fmt (plist-get org-time-clocksum-format :days))
18133 (or (> (setq n (/ (truncate m) (* d h))) 0)
18134 (plist-get org-time-clocksum-format :require-days))
18135 (setq clocksum (concat clocksum (format fmt n))
18136 m (- m (* n d h))))
18137 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18138 (or (> (setq n (/ (truncate m) h)) 0)
18139 (plist-get org-time-clocksum-format :require-hours))
18140 (setq clocksum (concat clocksum (format fmt n))
18141 m (- m (* n h))))
18142 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18143 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18144 (setq clocksum (concat clocksum (format fmt m))))
18145 ;; return formatted time duration
18146 clocksum))))
18148 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18149 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18150 "Org mode version 8.0")
18152 (defun org-hours-to-clocksum-string (n)
18153 (org-minutes-to-clocksum-string (* n 60)))
18155 (defun org-hh:mm-string-to-minutes (s)
18156 "Convert a string H:MM to a number of minutes.
18157 If the string is just a number, interpret it as minutes.
18158 In fact, the first hh:mm or number in the string will be taken,
18159 there can be extra stuff in the string.
18160 If no number is found, the return value is 0."
18161 (cond
18162 ((integerp s) s)
18163 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18164 (+ (* (string-to-number (match-string 1 s)) 60)
18165 (string-to-number (match-string 2 s))))
18166 ((string-match "\\([0-9]+\\)" s)
18167 (string-to-number (match-string 1 s)))
18168 (t 0)))
18170 (defcustom org-image-actual-width t
18171 "Should we use the actual width of images when inlining them?
18173 When set to `t', always use the image width.
18175 When set to a number, use imagemagick (when available) to set
18176 the image's width to this value.
18178 When set to a number in a list, try to get the width from any
18179 #+ATTR.* keyword if it matches a width specification like
18181 #+ATTR_HTML: :width 300px
18183 and fall back on that number if none is found.
18185 When set to nil, try to get the width from an #+ATTR.* keyword
18186 and fall back on the original width if none is found.
18188 This requires Emacs >= 24.1, build with imagemagick support."
18189 :group 'org-appearance
18190 :version "24.4"
18191 :package-version '(Org . "8.0")
18192 :type '(choice
18193 (const :tag "Use the image width" t)
18194 (integer :tag "Use a number of pixels")
18195 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18196 (const :tag "Use #+ATTR* or don't resize" nil)))
18198 (defcustom org-agenda-inhibit-startup nil
18199 "Inhibit startup when preparing agenda buffers.
18200 When this variable is `t', the initialization of the Org agenda
18201 buffers is inhibited: e.g. the visibility state is not set, the
18202 tables are not re-aligned, etc."
18203 :type 'boolean
18204 :version "24.3"
18205 :group 'org-agenda)
18207 (define-obsolete-variable-alias
18208 'org-agenda-ignore-drawer-properties
18209 'org-agenda-ignore-properties "25.1")
18211 (defcustom org-agenda-ignore-properties nil
18212 "Avoid updating text properties when building the agenda.
18213 Properties are used to prepare buffers for effort estimates,
18214 appointments, statistics and subtree-local categories.
18215 If you don't use these in the agenda, you can add them to this
18216 list and agenda building will be a bit faster.
18217 The value is a list, with zero or more of the symbols `effort', `appt',
18218 `stats' or `category'."
18219 :type '(set :greedy t
18220 (const effort)
18221 (const appt)
18222 (const stats)
18223 (const category))
18224 :version "25.1"
18225 :package-version '(Org . "8.3")
18226 :group 'org-agenda)
18228 (defun org-duration-string-to-minutes (s &optional output-to-string)
18229 "Convert a duration string S to minutes.
18231 A bare number is interpreted as minutes, modifiers can be set by
18232 customizing `org-effort-durations' (which see).
18234 Entries containing a colon are interpreted as H:MM by
18235 `org-hh:mm-string-to-minutes'."
18236 (let ((result 0)
18237 (re (concat "\\([0-9.]+\\) *\\("
18238 (regexp-opt (mapcar 'car org-effort-durations))
18239 "\\)")))
18240 (while (string-match re s)
18241 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18242 (string-to-number (match-string 1 s))))
18243 (setq s (replace-match "" nil t s)))
18244 (setq result (floor result))
18245 (incf result (org-hh:mm-string-to-minutes s))
18246 (if output-to-string (number-to-string result) result)))
18248 ;;;; Files
18250 (defun org-save-all-org-buffers ()
18251 "Save all Org-mode buffers without user confirmation."
18252 (interactive)
18253 (message "Saving all Org-mode buffers...")
18254 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18255 (when (featurep 'org-id) (org-id-locations-save))
18256 (message "Saving all Org-mode buffers... done"))
18258 (defun org-revert-all-org-buffers ()
18259 "Revert all Org-mode buffers.
18260 Prompt for confirmation when there are unsaved changes.
18261 Be sure you know what you are doing before letting this function
18262 overwrite your changes.
18264 This function is useful in a setup where one tracks org files
18265 with a version control system, to revert on one machine after pulling
18266 changes from another. I believe the procedure must be like this:
18268 1. M-x org-save-all-org-buffers
18269 2. Pull changes from the other machine, resolve conflicts
18270 3. M-x org-revert-all-org-buffers"
18271 (interactive)
18272 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18273 (user-error "Abort"))
18274 (save-excursion
18275 (save-window-excursion
18276 (mapc
18277 (lambda (b)
18278 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18279 (with-current-buffer b buffer-file-name))
18280 (org-pop-to-buffer-same-window b)
18281 (revert-buffer t 'no-confirm)))
18282 (buffer-list))
18283 (when (and (featurep 'org-id) org-id-track-globally)
18284 (org-id-locations-load)))))
18286 ;;;; Agenda files
18288 ;;;###autoload
18289 (defun org-switchb (&optional arg)
18290 "Switch between Org buffers.
18291 With one prefix argument, restrict available buffers to files.
18292 With two prefix arguments, restrict available buffers to agenda files.
18294 Defaults to `iswitchb' for buffer name completion.
18295 Set `org-completion-use-ido' to make it use ido instead."
18296 (interactive "P")
18297 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18298 ((equal arg '(16)) (org-buffer-list 'agenda))
18299 (t (org-buffer-list))))
18300 (org-completion-use-iswitchb org-completion-use-iswitchb)
18301 (org-completion-use-ido org-completion-use-ido))
18302 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18303 (setq org-completion-use-iswitchb t))
18304 (org-pop-to-buffer-same-window
18305 (org-icompleting-read "Org buffer: "
18306 (mapcar 'list (mapcar 'buffer-name blist))
18307 nil t))))
18309 ;;; Define some older names previously used for this functionality
18310 ;;;###autoload
18311 (defalias 'org-ido-switchb 'org-switchb)
18312 ;;;###autoload
18313 (defalias 'org-iswitchb 'org-switchb)
18315 (defun org-buffer-list (&optional predicate exclude-tmp)
18316 "Return a list of Org buffers.
18317 PREDICATE can be `export', `files' or `agenda'.
18319 export restrict the list to Export buffers.
18320 files restrict the list to buffers visiting Org files.
18321 agenda restrict the list to buffers visiting agenda files.
18323 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18324 (let* ((bfn nil)
18325 (agenda-files (and (eq predicate 'agenda)
18326 (mapcar 'file-truename (org-agenda-files t))))
18327 (filter
18328 (cond
18329 ((eq predicate 'files)
18330 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18331 ((eq predicate 'export)
18332 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18333 ((eq predicate 'agenda)
18334 (lambda (b)
18335 (with-current-buffer b
18336 (and (derived-mode-p 'org-mode)
18337 (setq bfn (buffer-file-name b))
18338 (member (file-truename bfn) agenda-files)))))
18339 (t (lambda (b) (with-current-buffer b
18340 (or (derived-mode-p 'org-mode)
18341 (string-match "\*Org .*Export"
18342 (buffer-name b)))))))))
18343 (delq nil
18344 (mapcar
18345 (lambda(b)
18346 (if (and (funcall filter b)
18347 (or (not exclude-tmp)
18348 (not (string-match "tmp" (buffer-name b)))))
18350 nil))
18351 (buffer-list)))))
18353 (defun org-agenda-files (&optional unrestricted archives)
18354 "Get the list of agenda files.
18355 Optional UNRESTRICTED means return the full list even if a restriction
18356 is currently in place.
18357 When ARCHIVES is t, include all archive files that are really being
18358 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18359 `org-agenda-archives-mode' is t."
18360 (let ((files
18361 (cond
18362 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18363 ((stringp org-agenda-files) (org-read-agenda-file-list))
18364 ((listp org-agenda-files) org-agenda-files)
18365 (t (error "Invalid value of `org-agenda-files'")))))
18366 (setq files (apply 'append
18367 (mapcar (lambda (f)
18368 (if (file-directory-p f)
18369 (directory-files
18370 f t org-agenda-file-regexp)
18371 (list f)))
18372 files)))
18373 (when org-agenda-skip-unavailable-files
18374 (setq files (delq nil
18375 (mapcar (function
18376 (lambda (file)
18377 (and (file-readable-p file) file)))
18378 files))))
18379 (when (or (eq archives t)
18380 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18381 (setq files (org-add-archive-files files)))
18382 files))
18384 (defun org-agenda-file-p (&optional file)
18385 "Return non-nil, if FILE is an agenda file.
18386 If FILE is omitted, use the file associated with the current
18387 buffer."
18388 (let ((fname (or file (buffer-file-name))))
18389 (and fname
18390 (member (file-truename fname)
18391 (mapcar #'file-truename (org-agenda-files t))))))
18393 (defun org-edit-agenda-file-list ()
18394 "Edit the list of agenda files.
18395 Depending on setup, this either uses customize to edit the variable
18396 `org-agenda-files', or it visits the file that is holding the list. In the
18397 latter case, the buffer is set up in a way that saving it automatically kills
18398 the buffer and restores the previous window configuration."
18399 (interactive)
18400 (if (stringp org-agenda-files)
18401 (let ((cw (current-window-configuration)))
18402 (find-file org-agenda-files)
18403 (org-set-local 'org-window-configuration cw)
18404 (org-add-hook 'after-save-hook
18405 (lambda ()
18406 (set-window-configuration
18407 (prog1 org-window-configuration
18408 (kill-buffer (current-buffer))))
18409 (org-install-agenda-files-menu)
18410 (message "New agenda file list installed"))
18411 nil 'local)
18412 (message "%s" (substitute-command-keys
18413 "Edit list and finish with \\[save-buffer]")))
18414 (customize-variable 'org-agenda-files)))
18416 (defun org-store-new-agenda-file-list (list)
18417 "Set new value for the agenda file list and save it correctly."
18418 (if (stringp org-agenda-files)
18419 (let ((fe (org-read-agenda-file-list t)) b u)
18420 (while (setq b (find-buffer-visiting org-agenda-files))
18421 (kill-buffer b))
18422 (with-temp-file org-agenda-files
18423 (insert
18424 (mapconcat
18425 (lambda (f) ;; Keep un-expanded entries.
18426 (if (setq u (assoc f fe))
18427 (cdr u)
18429 list "\n")
18430 "\n")))
18431 (let ((org-mode-hook nil) (org-inhibit-startup t)
18432 (org-insert-mode-line-in-empty-file nil))
18433 (setq org-agenda-files list)
18434 (customize-save-variable 'org-agenda-files org-agenda-files))))
18436 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18437 "Read the list of agenda files from a file.
18438 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18439 filenames, used by `org-store-new-agenda-file-list' to write back
18440 un-expanded file names."
18441 (when (file-directory-p org-agenda-files)
18442 (error "`org-agenda-files' cannot be a single directory"))
18443 (when (stringp org-agenda-files)
18444 (with-temp-buffer
18445 (insert-file-contents org-agenda-files)
18446 (mapcar
18447 (lambda (f)
18448 (let ((e (expand-file-name (substitute-in-file-name f)
18449 org-directory)))
18450 (if pair-with-expansion
18451 (cons e f)
18452 e)))
18453 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18455 ;;;###autoload
18456 (defun org-cycle-agenda-files ()
18457 "Cycle through the files in `org-agenda-files'.
18458 If the current buffer visits an agenda file, find the next one in the list.
18459 If the current buffer does not, find the first agenda file."
18460 (interactive)
18461 (let* ((fs (org-agenda-files t))
18462 (files (append fs (list (car fs))))
18463 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18464 file)
18465 (unless files (user-error "No agenda files"))
18466 (catch 'exit
18467 (while (setq file (pop files))
18468 (if (equal (file-truename file) tcf)
18469 (when (car files)
18470 (find-file (car files))
18471 (throw 'exit t))))
18472 (find-file (car fs)))
18473 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18475 (defun org-agenda-file-to-front (&optional to-end)
18476 "Move/add the current file to the top of the agenda file list.
18477 If the file is not present in the list, it is added to the front. If it is
18478 present, it is moved there. With optional argument TO-END, add/move to the
18479 end of the list."
18480 (interactive "P")
18481 (let ((org-agenda-skip-unavailable-files nil)
18482 (file-alist (mapcar (lambda (x)
18483 (cons (file-truename x) x))
18484 (org-agenda-files t)))
18485 (ctf (file-truename
18486 (or buffer-file-name
18487 (user-error "Please save the current buffer to a file"))))
18488 x had)
18489 (setq x (assoc ctf file-alist) had x)
18491 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18492 (if to-end
18493 (setq file-alist (append (delq x file-alist) (list x)))
18494 (setq file-alist (cons x (delq x file-alist))))
18495 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18496 (org-install-agenda-files-menu)
18497 (message "File %s to %s of agenda file list"
18498 (if had "moved" "added") (if to-end "end" "front"))))
18500 (defun org-remove-file (&optional file)
18501 "Remove current file from the list of files in variable `org-agenda-files'.
18502 These are the files which are being checked for agenda entries.
18503 Optional argument FILE means use this file instead of the current."
18504 (interactive)
18505 (let* ((org-agenda-skip-unavailable-files nil)
18506 (file (or file buffer-file-name
18507 (user-error "Current buffer does not visit a file")))
18508 (true-file (file-truename file))
18509 (afile (abbreviate-file-name file))
18510 (files (delq nil (mapcar
18511 (lambda (x)
18512 (if (equal true-file
18513 (file-truename x))
18514 nil x))
18515 (org-agenda-files t)))))
18516 (if (not (= (length files) (length (org-agenda-files t))))
18517 (progn
18518 (org-store-new-agenda-file-list files)
18519 (org-install-agenda-files-menu)
18520 (message "Removed from Org Agenda list: %s" afile))
18521 (message "File was not in list: %s (not removed)" afile))))
18523 (defun org-file-menu-entry (file)
18524 (vector file (list 'find-file file) t))
18526 (defun org-check-agenda-file (file)
18527 "Make sure FILE exists. If not, ask user what to do."
18528 (when (not (file-exists-p file))
18529 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18530 (abbreviate-file-name file))
18531 (let ((r (downcase (read-char-exclusive))))
18532 (cond
18533 ((equal r ?r)
18534 (org-remove-file file)
18535 (throw 'nextfile t))
18536 (t (user-error "Abort"))))))
18538 (defun org-get-agenda-file-buffer (file)
18539 "Get an agenda buffer visiting FILE.
18540 If the buffer needs to be created, add it to the list of buffers
18541 which might be released later."
18542 (let ((buf (org-find-base-buffer-visiting file)))
18543 (if buf
18544 buf ; just return it
18545 ;; Make a new buffer and remember it
18546 (setq buf (find-file-noselect file))
18547 (if buf (push buf org-agenda-new-buffers))
18548 buf)))
18550 (defun org-release-buffers (blist)
18551 "Release all buffers in list, asking the user for confirmation when needed.
18552 When a buffer is unmodified, it is just killed. When modified, it is saved
18553 \(if the user agrees) and then killed."
18554 (let (buf file)
18555 (while (setq buf (pop blist))
18556 (setq file (buffer-file-name buf))
18557 (when (and (buffer-modified-p buf)
18558 file
18559 (y-or-n-p (format "Save file %s? " file)))
18560 (with-current-buffer buf (save-buffer)))
18561 (kill-buffer buf))))
18563 (defun org-agenda-prepare-buffers (files)
18564 "Create buffers for all agenda files, protect archived trees and comments."
18565 (interactive)
18566 (let ((pa '(:org-archived t))
18567 (pc '(:org-comment t))
18568 (pall '(:org-archived t :org-comment t))
18569 (inhibit-read-only t)
18570 (org-inhibit-startup org-agenda-inhibit-startup)
18571 (rea (concat ":" org-archive-tag ":"))
18572 file re pos)
18573 (setq org-tag-alist-for-agenda nil
18574 org-tag-groups-alist-for-agenda nil)
18575 (save-excursion
18576 (save-restriction
18577 (while (setq file (pop files))
18578 (catch 'nextfile
18579 (if (bufferp file)
18580 (set-buffer file)
18581 (org-check-agenda-file file)
18582 (set-buffer (org-get-agenda-file-buffer file)))
18583 (widen)
18584 (org-set-regexps-and-options 'tags-only)
18585 (setq pos (point))
18586 (or (memq 'category org-agenda-ignore-properties)
18587 (org-refresh-category-properties))
18588 (or (memq 'stats org-agenda-ignore-properties)
18589 (org-refresh-stats-properties))
18590 (or (memq 'effort org-agenda-ignore-properties)
18591 (org-refresh-effort-properties))
18592 (or (memq 'appt org-agenda-ignore-properties)
18593 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18594 (setq org-todo-keywords-for-agenda
18595 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18596 (setq org-done-keywords-for-agenda
18597 (append org-done-keywords-for-agenda org-done-keywords))
18598 (setq org-todo-keyword-alist-for-agenda
18599 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18600 (setq org-tag-alist-for-agenda
18601 (org-uniquify
18602 (append org-tag-alist-for-agenda
18603 org-tag-alist
18604 org-tag-persistent-alist)))
18605 (if org-group-tags
18606 (setq org-tag-groups-alist-for-agenda
18607 (org-uniquify-alist
18608 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18609 (org-with-silent-modifications
18610 (save-excursion
18611 (remove-text-properties (point-min) (point-max) pall)
18612 (when org-agenda-skip-archived-trees
18613 (goto-char (point-min))
18614 (while (re-search-forward rea nil t)
18615 (if (org-at-heading-p t)
18616 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18617 (goto-char (point-min))
18618 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18619 (while (re-search-forward re nil t)
18620 (when (save-match-data (org-in-commented-heading-p t))
18621 (add-text-properties
18622 (match-beginning 0) (org-end-of-subtree t) pc)))))
18623 (goto-char pos)))))
18624 (setq org-todo-keywords-for-agenda
18625 (org-uniquify org-todo-keywords-for-agenda))
18626 (setq org-todo-keyword-alist-for-agenda
18627 (org-uniquify org-todo-keyword-alist-for-agenda))))
18630 ;;;; CDLaTeX minor mode
18632 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18633 "Keymap for the minor `org-cdlatex-mode'.")
18635 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18636 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18637 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18638 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18639 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18641 (defvar org-cdlatex-texmathp-advice-is-done nil
18642 "Flag remembering if we have applied the advice to texmathp already.")
18644 (define-minor-mode org-cdlatex-mode
18645 "Toggle the minor `org-cdlatex-mode'.
18646 This mode supports entering LaTeX environment and math in LaTeX fragments
18647 in Org-mode.
18648 \\{org-cdlatex-mode-map}"
18649 nil " OCDL" nil
18650 (when org-cdlatex-mode
18651 (require 'cdlatex)
18652 (run-hooks 'cdlatex-mode-hook)
18653 (cdlatex-compute-tables))
18654 (unless org-cdlatex-texmathp-advice-is-done
18655 (setq org-cdlatex-texmathp-advice-is-done t)
18656 (defadvice texmathp (around org-math-always-on activate)
18657 "Always return t in org-mode buffers.
18658 This is because we want to insert math symbols without dollars even outside
18659 the LaTeX math segments. If Orgmode thinks that point is actually inside
18660 an embedded LaTeX fragment, let texmathp do its job.
18661 \\[org-cdlatex-mode-map]"
18662 (interactive)
18663 (let (p)
18664 (cond
18665 ((not (derived-mode-p 'org-mode)) ad-do-it)
18666 ((eq this-command 'cdlatex-math-symbol)
18667 (setq ad-return-value t
18668 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18670 (let ((p (org-inside-LaTeX-fragment-p)))
18671 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18672 (setq ad-return-value t
18673 texmathp-why '("Org-mode embedded math" . 0))
18674 (if p ad-do-it)))))))))
18676 (defun turn-on-org-cdlatex ()
18677 "Unconditionally turn on `org-cdlatex-mode'."
18678 (org-cdlatex-mode 1))
18680 (defun org-try-cdlatex-tab ()
18681 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18682 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18683 - inside a LaTeX fragment, or
18684 - after the first word in a line, where an abbreviation expansion could
18685 insert a LaTeX environment."
18686 (when org-cdlatex-mode
18687 (cond
18688 ;; Before any word on the line: No expansion possible.
18689 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18690 ;; Just after first word on the line: Expand it. Make sure it
18691 ;; cannot happen on headlines, though.
18692 ((save-excursion
18693 (skip-chars-backward "a-zA-Z0-9*")
18694 (skip-chars-backward " \t")
18695 (and (bolp) (not (org-at-heading-p))))
18696 (cdlatex-tab) t)
18697 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18699 (defun org-cdlatex-underscore-caret (&optional arg)
18700 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18701 Revert to the normal definition outside of these fragments."
18702 (interactive "P")
18703 (if (org-inside-LaTeX-fragment-p)
18704 (call-interactively 'cdlatex-sub-superscript)
18705 (let (org-cdlatex-mode)
18706 (call-interactively (key-binding (vector last-input-event))))))
18708 (defun org-cdlatex-math-modify (&optional arg)
18709 "Execute `cdlatex-math-modify' in LaTeX fragments.
18710 Revert to the normal definition outside of these fragments."
18711 (interactive "P")
18712 (if (org-inside-LaTeX-fragment-p)
18713 (call-interactively 'cdlatex-math-modify)
18714 (let (org-cdlatex-mode)
18715 (call-interactively (key-binding (vector last-input-event))))))
18717 (defun org-cdlatex-environment-indent (&optional environment item)
18718 "Execute `cdlatex-environment' and indent the inserted environment.
18720 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18722 The inserted environment is indented to current indentation
18723 unless point is at the beginning of the line, in which the
18724 environment remains unintended."
18725 (interactive)
18726 ;; cdlatex-environment always return nil. Therefore, capture output
18727 ;; first and determine if an environment was selected.
18728 (let* ((beg (point-marker))
18729 (end (copy-marker (point) t))
18730 (inserted (progn
18731 (ignore-errors (cdlatex-environment environment item))
18732 (< beg end)))
18733 ;; Figure out how many lines to move forward after the
18734 ;; environment has been inserted.
18735 (lines (when inserted
18736 (save-excursion
18737 (- (loop while (< beg (point))
18738 with x = 0
18739 do (forward-line -1)
18740 (incf x)
18741 finally return x)
18742 (if (progn (goto-char beg)
18743 (and (progn (skip-chars-forward " \t") (eolp))
18744 (progn (skip-chars-backward " \t") (bolp))))
18745 1 0)))))
18746 (env (org-trim (delete-and-extract-region beg end))))
18747 (when inserted
18748 ;; Get indentation of next line unless at column 0.
18749 (let ((ind (if (bolp) 0
18750 (save-excursion
18751 (org-return-indent)
18752 (prog1 (org-get-indentation)
18753 (when (progn (skip-chars-forward " \t") (eolp))
18754 (delete-region beg (point)))))))
18755 (bol (progn (skip-chars-backward " \t") (bolp))))
18756 ;; Insert a newline before environment unless at column zero
18757 ;; to "escape" the current line. Insert a newline if
18758 ;; something is one the same line as \end{ENVIRONMENT}.
18759 (insert
18760 (concat (unless bol "\n") env
18761 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18762 (unless (zerop ind)
18763 (save-excursion
18764 (goto-char beg)
18765 (while (< (point) end)
18766 (unless (eolp) (org-indent-line-to ind))
18767 (forward-line))))
18768 (goto-char beg)
18769 (forward-line lines)
18770 (org-indent-line-to ind)))
18771 (set-marker beg nil)
18772 (set-marker end nil)))
18775 ;;;; LaTeX fragments
18777 (defun org-inside-LaTeX-fragment-p ()
18778 "Test if point is inside a LaTeX fragment.
18779 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18780 sequence appearing also before point.
18781 Even though the matchers for math are configurable, this function assumes
18782 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18783 delimiters are skipped when they have been removed by customization.
18784 The return value is nil, or a cons cell with the delimiter and the
18785 position of this delimiter.
18787 This function does a reasonably good job, but can locally be fooled by
18788 for example currency specifications. For example it will assume being in
18789 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18790 fragments that are properly closed, but during editing, we have to live
18791 with the uncertainty caused by missing closing delimiters. This function
18792 looks only before point, not after."
18793 (catch 'exit
18794 (let ((pos (point))
18795 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18796 (lim (progn
18797 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18798 (point)))
18799 dd-on str (start 0) m re)
18800 (goto-char pos)
18801 (when dodollar
18802 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18803 re (nth 1 (assoc "$" org-latex-regexps)))
18804 (while (string-match re str start)
18805 (cond
18806 ((= (match-end 0) (length str))
18807 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18808 ((= (match-end 0) (- (length str) 5))
18809 (throw 'exit nil))
18810 (t (setq start (match-end 0))))))
18811 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18812 (goto-char pos)
18813 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18814 (and (match-beginning 2) (throw 'exit nil))
18815 ;; count $$
18816 (while (re-search-backward "\\$\\$" lim t)
18817 (setq dd-on (not dd-on)))
18818 (goto-char pos)
18819 (if dd-on (cons "$$" m))))))
18821 (defun org-inside-latex-macro-p ()
18822 "Is point inside a LaTeX macro or its arguments?"
18823 (save-match-data
18824 (org-in-regexp
18825 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18827 (defvar org-latex-fragment-image-overlays nil
18828 "List of overlays carrying the images of latex fragments.")
18829 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18831 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18832 "Remove all overlays with LaTeX fragment images in current buffer.
18833 When optional arguments BEG and END are non-nil, remove all
18834 overlays between them instead. Return t when some overlays were
18835 removed, nil otherwise."
18836 (let (removedp)
18837 (setq org-latex-fragment-image-overlays
18838 (let ((beg (or beg (point-min)))
18839 (end (or end (point-max))))
18840 (org-remove-if
18841 (lambda (o)
18842 (and (>= (overlay-start o) beg)
18843 (<= (overlay-end o) end)
18844 (progn (delete-overlay o)
18845 (or removedp (setq removedp t)))))
18846 org-latex-fragment-image-overlays)))
18847 removedp))
18849 (define-obsolete-function-alias
18850 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18851 (defun org-toggle-latex-fragment (&optional arg)
18852 "Preview the LaTeX fragment at point, or all locally or globally.
18854 If the cursor is on a LaTeX fragment, create the image and overlay
18855 it over the source code, if there is none. Remove it otherwise.
18856 If there is no fragment at point, display all fragments in the
18857 current section.
18859 With prefix ARG, preview or clear image for all fragments in the
18860 current subtree or in the whole buffer when used before the first
18861 headline. With a double prefix ARG \\[universal-argument] \
18862 \\[universal-argument] preview or clear images
18863 for all fragments in the buffer."
18864 (interactive "P")
18865 (unless (buffer-file-name (buffer-base-buffer))
18866 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18867 (when (display-graphic-p)
18868 (catch 'exit
18869 (save-excursion
18870 (let ((window-start (window-start)) msg)
18871 (save-restriction
18872 (cond
18873 ((or (equal arg '(16))
18874 (and (equal arg '(4))
18875 (org-with-limited-levels (org-before-first-heading-p))))
18876 (if (org-remove-latex-fragment-image-overlays)
18877 (progn (message "LaTeX fragments images removed from buffer")
18878 (throw 'exit nil))
18879 (setq msg "Creating images for buffer...")))
18880 ((equal arg '(4))
18881 (org-with-limited-levels (org-back-to-heading t))
18882 (let ((beg (point))
18883 (end (progn (org-end-of-subtree t) (point))))
18884 (if (org-remove-latex-fragment-image-overlays beg end)
18885 (progn
18886 (message "LaTeX fragment images removed from subtree")
18887 (throw 'exit nil))
18888 (setq msg "Creating images for subtree...")
18889 (narrow-to-region beg end))))
18890 ((let ((datum (org-element-context)))
18891 (when (memq (org-element-type datum)
18892 '(latex-environment latex-fragment))
18893 (let* ((beg (org-element-property :begin datum))
18894 (end (org-element-property :end datum)))
18895 (if (org-remove-latex-fragment-image-overlays beg end)
18896 (progn (message "LaTeX fragment image removed")
18897 (throw 'exit nil))
18898 (narrow-to-region beg end)
18899 (setq msg "Creating image..."))))))
18901 (org-with-limited-levels
18902 (let ((beg (if (org-at-heading-p) (line-beginning-position)
18903 (outline-previous-heading)
18904 (point)))
18905 (end (progn (outline-next-heading) (point))))
18906 (if (org-remove-latex-fragment-image-overlays beg end)
18907 (progn
18908 (message "LaTeX fragment images removed from section")
18909 (throw 'exit nil))
18910 (setq msg "Creating images for section...")
18911 (narrow-to-region beg end))))))
18912 (let ((file (buffer-file-name (buffer-base-buffer))))
18913 (org-format-latex
18914 (concat org-latex-preview-ltxpng-directory
18915 (file-name-sans-extension (file-name-nondirectory file)))
18916 ;; Emacs cannot overlay images from remote hosts.
18917 ;; Create it in `temporary-file-directory' instead.
18918 (if (file-remote-p file) temporary-file-directory
18919 default-directory)
18920 'overlays msg 'forbuffer
18921 org-latex-create-formula-image-program)))
18922 ;; Work around a bug that doesn't restore window's start
18923 ;; when widening back the buffer.
18924 (set-window-start nil window-start)
18925 (message (concat msg "done")))))))
18927 (defun org-format-latex
18928 (prefix &optional dir overlays msg forbuffer processing-type)
18929 "Replace LaTeX fragments with links to an image, and produce images.
18931 When optional argument OVERLAYS is non-nil, display the image on
18932 top of the fragment instead of replacing it.
18934 PROCESSING-TYPE is the conversion method to use, as a symbol.
18936 Some of the options can be changed using the variable
18937 `org-format-latex-options', which see."
18938 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18939 (unless (eq processing-type 'verbatim)
18940 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18941 (cnt 0)
18942 checkdir-flag)
18943 (goto-char (point-min))
18944 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18945 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18946 (overlay-recenter (point-max)))
18947 (while (re-search-forward math-regexp nil t)
18948 (unless (and overlays
18949 (eq (get-char-property (point) 'org-overlay-type)
18950 'org-latex-overlay))
18951 (let* ((context (org-element-context))
18952 (type (org-element-type context)))
18953 (when (memq type '(latex-environment latex-fragment))
18954 (let ((block-type (eq type 'latex-environment))
18955 (value (org-element-property :value context))
18956 (beg (org-element-property :begin context))
18957 (end (save-excursion
18958 (goto-char (org-element-property :end context))
18959 (skip-chars-backward " \r\t\n")
18960 (point))))
18961 (case processing-type
18962 (mathjax
18963 ;; Prepare for MathJax processing.
18964 (if (eq (char-after beg) ?$)
18965 (save-excursion
18966 (delete-region beg end)
18967 (insert "\\(" (substring value 1 -1) "\\)"))
18968 (goto-char end)))
18969 ((dvipng imagemagick)
18970 ;; Process to an image.
18971 (incf cnt)
18972 (goto-char beg)
18973 (let* ((face (face-at-point))
18974 ;; Get the colors from the face at point.
18976 (let ((color (plist-get org-format-latex-options
18977 :foreground)))
18978 (if (and forbuffer (eq color 'auto))
18979 (face-attribute face :foreground nil 'default)
18980 color)))
18982 (let ((color (plist-get org-format-latex-options
18983 :background)))
18984 (if (and forbuffer (eq color 'auto))
18985 (face-attribute face :background nil 'default)
18986 color)))
18987 (hash (sha1 (prin1-to-string
18988 (list org-format-latex-header
18989 org-latex-default-packages-alist
18990 org-latex-packages-alist
18991 org-format-latex-options
18992 forbuffer value fg bg))))
18993 (absprefix (expand-file-name prefix dir))
18994 (linkfile (format "%s_%s.png" prefix hash))
18995 (movefile (format "%s_%s.png" absprefix hash))
18996 (sep (and block-type "\n\n"))
18997 (link (concat sep "[[file:" linkfile "]]" sep))
18998 (options
18999 (org-combine-plists
19000 org-format-latex-options
19001 `(:foreground ,fg :background ,bg))))
19002 (when msg (message msg cnt))
19003 (unless checkdir-flag ; Ensure the directory exists.
19004 (setq checkdir-flag t)
19005 (let ((todir (file-name-directory absprefix)))
19006 (unless (file-directory-p todir)
19007 (make-directory todir t))))
19008 (unless (file-exists-p movefile)
19009 (org-create-formula-image
19010 value movefile options forbuffer processing-type))
19011 (if overlays
19012 (progn
19013 (dolist (o (overlays-in beg end))
19014 (when (eq (overlay-get o 'org-overlay-type)
19015 'org-latex-overlay)
19016 (delete-overlay o)))
19017 (let ((ov (make-overlay beg end)))
19018 (overlay-put ov
19019 'org-overlay-type
19020 'org-latex-overlay)
19021 (overlay-put ov 'evaporate t)
19022 (if (featurep 'xemacs)
19023 (progn
19024 (overlay-put ov 'invisible t)
19025 (overlay-put
19026 ov 'end-glyph
19027 (make-glyph
19028 (vector 'png :file movefile))))
19029 (overlay-put
19030 ov 'display
19031 (list 'image
19032 :type 'png
19033 :file movefile
19034 :ascent 'center)))
19035 (push ov org-latex-fragment-image-overlays))
19036 (goto-char end))
19037 (delete-region beg end)
19038 (insert
19039 (org-add-props link
19040 (list 'org-latex-src
19041 (replace-regexp-in-string "\"" "" value)
19042 'org-latex-src-embed-type
19043 (if block-type 'paragraph 'character)))))))
19044 (mathml
19045 ;; Process to MathML.
19046 (unless (org-format-latex-mathml-available-p)
19047 (user-error "LaTeX to MathML converter not configured"))
19048 (incf cnt)
19049 (when msg (message msg cnt))
19050 (goto-char beg)
19051 (delete-region beg end)
19052 (insert (org-format-latex-as-mathml
19053 value block-type prefix dir)))
19054 (otherwise
19055 (error "Unknown conversion type %s for LaTeX fragments"
19056 processing-type)))))))))))
19058 (defun org-create-math-formula (latex-frag &optional mathml-file)
19059 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19060 Use `org-latex-to-mathml-convert-command'. If the conversion is
19061 sucessful, return the portion between \"<math...> </math>\"
19062 elements otherwise return nil. When MATHML-FILE is specified,
19063 write the results in to that file. When invoked as an
19064 interactive command, prompt for LATEX-FRAG, with initial value
19065 set to the current active region and echo the results for user
19066 inspection."
19067 (interactive (list (let ((frag (when (org-region-active-p)
19068 (buffer-substring-no-properties
19069 (region-beginning) (region-end)))))
19070 (read-string "LaTeX Fragment: " frag nil frag))))
19071 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19072 (let* ((tmp-in-file (file-relative-name
19073 (make-temp-name (expand-file-name "ltxmathml-in"))))
19074 (ignore (write-region latex-frag nil tmp-in-file))
19075 (tmp-out-file (file-relative-name
19076 (make-temp-name (expand-file-name "ltxmathml-out"))))
19077 (cmd (format-spec
19078 org-latex-to-mathml-convert-command
19079 `((?j . ,(and org-latex-to-mathml-jar-file
19080 (shell-quote-argument
19081 (expand-file-name
19082 org-latex-to-mathml-jar-file))))
19083 (?I . ,(shell-quote-argument tmp-in-file))
19084 (?i . ,latex-frag)
19085 (?o . ,(shell-quote-argument tmp-out-file)))))
19086 mathml shell-command-output)
19087 (when (org-called-interactively-p 'any)
19088 (unless (org-format-latex-mathml-available-p)
19089 (user-error "LaTeX to MathML converter not configured")))
19090 (message "Running %s" cmd)
19091 (setq shell-command-output (shell-command-to-string cmd))
19092 (setq mathml
19093 (when (file-readable-p tmp-out-file)
19094 (with-current-buffer (find-file-noselect tmp-out-file t)
19095 (goto-char (point-min))
19096 (when (re-search-forward
19097 (concat
19098 (regexp-quote
19099 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19100 "[^>]*?>"
19101 "\\(.\\|\n\\)*"
19102 "</math>")
19103 nil t)
19104 (prog1 (match-string 0) (kill-buffer))))))
19105 (cond
19106 (mathml
19107 (setq mathml
19108 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19109 (when mathml-file
19110 (write-region mathml nil mathml-file))
19111 (when (org-called-interactively-p 'any)
19112 (message mathml)))
19113 ((message "LaTeX to MathML conversion failed")
19114 (message shell-command-output)))
19115 (delete-file tmp-in-file)
19116 (when (file-exists-p tmp-out-file)
19117 (delete-file tmp-out-file))
19118 mathml))
19120 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19121 prefix &optional dir)
19122 "Use `org-create-math-formula' but check local cache first."
19123 (let* ((absprefix (expand-file-name prefix dir))
19124 (print-length nil) (print-level nil)
19125 (formula-id (concat
19126 "formula-"
19127 (sha1
19128 (prin1-to-string
19129 (list latex-frag
19130 org-latex-to-mathml-convert-command)))))
19131 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19132 (formula-cache-dir (file-name-directory formula-cache)))
19134 (unless (file-directory-p formula-cache-dir)
19135 (make-directory formula-cache-dir t))
19137 (unless (file-exists-p formula-cache)
19138 (org-create-math-formula latex-frag formula-cache))
19140 (if (file-exists-p formula-cache)
19141 ;; Successful conversion. Return the link to MathML file.
19142 (org-add-props
19143 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19144 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19145 'org-latex-src-embed-type (if latex-frag-type
19146 'paragraph 'character)))
19147 ;; Failed conversion. Return the LaTeX fragment verbatim
19148 latex-frag)))
19150 (defun org-create-formula-image (string tofile options buffer &optional type)
19151 "Create an image from LaTeX source using dvipng or convert.
19152 This function calls either `org-create-formula-image-with-dvipng'
19153 or `org-create-formula-image-with-imagemagick' depending on the
19154 value of `org-latex-create-formula-image-program' or on the value
19155 of the optional TYPE variable.
19157 Note: ultimately these two function should be combined as they
19158 share a good deal of logic."
19159 (org-check-external-command
19160 "latex" "needed to convert LaTeX fragments to images")
19161 (funcall
19162 (case (or type org-latex-create-formula-image-program)
19163 (dvipng
19164 (org-check-external-command
19165 "dvipng" "needed to convert LaTeX fragments to images")
19166 #'org-create-formula-image-with-dvipng)
19167 (imagemagick
19168 (org-check-external-command
19169 "convert" "you need to install imagemagick")
19170 #'org-create-formula-image-with-imagemagick)
19171 (t (error
19172 "Invalid value of `org-latex-create-formula-image-program'")))
19173 string tofile options buffer))
19175 (declare-function org-export-get-backend "ox" (name))
19176 (declare-function org-export--get-global-options "ox" (&optional backend))
19177 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19178 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19179 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19180 (defun org-create-formula--latex-header ()
19181 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19182 (let ((info (org-combine-plists (org-export--get-global-options
19183 (org-export-get-backend 'latex))
19184 (org-export--get-inbuffer-options
19185 (org-export-get-backend 'latex)))))
19186 (org-latex-guess-babel-language
19187 (org-latex-guess-inputenc
19188 (org-splice-latex-header
19189 org-format-latex-header
19190 org-latex-default-packages-alist
19191 org-latex-packages-alist t
19192 (plist-get info :latex-header)))
19193 info)))
19195 (defun org--get-display-dpi ()
19196 "Get the DPI of the display.
19198 Assumes that the display has the same pixel width in the
19199 horizontal and vertical directions."
19200 (if (display-graphic-p)
19201 (round (/ (display-pixel-height)
19202 (/ (display-mm-height) 25.4)))
19203 (error "Attempt to calculate the dpi of a non-graphic display")))
19205 ;; This function borrows from Ganesh Swami's latex2png.el
19206 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19207 "This calls dvipng."
19208 (require 'ox-latex)
19209 (let* ((tmpdir (if (featurep 'xemacs)
19210 (temp-directory)
19211 temporary-file-directory))
19212 (texfilebase (make-temp-name
19213 (expand-file-name "orgtex" tmpdir)))
19214 (texfile (concat texfilebase ".tex"))
19215 (dvifile (concat texfilebase ".dvi"))
19216 (pngfile (concat texfilebase ".png"))
19217 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19218 ;; This assumes that the display has the same pixel width in
19219 ;; the horizontal and vertical directions
19220 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19221 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19222 "Black"))
19223 (bg (or (plist-get options (if buffer :background :html-background))
19224 "Transparent")))
19225 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19226 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19227 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19228 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19229 (let ((latex-header (org-create-formula--latex-header)))
19230 (with-temp-file texfile
19231 (insert latex-header)
19232 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19233 (let ((dir default-directory))
19234 (ignore-errors
19235 (cd tmpdir)
19236 (call-process "latex" nil nil nil texfile))
19237 (cd dir))
19238 (if (not (file-exists-p dvifile))
19239 (progn (message "Failed to create dvi file from %s" texfile) nil)
19240 (ignore-errors
19241 (if (featurep 'xemacs)
19242 (call-process "dvipng" nil nil nil
19243 "-fg" fg "-bg" bg
19244 "-T" "tight"
19245 "-o" pngfile
19246 dvifile)
19247 (call-process "dvipng" nil nil nil
19248 "-fg" fg "-bg" bg
19249 "-D" dpi
19250 ;;"-x" scale "-y" scale
19251 "-T" "tight"
19252 "-o" pngfile
19253 dvifile)))
19254 (if (not (file-exists-p pngfile))
19255 (if org-format-latex-signal-error
19256 (error "Failed to create png file from %s" texfile)
19257 (message "Failed to create png file from %s" texfile)
19258 nil)
19259 ;; Use the requested file name and clean up
19260 (copy-file pngfile tofile 'replace)
19261 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
19262 (if (file-exists-p (concat texfilebase e))
19263 (delete-file (concat texfilebase e))))
19264 pngfile))))
19266 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19267 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19268 "This calls convert, which is included into imagemagick."
19269 (require 'ox-latex)
19270 (let* ((tmpdir (if (featurep 'xemacs)
19271 (temp-directory)
19272 temporary-file-directory))
19273 (texfilebase (make-temp-name
19274 (expand-file-name "orgtex" tmpdir)))
19275 (texfile (concat texfilebase ".tex"))
19276 (pdffile (concat texfilebase ".pdf"))
19277 (pngfile (concat texfilebase ".png"))
19278 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19279 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19280 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19281 "black"))
19282 (bg (or (plist-get options (if buffer :background :html-background))
19283 "white")))
19284 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19285 (setq fg (org-latex-color-format fg)))
19286 (if (eq bg 'default) (setq bg (org-latex-color :background))
19287 (setq bg (org-latex-color-format
19288 (if (string= bg "Transparent") "white" bg))))
19289 (let ((latex-header (org-create-formula--latex-header)))
19290 (with-temp-file texfile
19291 (insert latex-header)
19292 (insert "\n\\begin{document}\n"
19293 "\\definecolor{fg}{rgb}{" fg "}\n"
19294 "\\definecolor{bg}{rgb}{" bg "}\n"
19295 "\n\\pagecolor{bg}\n"
19296 "\n{\\color{fg}\n"
19297 string
19298 "\n}\n"
19299 "\n\\end{document}\n")))
19300 (org-latex-compile texfile t)
19301 (if (not (file-exists-p pdffile))
19302 (progn (message "Failed to create pdf file from %s" texfile) nil)
19303 (ignore-errors
19304 (if (featurep 'xemacs)
19305 (call-process "convert" nil nil nil
19306 "-density" "96"
19307 "-trim"
19308 "-antialias"
19309 pdffile
19310 "-quality" "100"
19311 ;; "-sharpen" "0x1.0"
19312 pngfile)
19313 (call-process "convert" nil nil nil
19314 "-density" dpi
19315 "-trim"
19316 "-antialias"
19317 pdffile
19318 "-quality" "100"
19319 ;; "-sharpen" "0x1.0"
19320 pngfile)))
19321 (if (not (file-exists-p pngfile))
19322 (if org-format-latex-signal-error
19323 (error "Failed to create png file from %s" texfile)
19324 (message "Failed to create png file from %s" texfile)
19325 nil)
19326 ;; Use the requested file name and clean up
19327 (copy-file pngfile tofile 'replace)
19328 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19329 (if (file-exists-p (concat texfilebase e))
19330 (delete-file (concat texfilebase e))))
19331 pngfile))))
19333 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19334 "Fill a LaTeX header template TPL.
19335 In the template, the following place holders will be recognized:
19337 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19338 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19339 [PACKAGES] \\usepackage statements for PKG
19340 [NO-PACKAGES] do not include PKG
19341 [EXTRA] the string EXTRA
19342 [NO-EXTRA] do not include EXTRA
19344 For backward compatibility, if both the positive and the negative place
19345 holder is missing, the positive one (without the \"NO-\") will be
19346 assumed to be present at the end of the template.
19347 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19348 EXTRA is a string.
19349 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19350 (let (rpl (end ""))
19351 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19352 (setq rpl (if (or (match-end 1) (not def-pkg))
19353 "" (org-latex-packages-to-string def-pkg snippets-p t))
19354 tpl (replace-match rpl t t tpl))
19355 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19357 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19358 (setq rpl (if (or (match-end 1) (not pkg))
19359 "" (org-latex-packages-to-string pkg snippets-p t))
19360 tpl (replace-match rpl t t tpl))
19361 (if pkg (setq end
19362 (concat end "\n"
19363 (org-latex-packages-to-string pkg snippets-p)))))
19365 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19366 (setq rpl (if (or (match-end 1) (not extra))
19367 "" (concat extra "\n"))
19368 tpl (replace-match rpl t t tpl))
19369 (if (and extra (string-match "\\S-" extra))
19370 (setq end (concat end "\n" extra))))
19372 (if (string-match "\\S-" end)
19373 (concat tpl "\n" end)
19374 tpl)))
19376 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19377 "Turn an alist of packages into a string with the \\usepackage macros."
19378 (setq pkg (mapconcat (lambda(p)
19379 (cond
19380 ((stringp p) p)
19381 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19382 (format "%% Package %s omitted" (cadr p)))
19383 ((equal "" (car p))
19384 (format "\\usepackage{%s}" (cadr p)))
19386 (format "\\usepackage[%s]{%s}"
19387 (car p) (cadr p)))))
19389 "\n"))
19390 (if newline (concat pkg "\n") pkg))
19392 (defun org-dvipng-color (attr)
19393 "Return a RGB color specification for dvipng."
19394 (apply 'format "rgb %s %s %s"
19395 (mapcar 'org-normalize-color
19396 (if (featurep 'xemacs)
19397 (color-rgb-components
19398 (face-property 'default
19399 (cond ((eq attr :foreground) 'foreground)
19400 ((eq attr :background) 'background))))
19401 (color-values (face-attribute 'default attr nil))))))
19403 (defun org-dvipng-color-format (color-name)
19404 "Convert COLOR-NAME to a RGB color value for dvipng."
19405 (apply 'format "rgb %s %s %s"
19406 (mapcar 'org-normalize-color
19407 (color-values color-name))))
19409 (defun org-latex-color (attr)
19410 "Return a RGB color for the LaTeX color package."
19411 (apply 'format "%s,%s,%s"
19412 (mapcar 'org-normalize-color
19413 (if (featurep 'xemacs)
19414 (color-rgb-components
19415 (face-property 'default
19416 (cond ((eq attr :foreground) 'foreground)
19417 ((eq attr :background) 'background))))
19418 (color-values (face-attribute 'default attr nil))))))
19420 (defun org-latex-color-format (color-name)
19421 "Convert COLOR-NAME to a RGB color value."
19422 (apply 'format "%s,%s,%s"
19423 (mapcar 'org-normalize-color
19424 (color-values color-name))))
19426 (defun org-normalize-color (value)
19427 "Return string to be used as color value for an RGB component."
19428 (format "%g" (/ value 65535.0)))
19432 ;; Image display
19434 (defvar org-inline-image-overlays nil)
19435 (make-variable-buffer-local 'org-inline-image-overlays)
19437 (defun org-toggle-inline-images (&optional include-linked)
19438 "Toggle the display of inline images.
19439 INCLUDE-LINKED is passed to `org-display-inline-images'."
19440 (interactive "P")
19441 (if org-inline-image-overlays
19442 (progn
19443 (org-remove-inline-images)
19444 (when (org-called-interactively-p 'interactive)
19445 (message "Inline image display turned off")))
19446 (org-display-inline-images include-linked)
19447 (when (org-called-interactively-p 'interactive)
19448 (message (if org-inline-image-overlays
19449 (format "%d images displayed inline"
19450 (length org-inline-image-overlays))
19451 "No images to display inline")))))
19453 (defun org-redisplay-inline-images ()
19454 "Refresh the display of inline images."
19455 (interactive)
19456 (if (not org-inline-image-overlays)
19457 (org-toggle-inline-images)
19458 (org-toggle-inline-images)
19459 (org-toggle-inline-images)))
19461 (defun org-display-inline-images (&optional include-linked refresh beg end)
19462 "Display inline images.
19464 An inline image is a link which follows either of these
19465 conventions:
19467 1. Its path is a file with an extension matching return value
19468 from `image-file-name-regexp' and it has no contents.
19470 2. Its description consists in a single link of the previous
19471 type.
19473 When optional argument INCLUDE-LINKED is non-nil, also links with
19474 a text description part will be inlined. This can be nice for
19475 a quick look at those images, but it does not reflect what
19476 exported files will look like.
19478 When optional argument REFRESH is non-nil, refresh existing
19479 images between BEG and END. This will create new image displays
19480 only if necessary. BEG and END default to the buffer
19481 boundaries."
19482 (interactive "P")
19483 (when (display-graphic-p)
19484 (unless refresh
19485 (org-remove-inline-images)
19486 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19487 (org-with-wide-buffer
19488 (goto-char (or beg (point-min)))
19489 (let ((case-fold-search t)
19490 (file-extension-re (org-image-file-name-regexp)))
19491 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19492 (let ((link (save-match-data (org-element-context))))
19493 ;; Check if we're at an inline image.
19494 (when (and (equal (org-element-property :type link) "file")
19495 (or include-linked
19496 (not (org-element-property :contents-begin link)))
19497 (let ((parent (org-element-property :parent link)))
19498 (or (not (eq (org-element-type parent) 'link))
19499 (not (cdr (org-element-contents parent)))))
19500 (org-string-match-p file-extension-re
19501 (org-element-property :path link)))
19502 (let ((file (expand-file-name
19503 (org-link-unescape
19504 (org-element-property :path link)))))
19505 (when (file-exists-p file)
19506 (let ((width
19507 ;; Apply `org-image-actual-width' specifications.
19508 (cond
19509 ((not (image-type-available-p 'imagemagick)) nil)
19510 ((eq org-image-actual-width t) nil)
19511 ((listp org-image-actual-width)
19513 ;; First try to find a width among
19514 ;; attributes associated to the paragraph
19515 ;; containing link.
19516 (let ((paragraph
19517 (let ((e link))
19518 (while (and (setq e (org-element-property
19519 :parent e))
19520 (not (eq (org-element-type e)
19521 'paragraph))))
19522 e)))
19523 (when paragraph
19524 (save-excursion
19525 (goto-char (org-element-property :begin paragraph))
19526 (when
19527 (re-search-forward
19528 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19529 (org-element-property
19530 :post-affiliated paragraph)
19532 (string-to-number (match-string 1))))))
19533 ;; Otherwise, fall-back to provided number.
19534 (car org-image-actual-width)))
19535 ((numberp org-image-actual-width)
19536 org-image-actual-width)))
19537 (old (get-char-property-and-overlay
19538 (org-element-property :begin link)
19539 'org-image-overlay)))
19540 (if (and (car-safe old) refresh)
19541 (image-refresh (overlay-get (cdr old) 'display))
19542 (let ((image (create-image file
19543 (and width 'imagemagick)
19545 :width width)))
19546 (when image
19547 (let* ((link
19548 ;; If inline image is the description
19549 ;; of another link, be sure to
19550 ;; consider the latter as the one to
19551 ;; apply the overlay on.
19552 (let ((parent
19553 (org-element-property :parent link)))
19554 (if (eq (org-element-type parent) 'link)
19555 parent
19556 link)))
19557 (ov (make-overlay
19558 (org-element-property :begin link)
19559 (progn
19560 (goto-char
19561 (org-element-property :end link))
19562 (skip-chars-backward " \t")
19563 (point)))))
19564 (overlay-put ov 'display image)
19565 (overlay-put ov 'face 'default)
19566 (overlay-put ov 'org-image-overlay t)
19567 (overlay-put
19568 ov 'modification-hooks
19569 (list 'org-display-inline-remove-overlay))
19570 (push ov org-inline-image-overlays)))))))))))))))
19572 (define-obsolete-function-alias
19573 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19575 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19576 "Remove inline-display overlay if a corresponding region is modified."
19577 (let ((inhibit-modification-hooks t))
19578 (when (and ov after)
19579 (delete ov org-inline-image-overlays)
19580 (delete-overlay ov))))
19582 (defun org-remove-inline-images ()
19583 "Remove inline display of images."
19584 (interactive)
19585 (mapc 'delete-overlay org-inline-image-overlays)
19586 (setq org-inline-image-overlays nil))
19588 ;;;; Key bindings
19590 ;; Outline functions from `outline-mode-prefix-map'
19591 ;; that can be remapped in Org:
19592 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19593 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19594 (define-key org-mode-map [remap outline-forward-same-level]
19595 'org-forward-heading-same-level)
19596 (define-key org-mode-map [remap outline-backward-same-level]
19597 'org-backward-heading-same-level)
19598 (define-key org-mode-map [remap show-branches]
19599 'org-kill-note-or-show-branches)
19600 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19601 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19602 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19603 (define-key org-mode-map [remap outline-next-visible-heading]
19604 'org-next-visible-heading)
19605 (define-key org-mode-map [remap outline-previous-visible-heading]
19606 'org-previous-visible-heading)
19608 ;; Outline functions from `outline-mode-prefix-map' that can not
19609 ;; be remapped in Org:
19611 ;; - the column "key binding" shows whether the Outline function is still
19612 ;; available in Org mode on the same key that it has been bound to in
19613 ;; Outline mode:
19614 ;; - "overridden": key used for a different functionality in Org mode
19615 ;; - else: key still bound to the same Outline function in Org mode
19617 ;; | Outline function | key binding | Org replacement |
19618 ;; |------------------------------------+-------------+--------------------------|
19619 ;; | `outline-next-visible-heading' | `C-c C-n' | better: skip inlinetasks |
19620 ;; | `outline-previous-visible-heading' | `C-c C-p' | better: skip inlinetasks |
19621 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19622 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19623 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19624 ;; | `show-entry' | overridden | no replacement |
19625 ;; | `show-children' | `C-c C-i' | visibility cycling |
19626 ;; | `show-branches' | `C-c C-k' | still same function |
19627 ;; | `show-subtree' | overridden | visibility cycling |
19628 ;; | `show-all' | overridden | no replacement |
19629 ;; | `hide-subtree' | overridden | visibility cycling |
19630 ;; | `hide-body' | overridden | no replacement |
19631 ;; | `hide-entry' | overridden | visibility cycling |
19632 ;; | `hide-leaves' | overridden | no replacement |
19633 ;; | `hide-sublevels' | overridden | no replacement |
19634 ;; | `hide-other' | overridden | no replacement |
19636 ;; Make `C-c C-x' a prefix key
19637 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19639 ;; TAB key with modifiers
19640 (org-defkey org-mode-map "\C-i" 'org-cycle)
19641 (org-defkey org-mode-map [(tab)] 'org-cycle)
19642 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19643 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19644 ;; The following line is necessary under Suse GNU/Linux
19645 (unless (featurep 'xemacs)
19646 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19647 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19648 (define-key org-mode-map [backtab] 'org-shifttab)
19650 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19651 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19652 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19654 ;; Cursor keys with modifiers
19655 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19656 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19657 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19658 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19660 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19661 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19662 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19663 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19664 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19665 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19667 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19668 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19669 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19670 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19672 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19673 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19674 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19675 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19677 ;; Babel keys
19678 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19679 (mapc (lambda (pair)
19680 (define-key org-babel-map (car pair) (cdr pair)))
19681 org-babel-key-bindings)
19683 ;;; Extra keys for tty access.
19684 ;; We only set them when really needed because otherwise the
19685 ;; menus don't show the simple keys
19687 (when (or org-use-extra-keys
19688 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19689 (not window-system))
19690 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19691 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19692 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19693 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19694 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19695 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19696 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19697 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19698 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19699 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19700 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19701 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19702 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19703 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19704 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19705 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19706 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19707 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19708 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19709 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19710 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19711 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19712 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19713 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19714 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19715 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19716 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19717 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19719 ;; All the other keys
19721 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19722 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19723 (if (boundp 'narrow-map)
19724 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19725 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19726 (if (boundp 'narrow-map)
19727 (org-defkey narrow-map "b" 'org-narrow-to-block)
19728 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19729 (if (boundp 'narrow-map)
19730 (org-defkey narrow-map "e" 'org-narrow-to-element)
19731 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19732 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19733 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19734 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19735 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19736 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19737 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19738 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19739 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19740 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19741 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19742 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19743 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19744 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19745 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19746 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19747 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19748 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19749 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19750 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19751 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19752 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19753 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19754 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19755 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19756 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19757 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19758 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19759 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19760 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19761 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19762 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19763 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19764 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19765 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19766 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19767 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19768 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19769 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19770 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19771 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19772 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19773 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19774 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19775 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19776 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19777 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19778 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19779 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19780 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19781 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19782 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19783 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19784 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19785 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19786 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19787 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19788 (org-defkey org-mode-map "\C-c^" 'org-sort)
19789 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19790 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19791 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19792 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19793 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19794 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19795 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19796 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19797 (org-defkey org-mode-map "\C-m" 'org-return)
19798 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19799 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19800 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19801 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19802 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19803 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19804 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19805 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19806 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19807 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19808 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19809 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19810 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19811 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19812 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19813 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19814 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19815 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19816 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19817 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19818 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19819 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19820 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19821 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19822 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19824 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19825 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19826 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19828 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19829 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19830 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19831 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19832 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19833 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19834 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19835 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19836 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19837 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19838 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19839 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19840 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19841 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19842 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19843 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19844 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19845 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19846 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19847 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19848 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19849 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19851 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19852 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19853 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19854 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19855 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19857 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19859 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19861 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19862 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19864 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19867 (when (featurep 'xemacs)
19868 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19871 (defconst org-speed-commands-default
19873 ("Outline Navigation")
19874 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19875 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19876 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19877 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19878 ("F" . org-next-block)
19879 ("B" . org-previous-block)
19880 ("u" . (org-speed-move-safe 'outline-up-heading))
19881 ("j" . org-goto)
19882 ("g" . (org-refile t))
19883 ("Outline Visibility")
19884 ("c" . org-cycle)
19885 ("C" . org-shifttab)
19886 (" " . org-display-outline-path)
19887 ("s" . org-narrow-to-subtree)
19888 ("=" . org-columns)
19889 ("Outline Structure Editing")
19890 ("U" . org-metaup)
19891 ("D" . org-metadown)
19892 ("r" . org-metaright)
19893 ("l" . org-metaleft)
19894 ("R" . org-shiftmetaright)
19895 ("L" . org-shiftmetaleft)
19896 ("i" . (progn (forward-char 1) (call-interactively
19897 'org-insert-heading-respect-content)))
19898 ("^" . org-sort)
19899 ("w" . org-refile)
19900 ("a" . org-archive-subtree-default-with-confirmation)
19901 ("@" . org-mark-subtree)
19902 ("#" . org-toggle-comment)
19903 ("Clock Commands")
19904 ("I" . org-clock-in)
19905 ("O" . org-clock-out)
19906 ("Meta Data Editing")
19907 ("t" . org-todo)
19908 ("," . (org-priority))
19909 ("0" . (org-priority ?\ ))
19910 ("1" . (org-priority ?A))
19911 ("2" . (org-priority ?B))
19912 ("3" . (org-priority ?C))
19913 (":" . org-set-tags-command)
19914 ("e" . org-set-effort)
19915 ("E" . org-inc-effort)
19916 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19917 (org-entry-put (point) "APPT_WARNTIME" m)))
19918 ("Agenda Views etc")
19919 ("v" . org-agenda)
19920 ("/" . org-sparse-tree)
19921 ("Misc")
19922 ("o" . org-open-at-point)
19923 ("?" . org-speed-command-help)
19924 ("<" . (org-agenda-set-restriction-lock 'subtree))
19925 (">" . (org-agenda-remove-restriction-lock))
19927 "The default speed commands.")
19929 (defun org-print-speed-command (e)
19930 (if (> (length (car e)) 1)
19931 (progn
19932 (princ "\n")
19933 (princ (car e))
19934 (princ "\n")
19935 (princ (make-string (length (car e)) ?-))
19936 (princ "\n"))
19937 (princ (car e))
19938 (princ " ")
19939 (if (symbolp (cdr e))
19940 (princ (symbol-name (cdr e)))
19941 (prin1 (cdr e)))
19942 (princ "\n")))
19944 (defun org-speed-command-help ()
19945 "Show the available speed commands."
19946 (interactive)
19947 (if (not org-use-speed-commands)
19948 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19949 (with-output-to-temp-buffer "*Help*"
19950 (princ "User-defined Speed commands\n===========================\n")
19951 (mapc 'org-print-speed-command org-speed-commands-user)
19952 (princ "\n")
19953 (princ "Built-in Speed commands\n=======================\n")
19954 (mapc 'org-print-speed-command org-speed-commands-default))
19955 (with-current-buffer "*Help*"
19956 (setq truncate-lines t))))
19958 (defun org-speed-move-safe (cmd)
19959 "Execute CMD, but make sure that the cursor always ends up in a headline.
19960 If not, return to the original position and throw an error."
19961 (interactive)
19962 (let ((pos (point)))
19963 (call-interactively cmd)
19964 (unless (and (bolp) (org-at-heading-p))
19965 (goto-char pos)
19966 (error "Boundary reached while executing %s" cmd))))
19968 (defvar org-self-insert-command-undo-counter 0)
19970 (defvar org-table-auto-blank-field) ; defined in org-table.el
19971 (defvar org-speed-command nil)
19973 (define-obsolete-function-alias
19974 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19976 (defun org-speed-command-activate (keys)
19977 "Hook for activating single-letter speed commands.
19978 `org-speed-commands-default' specifies a minimal command set.
19979 Use `org-speed-commands-user' for further customization."
19980 (when (or (and (bolp) (looking-at org-outline-regexp))
19981 (and (functionp org-use-speed-commands)
19982 (funcall org-use-speed-commands)))
19983 (cdr (assoc keys (append org-speed-commands-user
19984 org-speed-commands-default)))))
19986 (define-obsolete-function-alias
19987 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19989 (defun org-babel-speed-command-activate (keys)
19990 "Hook for activating single-letter code block commands."
19991 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19992 (cdr (assoc keys org-babel-key-bindings))))
19994 (defcustom org-speed-command-hook
19995 '(org-speed-command-default-hook org-babel-speed-command-hook)
19996 "Hook for activating speed commands at strategic locations.
19997 Hook functions are called in sequence until a valid handler is
19998 found.
20000 Each hook takes a single argument, a user-pressed command key
20001 which is also a `self-insert-command' from the global map.
20003 Within the hook, examine the cursor position and the command key
20004 and return nil or a valid handler as appropriate. Handler could
20005 be one of an interactive command, a function, or a form.
20007 Set `org-use-speed-commands' to non-nil value to enable this
20008 hook. The default setting is `org-speed-command-activate'."
20009 :group 'org-structure
20010 :version "24.1"
20011 :type 'hook)
20013 (defun org-self-insert-command (N)
20014 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20015 If the cursor is in a table looking at whitespace, the whitespace is
20016 overwritten, and the table is not marked as requiring realignment."
20017 (interactive "p")
20018 (org-check-before-invisible-edit 'insert)
20019 (cond
20020 ((and org-use-speed-commands
20021 (let ((kv (this-command-keys-vector)))
20022 (setq org-speed-command
20023 (run-hook-with-args-until-success
20024 'org-speed-command-hook
20025 (make-string 1 (aref kv (1- (length kv))))))))
20026 (cond
20027 ((commandp org-speed-command)
20028 (setq this-command org-speed-command)
20029 (call-interactively org-speed-command))
20030 ((functionp org-speed-command)
20031 (funcall org-speed-command))
20032 ((and org-speed-command (listp org-speed-command))
20033 (eval org-speed-command))
20034 (t (let (org-use-speed-commands)
20035 (call-interactively 'org-self-insert-command)))))
20036 ((and
20037 (org-table-p)
20038 (progn
20039 ;; check if we blank the field, and if that triggers align
20040 (and (featurep 'org-table) org-table-auto-blank-field
20041 (memq last-command
20042 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20043 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
20044 ;; got extra space, this field does not determine column width
20045 (let (org-table-may-need-update) (org-table-blank-field))
20046 ;; no extra space, this field may determine column width
20047 (org-table-blank-field)))
20049 (eq N 1)
20050 (looking-at "[^|\n]* |"))
20051 (let (org-table-may-need-update)
20052 (goto-char (1- (match-end 0)))
20053 (backward-delete-char 1)
20054 (goto-char (match-beginning 0))
20055 (self-insert-command N)))
20057 (setq org-table-may-need-update t)
20058 (self-insert-command N)
20059 (org-fix-tags-on-the-fly)
20060 (if org-self-insert-cluster-for-undo
20061 (if (not (eq last-command 'org-self-insert-command))
20062 (setq org-self-insert-command-undo-counter 1)
20063 (if (>= org-self-insert-command-undo-counter 20)
20064 (setq org-self-insert-command-undo-counter 1)
20065 (and (> org-self-insert-command-undo-counter 0)
20066 buffer-undo-list (listp buffer-undo-list)
20067 (not (cadr buffer-undo-list)) ; remove nil entry
20068 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20069 (setq org-self-insert-command-undo-counter
20070 (1+ org-self-insert-command-undo-counter))))))))
20072 (defun org-check-before-invisible-edit (kind)
20073 "Check is editing if kind KIND would be dangerous with invisible text around.
20074 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20075 ;; First, try to get out of here as quickly as possible, to reduce overhead
20076 (if (and org-catch-invisible-edits
20077 (or (not (boundp 'visible-mode)) (not visible-mode))
20078 (or (get-char-property (point) 'invisible)
20079 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20080 ;; OK, we need to take a closer look
20081 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20082 (invisible-before-point (if (bobp) nil (get-char-property
20083 (1- (point)) 'invisible)))
20084 (border-and-ok-direction
20086 ;; Check if we are acting predictably before invisible text
20087 (and invisible-at-point (not invisible-before-point)
20088 (memq kind '(insert delete-backward)))
20089 ;; Check if we are acting predictably after invisible text
20090 ;; This works not well, and I have turned it off. It seems
20091 ;; better to always show and stop after invisible text.
20092 ;; (and (not invisible-at-point) invisible-before-point
20093 ;; (memq kind '(insert delete)))
20095 (when (or (memq invisible-at-point '(outline org-hide-block t))
20096 (memq invisible-before-point '(outline org-hide-block t)))
20097 (if (eq org-catch-invisible-edits 'error)
20098 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20099 (if (and org-custom-properties-overlays
20100 (y-or-n-p "Display invisible properties in this buffer? "))
20101 (org-toggle-custom-properties-visibility)
20102 ;; Make the area visible
20103 (save-excursion
20104 (if invisible-before-point
20105 (goto-char (previous-single-char-property-change
20106 (point) 'invisible)))
20107 (show-subtree))
20108 (cond
20109 ((eq org-catch-invisible-edits 'show)
20110 ;; That's it, we do the edit after showing
20111 (message
20112 "Unfolding invisible region around point before editing")
20113 (sit-for 1))
20114 ((and (eq org-catch-invisible-edits 'smart)
20115 border-and-ok-direction)
20116 (message "Unfolding invisible region around point before editing"))
20118 ;; Don't do the edit, make the user repeat it in full visibility
20119 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20121 (defun org-fix-tags-on-the-fly ()
20122 (when (and (equal (char-after (point-at-bol)) ?*)
20123 (org-at-heading-p))
20124 (org-align-tags-here org-tags-column)))
20126 (defun org-delete-backward-char (N)
20127 "Like `delete-backward-char', insert whitespace at field end in tables.
20128 When deleting backwards, in tables this function will insert whitespace in
20129 front of the next \"|\" separator, to keep the table aligned. The table will
20130 still be marked for re-alignment if the field did fill the entire column,
20131 because, in this case the deletion might narrow the column."
20132 (interactive "p")
20133 (save-match-data
20134 (org-check-before-invisible-edit 'delete-backward)
20135 (if (and (org-table-p)
20136 (eq N 1)
20137 (string-match "|" (buffer-substring (point-at-bol) (point)))
20138 (looking-at ".*?|"))
20139 (let ((pos (point))
20140 (noalign (looking-at "[^|\n\r]* |"))
20141 (c org-table-may-need-update))
20142 (backward-delete-char N)
20143 (if (not overwrite-mode)
20144 (progn
20145 (skip-chars-forward "^|")
20146 (insert " ")
20147 (goto-char (1- pos))))
20148 ;; noalign: if there were two spaces at the end, this field
20149 ;; does not determine the width of the column.
20150 (if noalign (setq org-table-may-need-update c)))
20151 (backward-delete-char N)
20152 (org-fix-tags-on-the-fly))))
20154 (defun org-delete-char (N)
20155 "Like `delete-char', but insert whitespace at field end in tables.
20156 When deleting characters, in tables this function will insert whitespace in
20157 front of the next \"|\" separator, to keep the table aligned. The table will
20158 still be marked for re-alignment if the field did fill the entire column,
20159 because, in this case the deletion might narrow the column."
20160 (interactive "p")
20161 (save-match-data
20162 (org-check-before-invisible-edit 'delete)
20163 (if (and (org-table-p)
20164 (not (bolp))
20165 (not (= (char-after) ?|))
20166 (eq N 1))
20167 (if (looking-at ".*?|")
20168 (let ((pos (point))
20169 (noalign (looking-at "[^|\n\r]* |"))
20170 (c org-table-may-need-update))
20171 (replace-match
20172 (concat (substring (match-string 0) 1 -1) " |") nil t)
20173 (goto-char pos)
20174 ;; noalign: if there were two spaces at the end, this field
20175 ;; does not determine the width of the column.
20176 (if noalign (setq org-table-may-need-update c)))
20177 (delete-char N))
20178 (delete-char N)
20179 (org-fix-tags-on-the-fly))))
20181 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20182 (put 'org-self-insert-command 'delete-selection
20183 (lambda ()
20184 (not (run-hook-with-args-until-success
20185 'self-insert-uses-region-functions))))
20186 (put 'orgtbl-self-insert-command 'delete-selection
20187 (lambda ()
20188 (not (run-hook-with-args-until-success
20189 'self-insert-uses-region-functions))))
20190 (put 'org-delete-char 'delete-selection 'supersede)
20191 (put 'org-delete-backward-char 'delete-selection 'supersede)
20192 (put 'org-yank 'delete-selection 'yank)
20194 ;; Make `flyspell-mode' delay after some commands
20195 (put 'org-self-insert-command 'flyspell-delayed t)
20196 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20197 (put 'org-delete-char 'flyspell-delayed t)
20198 (put 'org-delete-backward-char 'flyspell-delayed t)
20200 ;; Make pabbrev-mode expand after org-mode commands
20201 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20202 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20204 (defun org-remap (map &rest commands)
20205 "In MAP, remap the functions given in COMMANDS.
20206 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20207 (let (new old)
20208 (while commands
20209 (setq old (pop commands) new (pop commands))
20210 (if (fboundp 'command-remapping)
20211 (org-defkey map (vector 'remap old) new)
20212 (substitute-key-definition old new map global-map)))))
20214 (defun org-transpose-words ()
20215 "Transpose words for Org.
20216 This uses the `org-mode-transpose-word-syntax-table' syntax
20217 table, which interprets characters in `org-emphasis-alist' as
20218 word constituents."
20219 (interactive)
20220 (with-syntax-table org-mode-transpose-word-syntax-table
20221 (call-interactively 'transpose-words)))
20222 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20224 (when (eq org-enable-table-editor 'optimized)
20225 ;; If the user wants maximum table support, we need to hijack
20226 ;; some standard editing functions
20227 (org-remap org-mode-map
20228 'self-insert-command 'org-self-insert-command
20229 'delete-char 'org-delete-char
20230 'delete-backward-char 'org-delete-backward-char)
20231 (org-defkey org-mode-map "|" 'org-force-self-insert))
20233 (defvar org-ctrl-c-ctrl-c-hook nil
20234 "Hook for functions attaching themselves to `C-c C-c'.
20236 This can be used to add additional functionality to the C-c C-c
20237 key which executes context-dependent commands. This hook is run
20238 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20239 run after the last test.
20241 Each function will be called with no arguments. The function
20242 must check if the context is appropriate for it to act. If yes,
20243 it should do its thing and then return a non-nil value. If the
20244 context is wrong, just do nothing and return nil.")
20246 (defvar org-ctrl-c-ctrl-c-final-hook nil
20247 "Hook for functions attaching themselves to `C-c C-c'.
20249 This can be used to add additional functionality to the C-c C-c
20250 key which executes context-dependent commands. This hook is run
20251 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20252 before the first test.
20254 Each function will be called with no arguments. The function
20255 must check if the context is appropriate for it to act. If yes,
20256 it should do its thing and then return a non-nil value. If the
20257 context is wrong, just do nothing and return nil.")
20259 (defvar org-tab-first-hook nil
20260 "Hook for functions to attach themselves to TAB.
20261 See `org-ctrl-c-ctrl-c-hook' for more information.
20262 This hook runs as the first action when TAB is pressed, even before
20263 `org-cycle' messes around with the `outline-regexp' to cater for
20264 inline tasks and plain list item folding.
20265 If any function in this hook returns t, any other actions that
20266 would have been caused by TAB (such as table field motion or visibility
20267 cycling) will not occur.")
20269 (defvar org-tab-after-check-for-table-hook nil
20270 "Hook for functions to attach themselves to TAB.
20271 See `org-ctrl-c-ctrl-c-hook' for more information.
20272 This hook runs after it has been established that the cursor is not in a
20273 table, but before checking if the cursor is in a headline or if global cycling
20274 should be done.
20275 If any function in this hook returns t, not other actions like visibility
20276 cycling will be done.")
20278 (defvar org-tab-after-check-for-cycling-hook nil
20279 "Hook for functions to attach themselves to TAB.
20280 See `org-ctrl-c-ctrl-c-hook' for more information.
20281 This hook runs after it has been established that not table field motion and
20282 not visibility should be done because of current context. This is probably
20283 the place where a package like yasnippets can hook in.")
20285 (defvar org-tab-before-tab-emulation-hook nil
20286 "Hook for functions to attach themselves to TAB.
20287 See `org-ctrl-c-ctrl-c-hook' for more information.
20288 This hook runs after every other options for TAB have been exhausted, but
20289 before indentation and \t insertion takes place.")
20291 (defvar org-metaleft-hook nil
20292 "Hook for functions attaching themselves to `M-left'.
20293 See `org-ctrl-c-ctrl-c-hook' for more information.")
20294 (defvar org-metaright-hook nil
20295 "Hook for functions attaching themselves to `M-right'.
20296 See `org-ctrl-c-ctrl-c-hook' for more information.")
20297 (defvar org-metaup-hook nil
20298 "Hook for functions attaching themselves to `M-up'.
20299 See `org-ctrl-c-ctrl-c-hook' for more information.")
20300 (defvar org-metadown-hook nil
20301 "Hook for functions attaching themselves to `M-down'.
20302 See `org-ctrl-c-ctrl-c-hook' for more information.")
20303 (defvar org-shiftmetaleft-hook nil
20304 "Hook for functions attaching themselves to `M-S-left'.
20305 See `org-ctrl-c-ctrl-c-hook' for more information.")
20306 (defvar org-shiftmetaright-hook nil
20307 "Hook for functions attaching themselves to `M-S-right'.
20308 See `org-ctrl-c-ctrl-c-hook' for more information.")
20309 (defvar org-shiftmetaup-hook nil
20310 "Hook for functions attaching themselves to `M-S-up'.
20311 See `org-ctrl-c-ctrl-c-hook' for more information.")
20312 (defvar org-shiftmetadown-hook nil
20313 "Hook for functions attaching themselves to `M-S-down'.
20314 See `org-ctrl-c-ctrl-c-hook' for more information.")
20315 (defvar org-metareturn-hook nil
20316 "Hook for functions attaching themselves to `M-RET'.
20317 See `org-ctrl-c-ctrl-c-hook' for more information.")
20318 (defvar org-shiftup-hook nil
20319 "Hook for functions attaching themselves to `S-up'.
20320 See `org-ctrl-c-ctrl-c-hook' for more information.")
20321 (defvar org-shiftup-final-hook nil
20322 "Hook for functions attaching themselves to `S-up'.
20323 This one runs after all other options except shift-select have been excluded.
20324 See `org-ctrl-c-ctrl-c-hook' for more information.")
20325 (defvar org-shiftdown-hook nil
20326 "Hook for functions attaching themselves to `S-down'.
20327 See `org-ctrl-c-ctrl-c-hook' for more information.")
20328 (defvar org-shiftdown-final-hook nil
20329 "Hook for functions attaching themselves to `S-down'.
20330 This one runs after all other options except shift-select have been excluded.
20331 See `org-ctrl-c-ctrl-c-hook' for more information.")
20332 (defvar org-shiftleft-hook nil
20333 "Hook for functions attaching themselves to `S-left'.
20334 See `org-ctrl-c-ctrl-c-hook' for more information.")
20335 (defvar org-shiftleft-final-hook nil
20336 "Hook for functions attaching themselves to `S-left'.
20337 This one runs after all other options except shift-select have been excluded.
20338 See `org-ctrl-c-ctrl-c-hook' for more information.")
20339 (defvar org-shiftright-hook nil
20340 "Hook for functions attaching themselves to `S-right'.
20341 See `org-ctrl-c-ctrl-c-hook' for more information.")
20342 (defvar org-shiftright-final-hook nil
20343 "Hook for functions attaching themselves to `S-right'.
20344 This one runs after all other options except shift-select have been excluded.
20345 See `org-ctrl-c-ctrl-c-hook' for more information.")
20347 (defun org-modifier-cursor-error ()
20348 "Throw an error, a modified cursor command was applied in wrong context."
20349 (user-error "This command is active in special context like tables, headlines or items"))
20351 (defun org-shiftselect-error ()
20352 "Throw an error because Shift-Cursor command was applied in wrong context."
20353 (if (and (boundp 'shift-select-mode) shift-select-mode)
20354 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20355 (user-error "This command works only in special context like headlines or timestamps")))
20357 (defun org-call-for-shift-select (cmd)
20358 (let ((this-command-keys-shift-translated t))
20359 (call-interactively cmd)))
20361 (defun org-shifttab (&optional arg)
20362 "Global visibility cycling or move to previous table field.
20363 Call `org-table-previous-field' within a table.
20364 When ARG is nil, cycle globally through visibility states.
20365 When ARG is a numeric prefix, show contents of this level."
20366 (interactive "P")
20367 (cond
20368 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20369 ((integerp arg)
20370 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20371 (message "Content view to level: %d" arg)
20372 (org-content (prefix-numeric-value arg2))
20373 (org-cycle-show-empty-lines t)
20374 (setq org-cycle-global-status 'overview)))
20375 (t (call-interactively 'org-global-cycle))))
20377 (defun org-shiftmetaleft ()
20378 "Promote subtree or delete table column.
20379 Calls `org-promote-subtree', `org-outdent-item-tree', or
20380 `org-table-delete-column', depending on context. See the
20381 individual commands for more information."
20382 (interactive)
20383 (cond
20384 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20385 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20386 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20387 ((if (not (org-region-active-p)) (org-at-item-p)
20388 (save-excursion (goto-char (region-beginning))
20389 (org-at-item-p)))
20390 (call-interactively 'org-outdent-item-tree))
20391 (t (org-modifier-cursor-error))))
20393 (defun org-shiftmetaright ()
20394 "Demote subtree or insert table column.
20395 Calls `org-demote-subtree', `org-indent-item-tree', or
20396 `org-table-insert-column', depending on context. See the
20397 individual commands for more information."
20398 (interactive)
20399 (cond
20400 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20401 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20402 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20403 ((if (not (org-region-active-p)) (org-at-item-p)
20404 (save-excursion (goto-char (region-beginning))
20405 (org-at-item-p)))
20406 (call-interactively 'org-indent-item-tree))
20407 (t (org-modifier-cursor-error))))
20409 (defun org-shiftmetaup (&optional arg)
20410 "Drag the line at point up.
20411 In a table, kill the current row.
20412 On a clock timestamp, update the value of the timestamp like `S-<up>'
20413 but also adjust the previous clocked item in the clock history.
20414 Everywhere else, drag the line at point up."
20415 (interactive "P")
20416 (cond
20417 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20418 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20419 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20420 (call-interactively 'org-timestamp-up)))
20421 (t (call-interactively 'org-drag-line-backward))))
20423 (defun org-shiftmetadown (&optional arg)
20424 "Drag the line at point down.
20425 In a table, insert an empty row at the current line.
20426 On a clock timestamp, update the value of the timestamp like `S-<down>'
20427 but also adjust the previous clocked item in the clock history.
20428 Everywhere else, drag the line at point down."
20429 (interactive "P")
20430 (cond
20431 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20432 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20433 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20434 (call-interactively 'org-timestamp-down)))
20435 (t (call-interactively 'org-drag-line-forward))))
20437 (defsubst org-hidden-tree-error ()
20438 (user-error
20439 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20441 (defun org-metaleft (&optional arg)
20442 "Promote heading, list item at point or move table column left.
20444 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20445 depending on context. With no specific context, calls the Emacs
20446 default `backward-word'. See the individual commands for more
20447 information.
20449 This function runs the hook `org-metaleft-hook' as a first step,
20450 and returns at first non-nil value."
20451 (interactive "P")
20452 (cond
20453 ((run-hook-with-args-until-success 'org-metaleft-hook))
20454 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20455 ((org-with-limited-levels
20456 (or (org-at-heading-p)
20457 (and (org-region-active-p)
20458 (save-excursion
20459 (goto-char (region-beginning))
20460 (org-at-heading-p)))))
20461 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20462 (call-interactively 'org-do-promote))
20463 ;; At an inline task.
20464 ((org-at-heading-p)
20465 (call-interactively 'org-inlinetask-promote))
20466 ((or (org-at-item-p)
20467 (and (org-region-active-p)
20468 (save-excursion
20469 (goto-char (region-beginning))
20470 (org-at-item-p))))
20471 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20472 (call-interactively 'org-outdent-item))
20473 (t (call-interactively 'backward-word))))
20475 (defun org-metaright (&optional arg)
20476 "Demote heading, list item at point or move table column right.
20478 In front of a drawer or a block keyword, indent it correctly.
20480 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20481 `org-indnet-drawer' or `org-indent-block' depending on context.
20482 With no specific context, calls the Emacs default `forward-word'.
20483 See the individual commands for more information.
20485 This function runs the hook `org-metaright-hook' as a first step,
20486 and returns at first non-nil value."
20487 (interactive "P")
20488 (cond
20489 ((run-hook-with-args-until-success 'org-metaright-hook))
20490 ((org-at-table-p) (call-interactively 'org-table-move-column))
20491 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20492 ((org-at-block-p) (call-interactively 'org-indent-block))
20493 ((org-with-limited-levels
20494 (or (org-at-heading-p)
20495 (and (org-region-active-p)
20496 (save-excursion
20497 (goto-char (region-beginning))
20498 (org-at-heading-p)))))
20499 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20500 (call-interactively 'org-do-demote))
20501 ;; At an inline task.
20502 ((org-at-heading-p)
20503 (call-interactively 'org-inlinetask-demote))
20504 ((or (org-at-item-p)
20505 (and (org-region-active-p)
20506 (save-excursion
20507 (goto-char (region-beginning))
20508 (org-at-item-p))))
20509 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20510 (call-interactively 'org-indent-item))
20511 (t (call-interactively 'forward-word))))
20513 (defun org-check-for-hidden (what)
20514 "Check if there are hidden headlines/items in the current visual line.
20515 WHAT can be either `headlines' or `items'. If the current line is
20516 an outline or item heading and it has a folded subtree below it,
20517 this function returns t, nil otherwise."
20518 (let ((re (cond
20519 ((eq what 'headlines) org-outline-regexp-bol)
20520 ((eq what 'items) (org-item-beginning-re))
20521 (t (error "This should not happen"))))
20522 beg end)
20523 (save-excursion
20524 (catch 'exit
20525 (unless (org-region-active-p)
20526 (setq beg (point-at-bol))
20527 (beginning-of-line 2)
20528 (while (and (not (eobp)) ;; this is like `next-line'
20529 (get-char-property (1- (point)) 'invisible))
20530 (beginning-of-line 2))
20531 (setq end (point))
20532 (goto-char beg)
20533 (goto-char (point-at-eol))
20534 (setq end (max end (point)))
20535 (while (re-search-forward re end t)
20536 (if (get-char-property (match-beginning 0) 'invisible)
20537 (throw 'exit t))))
20538 nil))))
20540 (defun org-metaup (&optional arg)
20541 "Move subtree up or move table row up.
20542 Calls `org-move-subtree-up' or `org-table-move-row' or
20543 `org-move-item-up', depending on context. See the individual commands
20544 for more information."
20545 (interactive "P")
20546 (cond
20547 ((run-hook-with-args-until-success 'org-metaup-hook))
20548 ((org-region-active-p)
20549 (let* ((a (min (region-beginning) (region-end)))
20550 (b (1- (max (region-beginning) (region-end))))
20551 (c (save-excursion (goto-char a)
20552 (move-beginning-of-line 0)))
20553 (d (save-excursion (goto-char a)
20554 (move-end-of-line 0) (point))))
20555 (transpose-regions a b c d)
20556 (goto-char c)))
20557 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20558 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20559 ((org-at-item-p) (call-interactively 'org-move-item-up))
20560 (t (org-drag-element-backward))))
20562 (defun org-metadown (&optional arg)
20563 "Move subtree down or move table row down.
20564 Calls `org-move-subtree-down' or `org-table-move-row' or
20565 `org-move-item-down', depending on context. See the individual
20566 commands for more information."
20567 (interactive "P")
20568 (cond
20569 ((run-hook-with-args-until-success 'org-metadown-hook))
20570 ((org-region-active-p)
20571 (let* ((a (min (region-beginning) (region-end)))
20572 (b (max (region-beginning) (region-end)))
20573 (c (save-excursion (goto-char b)
20574 (move-beginning-of-line 1)))
20575 (d (save-excursion (goto-char b)
20576 (move-end-of-line 1) (1+ (point)))))
20577 (transpose-regions a b c d)
20578 (goto-char d)))
20579 ((org-at-table-p) (call-interactively 'org-table-move-row))
20580 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20581 ((org-at-item-p) (call-interactively 'org-move-item-down))
20582 (t (org-drag-element-forward))))
20584 (defun org-shiftup (&optional arg)
20585 "Increase item in timestamp or increase priority of current headline.
20586 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20587 depending on context. See the individual commands for more information."
20588 (interactive "P")
20589 (cond
20590 ((run-hook-with-args-until-success 'org-shiftup-hook))
20591 ((and org-support-shift-select (org-region-active-p))
20592 (org-call-for-shift-select 'previous-line))
20593 ((org-at-timestamp-p t)
20594 (call-interactively (if org-edit-timestamp-down-means-later
20595 'org-timestamp-down 'org-timestamp-up)))
20596 ((and (not (eq org-support-shift-select 'always))
20597 org-enable-priority-commands
20598 (org-at-heading-p))
20599 (call-interactively 'org-priority-up))
20600 ((and (not org-support-shift-select) (org-at-item-p))
20601 (call-interactively 'org-previous-item))
20602 ((org-clocktable-try-shift 'up arg))
20603 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20604 (org-support-shift-select
20605 (org-call-for-shift-select 'previous-line))
20606 (t (org-shiftselect-error))))
20608 (defun org-shiftdown (&optional arg)
20609 "Decrease item in timestamp or decrease priority of current headline.
20610 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20611 depending on context. See the individual commands for more information."
20612 (interactive "P")
20613 (cond
20614 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20615 ((and org-support-shift-select (org-region-active-p))
20616 (org-call-for-shift-select 'next-line))
20617 ((org-at-timestamp-p t)
20618 (call-interactively (if org-edit-timestamp-down-means-later
20619 'org-timestamp-up 'org-timestamp-down)))
20620 ((and (not (eq org-support-shift-select 'always))
20621 org-enable-priority-commands
20622 (org-at-heading-p))
20623 (call-interactively 'org-priority-down))
20624 ((and (not org-support-shift-select) (org-at-item-p))
20625 (call-interactively 'org-next-item))
20626 ((org-clocktable-try-shift 'down arg))
20627 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20628 (org-support-shift-select
20629 (org-call-for-shift-select 'next-line))
20630 (t (org-shiftselect-error))))
20632 (defun org-shiftright (&optional arg)
20633 "Cycle the thing at point or in the current line, depending on context.
20634 Depending on context, this does one of the following:
20636 - switch a timestamp at point one day into the future
20637 - on a headline, switch to the next TODO keyword.
20638 - on an item, switch entire list to the next bullet type
20639 - on a property line, switch to the next allowed value
20640 - on a clocktable definition line, move time block into the future"
20641 (interactive "P")
20642 (cond
20643 ((run-hook-with-args-until-success 'org-shiftright-hook))
20644 ((and org-support-shift-select (org-region-active-p))
20645 (org-call-for-shift-select 'forward-char))
20646 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20647 ((and (not (eq org-support-shift-select 'always))
20648 (org-at-heading-p))
20649 (let ((org-inhibit-logging
20650 (not org-treat-S-cursor-todo-selection-as-state-change))
20651 (org-inhibit-blocking
20652 (not org-treat-S-cursor-todo-selection-as-state-change)))
20653 (org-call-with-arg 'org-todo 'right)))
20654 ((or (and org-support-shift-select
20655 (not (eq org-support-shift-select 'always))
20656 (org-at-item-bullet-p))
20657 (and (not org-support-shift-select) (org-at-item-p)))
20658 (org-call-with-arg 'org-cycle-list-bullet nil))
20659 ((and (not (eq org-support-shift-select 'always))
20660 (org-at-property-p))
20661 (call-interactively 'org-property-next-allowed-value))
20662 ((org-clocktable-try-shift 'right arg))
20663 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20664 (org-support-shift-select
20665 (org-call-for-shift-select 'forward-char))
20666 (t (org-shiftselect-error))))
20668 (defun org-shiftleft (&optional arg)
20669 "Cycle the thing at point or in the current line, depending on context.
20670 Depending on context, this does one of the following:
20672 - switch a timestamp at point one day into the past
20673 - on a headline, switch to the previous TODO keyword.
20674 - on an item, switch entire list to the previous bullet type
20675 - on a property line, switch to the previous allowed value
20676 - on a clocktable definition line, move time block into the past"
20677 (interactive "P")
20678 (cond
20679 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20680 ((and org-support-shift-select (org-region-active-p))
20681 (org-call-for-shift-select 'backward-char))
20682 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20683 ((and (not (eq org-support-shift-select 'always))
20684 (org-at-heading-p))
20685 (let ((org-inhibit-logging
20686 (not org-treat-S-cursor-todo-selection-as-state-change))
20687 (org-inhibit-blocking
20688 (not org-treat-S-cursor-todo-selection-as-state-change)))
20689 (org-call-with-arg 'org-todo 'left)))
20690 ((or (and org-support-shift-select
20691 (not (eq org-support-shift-select 'always))
20692 (org-at-item-bullet-p))
20693 (and (not org-support-shift-select) (org-at-item-p)))
20694 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20695 ((and (not (eq org-support-shift-select 'always))
20696 (org-at-property-p))
20697 (call-interactively 'org-property-previous-allowed-value))
20698 ((org-clocktable-try-shift 'left arg))
20699 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20700 (org-support-shift-select
20701 (org-call-for-shift-select 'backward-char))
20702 (t (org-shiftselect-error))))
20704 (defun org-shiftcontrolright ()
20705 "Switch to next TODO set."
20706 (interactive)
20707 (cond
20708 ((and org-support-shift-select (org-region-active-p))
20709 (org-call-for-shift-select 'forward-word))
20710 ((and (not (eq org-support-shift-select 'always))
20711 (org-at-heading-p))
20712 (org-call-with-arg 'org-todo 'nextset))
20713 (org-support-shift-select
20714 (org-call-for-shift-select 'forward-word))
20715 (t (org-shiftselect-error))))
20717 (defun org-shiftcontrolleft ()
20718 "Switch to previous TODO set."
20719 (interactive)
20720 (cond
20721 ((and org-support-shift-select (org-region-active-p))
20722 (org-call-for-shift-select 'backward-word))
20723 ((and (not (eq org-support-shift-select 'always))
20724 (org-at-heading-p))
20725 (org-call-with-arg 'org-todo 'previousset))
20726 (org-support-shift-select
20727 (org-call-for-shift-select 'backward-word))
20728 (t (org-shiftselect-error))))
20730 (defun org-shiftcontrolup (&optional n)
20731 "Change timestamps synchronously up in CLOCK log lines.
20732 Optional argument N tells to change by that many units."
20733 (interactive "P")
20734 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20735 (let (org-support-shift-select)
20736 (org-clock-timestamps-up n))
20737 (user-error "Not at a clock log")))
20739 (defun org-shiftcontroldown (&optional n)
20740 "Change timestamps synchronously down in CLOCK log lines.
20741 Optional argument N tells to change by that many units."
20742 (interactive "P")
20743 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20744 (let (org-support-shift-select)
20745 (org-clock-timestamps-down n))
20746 (user-error "Not at a clock log")))
20748 (defun org-increase-number-at-point (&optional inc)
20749 "Increment the number at point.
20750 With an optional prefix numeric argument INC, increment using
20751 this numeric value."
20752 (interactive "p")
20753 (if (not (number-at-point))
20754 (user-error "Not on a number")
20755 (unless inc (setq inc 1))
20756 (let ((pos (point))
20757 (beg (skip-chars-backward "-+^/*0-9eE."))
20758 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20759 (setq nap (buffer-substring-no-properties
20760 (+ pos beg) (+ pos beg end)))
20761 (delete-region (+ pos beg) (+ pos beg end))
20762 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20763 (when (org-at-table-p)
20764 (org-table-align)
20765 (org-table-end-of-field 1))))
20767 (defun org-decrease-number-at-point (&optional inc)
20768 "Decrement the number at point.
20769 With an optional prefix numeric argument INC, decrement using
20770 this numeric value."
20771 (interactive "p")
20772 (org-increase-number-at-point (- inc)))
20774 (defun org-ctrl-c-ret ()
20775 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20776 (interactive)
20777 (cond
20778 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20779 (t (call-interactively 'org-insert-heading))))
20781 (defun org-find-visible ()
20782 (let ((s (point)))
20783 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20784 (get-char-property s 'invisible)))
20786 (defun org-find-invisible ()
20787 (let ((s (point)))
20788 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20789 (not (get-char-property s 'invisible))))
20792 (defun org-copy-visible (beg end)
20793 "Copy the visible parts of the region."
20794 (interactive "r")
20795 (let (snippets s)
20796 (save-excursion
20797 (save-restriction
20798 (narrow-to-region beg end)
20799 (setq s (goto-char (point-min)))
20800 (while (not (= (point) (point-max)))
20801 (goto-char (org-find-invisible))
20802 (push (buffer-substring s (point)) snippets)
20803 (setq s (goto-char (org-find-visible))))))
20804 (kill-new (apply 'concat (nreverse snippets)))))
20806 (defun org-copy-special ()
20807 "Copy region in table or copy current subtree.
20808 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20809 See the individual commands for more information."
20810 (interactive)
20811 (call-interactively
20812 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20814 (defun org-cut-special ()
20815 "Cut region in table or cut current subtree.
20816 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20817 See the individual commands for more information."
20818 (interactive)
20819 (call-interactively
20820 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20822 (defun org-paste-special (arg)
20823 "Paste rectangular region into table, or past subtree relative to level.
20824 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20825 See the individual commands for more information."
20826 (interactive "P")
20827 (if (org-at-table-p)
20828 (org-table-paste-rectangle)
20829 (org-paste-subtree arg)))
20831 (defsubst org-in-fixed-width-region-p ()
20832 "Is point in a fixed-width region?"
20833 (save-match-data
20834 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20836 (defun org-edit-special (&optional arg)
20837 "Call a special editor for the element at point.
20838 When at a table, call the formula editor with `org-table-edit-formulas'.
20839 When in a source code block, call `org-edit-src-code'.
20840 When in a fixed-width region, call `org-edit-fixed-width-region'.
20841 When in an export block, call `org-edit-export-block'.
20842 When at an #+INCLUDE keyword, visit the included file.
20843 When at a footnote reference, call `org-edit-footnote-reference'
20844 On a link, call `ffap' to visit the link at point.
20845 Otherwise, return a user error."
20846 (interactive "P")
20847 (let ((element (org-element-at-point)))
20848 (assert (not buffer-read-only) nil
20849 "Buffer is read-only: %s" (buffer-name))
20850 (case (org-element-type element)
20851 (src-block
20852 (if (not arg) (org-edit-src-code)
20853 (let* ((info (org-babel-get-src-block-info))
20854 (lang (nth 0 info))
20855 (params (nth 2 info))
20856 (session (cdr (assq :session params))))
20857 (if (not session) (org-edit-src-code)
20858 ;; At a src-block with a session and function called with
20859 ;; an ARG: switch to the buffer related to the inferior
20860 ;; process.
20861 (switch-to-buffer
20862 (funcall (intern (concat "org-babel-prep-session:" lang))
20863 session params))))))
20864 (keyword
20865 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20866 (org-open-link-from-string
20867 (format "[[%s]]"
20868 (expand-file-name
20869 (let ((value (org-element-property :value element)))
20870 (cond ((not (org-string-nw-p value))
20871 (user-error "No file to edit"))
20872 ((string-match "\\`\"\\(.*?\\)\"" value)
20873 (match-string 1 value))
20874 ((string-match "\\`[^ \t\"]\\S-*" value)
20875 (match-string 0 value))
20876 (t (user-error "No valid file specified")))))))
20877 (user-error "No special environment to edit here")))
20878 (table
20879 (if (eq (org-element-property :type element) 'table.el)
20880 (org-edit-table.el)
20881 (call-interactively 'org-table-edit-formulas)))
20882 ;; Only Org tables contain `table-row' type elements.
20883 (table-row (call-interactively 'org-table-edit-formulas))
20884 (example-block (org-edit-src-code))
20885 (export-block (org-edit-export-block))
20886 (fixed-width (org-edit-fixed-width-region))
20887 (otherwise
20888 ;; No notable element at point. Though, we may be at a link or
20889 ;; a footnote reference, which are objects. Thus, scan deeper.
20890 (let ((context (org-element-context element)))
20891 (case (org-element-type context)
20892 (link (call-interactively #'ffap))
20893 (footnote-reference (org-edit-footnote-reference))
20894 (t (user-error "No special environment to edit here"))))))))
20896 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20897 (defun org-ctrl-c-ctrl-c (&optional arg)
20898 "Set tags in headline, or update according to changed information at point.
20900 This command does many different things, depending on context:
20902 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20903 this is what we do.
20905 - If the cursor is on a statistics cookie, update it.
20907 - If the cursor is in a headline, prompt for tags and insert them
20908 into the current line, aligned to `org-tags-column'. When called
20909 with prefix arg, realign all tags in the current buffer.
20911 - If the cursor is in one of the special #+KEYWORD lines, this
20912 triggers scanning the buffer for these lines and updating the
20913 information.
20915 - If the cursor is inside a table, realign the table. This command
20916 works even if the automatic table editor has been turned off.
20918 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20919 the entire table.
20921 - If the cursor is at a footnote reference or definition, jump to
20922 the corresponding definition or references, respectively.
20924 - If the cursor is a the beginning of a dynamic block, update it.
20926 - If the current buffer is a capture buffer, close note and file it.
20928 - If the cursor is on a <<<target>>>, update radio targets and
20929 corresponding links in this buffer.
20931 - If the cursor is on a numbered item in a plain list, renumber the
20932 ordered list.
20934 - If the cursor is on a checkbox, toggle it.
20936 - If the cursor is on a code block, evaluate it. The variable
20937 `org-confirm-babel-evaluate' can be used to control prompting
20938 before code block evaluation, by default every code block
20939 evaluation requires confirmation. Code block evaluation can be
20940 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20941 (interactive "P")
20942 (cond
20943 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20944 org-occur-highlights)
20945 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20946 (org-remove-occur-highlights)
20947 (message "Temporary highlights/overlays removed from current buffer"))
20948 ((and (local-variable-p 'org-finish-function (current-buffer))
20949 (fboundp org-finish-function))
20950 (funcall org-finish-function))
20951 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20953 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20954 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20955 (user-error "C-c C-c can do nothing useful at this location"))
20956 (let* ((context (org-element-context))
20957 (type (org-element-type context)))
20958 (case type
20959 ;; When at a link, act according to the parent instead.
20960 (link (setq context (org-element-property :parent context))
20961 (setq type (org-element-type context)))
20962 ;; Unsupported object types: refer to the first supported
20963 ;; element or object containing it.
20964 ((bold code entity export-snippet inline-babel-call inline-src-block
20965 italic latex-fragment line-break macro strike-through subscript
20966 superscript underline verbatim)
20967 (setq context
20968 (org-element-lineage
20969 context '(radio-target paragraph verse-block table-cell)))))
20970 ;; For convenience: at the first line of a paragraph on the
20971 ;; same line as an item, apply function on that item instead.
20972 (when (eq type 'paragraph)
20973 (let ((parent (org-element-property :parent context)))
20974 (when (and (eq (org-element-type parent) 'item)
20975 (= (line-beginning-position)
20976 (org-element-property :begin parent)))
20977 (setq context parent type 'item))))
20978 ;; Act according to type of element or object at point.
20979 (case type
20980 (clock (org-clock-update-time-maybe))
20981 (dynamic-block
20982 (save-excursion
20983 (goto-char (org-element-property :post-affiliated context))
20984 (org-update-dblock)))
20985 (footnote-definition
20986 (goto-char (org-element-property :post-affiliated context))
20987 (call-interactively 'org-footnote-action))
20988 (footnote-reference (call-interactively 'org-footnote-action))
20989 ((headline inlinetask)
20990 (save-excursion (goto-char (org-element-property :begin context))
20991 (call-interactively 'org-set-tags)))
20992 (item
20993 ;; At an item: a double C-u set checkbox to "[-]"
20994 ;; unconditionally, whereas a single one will toggle its
20995 ;; presence. Without an universal argument, if the item
20996 ;; has a checkbox, toggle it. Otherwise repair the list.
20997 (let* ((box (org-element-property :checkbox context))
20998 (struct (org-element-property :structure context))
20999 (old-struct (copy-tree struct))
21000 (parents (org-list-parents-alist struct))
21001 (prevs (org-list-prevs-alist struct))
21002 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21003 (org-list-set-checkbox
21004 (org-element-property :begin context) struct
21005 (cond ((equal arg '(16)) "[-]")
21006 ((and (not box) (equal arg '(4))) "[ ]")
21007 ((or (not box) (equal arg '(4))) nil)
21008 ((eq box 'on) "[ ]")
21009 (t "[X]")))
21010 ;; Mimic `org-list-write-struct' but with grabbing
21011 ;; a return value from `org-list-struct-fix-box'.
21012 (org-list-struct-fix-ind struct parents 2)
21013 (org-list-struct-fix-item-end struct)
21014 (org-list-struct-fix-bul struct prevs)
21015 (org-list-struct-fix-ind struct parents)
21016 (let ((block-item
21017 (org-list-struct-fix-box struct parents prevs orderedp)))
21018 (if (and box (equal struct old-struct))
21019 (if (equal arg '(16))
21020 (message "Checkboxes already reset")
21021 (user-error "Cannot toggle this checkbox: %s"
21022 (if (eq box 'on)
21023 "all subitems checked"
21024 "unchecked subitems")))
21025 (org-list-struct-apply-struct struct old-struct)
21026 (org-update-checkbox-count-maybe))
21027 (when block-item
21028 (message "Checkboxes were removed due to empty box at line %d"
21029 (org-current-line block-item))))))
21030 (keyword
21031 (let ((org-inhibit-startup-visibility-stuff t)
21032 (org-startup-align-all-tables nil))
21033 (when (boundp 'org-table-coordinate-overlays)
21034 (mapc 'delete-overlay org-table-coordinate-overlays)
21035 (setq org-table-coordinate-overlays nil))
21036 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21037 (message "Local setup has been refreshed"))
21038 (plain-list
21039 ;; At a plain list, with a double C-u argument, set
21040 ;; checkboxes of each item to "[-]", whereas a single one
21041 ;; will toggle their presence according to the state of the
21042 ;; first item in the list. Without an argument, repair the
21043 ;; list.
21044 (let* ((begin (org-element-property :contents-begin context))
21045 (beginm (move-marker (make-marker) begin))
21046 (struct (org-element-property :structure context))
21047 (old-struct (copy-tree struct))
21048 (first-box (save-excursion
21049 (goto-char begin)
21050 (looking-at org-list-full-item-re)
21051 (match-string-no-properties 3)))
21052 (new-box (cond ((equal arg '(16)) "[-]")
21053 ((equal arg '(4)) (unless first-box "[ ]"))
21054 ((equal first-box "[X]") "[ ]")
21055 (t "[X]"))))
21056 (cond
21057 (arg
21058 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
21059 (org-list-get-all-items
21060 begin struct (org-list-prevs-alist struct))))
21061 ((and first-box (eq (point) begin))
21062 ;; For convenience, when point is at bol on the first
21063 ;; item of the list and no argument is provided, simply
21064 ;; toggle checkbox of that item, if any.
21065 (org-list-set-checkbox begin struct new-box)))
21066 (org-list-write-struct
21067 struct (org-list-parents-alist struct) old-struct)
21068 (org-update-checkbox-count-maybe)
21069 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21070 ((property-drawer node-property)
21071 (call-interactively 'org-property-action))
21072 ((radio-target target)
21073 (call-interactively 'org-update-radio-target-regexp))
21074 (statistics-cookie
21075 (call-interactively 'org-update-statistics-cookies))
21076 ((table table-cell table-row)
21077 ;; At a table, recalculate every field and align it. Also
21078 ;; send the table if necessary. If the table has
21079 ;; a `table.el' type, just give up. At a table row or
21080 ;; cell, maybe recalculate line but always align table.
21081 (if (eq (org-element-property :type context) 'table.el)
21082 (message "Use C-c ' to edit table.el tables")
21083 (let ((org-enable-table-editor t))
21084 (if (or (eq type 'table)
21085 ;; Check if point is at a TBLFM line.
21086 (and (eq type 'table-row)
21087 (= (point) (org-element-property :end context))))
21088 (save-excursion
21089 (if (org-at-TBLFM-p)
21090 (progn (require 'org-table)
21091 (org-table-calc-current-TBLFM))
21092 (goto-char (org-element-property :contents-begin context))
21093 (org-call-with-arg 'org-table-recalculate (or arg t))
21094 (orgtbl-send-table 'maybe)))
21095 (org-table-maybe-eval-formula)
21096 (cond (arg (call-interactively 'org-table-recalculate))
21097 ((org-table-maybe-recalculate-line))
21098 (t (org-table-align)))))))
21099 (timestamp (org-timestamp-change 0 'day))
21100 (otherwise
21101 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21102 (user-error
21103 "C-c C-c can do nothing useful at this location")))))))))
21105 (defun org-mode-restart ()
21106 (interactive)
21107 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21108 (funcall major-mode)
21109 (hack-local-variables)
21110 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21111 (org-indent-mode -1)))
21112 (message "%s restarted" major-mode))
21114 (defun org-kill-note-or-show-branches ()
21115 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21116 (interactive)
21117 (if (not org-finish-function)
21118 (progn
21119 (hide-subtree)
21120 (call-interactively 'show-branches))
21121 (let ((org-note-abort t))
21122 (funcall org-finish-function))))
21124 (defun org-delete-indentation (&optional ARG)
21125 "Join current line to previous and fix whitespace at join.
21127 If previous line is a headline add to headline title. Otherwise
21128 the function calls `delete-indentation'.
21130 With argument, join this line to following line."
21131 (interactive "*P")
21132 (if (save-excursion
21133 (if ARG (beginning-of-line)
21134 (forward-line -1))
21135 (looking-at org-complex-heading-regexp))
21136 ;; At headline.
21137 (let ((tags-column (when (match-beginning 5)
21138 (save-excursion (goto-char (match-beginning 5))
21139 (current-column))))
21140 (string (concat " " (progn (when ARG (forward-line 1))
21141 (org-trim (delete-and-extract-region
21142 (line-beginning-position)
21143 (line-end-position)))))))
21144 (unless (bobp) (delete-region (point) (1- (point))))
21145 (goto-char (or (match-end 4)
21146 (match-beginning 5)
21147 (match-end 0)))
21148 (skip-chars-backward " \t")
21149 (save-excursion (insert string))
21150 ;; Adjust alignment of tags.
21151 (when tags-column
21152 (org-align-tags-here (if org-auto-align-tags
21153 org-tags-column
21154 tags-column))))
21155 (delete-indentation ARG)))
21157 (defun org-open-line (n)
21158 "Insert a new row in tables, call `open-line' elsewhere.
21159 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21160 (interactive "*p")
21161 (cond
21162 ((not org-special-ctrl-o)
21163 (open-line n))
21164 ((org-at-table-p)
21165 (org-table-insert-row))
21167 (open-line n))))
21169 (defun org-return (&optional indent)
21170 "Goto next table row or insert a newline.
21172 Calls `org-table-next-row' or `newline', depending on context.
21174 When optional INDENT argument is non-nil, call
21175 `newline-and-indent' instead of `newline'.
21177 When `org-return-follows-link' is non-nil and point is on
21178 a timestamp or a link, call `org-open-at-point'. However, it
21179 will not happen if point is in a table or on a \"dead\"
21180 object (e.g., within a comment). In these case, you need to use
21181 `org-open-at-point' directly."
21182 (interactive)
21183 (if (and (not (bolp))
21184 (save-excursion (beginning-of-line)
21185 (looking-at org-complex-heading-regexp)))
21186 ;; At headline.
21187 (let ((tags-column (when (match-beginning 5)
21188 (save-excursion (goto-char (match-beginning 5))
21189 (current-column))))
21190 ;; Test if before or after headline title.
21191 (string (when (and (match-end 4)
21192 (not (or (< (point)
21193 (or (match-end 3)
21194 (match-end 2)
21195 (save-excursion
21196 (goto-char (match-beginning 4))
21197 (skip-chars-backward " \t")
21198 (point))))
21199 (and (match-beginning 5)
21200 (>= (point) (match-beginning 5))))))
21201 ;; Point is on headline keywords, tags or cookies. Do not break
21202 ;; them: add a newline after the headline instead.
21203 (org-string-nw-p
21204 (delete-and-extract-region (point) (match-end 4))))))
21205 ;; Adjust alignment of tags.
21206 (when (and tags-column string)
21207 (org-align-tags-here (if org-auto-align-tags
21208 org-tags-column
21209 tags-column)))
21210 (end-of-line)
21211 (org-show-entry)
21212 (if indent (newline-and-indent) (newline))
21213 (and string (save-excursion (insert (org-trim string)))))
21214 (let* ((context (if org-return-follows-link (org-element-context)
21215 (org-element-at-point)))
21216 (type (org-element-type context)))
21217 (cond
21218 ;; In a table, call `org-table-next-row'.
21219 ((or (and (eq type 'table)
21220 (>= (point) (org-element-property :contents-begin context))
21221 (< (point) (org-element-property :contents-end context)))
21222 (org-element-lineage context '(table-row table-cell) t))
21223 (org-table-justify-field-maybe)
21224 (call-interactively #'org-table-next-row))
21225 ;; On a link or a timestamp but not on white spaces after it,
21226 ;; call `org-open-line' if `org-return-follows-link' allows it.
21227 ((and org-return-follows-link
21228 (memq type '(link timestamp))
21229 (< (point)
21230 (save-excursion (goto-char (org-element-property :end context))
21231 (skip-chars-backward " \t")
21232 (point))))
21233 (call-interactively #'org-open-at-point))
21234 ;; In a list, make sure indenting keeps trailing text within.
21235 ((and indent
21236 (not (eolp))
21237 (org-element-lineage context '(item)))
21238 (let ((trailing-data
21239 (delete-and-extract-region (point) (line-end-position))))
21240 (newline-and-indent)
21241 (save-excursion (insert trailing-data))))
21242 (t (if indent (newline-and-indent) (newline)))))))
21244 (defun org-return-indent ()
21245 "Goto next table row or insert a newline and indent.
21246 Calls `org-table-next-row' or `newline-and-indent', depending on
21247 context. See the individual commands for more information."
21248 (interactive)
21249 (org-return t))
21251 (defun org-ctrl-c-star ()
21252 "Compute table, or change heading status of lines.
21253 Calls `org-table-recalculate' or `org-toggle-heading',
21254 depending on context."
21255 (interactive)
21256 (cond
21257 ((org-at-table-p)
21258 (call-interactively 'org-table-recalculate))
21260 ;; Convert all lines in region to list items
21261 (call-interactively 'org-toggle-heading))))
21263 (defun org-ctrl-c-minus ()
21264 "Insert separator line in table or modify bullet status of line.
21265 Also turns a plain line or a region of lines into list items.
21266 Calls `org-table-insert-hline', `org-toggle-item', or
21267 `org-cycle-list-bullet', depending on context."
21268 (interactive)
21269 (cond
21270 ((org-at-table-p)
21271 (call-interactively 'org-table-insert-hline))
21272 ((org-region-active-p)
21273 (call-interactively 'org-toggle-item))
21274 ((org-in-item-p)
21275 (call-interactively 'org-cycle-list-bullet))
21277 (call-interactively 'org-toggle-item))))
21279 (defun org-toggle-item (arg)
21280 "Convert headings or normal lines to items, items to normal lines.
21281 If there is no active region, only the current line is considered.
21283 If the first non blank line in the region is a headline, convert
21284 all headlines to items, shifting text accordingly.
21286 If it is an item, convert all items to normal lines.
21288 If it is normal text, change region into a list of items.
21289 With a prefix argument ARG, change the region in a single item."
21290 (interactive "P")
21291 (let ((shift-text
21292 (function
21293 ;; Shift text in current section to IND, from point to END.
21294 ;; The function leaves point to END line.
21295 (lambda (ind end)
21296 (let ((min-i 1000) (end (copy-marker end)))
21297 ;; First determine the minimum indentation (MIN-I) of
21298 ;; the text.
21299 (save-excursion
21300 (catch 'exit
21301 (while (< (point) end)
21302 (let ((i (org-get-indentation)))
21303 (cond
21304 ;; Skip blank lines and inline tasks.
21305 ((looking-at "^[ \t]*$"))
21306 ((looking-at org-outline-regexp-bol))
21307 ;; We can't find less than 0 indentation.
21308 ((zerop i) (throw 'exit (setq min-i 0)))
21309 ((< i min-i) (setq min-i i))))
21310 (forward-line))))
21311 ;; Then indent each line so that a line indented to
21312 ;; MIN-I becomes indented to IND. Ignore blank lines
21313 ;; and inline tasks in the process.
21314 (let ((delta (- ind min-i)))
21315 (while (< (point) end)
21316 (unless (or (looking-at "^[ \t]*$")
21317 (looking-at org-outline-regexp-bol))
21318 (org-indent-line-to (+ (org-get-indentation) delta)))
21319 (forward-line)))))))
21320 (skip-blanks
21321 (function
21322 ;; Return beginning of first non-blank line, starting from
21323 ;; line at POS.
21324 (lambda (pos)
21325 (save-excursion
21326 (goto-char pos)
21327 (skip-chars-forward " \r\t\n")
21328 (point-at-bol)))))
21329 beg end)
21330 ;; Determine boundaries of changes.
21331 (if (org-region-active-p)
21332 (setq beg (funcall skip-blanks (region-beginning))
21333 end (copy-marker (region-end)))
21334 (setq beg (funcall skip-blanks (point-at-bol))
21335 end (copy-marker (point-at-eol))))
21336 ;; Depending on the starting line, choose an action on the text
21337 ;; between BEG and END.
21338 (org-with-limited-levels
21339 (save-excursion
21340 (goto-char beg)
21341 (cond
21342 ;; Case 1. Start at an item: de-itemize. Note that it only
21343 ;; happens when a region is active: `org-ctrl-c-minus'
21344 ;; would call `org-cycle-list-bullet' otherwise.
21345 ((org-at-item-p)
21346 (while (< (point) end)
21347 (when (org-at-item-p)
21348 (skip-chars-forward " \t")
21349 (delete-region (point) (match-end 0)))
21350 (forward-line)))
21351 ;; Case 2. Start at an heading: convert to items.
21352 ((org-at-heading-p)
21353 (let* ((bul (org-list-bullet-string "-"))
21354 (bul-len (length bul))
21355 (done (org-entry-is-done-p))
21356 (todo (org-entry-is-todo-p))
21357 ;; Indentation of the first heading. It should be
21358 ;; relative to the indentation of its parent, if any.
21359 (start-ind (save-excursion
21360 (cond
21361 ((not org-adapt-indentation) 0)
21362 ((not (outline-previous-heading)) 0)
21363 (t (length (match-string 0))))))
21364 ;; Level of first heading. Further headings will be
21365 ;; compared to it to determine hierarchy in the list.
21366 (ref-level (org-reduced-level (org-outline-level))))
21367 (when (or done todo) (org-todo ""))
21368 (while (< (point) end)
21369 (let* ((level (org-reduced-level (org-outline-level)))
21370 (delta (max 0 (- level ref-level))))
21371 ;; If current headline is less indented than the first
21372 ;; one, set it as reference, in order to preserve
21373 ;; subtrees.
21374 (when (< level ref-level) (setq ref-level level))
21375 (replace-match bul t t)
21376 (org-indent-line-to (+ start-ind (* delta bul-len)))
21377 (when (or done todo)
21378 (let* ((struct (org-list-struct))
21379 (old (copy-tree struct)))
21380 (org-list-set-checkbox (line-beginning-position)
21381 struct
21382 (if done "[X]" "[ ]"))
21383 (org-list-write-struct struct
21384 (org-list-parents-alist struct)
21385 old)))
21386 ;; Ensure all text down to END (or SECTION-END) belongs
21387 ;; to the newly created item.
21388 (let ((section-end (save-excursion
21389 (or (outline-next-heading) (point)))))
21390 (forward-line)
21391 (funcall shift-text
21392 (+ start-ind (* (1+ delta) bul-len))
21393 (min end section-end)))))))
21394 ;; Case 3. Normal line with ARG: make the first line of region
21395 ;; an item, and shift indentation of others lines to
21396 ;; set them as item's body.
21397 (arg (let* ((bul (org-list-bullet-string "-"))
21398 (bul-len (length bul))
21399 (ref-ind (org-get-indentation)))
21400 (skip-chars-forward " \t")
21401 (insert bul)
21402 (forward-line)
21403 (while (< (point) end)
21404 ;; Ensure that lines less indented than first one
21405 ;; still get included in item body.
21406 (funcall shift-text
21407 (+ ref-ind bul-len)
21408 (min end (save-excursion (or (outline-next-heading)
21409 (point)))))
21410 (forward-line))))
21411 ;; Case 4. Normal line without ARG: turn each non-item line
21412 ;; into an item.
21414 (while (< (point) end)
21415 (unless (or (org-at-heading-p) (org-at-item-p))
21416 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21417 (replace-match
21418 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21419 (forward-line))))))))
21421 (defun org-toggle-heading (&optional nstars)
21422 "Convert headings to normal text, or items or text to headings.
21423 If there is no active region, only convert the current line.
21425 With a \\[universal-argument] prefix, convert the whole list at
21426 point into heading.
21428 In a region:
21430 - If the first non blank line is a headline, remove the stars
21431 from all headlines in the region.
21433 - If it is a normal line, turn each and every normal line (i.e.,
21434 not an heading or an item) in the region into headings. If you
21435 want to convert only the first line of this region, use one
21436 universal prefix argument.
21438 - If it is a plain list item, turn all plain list items into headings.
21440 When converting a line into a heading, the number of stars is chosen
21441 such that the lines become children of the current entry. However,
21442 when a numeric prefix argument is given, its value determines the
21443 number of stars to add."
21444 (interactive "P")
21445 (let ((skip-blanks
21446 (function
21447 ;; Return beginning of first non-blank line, starting from
21448 ;; line at POS.
21449 (lambda (pos)
21450 (save-excursion
21451 (goto-char pos)
21452 (while (org-at-comment-p) (forward-line))
21453 (skip-chars-forward " \r\t\n")
21454 (point-at-bol)))))
21455 beg end toggled)
21456 ;; Determine boundaries of changes. If a universal prefix has
21457 ;; been given, put the list in a region. If region ends at a bol,
21458 ;; do not consider the last line to be in the region.
21460 (when (and current-prefix-arg (org-at-item-p))
21461 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21462 (org-mark-element))
21464 (if (org-region-active-p)
21465 (setq beg (funcall skip-blanks (region-beginning))
21466 end (copy-marker (save-excursion
21467 (goto-char (region-end))
21468 (if (bolp) (point) (point-at-eol)))))
21469 (setq beg (funcall skip-blanks (point-at-bol))
21470 end (copy-marker (point-at-eol))))
21471 ;; Ensure inline tasks don't count as headings.
21472 (org-with-limited-levels
21473 (save-excursion
21474 (goto-char beg)
21475 (cond
21476 ;; Case 1. Started at an heading: de-star headings.
21477 ((org-at-heading-p)
21478 (while (< (point) end)
21479 (when (org-at-heading-p t)
21480 (looking-at org-outline-regexp) (replace-match "")
21481 (setq toggled t))
21482 (forward-line)))
21483 ;; Case 2. Started at an item: change items into headlines.
21484 ;; One star will be added by `org-list-to-subtree'.
21485 ((org-at-item-p)
21486 (while (< (point) end)
21487 (when (org-at-item-p)
21488 ;; Pay attention to cases when region ends before list.
21489 (let* ((struct (org-list-struct))
21490 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21491 (save-restriction
21492 (narrow-to-region (point) list-end)
21493 (insert (org-list-to-subtree (org-list-parse-list t)))))
21494 (setq toggled t))
21495 (forward-line)))
21496 ;; Case 3. Started at normal text: make every line an heading,
21497 ;; skipping headlines and items.
21498 (t (let* ((stars
21499 (make-string
21500 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21501 (add-stars
21502 (cond (nstars "") ; stars from prefix only
21503 ((equal stars "") "*") ; before first heading
21504 (org-odd-levels-only "**") ; inside heading, odd
21505 (t "*"))) ; inside heading, oddeven
21506 (rpl (concat stars add-stars " "))
21507 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21508 (while (< (point) (if (equal nstars '(4)) lend end))
21509 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21510 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21511 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21512 (forward-line)))))))
21513 (unless toggled (message "Cannot toggle heading from here"))))
21515 (defun org-meta-return (&optional arg)
21516 "Insert a new heading or wrap a region in a table.
21517 Calls `org-insert-heading' or `org-table-wrap-region', depending
21518 on context. See the individual commands for more information."
21519 (interactive "P")
21520 (org-check-before-invisible-edit 'insert)
21521 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21522 (let* ((element (org-element-at-point))
21523 (type (org-element-type element)))
21524 (when (eq type 'table-row)
21525 (setq element (org-element-property :parent element))
21526 (setq type 'table))
21527 (if (and (eq type 'table)
21528 (eq (org-element-property :type element) 'org)
21529 (>= (point) (org-element-property :contents-begin element))
21530 (< (point) (org-element-property :contents-end element)))
21531 (call-interactively 'org-table-wrap-region)
21532 (call-interactively 'org-insert-heading)))))
21534 ;;; Menu entries
21536 (defsubst org-in-subtree-not-table-p ()
21537 "Are we in a subtree and not in a table?"
21538 (and (not (org-before-first-heading-p))
21539 (not (org-at-table-p))))
21541 ;; Define the Org-mode menus
21542 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21543 '("Tbl"
21544 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21545 ["Next Field" org-cycle (org-at-table-p)]
21546 ["Previous Field" org-shifttab (org-at-table-p)]
21547 ["Next Row" org-return (org-at-table-p)]
21548 "--"
21549 ["Blank Field" org-table-blank-field (org-at-table-p)]
21550 ["Edit Field" org-table-edit-field (org-at-table-p)]
21551 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21552 "--"
21553 ("Column"
21554 ["Move Column Left" org-metaleft (org-at-table-p)]
21555 ["Move Column Right" org-metaright (org-at-table-p)]
21556 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21557 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21558 ("Row"
21559 ["Move Row Up" org-metaup (org-at-table-p)]
21560 ["Move Row Down" org-metadown (org-at-table-p)]
21561 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21562 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21563 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21564 "--"
21565 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21566 ("Rectangle"
21567 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21568 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21569 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21570 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21571 "--"
21572 ("Calculate"
21573 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21574 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21575 ["Edit Formulas" org-edit-special (org-at-table-p)]
21576 "--"
21577 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21578 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21579 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21580 "--"
21581 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21582 "--"
21583 ["Sum Column/Rectangle" org-table-sum
21584 (or (org-at-table-p) (org-region-active-p))]
21585 ["Which Column?" org-table-current-column (org-at-table-p)])
21586 ["Debug Formulas"
21587 org-table-toggle-formula-debugger
21588 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21589 ["Show Col/Row Numbers"
21590 org-table-toggle-coordinate-overlays
21591 :style toggle
21592 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21593 "--"
21594 ["Create" org-table-create (and (not (org-at-table-p))
21595 org-enable-table-editor)]
21596 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21597 ["Import from File" org-table-import (not (org-at-table-p))]
21598 ["Export to File" org-table-export (org-at-table-p)]
21599 "--"
21600 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21601 "--"
21602 ("Plot"
21603 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21604 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21606 (easy-menu-define org-org-menu org-mode-map "Org menu"
21607 '("Org"
21608 ("Show/Hide"
21609 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21610 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21611 ["Sparse Tree..." org-sparse-tree t]
21612 ["Reveal Context" org-reveal t]
21613 ["Show All" show-all t]
21614 "--"
21615 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21616 "--"
21617 ["New Heading" org-insert-heading t]
21618 ("Navigate Headings"
21619 ["Up" outline-up-heading t]
21620 ["Next" outline-next-visible-heading t]
21621 ["Previous" outline-previous-visible-heading t]
21622 ["Next Same Level" outline-forward-same-level t]
21623 ["Previous Same Level" outline-backward-same-level t]
21624 "--"
21625 ["Jump" org-goto t])
21626 ("Edit Structure"
21627 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21628 "--"
21629 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21630 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21631 "--"
21632 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21633 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21634 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21635 "--"
21636 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21637 "--"
21638 ["Copy visible text" org-copy-visible t]
21639 "--"
21640 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21641 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21642 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21643 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21644 "--"
21645 ["Sort Region/Children" org-sort t]
21646 "--"
21647 ["Convert to odd levels" org-convert-to-odd-levels t]
21648 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21649 ("Editing"
21650 ["Emphasis..." org-emphasize t]
21651 ["Edit Source Example" org-edit-special t]
21652 "--"
21653 ["Footnote new/jump" org-footnote-action t]
21654 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21655 ("Archive"
21656 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21657 "--"
21658 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21659 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21660 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21662 "--"
21663 ("Hyperlinks"
21664 ["Store Link (Global)" org-store-link t]
21665 ["Find existing link to here" org-occur-link-in-agenda-files t]
21666 ["Insert Link" org-insert-link t]
21667 ["Follow Link" org-open-at-point t]
21668 "--"
21669 ["Next link" org-next-link t]
21670 ["Previous link" org-previous-link t]
21671 "--"
21672 ["Descriptive Links"
21673 org-toggle-link-display
21674 :style radio
21675 :selected org-descriptive-links
21677 ["Literal Links"
21678 org-toggle-link-display
21679 :style radio
21680 :selected (not org-descriptive-links)])
21681 "--"
21682 ("TODO Lists"
21683 ["TODO/DONE/-" org-todo t]
21684 ("Select keyword"
21685 ["Next keyword" org-shiftright (org-at-heading-p)]
21686 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21687 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21688 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21689 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21690 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21691 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21692 "--"
21693 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21694 :selected org-enforce-todo-dependencies :style toggle :active t]
21695 "Settings for tree at point"
21696 ["Do Children sequentially" org-toggle-ordered-property :style radio
21697 :selected (org-entry-get nil "ORDERED")
21698 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21699 ["Do Children parallel" org-toggle-ordered-property :style radio
21700 :selected (not (org-entry-get nil "ORDERED"))
21701 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21702 "--"
21703 ["Set Priority" org-priority t]
21704 ["Priority Up" org-shiftup t]
21705 ["Priority Down" org-shiftdown t]
21706 "--"
21707 ["Get news from all feeds" org-feed-update-all t]
21708 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21709 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21710 ("TAGS and Properties"
21711 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21712 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21713 "--"
21714 ["Set property" org-set-property (not (org-before-first-heading-p))]
21715 ["Column view of properties" org-columns t]
21716 ["Insert Column View DBlock" org-insert-columns-dblock t])
21717 ("Dates and Scheduling"
21718 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21719 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21720 ("Change Date"
21721 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21722 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21723 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21724 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21725 ["Compute Time Range" org-evaluate-time-range t]
21726 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21727 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21728 "--"
21729 ["Custom time format" org-toggle-time-stamp-overlays
21730 :style radio :selected org-display-custom-times]
21731 "--"
21732 ["Goto Calendar" org-goto-calendar t]
21733 ["Date from Calendar" org-date-from-calendar t]
21734 "--"
21735 ["Start/Restart Timer" org-timer-start t]
21736 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21737 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21738 ["Insert Timer String" org-timer t]
21739 ["Insert Timer Item" org-timer-item t])
21740 ("Logging work"
21741 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21742 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21743 ["Clock out" org-clock-out t]
21744 ["Clock cancel" org-clock-cancel t]
21745 "--"
21746 ["Mark as default task" org-clock-mark-default-task t]
21747 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21748 ["Goto running clock" org-clock-goto t]
21749 "--"
21750 ["Display times" org-clock-display t]
21751 ["Create clock table" org-clock-report t]
21752 "--"
21753 ["Record DONE time"
21754 (progn (setq org-log-done (not org-log-done))
21755 (message "Switching to %s will %s record a timestamp"
21756 (car org-done-keywords)
21757 (if org-log-done "automatically" "not")))
21758 :style toggle :selected org-log-done])
21759 "--"
21760 ["Agenda Command..." org-agenda t]
21761 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21762 ("File List for Agenda")
21763 ("Special views current file"
21764 ["TODO Tree" org-show-todo-tree t]
21765 ["Check Deadlines" org-check-deadlines t]
21766 ["Timeline" org-timeline t]
21767 ["Tags/Property tree" org-match-sparse-tree t])
21768 "--"
21769 ["Export/Publish..." org-export-dispatch t]
21770 ("LaTeX"
21771 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21772 :selected org-cdlatex-mode]
21773 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21774 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21775 ["Modify math symbol" org-cdlatex-math-modify
21776 (org-inside-LaTeX-fragment-p)]
21777 ["Insert citation" org-reftex-citation t]
21778 "--"
21779 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21780 "--"
21781 ("MobileOrg"
21782 ["Push Files and Views" org-mobile-push t]
21783 ["Get Captured and Flagged" org-mobile-pull t]
21784 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21785 "--"
21786 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21787 "--"
21788 ("Documentation"
21789 ["Show Version" org-version t]
21790 ["Info Documentation" org-info t])
21791 ("Customize"
21792 ["Browse Org Group" org-customize t]
21793 "--"
21794 ["Expand This Menu" org-create-customize-menu
21795 (fboundp 'customize-menu-create)])
21796 ["Send bug report" org-submit-bug-report t]
21797 "--"
21798 ("Refresh/Reload"
21799 ["Refresh setup current buffer" org-mode-restart t]
21800 ["Reload Org (after update)" org-reload t]
21801 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21804 (defun org-info (&optional node)
21805 "Read documentation for Org-mode in the info system.
21806 With optional NODE, go directly to that node."
21807 (interactive)
21808 (info (format "(org)%s" (or node ""))))
21810 ;;;###autoload
21811 (defun org-submit-bug-report ()
21812 "Submit a bug report on Org-mode via mail.
21814 Don't hesitate to report any problems or inaccurate documentation.
21816 If you don't have setup sending mail from (X)Emacs, please copy the
21817 output buffer into your mail program, as it gives us important
21818 information about your Org-mode version and configuration."
21819 (interactive)
21820 (require 'reporter)
21821 (org-load-modules-maybe)
21822 (org-require-autoloaded-modules)
21823 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21824 (reporter-submit-bug-report
21825 "emacs-orgmode@gnu.org"
21826 (org-version nil 'full)
21827 (let (list)
21828 (save-window-excursion
21829 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21830 (delete-other-windows)
21831 (erase-buffer)
21832 (insert "You are about to submit a bug report to the Org-mode mailing list.
21834 We would like to add your full Org-mode and Outline configuration to the
21835 bug report. This greatly simplifies the work of the maintainer and
21836 other experts on the mailing list.
21838 HOWEVER, some variables you have customized may contain private
21839 information. The names of customers, colleagues, or friends, might
21840 appear in the form of file names, tags, todo states, or search strings.
21841 If you answer yes to the prompt, you might want to check and remove
21842 such private information before sending the email.")
21843 (add-text-properties (point-min) (point-max) '(face org-warning))
21844 (when (yes-or-no-p "Include your Org-mode configuration ")
21845 (mapatoms
21846 (lambda (v)
21847 (and (boundp v)
21848 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21849 (or (and (symbol-value v)
21850 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21851 (and
21852 (get v 'custom-type) (get v 'standard-value)
21853 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21854 (push v list)))))
21855 (kill-buffer (get-buffer "*Warn about privacy*"))
21856 list))
21857 nil nil
21858 "Remember to cover the basics, that is, what you expected to happen and
21859 what in fact did happen. You don't know how to make a good report? See
21861 http://orgmode.org/manual/Feedback.html#Feedback
21863 Your bug report will be posted to the Org-mode mailing list.
21864 ------------------------------------------------------------------------")
21865 (save-excursion
21866 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21867 (replace-match "\\1Bug: \\3 [\\2]")))))
21870 (defun org-install-agenda-files-menu ()
21871 (let ((bl (buffer-list)))
21872 (save-excursion
21873 (while bl
21874 (set-buffer (pop bl))
21875 (if (derived-mode-p 'org-mode) (setq bl nil)))
21876 (when (derived-mode-p 'org-mode)
21877 (easy-menu-change
21878 '("Org") "File List for Agenda"
21879 (append
21880 (list
21881 ["Edit File List" (org-edit-agenda-file-list) t]
21882 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21883 ["Remove Current File from List" org-remove-file t]
21884 ["Cycle through agenda files" org-cycle-agenda-files t]
21885 ["Occur in all agenda files" org-occur-in-agenda-files t]
21886 "--")
21887 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21889 ;;;; Documentation
21891 (defun org-require-autoloaded-modules ()
21892 (interactive)
21893 (mapc 'require
21894 '(org-agenda org-archive org-attach org-clock org-colview org-id
21895 org-table org-timer)))
21897 ;;;###autoload
21898 (defun org-reload (&optional uncompiled)
21899 "Reload all org lisp files.
21900 With prefix arg UNCOMPILED, load the uncompiled versions."
21901 (interactive "P")
21902 (require 'loadhist)
21903 (let* ((org-dir (org-find-library-dir "org"))
21904 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21905 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21906 (remove-re (mapconcat 'identity
21907 (mapcar (lambda (f) (concat "^" f "$"))
21908 (list (if (featurep 'xemacs)
21909 "org-colview"
21910 "org-colview-xemacs")
21911 "org" "org-loaddefs" "org-version"))
21912 "\\|"))
21913 (feats (delete-dups
21914 (mapcar 'file-name-sans-extension
21915 (mapcar 'file-name-nondirectory
21916 (delq nil
21917 (mapcar 'feature-file
21918 features))))))
21919 (lfeat (append
21920 (sort
21921 (setq feats
21922 (delq nil (mapcar
21923 (lambda (f)
21924 (if (and (string-match feature-re f)
21925 (not (string-match remove-re f)))
21926 f nil))
21927 feats)))
21928 'string-lessp)
21929 (list "org-version" "org")))
21930 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21931 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21932 load-uncore load-misses)
21933 (setq load-misses
21934 (delq 't
21935 (mapcar (lambda (f)
21936 (or (org-load-noerror-mustsuffix (concat org-dir f))
21937 (and (string= org-dir contrib-dir)
21938 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21939 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21940 (add-to-list 'load-uncore f 'append)
21943 lfeat)))
21944 (if load-uncore
21945 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21946 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21947 (if load-misses
21948 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21949 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21950 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21952 ;;;###autoload
21953 (defun org-customize ()
21954 "Call the customize function with org as argument."
21955 (interactive)
21956 (org-load-modules-maybe)
21957 (org-require-autoloaded-modules)
21958 (customize-browse 'org))
21960 (defun org-create-customize-menu ()
21961 "Create a full customization menu for Org-mode, insert it into the menu."
21962 (interactive)
21963 (org-load-modules-maybe)
21964 (org-require-autoloaded-modules)
21965 (if (fboundp 'customize-menu-create)
21966 (progn
21967 (easy-menu-change
21968 '("Org") "Customize"
21969 `(["Browse Org group" org-customize t]
21970 "--"
21971 ,(customize-menu-create 'org)
21972 ["Set" Custom-set t]
21973 ["Save" Custom-save t]
21974 ["Reset to Current" Custom-reset-current t]
21975 ["Reset to Saved" Custom-reset-saved t]
21976 ["Reset to Standard Settings" Custom-reset-standard t]))
21977 (message "\"Org\"-menu now contains full customization menu"))
21978 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21980 ;;;; Miscellaneous stuff
21982 ;;; Generally useful functions
21984 (defsubst org-get-at-eol (property n)
21985 "Get text property PROPERTY at the end of line less N characters."
21986 (get-text-property (- (point-at-eol) n) property))
21988 (defun org-find-text-property-in-string (prop s)
21989 "Return the first non-nil value of property PROP in string S."
21990 (or (get-text-property 0 prop s)
21991 (get-text-property (or (next-single-property-change 0 prop s) 0)
21992 prop s)))
21994 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21995 "Display the given MESSAGE as a warning."
21996 (if (fboundp 'display-warning)
21997 (display-warning 'org message
21998 (if (featurep 'xemacs) 'warning :warning))
21999 (let ((buf (get-buffer-create "*Org warnings*")))
22000 (with-current-buffer buf
22001 (goto-char (point-max))
22002 (insert "Warning (Org): " message)
22003 (unless (bolp)
22004 (newline)))
22005 (display-buffer buf)
22006 (sit-for 0))))
22008 (defun org-eval (form)
22009 "Eval FORM and return result."
22010 (condition-case error
22011 (eval form)
22012 (error (format "%%![Error: %s]" error))))
22014 (defun org-in-clocktable-p ()
22015 "Check if the cursor is in a clocktable."
22016 (let ((pos (point)) start)
22017 (save-excursion
22018 (end-of-line 1)
22019 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22020 (setq start (match-beginning 0))
22021 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22022 (>= (match-end 0) pos)
22023 start))))
22025 (defun org-in-verbatim-emphasis ()
22026 (save-match-data
22027 (and (org-in-regexp org-emph-re 2)
22028 (>= (point) (match-beginning 3))
22029 (<= (point) (match-end 4))
22030 (member (match-string 3) '("=" "~")))))
22032 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22033 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22034 (if (and marker (marker-buffer marker)
22035 (buffer-live-p (marker-buffer marker)))
22036 (progn
22037 (org-pop-to-buffer-same-window (marker-buffer marker))
22038 (if (or (> marker (point-max)) (< marker (point-min)))
22039 (widen))
22040 (goto-char marker)
22041 (org-show-context 'org-goto))
22042 (if bookmark
22043 (bookmark-jump bookmark)
22044 (error "Cannot find location"))))
22046 (defun org-quote-csv-field (s)
22047 "Quote field for inclusion in CSV material."
22048 (if (string-match "[\",]" s)
22049 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22052 (defun org-force-self-insert (N)
22053 "Needed to enforce self-insert under remapping."
22054 (interactive "p")
22055 (self-insert-command N))
22057 (defun org-string-width (s)
22058 "Compute width of string, ignoring invisible characters.
22059 This ignores character with invisibility property `org-link', and also
22060 characters with property `org-cwidth', because these will become invisible
22061 upon the next fontification round."
22062 (let (b l)
22063 (when (or (eq t buffer-invisibility-spec)
22064 (assq 'org-link buffer-invisibility-spec))
22065 (while (setq b (text-property-any 0 (length s)
22066 'invisible 'org-link s))
22067 (setq s (concat (substring s 0 b)
22068 (substring s (or (next-single-property-change
22069 b 'invisible s) (length s)))))))
22070 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22071 (setq s (concat (substring s 0 b)
22072 (substring s (or (next-single-property-change
22073 b 'org-cwidth s) (length s))))))
22074 (setq l (string-width s) b -1)
22075 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22076 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22079 (defun org-shorten-string (s maxlength)
22080 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22081 If the string is shorter or has length MAXLENGTH, just return the
22082 original string. If it is longer, the functions finds a space in the
22083 string, breaks this string off at that locations and adds three dots
22084 as ellipsis. Including the ellipsis, the string will not be longer
22085 than MAXLENGTH. If finding a good breaking point in the string does
22086 not work, the string is just chopped off in the middle of a word
22087 if necessary."
22088 (if (<= (length s) maxlength)
22090 (let* ((n (max (- maxlength 4) 1))
22091 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22092 (if (string-match re s)
22093 (concat (match-string 1 s) "...")
22094 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22096 (defun org-get-indentation (&optional line)
22097 "Get the indentation of the current line, interpreting tabs.
22098 When LINE is given, assume it represents a line and compute its indentation."
22099 (if line
22100 (if (string-match "^ *" (org-remove-tabs line))
22101 (match-end 0))
22102 (save-excursion
22103 (beginning-of-line 1)
22104 (skip-chars-forward " \t")
22105 (current-column))))
22107 (defun org-get-string-indentation (s)
22108 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22109 (let ((n -1) (i 0) (w tab-width) c)
22110 (catch 'exit
22111 (while (< (setq n (1+ n)) (length s))
22112 (setq c (aref s n))
22113 (cond ((= c ?\ ) (setq i (1+ i)))
22114 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22115 (t (throw 'exit t)))))
22118 (defun org-remove-tabs (s &optional width)
22119 "Replace tabulators in S with spaces.
22120 Assumes that s is a single line, starting in column 0."
22121 (setq width (or width tab-width))
22122 (while (string-match "\t" s)
22123 (setq s (replace-match
22124 (make-string
22125 (- (* width (/ (+ (match-beginning 0) width) width))
22126 (match-beginning 0)) ?\ )
22127 t t s)))
22130 (defun org-fix-indentation (line ind)
22131 "Fix indentation in LINE.
22132 IND is a cons cell with target and minimum indentation.
22133 If the current indentation in LINE is smaller than the minimum,
22134 leave it alone. If it is larger than ind, set it to the target."
22135 (let* ((l (org-remove-tabs line))
22136 (i (org-get-indentation l))
22137 (i1 (car ind)) (i2 (cdr ind)))
22138 (if (>= i i2) (setq l (substring line i2)))
22139 (if (> i1 0)
22140 (concat (make-string i1 ?\ ) l)
22141 l)))
22143 (defun org-remove-indentation (code &optional n)
22144 "Remove the maximum common indentation from the lines in CODE.
22145 N may optionally be the number of spaces to remove."
22146 (with-temp-buffer
22147 (insert code)
22148 (org-do-remove-indentation n)
22149 (buffer-string)))
22151 (defun org-do-remove-indentation (&optional n)
22152 "Remove the maximum common indentation from the buffer."
22153 (untabify (point-min) (point-max))
22154 (let ((min 10000) re)
22155 (if n
22156 (setq min n)
22157 (goto-char (point-min))
22158 (while (re-search-forward "^ *[^ \n]" nil t)
22159 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
22160 (unless (or (= min 0) (= min 10000))
22161 (setq re (format "^ \\{%d\\}" min))
22162 (goto-char (point-min))
22163 (while (re-search-forward re nil t)
22164 (replace-match "")
22165 (end-of-line 1))
22166 min)))
22168 (defun org-fill-template (template alist)
22169 "Find each %key of ALIST in TEMPLATE and replace it."
22170 (let ((case-fold-search nil)
22171 entry key value)
22172 (setq alist (sort (copy-sequence alist)
22173 (lambda (a b) (< (length (car a)) (length (car b))))))
22174 (while (setq entry (pop alist))
22175 (setq template
22176 (replace-regexp-in-string
22177 (concat "%" (regexp-quote (car entry)))
22178 (or (cdr entry) "") template t t)))
22179 template))
22181 (defun org-base-buffer (buffer)
22182 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22183 (if (not buffer)
22184 buffer
22185 (or (buffer-base-buffer buffer)
22186 buffer)))
22188 (defun org-wrap (string &optional width lines)
22189 "Wrap string to either a number of lines, or a width in characters.
22190 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22191 that costs. If there is a word longer than WIDTH, the text is actually
22192 wrapped to the length of that word.
22193 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22194 many lines, whatever width that takes.
22195 The return value is a list of lines, without newlines at the end."
22196 (let* ((words (org-split-string string "[ \t\n]+"))
22197 (maxword (apply 'max (mapcar 'org-string-width words)))
22198 w ll)
22199 (cond (width
22200 (org-do-wrap words (max maxword width)))
22201 (lines
22202 (setq w maxword)
22203 (setq ll (org-do-wrap words maxword))
22204 (if (<= (length ll) lines)
22206 (setq ll words)
22207 (while (> (length ll) lines)
22208 (setq w (1+ w))
22209 (setq ll (org-do-wrap words w)))
22210 ll))
22211 (t (error "Cannot wrap this")))))
22213 (defun org-do-wrap (words width)
22214 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22215 (let (lines line)
22216 (while words
22217 (setq line (pop words))
22218 (while (and words (< (+ (length line) (length (car words))) width))
22219 (setq line (concat line " " (pop words))))
22220 (setq lines (push line lines)))
22221 (nreverse lines)))
22223 (defun org-split-string (string &optional separators)
22224 "Splits STRING into substrings at SEPARATORS.
22225 No empty strings are returned if there are matches at the beginning
22226 and end of string."
22227 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
22228 (start 0)
22229 notfirst
22230 (list nil))
22231 (while (and (string-match rexp string
22232 (if (and notfirst
22233 (= start (match-beginning 0))
22234 (< start (length string)))
22235 (1+ start) start))
22236 (< (match-beginning 0) (length string)))
22237 (setq notfirst t)
22238 (or (eq (match-beginning 0) 0)
22239 (and (eq (match-beginning 0) (match-end 0))
22240 (eq (match-beginning 0) start))
22241 (setq list
22242 (cons (substring string start (match-beginning 0))
22243 list)))
22244 (setq start (match-end 0)))
22245 (or (eq start (length string))
22246 (setq list
22247 (cons (substring string start)
22248 list)))
22249 (nreverse list)))
22251 (defun org-quote-vert (s)
22252 "Replace \"|\" with \"\\vert\"."
22253 (while (string-match "|" s)
22254 (setq s (replace-match "\\vert" t t s)))
22257 (defun org-uuidgen-p (s)
22258 "Is S an ID created by UUIDGEN?"
22259 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22261 (defun org-in-src-block-p (&optional inside)
22262 "Whether point is in a code source block.
22263 When INSIDE is non-nil, don't consider we are within a src block
22264 when point is at #+BEGIN_SRC or #+END_SRC."
22265 (let ((case-fold-search t) ov)
22266 (or (and (eq (get-char-property (point) 'src-block) t))
22267 (and (not inside)
22268 (save-match-data
22269 (save-excursion
22270 (beginning-of-line)
22271 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22273 (defun org-context ()
22274 "Return a list of contexts of the current cursor position.
22275 If several contexts apply, all are returned.
22276 Each context entry is a list with a symbol naming the context, and
22277 two positions indicating start and end of the context. Possible
22278 contexts are:
22280 :headline anywhere in a headline
22281 :headline-stars on the leading stars in a headline
22282 :todo-keyword on a TODO keyword (including DONE) in a headline
22283 :tags on the TAGS in a headline
22284 :priority on the priority cookie in a headline
22285 :item on the first line of a plain list item
22286 :item-bullet on the bullet/number of a plain list item
22287 :checkbox on the checkbox in a plain list item
22288 :table in an org-mode table
22289 :table-special on a special filed in a table
22290 :table-table in a table.el table
22291 :clocktable in a clocktable
22292 :src-block in a source block
22293 :link on a hyperlink
22294 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22295 :target on a <<target>>
22296 :radio-target on a <<<radio-target>>>
22297 :latex-fragment on a LaTeX fragment
22298 :latex-preview on a LaTeX fragment with overlaid preview image
22300 This function expects the position to be visible because it uses font-lock
22301 faces as a help to recognize the following contexts: :table-special, :link,
22302 and :keyword."
22303 (let* ((f (get-text-property (point) 'face))
22304 (faces (if (listp f) f (list f)))
22305 (case-fold-search t)
22306 (p (point)) clist o)
22307 ;; First the large context
22308 (cond
22309 ((org-at-heading-p t)
22310 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22311 (when (progn
22312 (beginning-of-line 1)
22313 (looking-at org-todo-line-tags-regexp))
22314 (push (org-point-in-group p 1 :headline-stars) clist)
22315 (push (org-point-in-group p 2 :todo-keyword) clist)
22316 (push (org-point-in-group p 4 :tags) clist))
22317 (goto-char p)
22318 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22319 (if (looking-at "\\[#[A-Z0-9]\\]")
22320 (push (org-point-in-group p 0 :priority) clist)))
22322 ((org-at-item-p)
22323 (push (org-point-in-group p 2 :item-bullet) clist)
22324 (push (list :item (point-at-bol)
22325 (save-excursion (org-end-of-item) (point)))
22326 clist)
22327 (and (org-at-item-checkbox-p)
22328 (push (org-point-in-group p 0 :checkbox) clist)))
22330 ((org-at-table-p)
22331 (push (list :table (org-table-begin) (org-table-end)) clist)
22332 (if (memq 'org-formula faces)
22333 (push (list :table-special
22334 (previous-single-property-change p 'face)
22335 (next-single-property-change p 'face)) clist)))
22336 ((org-at-table-p 'any)
22337 (push (list :table-table) clist)))
22338 (goto-char p)
22340 (let ((case-fold-search t))
22341 ;; New the "medium" contexts: clocktables, source blocks
22342 (cond ((org-in-clocktable-p)
22343 (push (list :clocktable
22344 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22345 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22346 (match-beginning 1))
22347 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22348 (match-end 0))) clist))
22349 ((org-in-src-block-p)
22350 (push (list :src-block
22351 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22352 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22353 (match-beginning 1))
22354 (and (search-forward "#+END_SRC" nil t)
22355 (match-beginning 0))) clist))))
22356 (goto-char p)
22358 ;; Now the small context
22359 (cond
22360 ((org-at-timestamp-p)
22361 (push (org-point-in-group p 0 :timestamp) clist))
22362 ((memq 'org-link faces)
22363 (push (list :link
22364 (previous-single-property-change p 'face)
22365 (next-single-property-change p 'face)) clist))
22366 ((memq 'org-special-keyword faces)
22367 (push (list :keyword
22368 (previous-single-property-change p 'face)
22369 (next-single-property-change p 'face)) clist))
22370 ((org-at-target-p)
22371 (push (org-point-in-group p 0 :target) clist)
22372 (goto-char (1- (match-beginning 0)))
22373 (if (looking-at org-radio-target-regexp)
22374 (push (org-point-in-group p 0 :radio-target) clist))
22375 (goto-char p))
22376 ((setq o (car (delq nil
22377 (mapcar
22378 (lambda (x)
22379 (if (memq x org-latex-fragment-image-overlays) x))
22380 (overlays-at (point))))))
22381 (push (list :latex-fragment
22382 (overlay-start o) (overlay-end o)) clist)
22383 (push (list :latex-preview
22384 (overlay-start o) (overlay-end o)) clist))
22385 ((org-inside-LaTeX-fragment-p)
22386 ;; FIXME: positions wrong.
22387 (push (list :latex-fragment (point) (point)) clist)))
22389 (setq clist (nreverse (delq nil clist)))
22390 clist))
22392 (defun org-in-regexp (re &optional nlines visually)
22393 "Check if point is inside a match of RE.
22395 Normally only the current line is checked, but you can include
22396 NLINES extra lines after point into the search. If VISUALLY is
22397 set, require that the cursor is not after the match but really
22398 on, so that the block visually is on the match."
22399 (catch 'exit
22400 (let ((pos (point))
22401 (eol (point-at-eol (+ 1 (or nlines 0))))
22402 (inc (if visually 1 0)))
22403 (save-excursion
22404 (beginning-of-line (- 1 (or nlines 0)))
22405 (while (re-search-forward re eol t)
22406 (if (and (<= (match-beginning 0) pos)
22407 (>= (+ inc (match-end 0)) pos))
22408 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
22409 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22410 "Org mode 8.3")
22412 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22413 "Non-nil when point is between matches of START-RE and END-RE.
22415 Also return a non-nil value when point is on one of the matches.
22417 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22418 buffer positions. Default values are the positions of headlines
22419 surrounding the point.
22421 The functions returns a cons cell whose car (resp. cdr) is the
22422 position before START-RE (resp. after END-RE)."
22423 (save-match-data
22424 (let ((pos (point))
22425 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22426 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22427 beg end)
22428 (save-excursion
22429 ;; Point is on a block when on START-RE or if START-RE can be
22430 ;; found before it...
22431 (and (or (org-in-regexp start-re)
22432 (re-search-backward start-re limit-up t))
22433 (setq beg (match-beginning 0))
22434 ;; ... and END-RE after it...
22435 (goto-char (match-end 0))
22436 (re-search-forward end-re limit-down t)
22437 (> (setq end (match-end 0)) pos)
22438 ;; ... without another START-RE in-between.
22439 (goto-char (match-beginning 0))
22440 (not (re-search-backward start-re (1+ beg) t))
22441 ;; Return value.
22442 (cons beg end))))))
22444 (defun org-in-block-p (names)
22445 "Non-nil when point belongs to a block whose name belongs to NAMES.
22447 NAMES is a list of strings containing names of blocks.
22449 Return first block name matched, or nil. Beware that in case of
22450 nested blocks, the returned name may not belong to the closest
22451 block from point."
22452 (save-match-data
22453 (catch 'exit
22454 (let ((case-fold-search t)
22455 (lim-up (save-excursion (outline-previous-heading)))
22456 (lim-down (save-excursion (outline-next-heading))))
22457 (mapc (lambda (name)
22458 (let ((n (regexp-quote name)))
22459 (when (org-between-regexps-p
22460 (concat "^[ \t]*#\\+begin_" n)
22461 (concat "^[ \t]*#\\+end_" n)
22462 lim-up lim-down)
22463 (throw 'exit n))))
22464 names))
22465 nil)))
22467 (defun org-occur-in-agenda-files (regexp &optional nlines)
22468 "Call `multi-occur' with buffers for all agenda files."
22469 (interactive "sOrg-files matching: \np")
22470 (let* ((files (org-agenda-files))
22471 (tnames (mapcar 'file-truename files))
22472 (extra org-agenda-text-search-extra-files)
22474 (when (eq (car extra) 'agenda-archives)
22475 (setq extra (cdr extra))
22476 (setq files (org-add-archive-files files)))
22477 (while (setq f (pop extra))
22478 (unless (member (file-truename f) tnames)
22479 (add-to-list 'files f 'append)
22480 (add-to-list 'tnames (file-truename f) 'append)))
22481 (multi-occur
22482 (mapcar (lambda (x)
22483 (with-current-buffer
22484 (or (get-file-buffer x) (find-file-noselect x))
22485 (widen)
22486 (current-buffer)))
22487 files)
22488 regexp)))
22490 (if (boundp 'occur-mode-find-occurrence-hook)
22491 ;; Emacs 23
22492 (add-hook 'occur-mode-find-occurrence-hook
22493 (lambda ()
22494 (when (derived-mode-p 'org-mode)
22495 (org-reveal))))
22496 ;; Emacs 22
22497 (defadvice occur-mode-goto-occurrence
22498 (after org-occur-reveal activate)
22499 (and (derived-mode-p 'org-mode) (org-reveal)))
22500 (defadvice occur-mode-goto-occurrence-other-window
22501 (after org-occur-reveal activate)
22502 (and (derived-mode-p 'org-mode) (org-reveal)))
22503 (defadvice occur-mode-display-occurrence
22504 (after org-occur-reveal activate)
22505 (when (derived-mode-p 'org-mode)
22506 (let ((pos (occur-mode-find-occurrence)))
22507 (with-current-buffer (marker-buffer pos)
22508 (save-excursion
22509 (goto-char pos)
22510 (org-reveal)))))))
22512 (defun org-occur-link-in-agenda-files ()
22513 "Create a link and search for it in the agendas.
22514 The link is not stored in `org-stored-links', it is just created
22515 for the search purpose."
22516 (interactive)
22517 (let ((link (condition-case nil
22518 (org-store-link nil)
22519 (error "Unable to create a link to here"))))
22520 (org-occur-in-agenda-files (regexp-quote link))))
22522 (defun org-reverse-string (string)
22523 "Return the reverse of STRING."
22524 (apply 'string (reverse (string-to-list string))))
22526 ;; defsubst org-uniquify must be defined before first use
22528 (defun org-uniquify-alist (alist)
22529 "Merge elements of ALIST with the same key.
22531 For example, in this alist:
22533 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22534 => '((a 1 3) (b 2))
22536 merge (a 1) and (a 3) into (a 1 3).
22538 The function returns the new ALIST."
22539 (let (rtn)
22540 (mapc
22541 (lambda (e)
22542 (let (n)
22543 (if (not (assoc (car e) rtn))
22544 (push e rtn)
22545 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22546 (setq rtn (assq-delete-all (car e) rtn))
22547 (push n rtn))))
22548 alist)
22549 rtn))
22551 (defun org-delete-all (elts list)
22552 "Remove all elements in ELTS from LIST."
22553 (while elts
22554 (setq list (delete (pop elts) list)))
22555 list)
22557 (defun org-count (cl-item cl-seq)
22558 "Count the number of occurrences of ITEM in SEQ.
22559 Taken from `count' in cl-seq.el with all keyword arguments removed."
22560 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22561 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22562 (while (< cl-start cl-end)
22563 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22564 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22565 (setq cl-start (1+ cl-start)))
22566 cl-count))
22568 (defun org-remove-if (predicate seq)
22569 "Remove everything from SEQ that fulfills PREDICATE."
22570 (let (res e)
22571 (while seq
22572 (setq e (pop seq))
22573 (if (not (funcall predicate e)) (push e res)))
22574 (nreverse res)))
22576 (defun org-remove-if-not (predicate seq)
22577 "Remove everything from SEQ that does not fulfill PREDICATE."
22578 (let (res e)
22579 (while seq
22580 (setq e (pop seq))
22581 (if (funcall predicate e) (push e res)))
22582 (nreverse res)))
22584 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22585 "Reduce two-argument FUNCTION across SEQ.
22586 Taken from `reduce' in cl-seq.el with all keyword arguments but
22587 \":initial-value\" removed."
22588 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22589 (cadr (memq :initial-value cl-keys)))
22590 (cl-seq (pop cl-seq))
22591 (t (funcall cl-func)))))
22592 (while cl-seq
22593 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22594 cl-accum))
22596 (defun org-every (pred seq)
22597 "Return true if PREDICATE is true of every element of SEQ.
22598 Adapted from `every' in cl.el."
22599 (catch 'org-every
22600 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22603 (defun org-some (pred seq)
22604 "Return true if PREDICATE is true of any element of SEQ.
22605 Adapted from `some' in cl.el."
22606 (catch 'org-some
22607 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22608 nil))
22610 (defun org-back-over-empty-lines ()
22611 "Move backwards over whitespace, to the beginning of the first empty line.
22612 Returns the number of empty lines passed."
22613 (let ((pos (point)))
22614 (if (cdr (assoc 'heading org-blank-before-new-entry))
22615 (skip-chars-backward " \t\n\r")
22616 (unless (eobp)
22617 (forward-line -1)))
22618 (beginning-of-line 2)
22619 (goto-char (min (point) pos))
22620 (count-lines (point) pos)))
22622 (defun org-skip-whitespace ()
22623 (skip-chars-forward " \t\n\r"))
22625 (defun org-point-in-group (point group &optional context)
22626 "Check if POINT is in match-group GROUP.
22627 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22628 match. If the match group does not exist or point is not inside it,
22629 return nil."
22630 (and (match-beginning group)
22631 (>= point (match-beginning group))
22632 (<= point (match-end group))
22633 (if context
22634 (list context (match-beginning group) (match-end group))
22635 t)))
22637 (defun org-switch-to-buffer-other-window (&rest args)
22638 "Switch to buffer in a second window on the current frame.
22639 In particular, do not allow pop-up frames.
22640 Returns the newly created buffer."
22641 (org-no-popups
22642 (apply 'switch-to-buffer-other-window args)))
22644 (defun org-combine-plists (&rest plists)
22645 "Create a single property list from all plists in PLISTS.
22646 The process starts by copying the first list, and then setting properties
22647 from the other lists. Settings in the last list are the most significant
22648 ones and overrule settings in the other lists."
22649 (let ((rtn (copy-sequence (pop plists)))
22650 p v ls)
22651 (while plists
22652 (setq ls (pop plists))
22653 (while ls
22654 (setq p (pop ls) v (pop ls))
22655 (setq rtn (plist-put rtn p v))))
22656 rtn))
22658 (defun org-replace-escapes (string table)
22659 "Replace %-escapes in STRING with values in TABLE.
22660 TABLE is an association list with keys like \"%a\" and string values.
22661 The sequences in STRING may contain normal field width and padding information,
22662 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22663 so values can contain further %-escapes if they are define later in TABLE."
22664 (let ((tbl (copy-alist table))
22665 (case-fold-search nil)
22666 (pchg 0)
22667 e re rpl)
22668 (while (setq e (pop tbl))
22669 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22670 (when (and (cdr e) (string-match re (cdr e)))
22671 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22672 (safe "SREF"))
22673 (add-text-properties 0 3 (list 'sref sref) safe)
22674 (setcdr e (replace-match safe t t (cdr e)))))
22675 (while (string-match re string)
22676 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22677 (cdr e)))
22678 (setq string (replace-match rpl t t string))))
22679 (while (setq pchg (next-property-change pchg string))
22680 (let ((sref (get-text-property pchg 'sref string)))
22681 (when (and sref (string-match "SREF" string pchg))
22682 (setq string (replace-match sref t t string)))))
22683 string))
22685 (defun org-sublist (list start end)
22686 "Return a section of LIST, from START to END.
22687 Counting starts at 1."
22688 (let (rtn (c start))
22689 (setq list (nthcdr (1- start) list))
22690 (while (and list (<= c end))
22691 (push (pop list) rtn)
22692 (setq c (1+ c)))
22693 (nreverse rtn)))
22695 (defun org-find-base-buffer-visiting (file)
22696 "Like `find-buffer-visiting' but always return the base buffer and
22697 not an indirect buffer."
22698 (let ((buf (or (get-file-buffer file)
22699 (find-buffer-visiting file))))
22700 (if buf
22701 (or (buffer-base-buffer buf) buf)
22702 nil)))
22704 (defun org-image-file-name-regexp (&optional extensions)
22705 "Return regexp matching the file names of images.
22706 If EXTENSIONS is given, only match these."
22707 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22708 (image-file-name-regexp)
22709 (let ((image-file-name-extensions
22710 (or extensions
22711 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22712 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22713 (concat "\\."
22714 (regexp-opt (nconc (mapcar 'upcase
22715 image-file-name-extensions)
22716 image-file-name-extensions)
22718 "\\'"))))
22720 (defun org-file-image-p (file &optional extensions)
22721 "Return non-nil if FILE is an image."
22722 (save-match-data
22723 (string-match (org-image-file-name-regexp extensions) file)))
22725 (defun org-get-cursor-date (&optional with-time)
22726 "Return the date at cursor in as a time.
22727 This works in the calendar and in the agenda, anywhere else it just
22728 returns the current time.
22729 If WITH-TIME is non-nil, returns the time of the event at point (in
22730 the agenda) or the current time of the day."
22731 (let (date day defd tp tm hod mod)
22732 (when with-time
22733 (setq tp (get-text-property (point) 'time))
22734 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22735 (setq hod (string-to-number (match-string 1 tp))
22736 mod (string-to-number (match-string 2 tp))))
22737 (or tp (setq hod (nth 2 (decode-time (current-time)))
22738 mod (nth 1 (decode-time (current-time))))))
22739 (cond
22740 ((eq major-mode 'calendar-mode)
22741 (setq date (calendar-cursor-to-date)
22742 defd (encode-time 0 (or mod 0) (or hod 0)
22743 (nth 1 date) (nth 0 date) (nth 2 date))))
22744 ((eq major-mode 'org-agenda-mode)
22745 (setq day (get-text-property (point) 'day))
22746 (if day
22747 (setq date (calendar-gregorian-from-absolute day)
22748 defd (encode-time 0 (or mod 0) (or hod 0)
22749 (nth 1 date) (nth 0 date) (nth 2 date))))))
22750 (or defd (current-time))))
22752 (defun org-mark-subtree (&optional up)
22753 "Mark the current subtree.
22754 This puts point at the start of the current subtree, and mark at
22755 the end. If a numeric prefix UP is given, move up into the
22756 hierarchy of headlines by UP levels before marking the subtree."
22757 (interactive "P")
22758 (org-with-limited-levels
22759 (cond ((org-at-heading-p) (beginning-of-line))
22760 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22761 (t (outline-previous-visible-heading 1))))
22762 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22763 (if (org-called-interactively-p 'any)
22764 (call-interactively 'org-mark-element)
22765 (org-mark-element)))
22768 ;;; Indentation
22770 (defun org--get-expected-indentation (element contentsp)
22771 "Expected indentation column for current line, according to ELEMENT.
22772 ELEMENT is an element containing point. CONTENTSP is non-nil
22773 when indentation is to be computed according to contents of
22774 ELEMENT."
22775 (let ((type (org-element-type element))
22776 (start (org-element-property :begin element))
22777 (post-affiliated (org-element-property :post-affiliated element)))
22778 (org-with-wide-buffer
22779 (cond
22780 (contentsp
22781 (case type
22782 ((diary-sexp footnote-definition) 0)
22783 ((headline inlinetask nil)
22784 (if (not org-adapt-indentation) 0
22785 (let ((level (org-current-level)))
22786 (if level (1+ level) 0))))
22787 ((item plain-list) (org-list-item-body-column post-affiliated))
22789 (goto-char start)
22790 (org-get-indentation))))
22791 ((memq type '(headline inlinetask nil))
22792 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22793 (org--get-expected-indentation element t)
22795 ((memq type '(diary-sexp footnote-definition)) 0)
22796 ;; First paragraph of a footnote definition or an item.
22797 ;; Indent like parent.
22798 ((< (line-beginning-position) start)
22799 (org--get-expected-indentation
22800 (org-element-property :parent element) t))
22801 ;; At first line: indent according to previous sibling, if any,
22802 ;; ignoring footnote definitions and inline tasks, or parent's
22803 ;; contents.
22804 ((= (line-beginning-position) start)
22805 (catch 'exit
22806 (while t
22807 (if (= (point-min) start) (throw 'exit 0)
22808 (goto-char (1- start))
22809 (let* ((previous (org-element-at-point))
22810 (parent previous))
22811 (while (and parent (<= (org-element-property :end parent) start))
22812 (setq previous parent
22813 parent (org-element-property :parent parent)))
22814 (cond
22815 ((not previous) (throw 'exit 0))
22816 ((> (org-element-property :end previous) start)
22817 (throw 'exit (org--get-expected-indentation previous t)))
22818 ((memq (org-element-type previous)
22819 '(footnote-definition inlinetask))
22820 (setq start (org-element-property :begin previous)))
22821 (t (goto-char (org-element-property :begin previous))
22822 (throw 'exit
22823 (if (bolp) (org-get-indentation)
22824 ;; At first paragraph in an item or
22825 ;; a footnote definition.
22826 (org--get-expected-indentation
22827 (org-element-property :parent previous) t))))))))))
22828 ;; Otherwise, move to the first non-blank line above.
22830 (beginning-of-line)
22831 (let ((pos (point)))
22832 (skip-chars-backward " \r\t\n")
22833 (cond
22834 ;; Two blank lines end a footnote definition or a plain
22835 ;; list. When we indent an empty line after them, the
22836 ;; containing list or footnote definition is over, so it
22837 ;; qualifies as a previous sibling. Therefore, we indent
22838 ;; like its first line.
22839 ((and (memq type '(footnote-definition plain-list))
22840 (> (count-lines (point) pos) 2))
22841 (goto-char start)
22842 (org-get-indentation))
22843 ;; Line above is the first one of a paragraph at the
22844 ;; beginning of an item or a footnote definition. Indent
22845 ;; like parent.
22846 ((< (line-beginning-position) start)
22847 (org--get-expected-indentation
22848 (org-element-property :parent element) t))
22849 ;; Line above is the beginning of an element, i.e., point
22850 ;; was originally on the blank lines between element's start
22851 ;; and contents.
22852 ((= (line-beginning-position) post-affiliated)
22853 (org--get-expected-indentation element t))
22854 ;; POS is after contents in a greater element. Indent like
22855 ;; the beginning of the element.
22857 ;; As a special case, if point is at the end of a footnote
22858 ;; definition or an item, indent like the very last element
22859 ;; within.
22860 ((and (not (eq type 'paragraph))
22861 (let ((cend (org-element-property :contents-end element)))
22862 (and cend (<= cend pos))))
22863 (if (memq type '(footnote-definition item plain-list))
22864 (let ((last (org-element-at-point)))
22865 (org--get-expected-indentation
22866 last
22867 (memq (org-element-type last)
22868 '(footnote-definition item plain-list))))
22869 (goto-char start)
22870 (org-get-indentation)))
22871 ;; In any other case, indent like the current line.
22872 (t (org-get-indentation)))))))))
22874 (defun org--align-node-property ()
22875 "Align node property at point.
22876 Alignment is done according to `org-property-format', which see."
22877 (when (save-excursion
22878 (beginning-of-line)
22879 (looking-at org-property-re))
22880 (replace-match
22881 (concat (match-string 4)
22882 (org-trim
22883 (format org-property-format (match-string 1) (match-string 3))))
22884 t t)))
22886 (defun org-indent-line ()
22887 "Indent line depending on context.
22889 Indentation is done according to the following rules:
22891 - Footnote definitions, diary sexps, headlines and inline tasks
22892 have to start at column 0.
22894 - On the very first line of an element, consider, in order, the
22895 next rules until one matches:
22897 1. If there's a sibling element before, ignoring footnote
22898 definitions and inline tasks, indent like its first line.
22900 2. If element has a parent, indent like its contents. More
22901 precisely, if parent is an item, indent after the
22902 description part, if any, or the bullet (see
22903 `org-list-description-max-indent'). Else, indent like
22904 parent's first line.
22906 3. Otherwise, indent relatively to current level, if
22907 `org-adapt-indentation' is non-nil, or to left margin.
22909 - On a blank line at the end of an element, indent according to
22910 the type of the element. More precisely
22912 1. If element is a plain list, an item, or a footnote
22913 definition, indent like the very last element within.
22915 2. If element is a paragraph, indent like its last non blank
22916 line.
22918 3. Otherwise, indent like its very first line.
22920 - In the code part of a source block, use language major mode
22921 to indent current line if `org-src-tab-acts-natively' is
22922 non-nil. If it is nil, do nothing.
22924 - Otherwise, indent like the first non-blank line above.
22926 The function doesn't indent an item as it could break the whole
22927 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22928 \\[org-shiftmetaright].
22930 Also align node properties according to `org-property-format'."
22931 (interactive)
22932 (cond
22933 (orgstruct-is-++
22934 (let ((indent-line-function
22935 (cadadr (assq 'indent-line-function org-fb-vars))))
22936 (indent-according-to-mode)))
22937 ((org-at-heading-p) 'noindent)
22939 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22940 (type (org-element-type element)))
22941 (cond ((and (memq type '(plain-list item))
22942 (= (line-beginning-position)
22943 (org-element-property :post-affiliated element)))
22944 'noindent)
22945 ((and (eq type 'src-block)
22946 org-src-tab-acts-natively
22947 (> (line-beginning-position)
22948 (org-element-property :post-affiliated element))
22949 (< (line-beginning-position)
22950 (org-with-wide-buffer
22951 (goto-char (org-element-property :end element))
22952 (skip-chars-backward " \r\t\n")
22953 (line-beginning-position))))
22954 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22956 (let ((column (org--get-expected-indentation element nil)))
22957 ;; Preserve current column.
22958 (if (<= (current-column) (current-indentation))
22959 (org-indent-line-to column)
22960 (save-excursion (org-indent-line-to column))))
22961 ;; Align node property. Also preserve current column.
22962 (when (eq type 'node-property)
22963 (let ((column (current-column)))
22964 (org--align-node-property)
22965 (org-move-to-column column)))))))))
22967 (defun org-indent-region (start end)
22968 "Indent each non-blank line in the region.
22969 Called from a program, START and END specify the region to
22970 indent. The function will not indent contents of example blocks,
22971 verse blocks and export blocks as leading white spaces are
22972 assumed to be significant there."
22973 (interactive "r")
22974 (save-excursion
22975 (goto-char start)
22976 (skip-chars-forward " \r\t\n")
22977 (unless (eobp) (beginning-of-line))
22978 (let ((indent-to
22979 (lambda (ind pos)
22980 ;; Set IND as indentation for all lines between point and
22981 ;; POS or END, whichever comes first. Blank lines are
22982 ;; ignored. Leave point after POS once done.
22983 (let ((limit (copy-marker (min end pos))))
22984 (while (< (point) limit)
22985 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22986 (forward-line))
22987 (set-marker limit nil))))
22988 (end (copy-marker end)))
22989 (while (< (point) end)
22990 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22991 (let* ((element (org-element-at-point))
22992 (type (org-element-type element))
22993 (element-end (copy-marker (org-element-property :end element)))
22994 (ind (org--get-expected-indentation element nil)))
22995 (cond
22996 ((or (memq type '(paragraph table table-row))
22997 (not (or (org-element-property :contents-begin element)
22998 (memq type
22999 '(example-block export-block src-block)))))
23000 ;; Elements here are indented as a single block. Also
23001 ;; align node properties.
23002 (when (eq type 'node-property)
23003 (org--align-node-property)
23004 (beginning-of-line))
23005 (funcall indent-to ind element-end))
23007 ;; Elements in this category consist of three parts:
23008 ;; before the contents, the contents, and after the
23009 ;; contents. The contents are treated specially,
23010 ;; according to the element type, or not indented at
23011 ;; all. Other parts are indented as a single block.
23012 (let* ((post (copy-marker
23013 (org-element-property :post-affiliated element)))
23014 (cbeg
23015 (copy-marker
23016 (cond
23017 ((not (org-element-property :contents-begin element))
23018 ;; Fake contents for source blocks.
23019 (org-with-wide-buffer
23020 (goto-char post)
23021 (forward-line)
23022 (point)))
23023 ((memq type '(footnote-definition item plain-list))
23024 ;; Contents in these elements could start on
23025 ;; the same line as the beginning of the
23026 ;; element. Make sure we start indenting
23027 ;; from the second line.
23028 (org-with-wide-buffer
23029 (goto-char post)
23030 (end-of-line)
23031 (skip-chars-forward " \r\t\n")
23032 (if (eobp) (point) (line-beginning-position))))
23033 (t (org-element-property :contents-begin element)))))
23034 (cend (copy-marker
23035 (or (org-element-property :contents-end element)
23036 ;; Fake contents for source blocks.
23037 (org-with-wide-buffer
23038 (goto-char element-end)
23039 (skip-chars-backward " \r\t\n")
23040 (line-beginning-position)))
23041 t)))
23042 ;; Do not change items indentation individually as it
23043 ;; might break the list as a whole. On the other
23044 ;; hand, when at a plain list, indent it as a whole.
23045 (cond ((eq type 'plain-list)
23046 (let ((offset (- ind (org-get-indentation))))
23047 (unless (zerop offset)
23048 (indent-rigidly (org-element-property :begin element)
23049 (org-element-property :end element)
23050 offset))
23051 (goto-char cbeg)))
23052 ((eq type 'item) (goto-char cbeg))
23053 (t (funcall indent-to ind cbeg)))
23054 (when (< (point) end)
23055 (case type
23056 ((example-block export-block verse-block))
23057 (src-block
23058 ;; In a source block, indent source code
23059 ;; according to language major mode, but only if
23060 ;; `org-src-tab-acts-natively' is non-nil.
23061 (when (and (< (point) end) org-src-tab-acts-natively)
23062 (ignore-errors
23063 (org-babel-do-in-edit-buffer
23064 (indent-region (point-min) (point-max))))))
23065 (t (org-indent-region (point) (min cend end))))
23066 (goto-char (min cend end))
23067 (when (< (point) end) (funcall indent-to ind element-end)))
23068 (set-marker post nil)
23069 (set-marker cbeg nil)
23070 (set-marker cend nil))))
23071 (set-marker element-end nil))))
23072 (set-marker end nil))))
23074 (defun org-indent-drawer ()
23075 "Indent the drawer at point."
23076 (interactive)
23077 (unless (save-excursion
23078 (beginning-of-line)
23079 (org-looking-at-p org-drawer-regexp))
23080 (user-error "Not at a drawer"))
23081 (let ((element (org-element-at-point)))
23082 (unless (memq (org-element-type element) '(drawer property-drawer))
23083 (user-error "Not at a drawer"))
23084 (org-with-wide-buffer
23085 (org-indent-region (org-element-property :begin element)
23086 (org-element-property :end element))))
23087 (message "Drawer at point indented"))
23089 (defun org-indent-block ()
23090 "Indent the block at point."
23091 (interactive)
23092 (unless (save-excursion
23093 (beginning-of-line)
23094 (let ((case-fold-search t))
23095 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23096 (user-error "Not at a block"))
23097 (let ((element (org-element-at-point)))
23098 (unless (memq (org-element-type element)
23099 '(comment-block center-block dynamic-block example-block
23100 export-block quote-block special-block
23101 src-block verse-block))
23102 (user-error "Not at a block"))
23103 (org-with-wide-buffer
23104 (org-indent-region (org-element-property :begin element)
23105 (org-element-property :end element))))
23106 (message "Block at point indented"))
23109 ;;; Filling
23111 ;; We use our own fill-paragraph and auto-fill functions.
23113 ;; `org-fill-paragraph' relies on adaptive filling and context
23114 ;; checking. Appropriate `fill-prefix' is computed with
23115 ;; `org-adaptive-fill-function'.
23117 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23118 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23119 ;; `org-adaptive-fill-function' value. Internally,
23120 ;; `org-comment-line-break-function' breaks the line.
23122 ;; `org-setup-filling' installs filling and auto-filling related
23123 ;; variables during `org-mode' initialization.
23125 (defvar org-element-paragraph-separate) ; org-element.el
23126 (defun org-setup-filling ()
23127 (require 'org-element)
23128 ;; Prevent auto-fill from inserting unwanted new items.
23129 (when (boundp 'fill-nobreak-predicate)
23130 (org-set-local
23131 'fill-nobreak-predicate
23132 (org-uniquify
23133 (append fill-nobreak-predicate
23134 '(org-fill-line-break-nobreak-p
23135 org-fill-paragraph-with-timestamp-nobreak-p)))))
23136 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23137 (org-set-local 'paragraph-start paragraph-ending)
23138 (org-set-local 'paragraph-separate paragraph-ending))
23139 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
23140 (org-set-local 'auto-fill-inhibit-regexp nil)
23141 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
23142 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
23143 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
23145 (defun org-fill-line-break-nobreak-p ()
23146 "Non-nil when a new line at point would create an Org line break."
23147 (save-excursion
23148 (skip-chars-backward "[ \t]")
23149 (skip-chars-backward "\\\\")
23150 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23152 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23153 "Non-nil when a new line at point would split a timestamp."
23154 (and (org-at-timestamp-p t)
23155 (not (looking-at org-ts-regexp-both))))
23157 (declare-function message-in-body-p "message" ())
23158 (defvar orgtbl-line-start-regexp) ; From org-table.el
23159 (defun org-adaptive-fill-function ()
23160 "Compute a fill prefix for the current line.
23161 Return fill prefix, as a string, or nil if current line isn't
23162 meant to be filled. For convenience, if `adaptive-fill-regexp'
23163 matches in paragraphs or comments, use it."
23164 (catch 'exit
23165 (when (derived-mode-p 'message-mode)
23166 (save-excursion
23167 (beginning-of-line)
23168 (cond ((not (message-in-body-p)) (throw 'exit nil))
23169 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23170 ((looking-at message-cite-prefix-regexp)
23171 (throw 'exit (match-string-no-properties 0)))
23172 ((looking-at org-outline-regexp)
23173 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23174 (org-with-wide-buffer
23175 (unless (org-at-heading-p)
23176 (let* ((p (line-beginning-position))
23177 (element (save-excursion
23178 (beginning-of-line)
23179 (org-element-at-point)))
23180 (type (org-element-type element))
23181 (post-affiliated (org-element-property :post-affiliated element)))
23182 (unless (< p post-affiliated)
23183 (case type
23184 (comment
23185 (save-excursion
23186 (beginning-of-line)
23187 (looking-at "[ \t]*")
23188 (concat (match-string 0) "# ")))
23189 (footnote-definition "")
23190 ((item plain-list)
23191 (make-string (org-list-item-body-column post-affiliated) ?\s))
23192 (paragraph
23193 ;; Fill prefix is usually the same as the current line,
23194 ;; unless the paragraph is at the beginning of an item.
23195 (let ((parent (org-element-property :parent element)))
23196 (save-excursion
23197 (beginning-of-line)
23198 (cond ((eq (org-element-type parent) 'item)
23199 (make-string (org-list-item-body-column
23200 (org-element-property :begin parent))
23201 ?\s))
23202 ((and adaptive-fill-regexp
23203 ;; Locally disable
23204 ;; `adaptive-fill-function' to let
23205 ;; `fill-context-prefix' handle
23206 ;; `adaptive-fill-regexp' variable.
23207 (let (adaptive-fill-function)
23208 (fill-context-prefix
23209 post-affiliated
23210 (org-element-property :end element)))))
23211 ((looking-at "[ \t]+") (match-string 0))
23212 (t "")))))
23213 (comment-block
23214 ;; Only fill contents if P is within block boundaries.
23215 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23216 (forward-line)
23217 (point)))
23218 (cend (save-excursion
23219 (goto-char (org-element-property :end element))
23220 (skip-chars-backward " \r\t\n")
23221 (line-beginning-position))))
23222 (when (and (>= p cbeg) (< p cend))
23223 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23224 (match-string 0)
23225 "")))))))))))
23227 (declare-function message-goto-body "message" ())
23228 (defvar message-cite-prefix-regexp) ; From message.el
23229 (defun org-fill-paragraph (&optional justify)
23230 "Fill element at point, when applicable.
23232 This function only applies to comment blocks, comments, example
23233 blocks and paragraphs. Also, as a special case, re-align table
23234 when point is at one.
23236 If JUSTIFY is non-nil (interactively, with prefix argument),
23237 justify as well. If `sentence-end-double-space' is non-nil, then
23238 period followed by one space does not end a sentence, so don't
23239 break a line there. The variable `fill-column' controls the
23240 width for filling.
23242 For convenience, when point is at a plain list, an item or
23243 a footnote definition, try to fill the first paragraph within."
23244 (interactive)
23245 (if (and (derived-mode-p 'message-mode)
23246 (or (not (message-in-body-p))
23247 (save-excursion (move-beginning-of-line 1)
23248 (looking-at message-cite-prefix-regexp))))
23249 ;; First ensure filling is correct in message-mode.
23250 (let ((fill-paragraph-function
23251 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
23252 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
23253 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
23254 (paragraph-separate
23255 (cadadr (assoc 'paragraph-separate org-fb-vars))))
23256 (fill-paragraph nil))
23257 (with-syntax-table org-mode-transpose-word-syntax-table
23258 ;; Move to end of line in order to get the first paragraph
23259 ;; within a plain list or a footnote definition.
23260 (let ((element (save-excursion
23261 (end-of-line)
23262 (or (ignore-errors (org-element-at-point))
23263 (user-error "An element cannot be parsed line %d"
23264 (line-number-at-pos (point)))))))
23265 ;; First check if point is in a blank line at the beginning of
23266 ;; the buffer. In that case, ignore filling.
23267 (case (org-element-type element)
23268 ;; Use major mode filling function is src blocks.
23269 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23270 ;; Align Org tables, leave table.el tables as-is.
23271 (table-row (org-table-align) t)
23272 (table
23273 (when (eq (org-element-property :type element) 'org)
23274 (save-excursion
23275 (goto-char (org-element-property :post-affiliated element))
23276 (org-table-align)))
23278 (paragraph
23279 ;; Paragraphs may contain `line-break' type objects.
23280 (let ((beg (max (point-min)
23281 (org-element-property :contents-begin element)))
23282 (end (min (point-max)
23283 (org-element-property :contents-end element))))
23284 ;; Do nothing if point is at an affiliated keyword.
23285 (if (< (line-end-position) beg) t
23286 (when (derived-mode-p 'message-mode)
23287 ;; In `message-mode', do not fill following citation
23288 ;; in current paragraph nor text before message body.
23289 (let ((body-start (save-excursion (message-goto-body))))
23290 (when body-start (setq beg (max body-start beg))))
23291 (when (save-excursion
23292 (re-search-forward
23293 (concat "^" message-cite-prefix-regexp) end t))
23294 (setq end (match-beginning 0))))
23295 ;; Fill paragraph, taking line breaks into account.
23296 (save-excursion
23297 (goto-char beg)
23298 (let ((cuts (list beg)))
23299 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23300 (when (eq 'line-break
23301 (org-element-type
23302 (save-excursion (backward-char)
23303 (org-element-context))))
23304 (push (point) cuts)))
23305 (dolist (c (delq end cuts))
23306 (fill-region-as-paragraph c end justify)
23307 (setq end c))))
23308 t)))
23309 ;; Contents of `comment-block' type elements should be
23310 ;; filled as plain text, but only if point is within block
23311 ;; markers.
23312 (comment-block
23313 (let* ((case-fold-search t)
23314 (beg (save-excursion
23315 (goto-char (org-element-property :begin element))
23316 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23317 (forward-line)
23318 (point)))
23319 (end (save-excursion
23320 (goto-char (org-element-property :end element))
23321 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23322 (line-beginning-position))))
23323 (if (or (< (point) beg) (> (point) end)) t
23324 (fill-region-as-paragraph
23325 (save-excursion (end-of-line)
23326 (re-search-backward "^[ \t]*$" beg 'move)
23327 (line-beginning-position))
23328 (save-excursion (beginning-of-line)
23329 (re-search-forward "^[ \t]*$" end 'move)
23330 (line-beginning-position))
23331 justify))))
23332 ;; Fill comments.
23333 (comment
23334 (let ((begin (org-element-property :post-affiliated element))
23335 (end (org-element-property :end element)))
23336 (when (and (>= (point) begin) (<= (point) end))
23337 (let ((begin (save-excursion
23338 (end-of-line)
23339 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23340 (progn (forward-line) (point))
23341 begin)))
23342 (end (save-excursion
23343 (end-of-line)
23344 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23345 (1- (line-beginning-position))
23346 (skip-chars-backward " \r\t\n")
23347 (line-end-position)))))
23348 ;; Do not fill comments when at a blank line.
23349 (when (> end begin)
23350 (let ((fill-prefix
23351 (save-excursion
23352 (beginning-of-line)
23353 (looking-at "[ \t]*#")
23354 (let ((comment-prefix (match-string 0)))
23355 (goto-char (match-end 0))
23356 (if (looking-at adaptive-fill-regexp)
23357 (concat comment-prefix (match-string 0))
23358 (concat comment-prefix " "))))))
23359 (save-excursion
23360 (fill-region-as-paragraph begin end justify))))))
23362 ;; Ignore every other element.
23363 (otherwise t))))))
23365 (defun org-auto-fill-function ()
23366 "Auto-fill function."
23367 ;; Check if auto-filling is meaningful.
23368 (let ((fc (current-fill-column)))
23369 (when (and fc (> (current-column) fc))
23370 (let* ((fill-prefix (org-adaptive-fill-function))
23371 ;; Enforce empty fill prefix, if required. Otherwise, it
23372 ;; will be computed again.
23373 (adaptive-fill-mode (not (equal fill-prefix ""))))
23374 (when fill-prefix (do-auto-fill))))))
23376 (defun org-comment-line-break-function (&optional soft)
23377 "Break line at point and indent, continuing comment if within one.
23378 The inserted newline is marked hard if variable
23379 `use-hard-newlines' is true, unless optional argument SOFT is
23380 non-nil."
23381 (if soft (insert-and-inherit ?\n) (newline 1))
23382 (save-excursion (forward-char -1) (delete-horizontal-space))
23383 (delete-horizontal-space)
23384 (indent-to-left-margin)
23385 (insert-before-markers-and-inherit fill-prefix))
23388 ;;; Fixed Width Areas
23390 (defun org-toggle-fixed-width ()
23391 "Toggle fixed-width markup.
23393 Add or remove fixed-width markup on current line, whenever it
23394 makes sense. Return an error otherwise.
23396 If a region is active and if it contains only fixed-width areas
23397 or blank lines, remove all fixed-width markup in it. If the
23398 region contains anything else, convert all non-fixed-width lines
23399 to fixed-width ones.
23401 Blank lines at the end of the region are ignored unless the
23402 region only contains such lines."
23403 (interactive)
23404 (if (not (org-region-active-p))
23405 ;; No region:
23407 ;; Remove fixed width marker only in a fixed-with element.
23409 ;; Add fixed width maker in paragraphs, in blank lines after
23410 ;; elements or at the beginning of a headline or an inlinetask,
23411 ;; and before any one-line elements (e.g., a clock).
23412 (progn
23413 (beginning-of-line)
23414 (let* ((element (org-element-at-point))
23415 (type (org-element-type element)))
23416 (cond
23417 ((and (eq type 'fixed-width)
23418 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23419 (replace-match
23420 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23421 ((and (memq type '(babel-call clock comment diary-sexp headline
23422 horizontal-rule keyword paragraph
23423 planning))
23424 (<= (org-element-property :post-affiliated element) (point)))
23425 (skip-chars-forward " \t")
23426 (insert ": "))
23427 ((and (org-looking-at-p "[ \t]*$")
23428 (or (eq type 'inlinetask)
23429 (save-excursion
23430 (skip-chars-forward " \r\t\n")
23431 (<= (org-element-property :end element) (point)))))
23432 (delete-region (point) (line-end-position))
23433 (org-indent-line)
23434 (insert ": "))
23435 (t (user-error "Cannot insert a fixed-width line here")))))
23436 ;; Region active.
23437 (let* ((begin (save-excursion
23438 (goto-char (region-beginning))
23439 (line-beginning-position)))
23440 (end (copy-marker
23441 (save-excursion
23442 (goto-char (region-end))
23443 (unless (eolp) (beginning-of-line))
23444 (if (save-excursion (re-search-backward "\\S-" begin t))
23445 (progn (skip-chars-backward " \r\t\n") (point))
23446 (point)))))
23447 (all-fixed-width-p
23448 (catch 'not-all-p
23449 (save-excursion
23450 (goto-char begin)
23451 (skip-chars-forward " \r\t\n")
23452 (when (eobp) (throw 'not-all-p nil))
23453 (while (< (point) end)
23454 (let ((element (org-element-at-point)))
23455 (if (eq (org-element-type element) 'fixed-width)
23456 (goto-char (org-element-property :end element))
23457 (throw 'not-all-p nil))))
23458 t))))
23459 (if all-fixed-width-p
23460 (save-excursion
23461 (goto-char begin)
23462 (while (< (point) end)
23463 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23464 (replace-match
23465 "" nil nil nil
23466 (if (= (line-end-position) (match-end 0)) 0 1)))
23467 (forward-line)))
23468 (let ((min-ind (point-max)))
23469 ;; Find minimum indentation across all lines.
23470 (save-excursion
23471 (goto-char begin)
23472 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23473 (setq min-ind 0)
23474 (catch 'zerop
23475 (while (< (point) end)
23476 (unless (org-looking-at-p "[ \t]*$")
23477 (let ((ind (org-get-indentation)))
23478 (setq min-ind (min min-ind ind))
23479 (when (zerop ind) (throw 'zerop t))))
23480 (forward-line)))))
23481 ;; Loop over all lines and add fixed-width markup everywhere
23482 ;; but in fixed-width lines.
23483 (save-excursion
23484 (goto-char begin)
23485 (while (< (point) end)
23486 (cond
23487 ((org-at-heading-p)
23488 (insert ": ")
23489 (forward-line)
23490 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23491 (insert ":")
23492 (forward-line)))
23493 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23494 (let* ((element (org-element-at-point))
23495 (element-end (org-element-property :end element)))
23496 (if (eq (org-element-type element) 'fixed-width)
23497 (progn (goto-char element-end)
23498 (skip-chars-backward " \r\t\n")
23499 (forward-line))
23500 (let ((limit (min end element-end)))
23501 (while (< (point) limit)
23502 (org-move-to-column min-ind t)
23503 (insert ": ")
23504 (forward-line))))))
23506 (org-move-to-column min-ind t)
23507 (insert ": ")
23508 (forward-line)))))))
23509 (set-marker end nil))))
23512 ;;; Comments
23514 ;; Org comments syntax is quite complex. It requires the entire line
23515 ;; to be just a comment. Also, even with the right syntax at the
23516 ;; beginning of line, some some elements (i.e. verse-block or
23517 ;; example-block) don't accept comments. Usual Emacs comment commands
23518 ;; cannot cope with those requirements. Therefore, Org replaces them.
23520 ;; Org still relies on `comment-dwim', but cannot trust
23521 ;; `comment-only-p'. So, `comment-region-function' and
23522 ;; `uncomment-region-function' both point
23523 ;; to`org-comment-or-uncomment-region'. Eventually,
23524 ;; `org-insert-comment' takes care of insertion of comments at the
23525 ;; beginning of line.
23527 ;; `org-setup-comments-handling' install comments related variables
23528 ;; during `org-mode' initialization.
23530 (defun org-setup-comments-handling ()
23531 (interactive)
23532 (org-set-local 'comment-use-syntax nil)
23533 (org-set-local 'comment-start "# ")
23534 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23535 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23536 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23537 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23539 (defun org-insert-comment ()
23540 "Insert an empty comment above current line.
23541 If the line is empty, insert comment at its beginning. When
23542 point is within a source block, comment according to the related
23543 major mode."
23544 (if (let ((element (org-element-at-point)))
23545 (and (eq (org-element-type element) 'src-block)
23546 (< (save-excursion
23547 (goto-char (org-element-property :post-affiliated element))
23548 (line-end-position))
23549 (point))
23550 (> (save-excursion
23551 (goto-char (org-element-property :end element))
23552 (skip-chars-backward " \r\t\n")
23553 (line-beginning-position))
23554 (point))))
23555 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23556 (beginning-of-line)
23557 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23558 (open-line 1))
23559 (org-indent-line)
23560 (insert "# ")))
23562 (defvar comment-empty-lines) ; From newcomment.el.
23563 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23564 "Comment or uncomment each non-blank line in the region.
23565 Uncomment each non-blank line between BEG and END if it only
23566 contains commented lines. Otherwise, comment them. If region is
23567 strictly within a source block, use appropriate comment syntax."
23568 (if (let ((element (org-element-at-point)))
23569 (and (eq (org-element-type element) 'src-block)
23570 (< (save-excursion
23571 (goto-char (org-element-property :post-affiliated element))
23572 (line-end-position))
23573 beg)
23574 (>= (save-excursion
23575 (goto-char (org-element-property :end element))
23576 (skip-chars-backward " \r\t\n")
23577 (line-beginning-position))
23578 end)))
23579 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23580 (save-restriction
23581 ;; Restrict region
23582 (narrow-to-region (save-excursion (goto-char beg)
23583 (skip-chars-forward " \r\t\n" end)
23584 (line-beginning-position))
23585 (save-excursion (goto-char end)
23586 (skip-chars-backward " \r\t\n" beg)
23587 (line-end-position)))
23588 (let ((uncommentp
23589 ;; UNCOMMENTP is non-nil when every non blank line between
23590 ;; BEG and END is a comment.
23591 (save-excursion
23592 (goto-char (point-min))
23593 (while (and (not (eobp))
23594 (let ((element (org-element-at-point)))
23595 (and (eq (org-element-type element) 'comment)
23596 (goto-char (min (point-max)
23597 (org-element-property
23598 :end element)))))))
23599 (eobp))))
23600 (if uncommentp
23601 ;; Only blank lines and comments in region: uncomment it.
23602 (save-excursion
23603 (goto-char (point-min))
23604 (while (not (eobp))
23605 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23606 (replace-match "" nil nil nil 1))
23607 (forward-line)))
23608 ;; Comment each line in region.
23609 (let ((min-indent (point-max)))
23610 ;; First find the minimum indentation across all lines.
23611 (save-excursion
23612 (goto-char (point-min))
23613 (while (and (not (eobp)) (not (zerop min-indent)))
23614 (unless (looking-at "[ \t]*$")
23615 (setq min-indent (min min-indent (current-indentation))))
23616 (forward-line)))
23617 ;; Then loop over all lines.
23618 (save-excursion
23619 (goto-char (point-min))
23620 (while (not (eobp))
23621 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23622 ;; Don't get fooled by invisible text (e.g. link path)
23623 ;; when moving to column MIN-INDENT.
23624 (let ((buffer-invisibility-spec nil))
23625 (org-move-to-column min-indent t))
23626 (insert comment-start))
23627 (forward-line)))))))))
23629 (defun org-comment-dwim (arg)
23630 "Call `comment-dwim' within a source edit buffer if needed."
23631 (interactive "*P")
23632 (if (org-in-src-block-p)
23633 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23634 (call-interactively 'comment-dwim)))
23637 ;;; Timestamps API
23639 ;; This section contains tools to operate on timestamp objects, as
23640 ;; returned by, e.g. `org-element-context'.
23642 (defun org-timestamp--to-internal-time (timestamp &optional end)
23643 "Encode TIMESTAMP object into Emacs internal time.
23644 Use end of date range or time range when END is non-nil."
23645 (apply #'encode-time
23646 (cons 0
23647 (mapcar
23648 (lambda (prop) (or (org-element-property prop timestamp) 0))
23649 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23650 '(:minute-start :hour-start :day-start :month-start
23651 :year-start))))))
23653 (defun org-timestamp-has-time-p (timestamp)
23654 "Non-nil when TIMESTAMP has a time specified."
23655 (org-element-property :hour-start timestamp))
23657 (defun org-timestamp-format (timestamp format &optional end utc)
23658 "Format a TIMESTAMP object into a string.
23660 FORMAT is a format specifier to be passed to
23661 `format-time-string'.
23663 When optional argument END is non-nil, use end of date-range or
23664 time-range, if possible.
23666 When optional argument UTC is non-nil, time will be expressed as
23667 Universal Time."
23668 (format-time-string
23669 format (org-timestamp--to-internal-time timestamp end) utc))
23671 (defun org-timestamp-split-range (timestamp &optional end)
23672 "Extract a TIMESTAMP object from a date or time range.
23674 END, when non-nil, means extract the end of the range.
23675 Otherwise, extract its start.
23677 Return a new timestamp object."
23678 (let ((type (org-element-property :type timestamp)))
23679 (if (memq type '(active inactive diary)) timestamp
23680 (let ((split-ts (org-element-copy timestamp)))
23681 ;; Set new type.
23682 (org-element-put-property
23683 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23684 ;; Copy start properties over end properties if END is
23685 ;; non-nil. Otherwise, copy end properties over `start' ones.
23686 (let ((p-alist '((:minute-start . :minute-end)
23687 (:hour-start . :hour-end)
23688 (:day-start . :day-end)
23689 (:month-start . :month-end)
23690 (:year-start . :year-end))))
23691 (dolist (p-cell p-alist)
23692 (org-element-put-property
23693 split-ts
23694 (funcall (if end #'car #'cdr) p-cell)
23695 (org-element-property
23696 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23697 ;; Eventually refresh `:raw-value'.
23698 (org-element-put-property split-ts :raw-value nil)
23699 (org-element-put-property
23700 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23702 (defun org-timestamp-translate (timestamp &optional boundary)
23703 "Translate TIMESTAMP object to custom format.
23705 Format string is defined in `org-time-stamp-custom-formats',
23706 which see.
23708 When optional argument BOUNDARY is non-nil, it is either the
23709 symbol `start' or `end'. In this case, only translate the
23710 starting or ending part of TIMESTAMP if it is a date or time
23711 range. Otherwise, translate both parts.
23713 Return timestamp as-is if `org-display-custom-times' is nil or if
23714 it has a `diary' type."
23715 (let ((type (org-element-property :type timestamp)))
23716 (if (or (not org-display-custom-times) (eq type 'diary))
23717 (org-element-interpret-data timestamp)
23718 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23719 org-time-stamp-custom-formats)))
23720 (if (and (not boundary) (memq type '(active-range inactive-range)))
23721 (concat (org-timestamp-format timestamp fmt)
23722 "--"
23723 (org-timestamp-format timestamp fmt t))
23724 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23728 ;;; Other stuff.
23730 (defun org-reftex-citation ()
23731 "Use reftex-citation to insert a citation into the buffer.
23732 This looks for a line like
23734 #+BIBLIOGRAPHY: foo plain option:-d
23736 and derives from it that foo.bib is the bibliography file relevant
23737 for this document. It then installs the necessary environment for RefTeX
23738 to work in this buffer and calls `reftex-citation' to insert a citation
23739 into the buffer.
23741 Export of such citations to both LaTeX and HTML is handled by the contributed
23742 package ox-bibtex by Taru Karttunen."
23743 (interactive)
23744 (let ((reftex-docstruct-symbol 'rds)
23745 (reftex-cite-format "\\cite{%l}")
23746 rds bib)
23747 (save-excursion
23748 (save-restriction
23749 (widen)
23750 (let ((case-fold-search t)
23751 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23752 (if (not (save-excursion
23753 (or (re-search-forward re nil t)
23754 (re-search-backward re nil t))))
23755 (user-error "No bibliography defined in file")
23756 (setq bib (concat (match-string 1) ".bib")
23757 rds (list (list 'bib bib)))))))
23758 (call-interactively 'reftex-citation)))
23760 ;;;; Functions extending outline functionality
23762 (defun org-beginning-of-line (&optional arg)
23763 "Go to the beginning of the current line. If that is invisible, continue
23764 to a visible line beginning. This makes the function of C-a more intuitive.
23765 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23766 first attempt, and only move to after the tags when the cursor is already
23767 beyond the end of the headline."
23768 (interactive "P")
23769 (let ((pos (point))
23770 (special (if (consp org-special-ctrl-a/e)
23771 (car org-special-ctrl-a/e)
23772 org-special-ctrl-a/e))
23773 deactivate-mark refpos)
23774 (if (org-bound-and-true-p visual-line-mode)
23775 (beginning-of-visual-line 1)
23776 (beginning-of-line 1))
23777 (if (and arg (fboundp 'move-beginning-of-line))
23778 (call-interactively 'move-beginning-of-line)
23779 (if (bobp)
23781 (backward-char 1)
23782 (if (org-truely-invisible-p)
23783 (while (and (not (bobp)) (org-truely-invisible-p))
23784 (backward-char 1)
23785 (beginning-of-line 1))
23786 (forward-char 1))))
23787 (when special
23788 (cond
23789 ((and (looking-at org-complex-heading-regexp)
23790 (= (char-after (match-end 1)) ?\ ))
23791 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23792 (point-at-eol)))
23793 (goto-char
23794 (if (eq special t)
23795 (cond ((> pos refpos) refpos)
23796 ((= pos (point)) refpos)
23797 (t (point)))
23798 (cond ((> pos (point)) (point))
23799 ((not (eq last-command this-command)) (point))
23800 (t refpos)))))
23801 ((org-at-item-p)
23802 ;; Being at an item and not looking at an the item means point
23803 ;; was previously moved to beginning of a visual line, which
23804 ;; doesn't contain the item. Therefore, do nothing special,
23805 ;; just stay here.
23806 (when (looking-at org-list-full-item-re)
23807 ;; Set special position at first white space character after
23808 ;; bullet, and check-box, if any.
23809 (let ((after-bullet
23810 (let ((box (match-end 3)))
23811 (if (not box) (match-end 1)
23812 (let ((after (char-after box)))
23813 (if (and after (= after ? )) (1+ box) box))))))
23814 ;; Special case: Move point to special position when
23815 ;; currently after it or at beginning of line.
23816 (if (eq special t)
23817 (when (or (> pos after-bullet) (= (point) pos))
23818 (goto-char after-bullet))
23819 ;; Reversed case: Move point to special position when
23820 ;; point was already at beginning of line and command is
23821 ;; repeated.
23822 (when (and (= (point) pos) (eq last-command this-command))
23823 (goto-char after-bullet))))))))
23824 (org-no-warnings
23825 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23826 (setq disable-point-adjustment
23827 (or (not (invisible-p (point)))
23828 (not (invisible-p (max (point-min) (1- (point))))))))
23830 (defun org-end-of-line (&optional arg)
23831 "Go to the end of the line.
23832 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23833 tags on the first attempt, and only move to after the tags when
23834 the cursor is already beyond the end of the headline."
23835 (interactive "P")
23836 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23837 org-special-ctrl-a/e))
23838 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23839 'end-of-visual-line)
23840 ((fboundp 'move-end-of-line) 'move-end-of-line)
23841 (t 'end-of-line)))
23842 deactivate-mark)
23843 (if (or (not special) arg) (call-interactively move-fun)
23844 (let* ((element (save-excursion (beginning-of-line)
23845 (org-element-at-point)))
23846 (type (org-element-type element)))
23847 (cond
23848 ((memq type '(headline inlinetask))
23849 (let ((pos (point)))
23850 (beginning-of-line 1)
23851 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23852 (if (eq special t)
23853 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23854 (goto-char (match-beginning 1))
23855 (goto-char (match-end 0)))
23856 (if (or (< pos (match-end 0))
23857 (not (eq this-command last-command)))
23858 (goto-char (match-end 0))
23859 (goto-char (match-beginning 1))))
23860 (call-interactively move-fun))))
23861 ((outline-invisible-p (line-end-position))
23862 ;; If element is hidden, `move-end-of-line' would put point
23863 ;; after it. Use `end-of-line' to stay on current line.
23864 (call-interactively 'end-of-line))
23865 (t (call-interactively move-fun)))))
23866 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23867 (setq disable-point-adjustment
23868 (or (not (invisible-p (point)))
23869 (not (invisible-p (max (point-min) (1- (point))))))))
23871 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23872 (define-key org-mode-map "\C-e" 'org-end-of-line)
23874 (defun org-backward-sentence (&optional arg)
23875 "Go to beginning of sentence, or beginning of table field.
23876 This will call `backward-sentence' or `org-table-beginning-of-field',
23877 depending on context."
23878 (interactive "P")
23879 (let* ((element (org-element-at-point))
23880 (contents-begin (org-element-property :contents-begin element))
23881 (table (org-element-lineage element '(table) t)))
23882 (if (and table
23883 (> (point) contents-begin)
23884 (<= (point) (org-element-property :contents-end table)))
23885 (call-interactively #'org-table-beginning-of-field)
23886 (save-restriction
23887 (when (and contents-begin
23888 (< (point-min) contents-begin)
23889 (> (point) contents-begin))
23890 (narrow-to-region contents-begin
23891 (org-element-property :contents-end element)))
23892 (call-interactively #'backward-sentence)))))
23894 (defun org-forward-sentence (&optional arg)
23895 "Go to end of sentence, or end of table field.
23896 This will call `forward-sentence' or `org-table-end-of-field',
23897 depending on context."
23898 (interactive "P")
23899 (let* ((element (org-element-at-point))
23900 (contents-end (org-element-property :contents-end element))
23901 (table (org-element-lineage element '(table) t)))
23902 (if (and table
23903 (>= (point) (org-element-property :contents-begin table))
23904 (< (point) contents-end))
23905 (call-interactively #'org-table-end-of-field)
23906 (save-restriction
23907 (when (and contents-end
23908 (> (point-max) contents-end)
23909 ;; Skip blank lines between elements.
23910 (< (org-element-property :end element)
23911 (save-excursion (goto-char contents-end)
23912 (skip-chars-forward " \r\t\n"))))
23913 (narrow-to-region (org-element-property :contents-begin element)
23914 contents-end))
23915 (call-interactively #'forward-sentence)))))
23917 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23918 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23920 (defun org-kill-line (&optional arg)
23921 "Kill line, to tags or end of line."
23922 (interactive "P")
23923 (cond
23924 ((or (not org-special-ctrl-k)
23925 (bolp)
23926 (not (org-at-heading-p)))
23927 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23928 org-ctrl-k-protect-subtree)
23929 (if (or (eq org-ctrl-k-protect-subtree 'error)
23930 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23931 (user-error "C-k aborted as it would kill a hidden subtree")))
23932 (call-interactively
23933 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23934 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23935 (kill-region (point) (match-beginning 1))
23936 (org-set-tags nil t))
23937 (t (kill-region (point) (point-at-eol)))))
23939 (define-key org-mode-map "\C-k" 'org-kill-line)
23941 (defun org-yank (&optional arg)
23942 "Yank. If the kill is a subtree, treat it specially.
23943 This command will look at the current kill and check if is a single
23944 subtree, or a series of subtrees[1]. If it passes the test, and if the
23945 cursor is at the beginning of a line or after the stars of a currently
23946 empty headline, then the yank is handled specially. How exactly depends
23947 on the value of the following variables, both set by default.
23949 `org-yank-folded-subtrees'
23950 When set, the subtree(s) will be folded after insertion, but only
23951 if doing so would now swallow text after the yanked text.
23953 `org-yank-adjusted-subtrees'
23954 When set, the subtree will be promoted or demoted in order to
23955 fit into the local outline tree structure, which means that the
23956 level will be adjusted so that it becomes the smaller one of the
23957 two *visible* surrounding headings.
23959 Any prefix to this command will cause `yank' to be called directly with
23960 no special treatment. In particular, a simple \\[universal-argument] prefix \
23961 will just
23962 plainly yank the text as it is.
23964 \[1] The test checks if the first non-white line is a heading
23965 and if there are no other headings with fewer stars."
23966 (interactive "P")
23967 (org-yank-generic 'yank arg))
23969 (defun org-yank-generic (command arg)
23970 "Perform some yank-like command.
23972 This function implements the behavior described in the `org-yank'
23973 documentation. However, it has been generalized to work for any
23974 interactive command with similar behavior."
23976 ;; pretend to be command COMMAND
23977 (setq this-command command)
23979 (if arg
23980 (call-interactively command)
23982 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23983 (and (org-kill-is-subtree-p)
23984 (or (bolp)
23985 (and (looking-at "[ \t]*$")
23986 (string-match
23987 "\\`\\*+\\'"
23988 (buffer-substring (point-at-bol) (point)))))))
23989 swallowp)
23990 (cond
23991 ((and subtreep org-yank-folded-subtrees)
23992 (let ((beg (point))
23993 end)
23994 (if (and subtreep org-yank-adjusted-subtrees)
23995 (org-paste-subtree nil nil 'for-yank)
23996 (call-interactively command))
23998 (setq end (point))
23999 (goto-char beg)
24000 (when (and (bolp) subtreep
24001 (not (setq swallowp
24002 (org-yank-folding-would-swallow-text beg end))))
24003 (org-with-limited-levels
24004 (or (looking-at org-outline-regexp)
24005 (re-search-forward org-outline-regexp-bol end t))
24006 (while (and (< (point) end) (looking-at org-outline-regexp))
24007 (hide-subtree)
24008 (org-cycle-show-empty-lines 'folded)
24009 (condition-case nil
24010 (outline-forward-same-level 1)
24011 (error (goto-char end))))))
24012 (when swallowp
24013 (message
24014 "Inserted text not folded because that would swallow text"))
24016 (goto-char end)
24017 (skip-chars-forward " \t\n\r")
24018 (beginning-of-line 1)
24019 (push-mark beg 'nomsg)))
24020 ((and subtreep org-yank-adjusted-subtrees)
24021 (let ((beg (point-at-bol)))
24022 (org-paste-subtree nil nil 'for-yank)
24023 (push-mark beg 'nomsg)))
24025 (call-interactively command))))))
24027 (defun org-yank-folding-would-swallow-text (beg end)
24028 "Would hide-subtree at BEG swallow any text after END?"
24029 (let (level)
24030 (org-with-limited-levels
24031 (save-excursion
24032 (goto-char beg)
24033 (when (or (looking-at org-outline-regexp)
24034 (re-search-forward org-outline-regexp-bol end t))
24035 (setq level (org-outline-level)))
24036 (goto-char end)
24037 (skip-chars-forward " \t\r\n\v\f")
24038 (if (or (eobp)
24039 (and (bolp) (looking-at org-outline-regexp)
24040 (<= (org-outline-level) level)))
24041 nil ; Nothing would be swallowed
24042 t))))) ; something would swallow
24044 (define-key org-mode-map "\C-y" 'org-yank)
24046 (defun org-truely-invisible-p ()
24047 "Check if point is at a character currently not visible.
24048 This version does not only check the character property, but also
24049 `visible-mode'."
24050 ;; Early versions of noutline don't have `outline-invisible-p'.
24051 (if (org-bound-and-true-p visible-mode)
24053 (outline-invisible-p)))
24055 (defun org-invisible-p2 ()
24056 "Check if point is at a character currently not visible."
24057 (save-excursion
24058 (if (and (eolp) (not (bobp))) (backward-char 1))
24059 ;; Early versions of noutline don't have `outline-invisible-p'.
24060 (outline-invisible-p)))
24062 (defun org-back-to-heading (&optional invisible-ok)
24063 "Call `outline-back-to-heading', but provide a better error message."
24064 (condition-case nil
24065 (outline-back-to-heading invisible-ok)
24066 (error (error "Before first headline at position %d in buffer %s"
24067 (point) (current-buffer)))))
24069 (defun org-before-first-heading-p ()
24070 "Before first heading?"
24071 (save-excursion
24072 (end-of-line)
24073 (null (re-search-backward org-outline-regexp-bol nil t))))
24075 (defun org-at-heading-p (&optional ignored)
24076 (outline-on-heading-p t))
24077 ;; Compatibility alias with Org versions < 7.8.03
24078 (defalias 'org-on-heading-p 'org-at-heading-p)
24080 (defun org-in-commented-heading-p (&optional no-inheritance)
24081 "Non-nil if point is under a commented heading.
24082 This function also checks ancestors of the current headline,
24083 unless optional argument NO-INHERITANCE is non-nil."
24084 (cond
24085 ((org-before-first-heading-p) nil)
24086 ((let ((headline (nth 4 (org-heading-components))))
24087 (and headline
24088 (let ((case-fold-search nil))
24089 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24090 headline)))))
24091 (no-inheritance nil)
24093 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24095 (defun org-at-comment-p nil
24096 "Is cursor in a commented line?"
24097 (save-excursion
24098 (save-match-data
24099 (beginning-of-line)
24100 (looking-at "^[ \t]*# "))))
24102 (defun org-at-drawer-p nil
24103 "Is cursor at a drawer keyword?"
24104 (save-excursion
24105 (move-beginning-of-line 1)
24106 (looking-at org-drawer-regexp)))
24108 (defun org-at-block-p nil
24109 "Is cursor at a block keyword?"
24110 (save-excursion
24111 (move-beginning-of-line 1)
24112 (looking-at org-block-regexp)))
24114 (defun org-point-at-end-of-empty-headline ()
24115 "If point is at the end of an empty headline, return t, else nil.
24116 If the heading only contains a TODO keyword, it is still still considered
24117 empty."
24118 (and (looking-at "[ \t]*$")
24119 (when org-todo-line-regexp
24120 (save-excursion
24121 (beginning-of-line 1)
24122 (let ((case-fold-search nil))
24123 (looking-at org-todo-line-regexp)
24124 (string= (match-string 3) ""))))))
24126 (defun org-at-heading-or-item-p ()
24127 (or (org-at-heading-p) (org-at-item-p)))
24129 (defun org-at-target-p ()
24130 (or (org-in-regexp org-radio-target-regexp)
24131 (org-in-regexp org-target-regexp)))
24132 ;; Compatibility alias with Org versions < 7.8.03
24133 (defalias 'org-on-target-p 'org-at-target-p)
24135 (defun org-up-heading-all (arg)
24136 "Move to the heading line of which the present line is a subheading.
24137 This function considers both visible and invisible heading lines.
24138 With argument, move up ARG levels."
24139 (if (fboundp 'outline-up-heading-all)
24140 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24141 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24143 (defun org-up-heading-safe ()
24144 "Move to the heading line of which the present line is a subheading.
24145 This version will not throw an error. It will return the level of the
24146 headline found, or nil if no higher level is found.
24148 Also, this function will be a lot faster than `outline-up-heading',
24149 because it relies on stars being the outline starters. This can really
24150 make a significant difference in outlines with very many siblings."
24151 (when (ignore-errors (org-back-to-heading t))
24152 (let ((level-up (1- (funcall outline-level))))
24153 (and (> level-up 0)
24154 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24155 (funcall outline-level)))))
24157 (defun org-first-sibling-p ()
24158 "Is this heading the first child of its parents?"
24159 (interactive)
24160 (let ((re org-outline-regexp-bol)
24161 level l)
24162 (unless (org-at-heading-p t)
24163 (user-error "Not at a heading"))
24164 (setq level (funcall outline-level))
24165 (save-excursion
24166 (if (not (re-search-backward re nil t))
24168 (setq l (funcall outline-level))
24169 (< l level)))))
24171 (defun org-goto-sibling (&optional previous)
24172 "Goto the next sibling, even if it is invisible.
24173 When PREVIOUS is set, go to the previous sibling instead. Returns t
24174 when a sibling was found. When none is found, return nil and don't
24175 move point."
24176 (let ((fun (if previous 're-search-backward 're-search-forward))
24177 (pos (point))
24178 (re org-outline-regexp-bol)
24179 level l)
24180 (when (ignore-errors (org-back-to-heading t))
24181 (setq level (funcall outline-level))
24182 (catch 'exit
24183 (or previous (forward-char 1))
24184 (while (funcall fun re nil t)
24185 (setq l (funcall outline-level))
24186 (when (< l level) (goto-char pos) (throw 'exit nil))
24187 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24188 (goto-char pos)
24189 nil))))
24191 (defun org-show-siblings ()
24192 "Show all siblings of the current headline."
24193 (save-excursion
24194 (while (org-goto-sibling) (org-flag-heading nil)))
24195 (save-excursion
24196 (while (org-goto-sibling 'previous)
24197 (org-flag-heading nil))))
24199 (defun org-goto-first-child ()
24200 "Goto the first child, even if it is invisible.
24201 Return t when a child was found. Otherwise don't move point and
24202 return nil."
24203 (let (level (pos (point)) (re org-outline-regexp-bol))
24204 (when (ignore-errors (org-back-to-heading t))
24205 (setq level (outline-level))
24206 (forward-char 1)
24207 (if (and (re-search-forward re nil t) (> (outline-level) level))
24208 (progn (goto-char (match-beginning 0)) t)
24209 (goto-char pos) nil))))
24211 (defun org-show-hidden-entry ()
24212 "Show an entry where even the heading is hidden."
24213 (save-excursion
24214 (org-show-entry)))
24216 (defun org-flag-heading (flag &optional entry)
24217 "Flag the current heading. FLAG non-nil means make invisible.
24218 When ENTRY is non-nil, show the entire entry."
24219 (save-excursion
24220 (org-back-to-heading t)
24221 ;; Check if we should show the entire entry
24222 (if entry
24223 (progn
24224 (org-show-entry)
24225 (save-excursion
24226 (and (outline-next-heading)
24227 (org-flag-heading nil))))
24228 (outline-flag-region (max (point-min) (1- (point)))
24229 (save-excursion (outline-end-of-heading) (point))
24230 flag))))
24232 (defun org-get-next-sibling ()
24233 "Move to next heading of the same level, and return point.
24234 If there is no such heading, return nil.
24235 This is like outline-next-sibling, but invisible headings are ok."
24236 (let ((level (funcall outline-level)))
24237 (outline-next-heading)
24238 (while (and (not (eobp)) (> (funcall outline-level) level))
24239 (outline-next-heading))
24240 (if (or (eobp) (< (funcall outline-level) level))
24242 (point))))
24244 (defun org-get-last-sibling ()
24245 "Move to previous heading of the same level, and return point.
24246 If there is no such heading, return nil."
24247 (let ((opoint (point))
24248 (level (funcall outline-level)))
24249 (outline-previous-heading)
24250 (when (and (/= (point) opoint) (outline-on-heading-p t))
24251 (while (and (> (funcall outline-level) level)
24252 (not (bobp)))
24253 (outline-previous-heading))
24254 (if (< (funcall outline-level) level)
24256 (point)))))
24258 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24259 "Goto to the end of a subtree."
24260 ;; This contains an exact copy of the original function, but it uses
24261 ;; `org-back-to-heading', to make it work also in invisible
24262 ;; trees. And is uses an invisible-ok argument.
24263 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24264 ;; Furthermore, when used inside Org, finding the end of a large subtree
24265 ;; with many children and grandchildren etc, this can be much faster
24266 ;; than the outline version.
24267 (org-back-to-heading invisible-ok)
24268 (let ((first t)
24269 (level (funcall outline-level)))
24270 (if (and (derived-mode-p 'org-mode) (< level 1000))
24271 ;; A true heading (not a plain list item), in Org-mode
24272 ;; This means we can easily find the end by looking
24273 ;; only for the right number of stars. Using a regexp to do
24274 ;; this is so much faster than using a Lisp loop.
24275 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24276 (forward-char 1)
24277 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24278 ;; something else, do it the slow way
24279 (while (and (not (eobp))
24280 (or first (> (funcall outline-level) level)))
24281 (setq first nil)
24282 (outline-next-heading)))
24283 (unless to-heading
24284 (if (memq (preceding-char) '(?\n ?\^M))
24285 (progn
24286 ;; Go to end of line before heading
24287 (forward-char -1)
24288 (if (memq (preceding-char) '(?\n ?\^M))
24289 ;; leave blank line before heading
24290 (forward-char -1))))))
24291 (point))
24293 (defun org-end-of-meta-data (&optional full)
24294 "Skip planning line and properties drawer in current entry.
24295 When optional argument FULL is non-nil, also skip empty lines,
24296 clocking lines and regular drawers at the beginning of the
24297 entry."
24298 (org-back-to-heading t)
24299 (forward-line)
24300 (when (org-looking-at-p org-planning-line-re) (forward-line))
24301 (when (looking-at org-property-drawer-re)
24302 (goto-char (match-end 0))
24303 (forward-line))
24304 (when (and full (not (org-at-heading-p)))
24305 (catch 'exit
24306 (let ((end (save-excursion (outline-next-heading) (point)))
24307 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24308 (while (not (eobp))
24309 (cond ((org-looking-at-p org-drawer-regexp)
24310 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24311 (forward-line)
24312 (throw 'exit t)))
24313 ((org-looking-at-p re) (forward-line))
24314 (t (throw 'exit t))))))))
24316 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24317 "Move forward to the ARG'th subheading at same level as this one.
24318 Stop at the first and last subheadings of a superior heading.
24319 Normally this only looks at visible headings, but when INVISIBLE-OK is
24320 non-nil it will also look at invisible ones."
24321 (interactive "p")
24322 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24323 (if (and arg (< arg 0))
24324 (goto-char (point-min))
24325 (outline-next-heading))
24326 (org-at-heading-p)
24327 (let ((level (- (match-end 0) (match-beginning 0) 1))
24328 (f (if (and arg (< arg 0))
24329 're-search-backward
24330 're-search-forward))
24331 (count (if arg (abs arg) 1))
24332 (result (point)))
24333 (while (and (prog1 (> count 0)
24334 (forward-char (if (and arg (< arg 0)) -1 1)))
24335 (funcall f org-outline-regexp-bol nil 'move))
24336 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24337 (cond ((< l level) (setq count 0))
24338 ((and (= l level)
24339 (or invisible-ok
24340 (progn
24341 (goto-char (line-beginning-position))
24342 (not (outline-invisible-p)))))
24343 (setq count (1- count))
24344 (when (eq l level)
24345 (setq result (point)))))))
24346 (goto-char result))
24347 (beginning-of-line 1)))
24349 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24350 "Move backward to the ARG'th subheading at same level as this one.
24351 Stop at the first and last subheadings of a superior heading."
24352 (interactive "p")
24353 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24355 (defun org-next-visible-heading (arg)
24356 "Move to the next visible heading.
24358 This function wraps `outline-next-visible-heading' with
24359 `org-with-limited-levels' in order to skip over inline tasks and
24360 respect customization of `org-odd-levels-only'."
24361 (interactive "p")
24362 (org-with-limited-levels
24363 (outline-next-visible-heading arg)))
24365 (defun org-previous-visible-heading (arg)
24366 "Move to the next visible heading.
24368 This function wraps `outline-previous-visible-heading' with
24369 `org-with-limited-levels' in order to skip over inline tasks and
24370 respect customization of `org-odd-levels-only'."
24371 (interactive "p")
24372 (org-with-limited-levels
24373 (outline-previous-visible-heading arg)))
24375 (defun org-next-block (arg &optional backward block-regexp)
24376 "Jump to the next block.
24378 With a prefix argument ARG, jump forward ARG many blocks.
24380 When BACKWARD is non-nil, jump to the previous block.
24382 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24383 Match data is set according to this regexp when the function
24384 returns.
24386 Return point at beginning of the opening line of found block.
24387 Throw an error if no block is found."
24388 (interactive "p")
24389 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24390 (case-fold-search t)
24391 (search-fn (if backward #'re-search-backward #'re-search-forward))
24392 (count (or arg 1))
24393 (origin (point))
24394 last-element)
24395 (if backward (beginning-of-line) (end-of-line))
24396 (while (and (> count 0) (funcall search-fn re nil t))
24397 (let ((element (save-excursion
24398 (goto-char (match-beginning 0))
24399 (save-match-data (org-element-at-point)))))
24400 (when (and (memq (org-element-type element)
24401 '(center-block comment-block dynamic-block
24402 example-block export-block quote-block
24403 special-block src-block verse-block))
24404 (<= (match-beginning 0)
24405 (org-element-property :post-affiliated element)))
24406 (setq last-element element)
24407 (decf count))))
24408 (if (= count 0)
24409 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24410 (save-match-data (org-show-context)))
24411 (goto-char origin)
24412 (user-error "No %s code blocks" (if backward "previous" "further")))))
24414 (defun org-previous-block (arg &optional block-regexp)
24415 "Jump to the previous block.
24416 With a prefix argument ARG, jump backward ARG many source blocks.
24417 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24418 (interactive "p")
24419 (org-next-block arg t block-regexp))
24421 (defun org-forward-paragraph ()
24422 "Move forward to beginning of next paragraph or equivalent.
24424 The function moves point to the beginning of the next visible
24425 structural element, which can be a paragraph, a table, a list
24426 item, etc. It also provides some special moves for convenience:
24428 - On an affiliated keyword, jump to the beginning of the
24429 relative element.
24430 - On an item or a footnote definition, move to the second
24431 element inside, if any.
24432 - On a table or a property drawer, jump after it.
24433 - On a verse or source block, stop after blank lines."
24434 (interactive)
24435 (when (eobp) (user-error "Cannot move further down"))
24436 (let* ((deactivate-mark nil)
24437 (element (org-element-at-point))
24438 (type (org-element-type element))
24439 (post-affiliated (org-element-property :post-affiliated element))
24440 (contents-begin (org-element-property :contents-begin element))
24441 (contents-end (org-element-property :contents-end element))
24442 (end (let ((end (org-element-property :end element)) (parent element))
24443 (while (and (setq parent (org-element-property :parent parent))
24444 (= (org-element-property :contents-end parent) end))
24445 (setq end (org-element-property :end parent)))
24446 end)))
24447 (cond ((not element)
24448 (skip-chars-forward " \r\t\n")
24449 (or (eobp) (beginning-of-line)))
24450 ;; On affiliated keywords, move to element's beginning.
24451 ((< (point) post-affiliated)
24452 (goto-char post-affiliated))
24453 ;; At a table row, move to the end of the table. Similarly,
24454 ;; at a node property, move to the end of the property
24455 ;; drawer.
24456 ((memq type '(node-property table-row))
24457 (goto-char (org-element-property
24458 :end (org-element-property :parent element))))
24459 ((memq type '(property-drawer table)) (goto-char end))
24460 ;; Consider blank lines as separators in verse and source
24461 ;; blocks to ease editing.
24462 ((memq type '(src-block verse-block))
24463 (when (eq type 'src-block)
24464 (setq contents-end
24465 (save-excursion (goto-char end)
24466 (skip-chars-backward " \r\t\n")
24467 (line-beginning-position))))
24468 (beginning-of-line)
24469 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24470 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24471 (goto-char end)
24472 (skip-chars-forward " \r\t\n")
24473 (if (= (point) contents-end) (goto-char end)
24474 (beginning-of-line))))
24475 ;; With no contents, just skip element.
24476 ((not contents-begin) (goto-char end))
24477 ;; If contents are invisible, skip the element altogether.
24478 ((outline-invisible-p (line-end-position))
24479 (case type
24480 (headline
24481 (org-with-limited-levels (outline-next-visible-heading 1)))
24482 ;; At a plain list, make sure we move to the next item
24483 ;; instead of skipping the whole list.
24484 (plain-list (forward-char)
24485 (org-forward-paragraph))
24486 (otherwise (goto-char end))))
24487 ((>= (point) contents-end) (goto-char end))
24488 ((>= (point) contents-begin)
24489 ;; This can only happen on paragraphs and plain lists.
24490 (case type
24491 (paragraph (goto-char end))
24492 ;; At a plain list, try to move to second element in
24493 ;; first item, if possible.
24494 (plain-list (end-of-line)
24495 (org-forward-paragraph))))
24496 ;; When contents start on the middle of a line (e.g. in
24497 ;; items and footnote definitions), try to reach first
24498 ;; element starting after current line.
24499 ((> (line-end-position) contents-begin)
24500 (end-of-line)
24501 (org-forward-paragraph))
24502 (t (goto-char contents-begin)))))
24504 (defun org-backward-paragraph ()
24505 "Move backward to start of previous paragraph or equivalent.
24507 The function moves point to the beginning of the current
24508 structural element, which can be a paragraph, a table, a list
24509 item, etc., or to the beginning of the previous visible one if
24510 point is already there. It also provides some special moves for
24511 convenience:
24513 - On an affiliated keyword, jump to the first one.
24514 - On a table or a property drawer, move to its beginning.
24515 - On a verse or source block, stop before blank lines."
24516 (interactive)
24517 (when (bobp) (user-error "Cannot move further up"))
24518 (let* ((deactivate-mark nil)
24519 (element (org-element-at-point))
24520 (type (org-element-type element))
24521 (contents-begin (org-element-property :contents-begin element))
24522 (contents-end (org-element-property :contents-end element))
24523 (post-affiliated (org-element-property :post-affiliated element))
24524 (begin (org-element-property :begin element)))
24525 (cond
24526 ((not element) (goto-char (point-min)))
24527 ((= (point) begin)
24528 (backward-char)
24529 (org-backward-paragraph))
24530 ((<= (point) post-affiliated) (goto-char begin))
24531 ((memq type '(node-property table-row))
24532 (goto-char (org-element-property
24533 :post-affiliated (org-element-property :parent element))))
24534 ((memq type '(property-drawer table)) (goto-char begin))
24535 ((memq type '(src-block verse-block))
24536 (when (eq type 'src-block)
24537 (setq contents-begin
24538 (save-excursion (goto-char begin) (forward-line) (point))))
24539 (if (= (point) contents-begin) (goto-char post-affiliated)
24540 ;; Inside a verse block, see blank lines as paragraph
24541 ;; separators.
24542 (let ((origin (point)))
24543 (skip-chars-backward " \r\t\n" contents-begin)
24544 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24545 (skip-chars-forward " \r\t\n" origin)
24546 (if (= (point) origin) (goto-char contents-begin)
24547 (beginning-of-line))))))
24548 ((not contents-begin) (goto-char (or post-affiliated begin)))
24549 ((eq type 'paragraph)
24550 (goto-char contents-begin)
24551 ;; When at first paragraph in an item or a footnote definition,
24552 ;; move directly to beginning of line.
24553 (let ((parent-contents
24554 (org-element-property
24555 :contents-begin (org-element-property :parent element))))
24556 (when (and parent-contents (= parent-contents contents-begin))
24557 (beginning-of-line))))
24558 ;; At the end of a greater element, move to the beginning of the
24559 ;; last element within.
24560 ((>= (point) contents-end)
24561 (goto-char (1- contents-end))
24562 (org-backward-paragraph))
24563 (t (goto-char (or post-affiliated begin))))
24564 ;; Ensure we never leave point invisible.
24565 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24567 (defun org-forward-element ()
24568 "Move forward by one element.
24569 Move to the next element at the same level, when possible."
24570 (interactive)
24571 (cond ((eobp) (user-error "Cannot move further down"))
24572 ((org-with-limited-levels (org-at-heading-p))
24573 (let ((origin (point)))
24574 (goto-char (org-end-of-subtree nil t))
24575 (unless (org-with-limited-levels (org-at-heading-p))
24576 (goto-char origin)
24577 (user-error "Cannot move further down"))))
24579 (let* ((elem (org-element-at-point))
24580 (end (org-element-property :end elem))
24581 (parent (org-element-property :parent elem)))
24582 (cond ((and parent (= (org-element-property :contents-end parent) end))
24583 (goto-char (org-element-property :end parent)))
24584 ((integer-or-marker-p end) (goto-char end))
24585 (t (message "No element at point")))))))
24587 (defun org-backward-element ()
24588 "Move backward by one element.
24589 Move to the previous element at the same level, when possible."
24590 (interactive)
24591 (cond ((bobp) (user-error "Cannot move further up"))
24592 ((org-with-limited-levels (org-at-heading-p))
24593 ;; At a headline, move to the previous one, if any, or stay
24594 ;; here.
24595 (let ((origin (point)))
24596 (org-with-limited-levels (org-backward-heading-same-level 1))
24597 ;; When current headline has no sibling above, move to its
24598 ;; parent.
24599 (when (= (point) origin)
24600 (or (org-with-limited-levels (org-up-heading-safe))
24601 (progn (goto-char origin)
24602 (user-error "Cannot move further up"))))))
24604 (let* ((elem (org-element-at-point))
24605 (beg (org-element-property :begin elem)))
24606 (cond
24607 ;; Move to beginning of current element if point isn't
24608 ;; there already.
24609 ((null beg) (message "No element at point"))
24610 ((/= (point) beg) (goto-char beg))
24611 (t (goto-char beg)
24612 (skip-chars-backward " \r\t\n")
24613 (unless (bobp)
24614 (let ((prev (org-element-at-point)))
24615 (goto-char (org-element-property :begin prev))
24616 (while (and (setq prev (org-element-property :parent prev))
24617 (<= (org-element-property :end prev) beg))
24618 (goto-char (org-element-property :begin prev)))))))))))
24620 (defun org-up-element ()
24621 "Move to upper element."
24622 (interactive)
24623 (if (org-with-limited-levels (org-at-heading-p))
24624 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24625 (let* ((elem (org-element-at-point))
24626 (parent (org-element-property :parent elem)))
24627 (if parent (goto-char (org-element-property :begin parent))
24628 (if (org-with-limited-levels (org-before-first-heading-p))
24629 (user-error "No surrounding element")
24630 (org-with-limited-levels (org-back-to-heading)))))))
24632 (defvar org-element-greater-elements)
24633 (defun org-down-element ()
24634 "Move to inner element."
24635 (interactive)
24636 (let ((element (org-element-at-point)))
24637 (cond
24638 ((memq (org-element-type element) '(plain-list table))
24639 (goto-char (org-element-property :contents-begin element))
24640 (forward-char))
24641 ((memq (org-element-type element) org-element-greater-elements)
24642 ;; If contents are hidden, first disclose them.
24643 (when (outline-invisible-p (line-end-position)) (org-cycle))
24644 (goto-char (or (org-element-property :contents-begin element)
24645 (user-error "No content for this element"))))
24646 (t (user-error "No inner element")))))
24648 (defun org-drag-element-backward ()
24649 "Move backward element at point."
24650 (interactive)
24651 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24652 (let* ((elem (org-element-at-point))
24653 (prev-elem
24654 (save-excursion
24655 (goto-char (org-element-property :begin elem))
24656 (skip-chars-backward " \r\t\n")
24657 (unless (bobp)
24658 (let* ((beg (org-element-property :begin elem))
24659 (prev (org-element-at-point))
24660 (up prev))
24661 (while (and (setq up (org-element-property :parent up))
24662 (<= (org-element-property :end up) beg))
24663 (setq prev up))
24664 prev)))))
24665 ;; Error out if no previous element or previous element is
24666 ;; a parent of the current one.
24667 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24668 (user-error "Cannot drag element backward")
24669 (let ((pos (point)))
24670 (org-element-swap-A-B prev-elem elem)
24671 (goto-char (+ (org-element-property :begin prev-elem)
24672 (- pos (org-element-property :begin elem)))))))))
24674 (defun org-drag-element-forward ()
24675 "Move forward element at point."
24676 (interactive)
24677 (let* ((pos (point))
24678 (elem (org-element-at-point)))
24679 (when (= (point-max) (org-element-property :end elem))
24680 (user-error "Cannot drag element forward"))
24681 (goto-char (org-element-property :end elem))
24682 (let ((next-elem (org-element-at-point)))
24683 (when (or (org-element-nested-p elem next-elem)
24684 (and (eq (org-element-type next-elem) 'headline)
24685 (not (eq (org-element-type elem) 'headline))))
24686 (goto-char pos)
24687 (user-error "Cannot drag element forward"))
24688 ;; Compute new position of point: it's shifted by NEXT-ELEM
24689 ;; body's length (without final blanks) and by the length of
24690 ;; blanks between ELEM and NEXT-ELEM.
24691 (let ((size-next (- (save-excursion
24692 (goto-char (org-element-property :end next-elem))
24693 (skip-chars-backward " \r\t\n")
24694 (forward-line)
24695 ;; Small correction if buffer doesn't end
24696 ;; with a newline character.
24697 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24698 (org-element-property :begin next-elem)))
24699 (size-blank (- (org-element-property :end elem)
24700 (save-excursion
24701 (goto-char (org-element-property :end elem))
24702 (skip-chars-backward " \r\t\n")
24703 (forward-line)
24704 (point)))))
24705 (org-element-swap-A-B elem next-elem)
24706 (goto-char (+ pos size-next size-blank))))))
24708 (defun org-drag-line-forward (arg)
24709 "Drag the line at point ARG lines forward."
24710 (interactive "p")
24711 (dotimes (n (abs arg))
24712 (let ((c (current-column)))
24713 (if (< 0 arg)
24714 (progn
24715 (beginning-of-line 2)
24716 (transpose-lines 1)
24717 (beginning-of-line 0))
24718 (transpose-lines 1)
24719 (beginning-of-line -1))
24720 (org-move-to-column c))))
24722 (defun org-drag-line-backward (arg)
24723 "Drag the line at point ARG lines backward."
24724 (interactive "p")
24725 (org-drag-line-forward (- arg)))
24727 (defun org-mark-element ()
24728 "Put point at beginning of this element, mark at end.
24730 Interactively, if this command is repeated or (in Transient Mark
24731 mode) if the mark is active, it marks the next element after the
24732 ones already marked."
24733 (interactive)
24734 (let (deactivate-mark)
24735 (if (and (org-called-interactively-p 'any)
24736 (or (and (eq last-command this-command) (mark t))
24737 (and transient-mark-mode mark-active)))
24738 (set-mark
24739 (save-excursion
24740 (goto-char (mark))
24741 (goto-char (org-element-property :end (org-element-at-point)))))
24742 (let ((element (org-element-at-point)))
24743 (end-of-line)
24744 (push-mark (org-element-property :end element) t t)
24745 (goto-char (org-element-property :begin element))))))
24747 (defun org-narrow-to-element ()
24748 "Narrow buffer to current element."
24749 (interactive)
24750 (let ((elem (org-element-at-point)))
24751 (cond
24752 ((eq (car elem) 'headline)
24753 (narrow-to-region
24754 (org-element-property :begin elem)
24755 (org-element-property :end elem)))
24756 ((memq (car elem) org-element-greater-elements)
24757 (narrow-to-region
24758 (org-element-property :contents-begin elem)
24759 (org-element-property :contents-end elem)))
24761 (narrow-to-region
24762 (org-element-property :begin elem)
24763 (org-element-property :end elem))))))
24765 (defun org-transpose-element ()
24766 "Transpose current and previous elements, keeping blank lines between.
24767 Point is moved after both elements."
24768 (interactive)
24769 (org-skip-whitespace)
24770 (let ((end (org-element-property :end (org-element-at-point))))
24771 (org-drag-element-backward)
24772 (goto-char end)))
24774 (defun org-unindent-buffer ()
24775 "Un-indent the visible part of the buffer.
24776 Relative indentation (between items, inside blocks, etc.) isn't
24777 modified."
24778 (interactive)
24779 (unless (eq major-mode 'org-mode)
24780 (user-error "Cannot un-indent a buffer not in Org mode"))
24781 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24782 unindent-tree ; For byte-compiler.
24783 (unindent-tree
24784 (function
24785 (lambda (contents)
24786 (mapc
24787 (lambda (element)
24788 (if (memq (org-element-type element) '(headline section))
24789 (funcall unindent-tree (org-element-contents element))
24790 (save-excursion
24791 (save-restriction
24792 (narrow-to-region
24793 (org-element-property :begin element)
24794 (org-element-property :end element))
24795 (org-do-remove-indentation)))))
24796 (reverse contents))))))
24797 (funcall unindent-tree (org-element-contents parse-tree))))
24799 (defun org-show-subtree ()
24800 "Show everything after this heading at deeper levels."
24801 (interactive)
24802 (outline-flag-region
24803 (point)
24804 (save-excursion
24805 (org-end-of-subtree t t))
24806 nil))
24808 (defun org-show-entry ()
24809 "Show the body directly following this heading.
24810 Show the heading too, if it is currently invisible."
24811 (interactive)
24812 (save-excursion
24813 (ignore-errors
24814 (org-back-to-heading t)
24815 (outline-flag-region
24816 (max (point-min) (1- (point)))
24817 (save-excursion
24818 (if (re-search-forward
24819 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24820 (match-beginning 1)
24821 (point-max)))
24822 nil)
24823 (org-cycle-hide-drawers 'children))))
24825 (defun org-make-options-regexp (kwds &optional extra)
24826 "Make a regular expression for keyword lines.
24827 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24828 when non-nil, is a regexp matching keywords names."
24829 (concat "^[ \t]*#\\+\\("
24830 (regexp-opt kwds)
24831 (and extra (concat (and kwds "\\|") extra))
24832 "\\):[ \t]*\\(.*\\)"))
24834 ;; Make isearch reveal the necessary context
24835 (defun org-isearch-end ()
24836 "Reveal context after isearch exits."
24837 (when isearch-success ; only if search was successful
24838 (if (featurep 'xemacs)
24839 ;; Under XEmacs, the hook is run in the correct place,
24840 ;; we directly show the context.
24841 (org-show-context 'isearch)
24842 ;; In Emacs the hook runs *before* restoring the overlays.
24843 ;; So we have to use a one-time post-command-hook to do this.
24844 ;; (Emacs 22 has a special variable, see function `org-mode')
24845 (unless (and (boundp 'isearch-mode-end-hook-quit)
24846 isearch-mode-end-hook-quit)
24847 ;; Only when the isearch was not quitted.
24848 (org-add-hook 'post-command-hook 'org-isearch-post-command
24849 'append 'local)))))
24851 (defun org-isearch-post-command ()
24852 "Remove self from hook, and show context."
24853 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24854 (org-show-context 'isearch))
24857 ;;;; Integration with and fixes for other packages
24859 ;;; Imenu support
24861 (defvar org-imenu-markers nil
24862 "All markers currently used by Imenu.")
24863 (make-variable-buffer-local 'org-imenu-markers)
24865 (defun org-imenu-new-marker (&optional pos)
24866 "Return a new marker for use by Imenu, and remember the marker."
24867 (let ((m (make-marker)))
24868 (move-marker m (or pos (point)))
24869 (push m org-imenu-markers)
24872 (defun org-imenu-get-tree ()
24873 "Produce the index for Imenu."
24874 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24875 (setq org-imenu-markers nil)
24876 (let* ((n org-imenu-depth)
24877 (re (concat "^" (org-get-limited-outline-regexp)))
24878 (subs (make-vector (1+ n) nil))
24879 (last-level 0)
24880 m level head0 head)
24881 (save-excursion
24882 (save-restriction
24883 (widen)
24884 (goto-char (point-max))
24885 (while (re-search-backward re nil t)
24886 (setq level (org-reduced-level (funcall outline-level)))
24887 (when (and (<= level n)
24888 (looking-at org-complex-heading-regexp)
24889 (setq head0 (org-match-string-no-properties 4)))
24890 (setq head (org-link-display-format head0)
24891 m (org-imenu-new-marker))
24892 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24893 (if (>= level last-level)
24894 (push (cons head m) (aref subs level))
24895 (push (cons head (aref subs (1+ level))) (aref subs level))
24896 (loop for i from (1+ level) to n do (aset subs i nil)))
24897 (setq last-level level)))))
24898 (aref subs 1)))
24900 (eval-after-load "imenu"
24901 '(progn
24902 (add-hook 'imenu-after-jump-hook
24903 (lambda ()
24904 (if (derived-mode-p 'org-mode)
24905 (org-show-context 'org-goto))))))
24907 (defun org-link-display-format (link)
24908 "Replace a link with its the description.
24909 If there is no description, use the link target."
24910 (save-match-data
24911 (if (string-match org-bracket-link-analytic-regexp link)
24912 (replace-match (if (match-end 5)
24913 (match-string 5 link)
24914 (concat (match-string 1 link)
24915 (match-string 3 link)))
24916 nil t link)
24917 link)))
24919 (defun org-toggle-link-display ()
24920 "Toggle the literal or descriptive display of links."
24921 (interactive)
24922 (if org-descriptive-links
24923 (progn (org-remove-from-invisibility-spec '(org-link))
24924 (org-restart-font-lock)
24925 (setq org-descriptive-links nil))
24926 (progn (add-to-invisibility-spec '(org-link))
24927 (org-restart-font-lock)
24928 (setq org-descriptive-links t))))
24930 ;; Speedbar support
24932 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24933 "Overlay marking the agenda restriction line in speedbar.")
24934 (overlay-put org-speedbar-restriction-lock-overlay
24935 'face 'org-agenda-restriction-lock)
24936 (overlay-put org-speedbar-restriction-lock-overlay
24937 'help-echo "Agendas are currently limited to this item.")
24938 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24940 (defun org-speedbar-set-agenda-restriction ()
24941 "Restrict future agenda commands to the location at point in speedbar.
24942 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24943 (interactive)
24944 (require 'org-agenda)
24945 (let (p m tp np dir txt)
24946 (cond
24947 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24948 'org-imenu t))
24949 (setq m (get-text-property p 'org-imenu-marker))
24950 (with-current-buffer (marker-buffer m)
24951 (goto-char m)
24952 (org-agenda-set-restriction-lock 'subtree)))
24953 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24954 'speedbar-function 'speedbar-find-file))
24955 (setq tp (previous-single-property-change
24956 (1+ p) 'speedbar-function)
24957 np (next-single-property-change
24958 tp 'speedbar-function)
24959 dir (speedbar-line-directory)
24960 txt (buffer-substring-no-properties (or tp (point-min))
24961 (or np (point-max))))
24962 (with-current-buffer (find-file-noselect
24963 (let ((default-directory dir))
24964 (expand-file-name txt)))
24965 (unless (derived-mode-p 'org-mode)
24966 (user-error "Cannot restrict to non-Org-mode file"))
24967 (org-agenda-set-restriction-lock 'file)))
24968 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24969 (move-overlay org-speedbar-restriction-lock-overlay
24970 (point-at-bol) (point-at-eol))
24971 (setq current-prefix-arg nil)
24972 (org-agenda-maybe-redo)))
24974 (defvar speedbar-file-key-map)
24975 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24976 (eval-after-load "speedbar"
24977 '(progn
24978 (speedbar-add-supported-extension ".org")
24979 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24980 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24981 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24982 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24983 (add-hook 'speedbar-visiting-tag-hook
24984 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24986 ;;; Fixes and Hacks for problems with other packages
24988 (defun org--flyspell-object-check-p (element)
24989 "Non-nil when Flyspell can check object at point.
24990 ELEMENT is the element at point."
24991 (let ((object (save-excursion
24992 (when (org-looking-at-p "\\>") (backward-char))
24993 (org-element-context element))))
24994 (case (org-element-type object)
24995 ;; Prevent checks in links due to keybinding conflict with
24996 ;; Flyspell.
24997 ((code entity export-snippet inline-babel-call
24998 inline-src-block line-break latex-fragment link macro
24999 statistics-cookie target timestamp verbatim)
25000 nil)
25001 (footnote-reference
25002 ;; Only in inline footnotes, within the definition.
25003 (and (eq (org-element-property :type object) 'inline)
25004 (< (save-excursion
25005 (goto-char (org-element-property :begin object))
25006 (search-forward ":" nil t 2))
25007 (point))))
25008 (otherwise t))))
25010 (defun org-mode-flyspell-verify ()
25011 "Function used for `flyspell-generic-check-word-predicate'."
25012 (if (org-at-heading-p)
25013 ;; At a headline or an inlinetask, check title only. This is
25014 ;; faster than relying on `org-element-at-point'.
25015 (and (save-excursion (beginning-of-line)
25016 (and (let ((case-fold-search t))
25017 (not (looking-at "\\*+ END[ \t]*$")))
25018 (looking-at org-complex-heading-regexp)))
25019 (match-beginning 4)
25020 (>= (point) (match-beginning 4))
25021 (or (not (match-beginning 5))
25022 (< (point) (match-beginning 5))))
25023 (let* ((element (org-element-at-point))
25024 (post-affiliated (org-element-property :post-affiliated element)))
25025 (cond
25026 ;; Ignore checks in all affiliated keywords but captions.
25027 ((< (point) post-affiliated)
25028 (and (save-excursion
25029 (beginning-of-line)
25030 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25031 (> (point) (match-end 0))
25032 (org--flyspell-object-check-p element)))
25033 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25034 ((let ((log (org-log-into-drawer)))
25035 (and log
25036 (let ((drawer (org-element-lineage element '(drawer))))
25037 (and drawer
25038 (eq (compare-strings
25039 log nil nil
25040 (org-element-property :drawer-name drawer) nil nil t)
25041 t)))))
25042 nil)
25044 (case (org-element-type element)
25045 ((comment quote-section) t)
25046 (comment-block
25047 ;; Allow checks between block markers, not on them.
25048 (and (> (line-beginning-position) post-affiliated)
25049 (save-excursion
25050 (end-of-line)
25051 (skip-chars-forward " \r\t\n")
25052 (< (point) (org-element-property :end element)))))
25053 ;; Arbitrary list of keywords where checks are meaningful.
25054 ;; Make sure point is on the value part of the element.
25055 (keyword
25056 (and (member (org-element-property :key element)
25057 '("DESCRIPTION" "TITLE"))
25058 (save-excursion
25059 (search-backward ":" (line-beginning-position) t))))
25060 ;; Check is globally allowed in paragraphs verse blocks and
25061 ;; table rows (after affiliated keywords) but some objects
25062 ;; must not be affected.
25063 ((paragraph table-row verse-block)
25064 (let ((cbeg (org-element-property :contents-begin element))
25065 (cend (org-element-property :contents-end element)))
25066 (and cbeg (>= (point) cbeg) (< (point) cend)
25067 (org--flyspell-object-check-p element))))))))))
25068 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25070 (defun org-remove-flyspell-overlays-in (beg end)
25071 "Remove flyspell overlays in region."
25072 (and (org-bound-and-true-p flyspell-mode)
25073 (fboundp 'flyspell-delete-region-overlays)
25074 (flyspell-delete-region-overlays beg end)))
25076 (defvar flyspell-delayed-commands)
25077 (eval-after-load "flyspell"
25078 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25080 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25081 (eval-after-load "bookmark"
25082 '(if (boundp 'bookmark-after-jump-hook)
25083 ;; We can use the hook
25084 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25085 ;; Hook not available, use advice
25086 (defadvice bookmark-jump (after org-make-visible activate)
25087 "Make the position visible."
25088 (org-bookmark-jump-unhide))))
25090 ;; Make sure saveplace shows the location if it was hidden
25091 (eval-after-load "saveplace"
25092 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25093 "Make the position visible."
25094 (org-bookmark-jump-unhide)))
25096 ;; Make sure ecb shows the location if it was hidden
25097 (eval-after-load "ecb"
25098 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25099 "Make hierarchy visible when jumping into location from ECB tree buffer."
25100 (if (derived-mode-p 'org-mode)
25101 (org-show-context))))
25103 (defun org-bookmark-jump-unhide ()
25104 "Unhide the current position, to show the bookmark location."
25105 (and (derived-mode-p 'org-mode)
25106 (or (outline-invisible-p)
25107 (save-excursion (goto-char (max (point-min) (1- (point))))
25108 (outline-invisible-p)))
25109 (org-show-context 'bookmark-jump)))
25111 (defun org-mark-jump-unhide ()
25112 "Make the point visible with `org-show-context' after jumping to the mark."
25113 (when (and (derived-mode-p 'org-mode)
25114 (outline-invisible-p))
25115 (org-show-context 'mark-goto)))
25117 (eval-after-load "simple"
25118 '(defadvice pop-to-mark-command (after org-make-visible activate)
25119 "Make the point visible with `org-show-context'."
25120 (org-mark-jump-unhide)))
25122 (eval-after-load "simple"
25123 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25124 "Make the point visible with `org-show-context'."
25125 (org-mark-jump-unhide)))
25127 (eval-after-load "simple"
25128 '(defadvice pop-global-mark (after org-make-visible activate)
25129 "Make the point visible with `org-show-context'."
25130 (org-mark-jump-unhide)))
25132 ;; Make session.el ignore our circular variable
25133 (defvar session-globals-exclude)
25134 (eval-after-load "session"
25135 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25137 ;;;; Finish up
25139 (provide 'org)
25141 (run-hooks 'org-load-hook)
25143 ;;; org.el ends here