Merge branch 'maint'
[org-mode.git] / lisp / org.el
blobdfaad81df6fd210f39f1204ba3188494a897e562
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-local org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
69 ;;;; Require other packages
71 (eval-when-compile
72 (require 'cl)
73 (require 'gnus-sum))
75 (require 'calendar)
76 (require 'find-func)
77 (require 'format-spec)
79 (or (equal this-command 'eval-buffer)
80 (condition-case nil
81 (load (concat (file-name-directory load-file-name)
82 "org-loaddefs.el")
83 nil t t t)
84 (error
85 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
86 (sit-for 3)
87 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
88 (sit-for 3))))
90 (require 'org-macs)
91 (require 'org-compat)
93 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
94 ;; some places -- e.g. see the macro `org-with-limited-levels'.
96 ;; In Org buffers, the value of `outline-regexp' is that of
97 ;; `org-outline-regexp'. The only function still directly relying on
98 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
99 ;; job when `orgstruct-mode' is active.
100 (defvar org-outline-regexp "\\*+ "
101 "Regexp to match Org headlines.")
103 (defvar org-outline-regexp-bol "^\\*+ "
104 "Regexp to match Org headlines.
105 This is similar to `org-outline-regexp' but additionally makes
106 sure that we are at the beginning of the line.")
108 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
109 "Matches a headline, putting stars and text into groups.
110 Stars are put in group 1 and the trimmed body in group 2.")
112 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
113 (unless (boundp 'calendar-view-holidays-initially-flag)
114 (org-defvaralias 'calendar-view-holidays-initially-flag
115 'view-calendar-holidays-initially))
116 (unless (boundp 'calendar-view-diary-initially-flag)
117 (org-defvaralias 'calendar-view-diary-initially-flag
118 'view-diary-entries-initially))
119 (unless (boundp 'diary-fancy-buffer)
120 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
122 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
123 (declare-function org-add-archive-files "org-archive" (files))
124 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
125 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
126 (declare-function org-agenda-redo "org-agenda" (&optional all))
127 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
128 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
129 (declare-function org-beamer-mode "ox-beamer" ())
130 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
131 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
132 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
133 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
134 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
135 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
136 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
137 (declare-function org-clock-update-time-maybe "org-clock" ())
138 (declare-function org-clocktable-shift "org-clock" (dir n))
139 (declare-function org-element-at-point "org-element" ())
140 (declare-function org-element-cache-refresh "org-element" (pos))
141 (declare-function org-element-cache-reset "org-element" (&optional all))
142 (declare-function org-element-contents "org-element" (element))
143 (declare-function org-element-context "org-element" (&optional element))
144 (declare-function org-element-copy "org-element" (datum))
145 (declare-function org-element-interpret-data "org-element" (data &optional parent))
146 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
149 (declare-function org-element-property "org-element" (property element))
150 (declare-function org-element-put-property "org-element" (element property value))
151 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
152 (declare-function org-element-type "org-element" (element))
153 (declare-function org-element-update-syntax "org-element" ())
154 (declare-function org-id-find-id-file "org-id" (id))
155 (declare-function org-id-get-create "org-id" (&optional force))
156 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
157 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
158 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
159 (declare-function org-plot/gnuplot "org-plot" (&optional params))
160 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
161 (declare-function org-table-align "org-table" ())
162 (declare-function org-table-begin "org-table" (&optional table-type))
163 (declare-function org-table-beginning-of-field "org-table" (&optional n))
164 (declare-function org-table-blank-field "org-table" ())
165 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
166 (declare-function org-table-edit-field "org-table" (arg))
167 (declare-function org-table-end "org-table" (&optional table-type))
168 (declare-function org-table-end-of-field "org-table" (&optional n))
169 (declare-function org-table-insert-row "org-table" (&optional arg))
170 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
171 (declare-function org-table-maybe-eval-formula "org-table" ())
172 (declare-function org-table-maybe-recalculate-line "org-table" ())
173 (declare-function org-table-next-row "org-table" ())
174 (declare-function org-table-paste-rectangle "org-table" ())
175 (declare-function org-table-wrap-region "org-table" (arg))
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 "Stan" stan)
303 (const :tag "ebnf2ps" ebnf2ps))
304 :value-type (boolean :tag "Activate" :value t)))
306 ;;;; Customization variables
307 (defcustom org-clone-delete-id nil
308 "Remove ID property of clones of a subtree.
309 When non-nil, clones of a subtree don't inherit the ID property.
310 Otherwise they inherit the ID property with a new unique
311 identifier."
312 :type 'boolean
313 :version "24.1"
314 :group 'org-id)
316 ;;; Version
317 (org-check-version)
319 ;;;###autoload
320 (defun org-version (&optional here full message)
321 "Show the org-mode version.
322 Interactively, or when MESSAGE is non-nil, show it in echo area.
323 With prefix argument, or when HERE is non-nil, insert it at point.
324 In non-interactive uses, a reduced version string is output unless
325 FULL is given."
326 (interactive (list current-prefix-arg t (not current-prefix-arg)))
327 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
328 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
329 (load-suffixes (list ".el"))
330 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
331 (org-trash (or
332 (and (fboundp 'org-release) (fboundp 'org-git-version))
333 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
334 (load-suffixes save-load-suffixes)
335 (org-version (org-release))
336 (git-version (org-git-version))
337 (version (format "Org-mode version %s (%s @ %s)"
338 org-version
339 git-version
340 (if org-install-dir
341 (if (string= org-dir org-install-dir)
342 org-install-dir
343 (concat "mixed installation! " org-install-dir " and " org-dir))
344 "org-loaddefs.el can not be found!")))
345 (version1 (if full version org-version)))
346 (when here (insert version1))
347 (when message (message "%s" version1))
348 version1))
350 (defconst org-version (org-version))
353 ;;; Syntax Constants
355 ;;;; Block
357 (defconst org-block-regexp
358 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
359 "Regular expression for hiding blocks.")
361 (defconst org-dblock-start-re
362 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
363 "Matches the start line of a dynamic block, with parameters.")
365 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
366 "Matches the end of a dynamic block.")
368 ;;;; Clock and Planning
370 (defconst org-clock-string "CLOCK:"
371 "String used as prefix for timestamps clocking work hours on an item.")
373 (defvar org-closed-string "CLOSED:"
374 "String used as the prefix for timestamps logging closing a TODO entry.")
376 (defvar org-deadline-string "DEADLINE:"
377 "String to mark deadline entries.
378 A deadline is this string, followed by a time stamp. Should be a word,
379 terminated by a colon. You can insert a schedule keyword and
380 a timestamp with \\[org-deadline].")
382 (defvar org-scheduled-string "SCHEDULED:"
383 "String to mark scheduled TODO entries.
384 A schedule is this string, followed by a time stamp. Should be a word,
385 terminated by a colon. You can insert a schedule keyword and
386 a timestamp with \\[org-schedule].")
388 (defconst org-ds-keyword-length
389 (+ 2
390 (apply #'max
391 (mapcar #'length
392 (list org-deadline-string org-scheduled-string
393 org-clock-string org-closed-string))))
394 "Maximum length of the DEADLINE and SCHEDULED keywords.")
396 (defconst org-planning-line-re
397 (concat "^[ \t]*"
398 (regexp-opt
399 (list org-closed-string org-deadline-string org-scheduled-string)
401 "Matches a line with planning info.
402 Matched keyword is in group 1.")
404 (defconst org-clock-line-re
405 (concat "^[ \t]*" org-clock-string)
406 "Matches a line with clock info.")
408 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
409 "Matches the DEADLINE keyword.")
411 (defconst org-deadline-time-regexp
412 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
413 "Matches the DEADLINE keyword together with a time stamp.")
415 (defconst org-deadline-time-hour-regexp
416 (concat "\\<" org-deadline-string
417 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
418 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
420 (defconst org-deadline-line-regexp
421 (concat "\\<\\(" org-deadline-string "\\).*")
422 "Matches the DEADLINE keyword and the rest of the line.")
424 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
425 "Matches the SCHEDULED keyword.")
427 (defconst org-scheduled-time-regexp
428 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
429 "Matches the SCHEDULED keyword together with a time stamp.")
431 (defconst org-scheduled-time-hour-regexp
432 (concat "\\<" org-scheduled-string
433 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
434 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
436 (defconst org-closed-time-regexp
437 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
438 "Matches the CLOSED keyword together with a time stamp.")
440 (defconst org-keyword-time-regexp
441 (concat "\\<"
442 (regexp-opt
443 (list org-scheduled-string org-deadline-string org-closed-string
444 org-clock-string)
446 " *[[<]\\([^]>]+\\)[]>]")
447 "Matches any of the 4 keywords, together with the time stamp.")
449 (defconst org-keyword-time-not-clock-regexp
450 (concat
451 "\\<"
452 (regexp-opt
453 (list org-scheduled-string org-deadline-string org-closed-string) t)
454 " *[[<]\\([^]>]+\\)[]>]")
455 "Matches any of the 3 keywords, together with the time stamp.")
457 (defconst org-maybe-keyword-time-regexp
458 (concat "\\(\\<"
459 (regexp-opt
460 (list org-scheduled-string org-deadline-string org-closed-string
461 org-clock-string)
463 "\\)?"
464 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
465 "\\|"
466 "<%%([^\r\n>]*>\\)")
467 "Matches a timestamp, possibly preceded by a keyword.")
469 (defconst org-all-time-keywords
470 (mapcar (lambda (w) (substring w 0 -1))
471 (list org-scheduled-string org-deadline-string
472 org-clock-string org-closed-string))
473 "List of time keywords.")
475 ;;;; Drawer
477 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
478 "Matches first or last line of a hidden block.
479 Group 1 contains drawer's name or \"END\".")
481 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
482 "Regular expression matching the first line of a property drawer.")
484 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
485 "Regular expression matching the last line of a property drawer.")
487 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
488 "Regular expression matching the first line of a clock drawer.")
490 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
491 "Regular expression matching the last line of a clock drawer.")
493 (defconst org-property-drawer-re
494 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
495 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
496 "[ \t]*:END:[ \t]*$")
497 "Matches an entire property drawer.")
499 (defconst org-clock-drawer-re
500 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
501 org-clock-drawer-end-re "\\)\n?")
502 "Matches an entire clock drawer.")
504 ;;;; Headline
506 (defconst org-heading-keyword-regexp-format
507 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
508 "Printf format for a regexp matching a headline with some keyword.
509 This regexp will match the headline of any node which has the
510 exact keyword that is put into the format. The keyword isn't in
511 any group by default, but the stars and the body are.")
513 (defconst org-heading-keyword-maybe-regexp-format
514 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
515 "Printf format for a regexp matching a headline, possibly with some keyword.
516 This regexp can match any headline with the specified keyword, or
517 without a keyword. The keyword isn't in any group by default,
518 but the stars and the body are.")
520 (defconst org-archive-tag "ARCHIVE"
521 "The tag that marks a subtree as archived.
522 An archived subtree does not open during visibility cycling, and does
523 not contribute to the agenda listings.")
525 (defconst org-comment-string "COMMENT"
526 "Entries starting with this keyword will never be exported.
527 An entry can be toggled between COMMENT and normal with
528 \\[org-toggle-comment].")
531 ;;;; LaTeX Environments and Fragments
533 (defconst org-latex-regexps
534 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
535 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
536 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
537 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
538 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
539 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
540 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
541 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
542 "Regular expressions for matching embedded LaTeX.")
544 ;;;; Node Property
546 (defconst org-effort-property "Effort"
547 "The property that is being used to keep track of effort estimates.
548 Effort estimates given in this property need to have the format H:MM.")
550 ;;;; Table
552 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
553 "Detect an org-type or table-type table.")
555 (defconst org-table-line-regexp "^[ \t]*|"
556 "Detect an org-type table line.")
558 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
559 "Detect an org-type table line.")
561 (defconst org-table-hline-regexp "^[ \t]*|-"
562 "Detect an org-type table hline.")
564 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
565 "Detect a table-type table hline.")
567 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
568 "Detect the first line outside a table when searching from within it.
569 This works for both table types.")
571 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
572 "Detect a #+TBLFM line.")
574 ;;;; Timestamp
576 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
577 "Regular expression for fast time stamp matching.")
579 (defconst org-ts-regexp-inactive
580 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
581 "Regular expression for fast inactive time stamp matching.")
583 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
584 "Regular expression for fast time stamp matching.")
586 (defconst org-ts-regexp0
587 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
588 "Regular expression matching time strings for analysis.
589 This one does not require the space after the date, so it can be used
590 on a string that terminates immediately after the date.")
592 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
593 "Regular expression matching time strings for analysis.")
595 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
596 "Regular expression matching time stamps, with groups.")
598 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
599 "Regular expression matching time stamps (also [..]), with groups.")
601 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
602 "Regular expression matching a time stamp range.")
604 (defconst org-tr-regexp-both
605 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
606 "Regular expression matching a time stamp range.")
608 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
609 org-ts-regexp "\\)?")
610 "Regular expression matching a time stamp or time stamp range.")
612 (defconst org-tsr-regexp-both
613 (concat org-ts-regexp-both "\\(--?-?"
614 org-ts-regexp-both "\\)?")
615 "Regular expression matching a time stamp or time stamp range.
616 The time stamps may be either active or inactive.")
618 (defconst org-repeat-re
619 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
620 "Regular expression for specifying repeated events.
621 After a match, group 1 contains the repeat expression.")
623 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
624 "Formats for `format-time-string' which are used for time stamps.")
627 ;;; The custom variables
629 (defgroup org nil
630 "Outline-based notes management and organizer."
631 :tag "Org"
632 :group 'outlines
633 :group 'calendar)
635 (defcustom org-mode-hook nil
636 "Mode hook for Org-mode, run after the mode was turned on."
637 :group 'org
638 :type 'hook)
640 (defcustom org-load-hook nil
641 "Hook that is run after org.el has been loaded."
642 :group 'org
643 :type 'hook)
645 (defcustom org-log-buffer-setup-hook nil
646 "Hook that is run after an Org log buffer is created."
647 :group 'org
648 :version "24.1"
649 :type 'hook)
651 (defvar org-modules) ; defined below
652 (defvar org-modules-loaded nil
653 "Have the modules been loaded already?")
655 (defun org-load-modules-maybe (&optional force)
656 "Load all extensions listed in `org-modules'."
657 (when (or force (not org-modules-loaded))
658 (mapc (lambda (ext)
659 (condition-case nil (require ext)
660 (error (message "Problems while trying to load feature `%s'" ext))))
661 org-modules)
662 (setq org-modules-loaded t)))
664 (defun org-set-modules (var value)
665 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
666 (set var value)
667 (when (featurep 'org)
668 (org-load-modules-maybe 'force)
669 (org-element-cache-reset 'all)))
671 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
672 "Modules that should always be loaded together with org.el.
674 If a description starts with <C>, the file is not part of Emacs
675 and loading it will require that you have downloaded and properly
676 installed the Org mode distribution.
678 You can also use this system to load external packages (i.e. neither Org
679 core modules, nor modules from the CONTRIB directory). Just add symbols
680 to the end of the list. If the package is called org-xyz.el, then you need
681 to add the symbol `xyz', and the package must have a call to:
683 (provide \\='org-xyz)
685 For export specific modules, see also `org-export-backends'."
686 :group 'org
687 :set 'org-set-modules
688 :version "24.4"
689 :package-version '(Org . "8.0")
690 :type
691 '(set :greedy t
692 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
693 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
694 (const :tag " crypt: Encryption of subtrees" org-crypt)
695 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
696 (const :tag " docview: Links to doc-view buffers" org-docview)
697 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
698 (const :tag " habit: Track your consistency with habits" org-habit)
699 (const :tag " id: Global IDs for identifying entries" org-id)
700 (const :tag " info: Links to Info nodes" org-info)
701 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
702 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
703 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
704 (const :tag " mouse: Additional mouse support" org-mouse)
705 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
706 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
707 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
709 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
710 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
711 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
712 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
713 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
714 (const :tag "C collector: Collect properties into tables" org-collector)
715 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
716 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
717 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
718 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
719 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
720 (const :tag "C eval: Include command output as text" org-eval)
721 (const :tag "C eww: Store link to url of eww" org-eww)
722 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
723 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
724 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
725 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
726 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
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.
852 \\<org-mode-map>\
854 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
855 start selecting a region, or enlarge regions started in this way.
856 In Org-mode, in special contexts, these same keys are used for
857 other purposes, important enough to compete with shift selection.
858 Org tries to balance these needs by supporting `shift-select-mode'
859 outside these special contexts, under control of this variable.
861 The default of this variable is nil, to avoid confusing behavior. Shifted
862 cursor keys will then execute Org commands in the following contexts:
863 - on a headline, changing TODO state (left/right) and priority (up/down)
864 - on a time stamp, changing the time
865 - in a plain list item, changing the bullet type
866 - in a property definition line, switching between allowed values
867 - in the BEGIN line of a clock table (changing the time block).
868 Outside these contexts, the commands will throw an error.
870 When this variable is t and the cursor is not in a special
871 context, Org-mode will support shift-selection for making and
872 enlarging regions. To make this more effective, the bullet
873 cycling will no longer happen anywhere in an item line, but only
874 if the cursor is exactly on the bullet.
876 If you set this variable to the symbol `always', then the keys
877 will not be special in headlines, property lines, and item lines,
878 to make shift selection work there as well. If this is what you
879 want, you can use the following alternative commands:
880 `\\[org-todo]' and `\\[org-priority]' \
881 to change TODO state and priority,
882 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
883 can be used to switch TODO sets,
884 `\\[org-ctrl-c-minus]' to cycle item bullet types,
885 and properties can be edited by hand or in column view.
887 However, when the cursor is on a timestamp, shift-cursor commands
888 will still edit the time stamp - this is just too good to give up.
890 XEmacs user should have this variable set to nil, because
891 `shift-select-mode' is in Emacs 23 or later only."
892 :group 'org
893 :type '(choice
894 (const :tag "Never" nil)
895 (const :tag "When outside special context" t)
896 (const :tag "Everywhere except timestamps" always)))
898 (defcustom org-loop-over-headlines-in-active-region nil
899 "Shall some commands act upon headlines in the active region?
901 When set to t, some commands will be performed in all headlines
902 within the active region.
904 When set to `start-level', some commands will be performed in all
905 headlines within the active region, provided that these headlines
906 are of the same level than the first one.
908 When set to a string, those commands will be performed on the
909 matching headlines within the active region. Such string must be
910 a tags/property/todo match as it is used in the agenda tags view.
912 The list of commands is: `org-schedule', `org-deadline',
913 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
914 `org-archive-to-archive-sibling'. The archiving commands skip
915 already archived entries."
916 :type '(choice (const :tag "Don't loop" nil)
917 (const :tag "All headlines in active region" t)
918 (const :tag "In active region, headlines at the same level than the first one" start-level)
919 (string :tag "Tags/Property/Todo matcher"))
920 :version "24.1"
921 :group 'org-todo
922 :group 'org-archive)
924 (defgroup org-startup nil
925 "Options concerning startup of Org-mode."
926 :tag "Org Startup"
927 :group 'org)
929 (defcustom org-startup-folded t
930 "Non-nil means entering Org-mode will switch to OVERVIEW.
931 This can also be configured on a per-file basis by adding one of
932 the following lines anywhere in the buffer:
934 #+STARTUP: fold (or `overview', this is equivalent)
935 #+STARTUP: nofold (or `showall', this is equivalent)
936 #+STARTUP: content
937 #+STARTUP: showeverything
939 By default, this option is ignored when Org opens agenda files
940 for the first time. If you want the agenda to honor the startup
941 option, set `org-agenda-inhibit-startup' to nil."
942 :group 'org-startup
943 :type '(choice
944 (const :tag "nofold: show all" nil)
945 (const :tag "fold: overview" t)
946 (const :tag "content: all headlines" content)
947 (const :tag "show everything, even drawers" showeverything)))
949 (defcustom org-startup-truncated t
950 "Non-nil means entering Org-mode will set `truncate-lines'.
951 This is useful since some lines containing links can be very long and
952 uninteresting. Also tables look terrible when wrapped."
953 :group 'org-startup
954 :type 'boolean)
956 (defcustom org-startup-indented nil
957 "Non-nil means turn on `org-indent-mode' on startup.
958 This can also be configured on a per-file basis by adding one of
959 the following lines anywhere in the buffer:
961 #+STARTUP: indent
962 #+STARTUP: noindent"
963 :group 'org-structure
964 :type '(choice
965 (const :tag "Not" nil)
966 (const :tag "Globally (slow on startup in large files)" t)))
968 (defcustom org-use-sub-superscripts t
969 "Non-nil means interpret \"_\" and \"^\" for display.
971 If you want to control how Org exports those characters, see
972 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
973 used to be an alias for `org-export-with-sub-superscripts' in
974 Org <8.0, it is not anymore.
976 When this option is turned on, you can use TeX-like syntax for
977 sub- and superscripts within the buffer. Several characters after
978 \"_\" or \"^\" will be considered as a single item - so grouping
979 with {} is normally not needed. For example, the following things
980 will be parsed as single sub- or superscripts:
982 10^24 or 10^tau several digits will be considered 1 item.
983 10^-12 or 10^-tau a leading sign with digits or a word
984 x^2-y^3 will be read as x^2 - y^3, because items are
985 terminated by almost any nonword/nondigit char.
986 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
988 Still, ambiguity is possible. So when in doubt, use {} to enclose
989 the sub/superscript. If you set this variable to the symbol `{}',
990 the braces are *required* in order to trigger interpretations as
991 sub/superscript. This can be helpful in documents that need \"_\"
992 frequently in plain text."
993 :group 'org-startup
994 :version "24.4"
995 :package-version '(Org . "8.0")
996 :type '(choice
997 (const :tag "Always interpret" t)
998 (const :tag "Only with braces" {})
999 (const :tag "Never interpret" nil)))
1001 (defcustom org-startup-with-beamer-mode nil
1002 "Non-nil means turn on `org-beamer-mode' on startup.
1003 This can also be configured on a per-file basis by adding one of
1004 the following lines anywhere in the buffer:
1006 #+STARTUP: beamer"
1007 :group 'org-startup
1008 :version "24.1"
1009 :type 'boolean)
1011 (defcustom org-startup-align-all-tables nil
1012 "Non-nil means align all tables when visiting a file.
1013 This is useful when the column width in tables is forced with <N> cookies
1014 in table fields. Such tables will look correct only after the first re-align.
1015 This can also be configured on a per-file basis by adding one of
1016 the following lines anywhere in the buffer:
1017 #+STARTUP: align
1018 #+STARTUP: noalign"
1019 :group 'org-startup
1020 :type 'boolean)
1022 (defcustom org-startup-with-inline-images nil
1023 "Non-nil means show inline images when loading a new Org file.
1024 This can also be configured on a per-file basis by adding one of
1025 the following lines anywhere in the buffer:
1026 #+STARTUP: inlineimages
1027 #+STARTUP: noinlineimages"
1028 :group 'org-startup
1029 :version "24.1"
1030 :type 'boolean)
1032 (defcustom org-startup-with-latex-preview nil
1033 "Non-nil means preview LaTeX fragments when loading a new Org file.
1035 This can also be configured on a per-file basis by adding one of
1036 the following lines anywhere in the buffer:
1037 #+STARTUP: latexpreview
1038 #+STARTUP: nolatexpreview"
1039 :group 'org-startup
1040 :version "24.4"
1041 :package-version '(Org . "8.0")
1042 :type 'boolean)
1044 (defcustom org-insert-mode-line-in-empty-file nil
1045 "Non-nil means insert the first line setting Org-mode in empty files.
1046 When the function `org-mode' is called interactively in an empty file, this
1047 normally means that the file name does not automatically trigger Org-mode.
1048 To ensure that the file will always be in Org-mode in the future, a
1049 line enforcing Org-mode will be inserted into the buffer, if this option
1050 has been set."
1051 :group 'org-startup
1052 :type 'boolean)
1054 (defcustom org-replace-disputed-keys nil
1055 "Non-nil means use alternative key bindings for some keys.
1056 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1057 These keys are also used by other packages like shift-selection-mode'
1058 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1059 If you want to use Org-mode together with one of these other modes,
1060 or more generally if you would like to move some Org-mode commands to
1061 other keys, set this variable and configure the keys with the variable
1062 `org-disputed-keys'.
1064 This option is only relevant at load-time of Org-mode, and must be set
1065 *before* org.el is loaded. Changing it requires a restart of Emacs to
1066 become effective."
1067 :group 'org-startup
1068 :type 'boolean)
1070 (defcustom org-use-extra-keys nil
1071 "Non-nil means use extra key sequence definitions for certain commands.
1072 This happens automatically if you run XEmacs or if `window-system'
1073 is nil. This variable lets you do the same manually. You must
1074 set it before loading org.
1076 Example: on Carbon Emacs 22 running graphically, with an external
1077 keyboard on a Powerbook, the default way of setting M-left might
1078 not work for either Alt or ESC. Setting this variable will make
1079 it work for ESC."
1080 :group 'org-startup
1081 :type 'boolean)
1083 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1085 (defcustom org-disputed-keys
1086 '(([(shift up)] . [(meta p)])
1087 ([(shift down)] . [(meta n)])
1088 ([(shift left)] . [(meta -)])
1089 ([(shift right)] . [(meta +)])
1090 ([(control shift right)] . [(meta shift +)])
1091 ([(control shift left)] . [(meta shift -)]))
1092 "Keys for which Org-mode and other modes compete.
1093 This is an alist, cars are the default keys, second element specifies
1094 the alternative to use when `org-replace-disputed-keys' is t.
1096 Keys can be specified in any syntax supported by `define-key'.
1097 The value of this option takes effect only at Org-mode's startup,
1098 therefore you'll have to restart Emacs to apply it after changing."
1099 :group 'org-startup
1100 :type 'alist)
1102 (defun org-key (key)
1103 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1104 Or return the original if not disputed.
1105 Also apply the translations defined in `org-xemacs-key-equivalents'."
1106 (when org-replace-disputed-keys
1107 (let* ((nkey (key-description key))
1108 (x (org-find-if (lambda (x)
1109 (equal (key-description (car x)) nkey))
1110 org-disputed-keys)))
1111 (setq key (if x (cdr x) key))))
1112 (when (featurep 'xemacs)
1113 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1114 key)
1116 (defun org-find-if (predicate seq)
1117 (catch 'exit
1118 (while seq
1119 (if (funcall predicate (car seq))
1120 (throw 'exit (car seq))
1121 (pop seq)))))
1123 (defun org-defkey (keymap key def)
1124 "Define a key, possibly translated, as returned by `org-key'."
1125 (define-key keymap (org-key key) def))
1127 (defcustom org-ellipsis nil
1128 "The ellipsis to use in the Org-mode outline.
1129 When nil, just use the standard three dots.
1130 When a string, use that string instead.
1131 When a face, use the standard 3 dots, but with the specified face.
1132 The change affects only Org-mode (which will then use its own display table).
1133 Changing this requires executing \\[org-mode] in a buffer to become
1134 effective."
1135 :group 'org-startup
1136 :type '(choice (const :tag "Default" nil)
1137 (face :tag "Face" :value org-warning)
1138 (string :tag "String" :value "...#")))
1140 (defvar org-display-table nil
1141 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1143 (defgroup org-keywords nil
1144 "Keywords in Org-mode."
1145 :tag "Org Keywords"
1146 :group 'org)
1148 (defcustom org-closed-keep-when-no-todo nil
1149 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1150 :group 'org-todo
1151 :group 'org-keywords
1152 :version "24.4"
1153 :package-version '(Org . "8.0")
1154 :type 'boolean)
1156 (defgroup org-structure nil
1157 "Options concerning the general structure of Org-mode files."
1158 :tag "Org Structure"
1159 :group 'org)
1161 (defgroup org-reveal-location nil
1162 "Options about how to make context of a location visible."
1163 :tag "Org Reveal Location"
1164 :group 'org-structure)
1166 (defcustom org-show-context-detail '((isearch . lineage)
1167 (bookmark-jump . lineage)
1168 (default . ancestors))
1169 "Alist between context and visibility span when revealing a location.
1171 \\<org-mode-map>Some actions may move point into invisible
1172 locations. As a consequence, Org always expose a neighborhood
1173 around point. How much is shown depends on the initial action,
1174 or context. Valid contexts are
1176 agenda when exposing an entry from the agenda
1177 org-goto when using the command `org-goto' (\\[org-goto])
1178 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1179 tags-tree when constructing a sparse tree based on tags matches
1180 link-search when exposing search matches associated with a link
1181 mark-goto when exposing the jump goal of a mark
1182 bookmark-jump when exposing a bookmark location
1183 isearch when exiting from an incremental search
1184 default default for all contexts not set explicitly
1186 Allowed visibility spans are
1188 minimal show current headline; if point is not on headline,
1189 also show entry
1191 local show current headline, entry and next headline
1193 ancestors show current headline and its direct ancestors; if
1194 point is not on headline, also show entry
1196 lineage show current headline, its direct ancestors and all
1197 their children; if point is not on headline, also show
1198 entry and first child
1200 tree show current headline, its direct ancestors and all
1201 their children; if point is not on headline, also show
1202 entry and all children
1204 canonical show current headline, its direct ancestors along with
1205 their entries and children; if point is not located on
1206 the headline, also show current entry and all children
1208 As special cases, a nil or t value means show all contexts in
1209 `minimal' or `canonical' view, respectively.
1211 Some views can make displayed information very compact, but also
1212 make it harder to edit the location of the match. In such
1213 a case, use the command `org-reveal' (\\[org-reveal]) to show
1214 more context."
1215 :group 'org-reveal-location
1216 :version "25.1"
1217 :package-version '(Org . "8.3")
1218 :type '(choice
1219 (const :tag "Canonical" t)
1220 (const :tag "Minimal" nil)
1221 (repeat :greedy t :tag "Individual contexts"
1222 (cons
1223 (choice :tag "Context"
1224 (const agenda)
1225 (const org-goto)
1226 (const occur-tree)
1227 (const tags-tree)
1228 (const link-search)
1229 (const mark-goto)
1230 (const bookmark-jump)
1231 (const isearch)
1232 (const default))
1233 (choice :tag "Detail level"
1234 (const minimal)
1235 (const local)
1236 (const ancestors)
1237 (const lineage)
1238 (const tree)
1239 (const canonical))))))
1241 (defcustom org-indirect-buffer-display 'other-window
1242 "How should indirect tree buffers be displayed?
1243 This applies to indirect buffers created with the commands
1244 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1245 Valid values are:
1246 current-window Display in the current window
1247 other-window Just display in another window.
1248 dedicated-frame Create one new frame, and re-use it each time.
1249 new-frame Make a new frame each time. Note that in this case
1250 previously-made indirect buffers are kept, and you need to
1251 kill these buffers yourself."
1252 :group 'org-structure
1253 :group 'org-agenda-windows
1254 :type '(choice
1255 (const :tag "In current window" current-window)
1256 (const :tag "In current frame, other window" other-window)
1257 (const :tag "Each time a new frame" new-frame)
1258 (const :tag "One dedicated frame" dedicated-frame)))
1260 (defcustom org-use-speed-commands nil
1261 "Non-nil means activate single letter commands at beginning of a headline.
1262 This may also be a function to test for appropriate locations where speed
1263 commands should be active.
1265 For example, to activate speed commands when the point is on any
1266 star at the beginning of the headline, you can do this:
1268 (setq org-use-speed-commands
1269 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1270 :group 'org-structure
1271 :type '(choice
1272 (const :tag "Never" nil)
1273 (const :tag "At beginning of headline stars" t)
1274 (function)))
1276 (defcustom org-speed-commands-user nil
1277 "Alist of additional speed commands.
1278 This list will be checked before `org-speed-commands-default'
1279 when the variable `org-use-speed-commands' is non-nil
1280 and when the cursor is at the beginning of a headline.
1281 The car if each entry is a string with a single letter, which must
1282 be assigned to `self-insert-command' in the global map.
1283 The cdr is either a command to be called interactively, a function
1284 to be called, or a form to be evaluated.
1285 An entry that is just a list with a single string will be interpreted
1286 as a descriptive headline that will be added when listing the speed
1287 commands in the Help buffer using the `?' speed command."
1288 :group 'org-structure
1289 :type '(repeat :value ("k" . ignore)
1290 (choice :value ("k" . ignore)
1291 (list :tag "Descriptive Headline" (string :tag "Headline"))
1292 (cons :tag "Letter and Command"
1293 (string :tag "Command letter")
1294 (choice
1295 (function)
1296 (sexp))))))
1298 (defcustom org-bookmark-names-plist
1299 '(:last-capture "org-capture-last-stored"
1300 :last-refile "org-refile-last-stored"
1301 :last-capture-marker "org-capture-last-stored-marker")
1302 "Names for bookmarks automatically set by some Org commands.
1303 This can provide strings as names for a number of bookmarks Org sets
1304 automatically. The following keys are currently implemented:
1305 :last-capture
1306 :last-capture-marker
1307 :last-refile
1308 When a key does not show up in the property list, the corresponding bookmark
1309 is not set."
1310 :group 'org-structure
1311 :type 'plist)
1313 (defgroup org-cycle nil
1314 "Options concerning visibility cycling in Org-mode."
1315 :tag "Org Cycle"
1316 :group 'org-structure)
1318 (defcustom org-cycle-skip-children-state-if-no-children t
1319 "Non-nil means skip CHILDREN state in entries that don't have any."
1320 :group 'org-cycle
1321 :type 'boolean)
1323 (defcustom org-cycle-max-level nil
1324 "Maximum level which should still be subject to visibility cycling.
1325 Levels higher than this will, for cycling, be treated as text, not a headline.
1326 When `org-odd-levels-only' is set, a value of N in this variable actually
1327 means 2N-1 stars as the limiting headline.
1328 When nil, cycle all levels.
1329 Note that the limiting level of cycling is also influenced by
1330 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1331 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1332 than its value."
1333 :group 'org-cycle
1334 :type '(choice
1335 (const :tag "No limit" nil)
1336 (integer :tag "Maximum level")))
1338 (defcustom org-hide-block-startup nil
1339 "Non-nil means entering Org-mode will fold all blocks.
1340 This can also be set in on a per-file basis with
1342 #+STARTUP: hideblocks
1343 #+STARTUP: showblocks"
1344 :group 'org-startup
1345 :group 'org-cycle
1346 :type 'boolean)
1348 (defcustom org-cycle-global-at-bob nil
1349 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1350 This makes it possible to do global cycling without having to use S-TAB or
1351 \\[universal-argument] TAB. For this special case to work, the first line
1352 of the buffer must not be a headline -- it may be empty or some other text.
1353 When used in this way, `org-cycle-hook' is disabled temporarily to make
1354 sure the cursor stays at the beginning of the buffer. When this option is
1355 nil, don't do anything special at the beginning of the buffer."
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-level-after-item/entry-creation t
1360 "Non-nil means cycle entry level or item indentation in new empty entries.
1362 When the cursor is at the end of an empty headline, i.e., with only stars
1363 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1364 and then all possible ancestor states, before returning to the original state.
1365 This makes data entry extremely fast: M-RET to create a new headline,
1366 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1368 When the cursor is at the end of an empty plain list item, one TAB will
1369 make it a subitem, two or more tabs will back up to make this an item
1370 higher up in the item hierarchy."
1371 :group 'org-cycle
1372 :type 'boolean)
1374 (defcustom org-cycle-emulate-tab t
1375 "Where should `org-cycle' emulate TAB.
1376 nil Never
1377 white Only in completely white lines
1378 whitestart Only at the beginning of lines, before the first non-white char
1379 t Everywhere except in headlines
1380 exc-hl-bol Everywhere except at the start of a headline
1381 If TAB is used in a place where it does not emulate TAB, the current subtree
1382 visibility is cycled."
1383 :group 'org-cycle
1384 :type '(choice (const :tag "Never" nil)
1385 (const :tag "Only in completely white lines" white)
1386 (const :tag "Before first char in a line" whitestart)
1387 (const :tag "Everywhere except in headlines" t)
1388 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1390 (defcustom org-cycle-separator-lines 2
1391 "Number of empty lines needed to keep an empty line between collapsed trees.
1392 If you leave an empty line between the end of a subtree and the following
1393 headline, this empty line is hidden when the subtree is folded.
1394 Org-mode will leave (exactly) one empty line visible if the number of
1395 empty lines is equal or larger to the number given in this variable.
1396 So the default 2 means at least 2 empty lines after the end of a subtree
1397 are needed to produce free space between a collapsed subtree and the
1398 following headline.
1400 If the number is negative, and the number of empty lines is at least -N,
1401 all empty lines are shown.
1403 Special case: when 0, never leave empty lines in collapsed view."
1404 :group 'org-cycle
1405 :type 'integer)
1406 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1408 (defcustom org-pre-cycle-hook nil
1409 "Hook that is run before visibility cycling is happening.
1410 The function(s) in this hook must accept a single argument which indicates
1411 the new state that will be set right after running this hook. The
1412 argument is a symbol. Before a global state change, it can have the values
1413 `overview', `content', or `all'. Before a local state change, it can have
1414 the values `folded', `children', or `subtree'."
1415 :group 'org-cycle
1416 :type 'hook)
1418 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1419 org-cycle-hide-drawers
1420 org-cycle-show-empty-lines
1421 org-optimize-window-after-visibility-change)
1422 "Hook that is run after `org-cycle' has changed the buffer visibility.
1423 The function(s) in this hook must accept a single argument which indicates
1424 the new state that was set by the most recent `org-cycle' command. The
1425 argument is a symbol. After a global state change, it can have the values
1426 `overview', `contents', or `all'. After a local state change, it can have
1427 the values `folded', `children', or `subtree'."
1428 :group 'org-cycle
1429 :type 'hook
1430 :version "25.1"
1431 :package-version '(Org . "8.3"))
1433 (defgroup org-edit-structure nil
1434 "Options concerning structure editing in Org-mode."
1435 :tag "Org Edit Structure"
1436 :group 'org-structure)
1438 (defcustom org-odd-levels-only nil
1439 "Non-nil means skip even levels and only use odd levels for the outline.
1440 This has the effect that two stars are being added/taken away in
1441 promotion/demotion commands. It also influences how levels are
1442 handled by the exporters.
1443 Changing it requires restart of `font-lock-mode' to become effective
1444 for fontification also in regions already fontified.
1445 You may also set this on a per-file basis by adding one of the following
1446 lines to the buffer:
1448 #+STARTUP: odd
1449 #+STARTUP: oddeven"
1450 :group 'org-edit-structure
1451 :group 'org-appearance
1452 :type 'boolean)
1454 (defcustom org-adapt-indentation t
1455 "Non-nil means adapt indentation to outline node level.
1457 When this variable is set, Org assumes that you write outlines by
1458 indenting text in each node to align with the headline (after the
1459 stars). The following issues are influenced by this variable:
1461 - The indentation is increased by one space in a demotion
1462 command, and decreased by one in a promotion command. However,
1463 in the latter case, if shifting some line in the entry body
1464 would alter document structure (e.g., insert a new headline),
1465 indentation is not changed at all.
1467 - Property drawers and planning information is inserted indented
1468 when this variable is set. When nil, they will not be indented.
1470 - TAB indents a line relative to current level. The lines below
1471 a headline will be indented when this variable is set.
1473 Note that this is all about true indentation, by adding and
1474 removing space characters. See also `org-indent.el' which does
1475 level-dependent indentation in a virtual way, i.e. at display
1476 time in Emacs."
1477 :group 'org-edit-structure
1478 :type 'boolean)
1480 (defcustom org-special-ctrl-a/e nil
1481 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1483 When t, `C-a' will bring back the cursor to the beginning of the
1484 headline text, i.e. after the stars and after a possible TODO
1485 keyword. In an item, this will be the position after bullet and
1486 check-box, if any. When the cursor is already at that position,
1487 another `C-a' will bring it to the beginning of the line.
1489 `C-e' will jump to the end of the headline, ignoring the presence
1490 of tags in the headline. A second `C-e' will then jump to the
1491 true end of the line, after any tags. This also means that, when
1492 this variable is non-nil, `C-e' also will never jump beyond the
1493 end of the heading of a folded section, i.e. not after the
1494 ellipses.
1496 When set to the symbol `reversed', the first `C-a' or `C-e' works
1497 normally, going to the true line boundary first. Only a directly
1498 following, identical keypress will bring the cursor to the
1499 special positions.
1501 This may also be a cons cell where the behavior for `C-a' and
1502 `C-e' is set separately."
1503 :group 'org-edit-structure
1504 :type '(choice
1505 (const :tag "off" nil)
1506 (const :tag "on: after stars/bullet and before tags first" t)
1507 (const :tag "reversed: true line boundary first" reversed)
1508 (cons :tag "Set C-a and C-e separately"
1509 (choice :tag "Special C-a"
1510 (const :tag "off" nil)
1511 (const :tag "on: after stars/bullet first" t)
1512 (const :tag "reversed: before stars/bullet first" reversed))
1513 (choice :tag "Special C-e"
1514 (const :tag "off" nil)
1515 (const :tag "on: before tags first" t)
1516 (const :tag "reversed: after tags first" reversed)))))
1517 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1519 (defcustom org-special-ctrl-k nil
1520 "Non-nil means `C-k' will behave specially in headlines.
1521 When nil, `C-k' will call the default `kill-line' command.
1522 When t, the following will happen while the cursor is in the headline:
1524 - When the cursor is at the beginning of a headline, kill the entire
1525 line and possible the folded subtree below the line.
1526 - When in the middle of the headline text, kill the headline up to the tags.
1527 - When after the headline text, kill the tags."
1528 :group 'org-edit-structure
1529 :type 'boolean)
1531 (defcustom org-ctrl-k-protect-subtree nil
1532 "Non-nil means, do not delete a hidden subtree with C-k.
1533 When set to the symbol `error', simply throw an error when C-k is
1534 used to kill (part-of) a headline that has hidden text behind it.
1535 Any other non-nil value will result in a query to the user, if it is
1536 OK to kill that hidden subtree. When nil, kill without remorse."
1537 :group 'org-edit-structure
1538 :version "24.1"
1539 :type '(choice
1540 (const :tag "Do not protect hidden subtrees" nil)
1541 (const :tag "Protect hidden subtrees with a security query" t)
1542 (const :tag "Never kill a hidden subtree with C-k" error)))
1544 (defcustom org-special-ctrl-o t
1545 "Non-nil means, make `C-o' insert a row in tables."
1546 :group 'org-edit-structure
1547 :type 'boolean)
1549 (defcustom org-catch-invisible-edits nil
1550 "Check if in invisible region before inserting or deleting a character.
1551 Valid values are:
1553 nil Do not check, so just do invisible edits.
1554 error Throw an error and do nothing.
1555 show Make point visible, and do the requested edit.
1556 show-and-error Make point visible, then throw an error and abort the edit.
1557 smart Make point visible, and do insertion/deletion if it is
1558 adjacent to visible text and the change feels predictable.
1559 Never delete a previously invisible character or add in the
1560 middle or right after an invisible region. Basically, this
1561 allows insertion and backward-delete right before ellipses.
1562 FIXME: maybe in this case we should not even show?"
1563 :group 'org-edit-structure
1564 :version "24.1"
1565 :type '(choice
1566 (const :tag "Do not check" nil)
1567 (const :tag "Throw error when trying to edit" error)
1568 (const :tag "Unhide, but do not do the edit" show-and-error)
1569 (const :tag "Show invisible part and do the edit" show)
1570 (const :tag "Be smart and do the right thing" smart)))
1572 (defcustom org-yank-folded-subtrees t
1573 "Non-nil means when yanking subtrees, fold them.
1574 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1575 it starts with a heading and all other headings in it are either children
1576 or siblings, then fold all the subtrees. However, do this only if no
1577 text after the yank would be swallowed into a folded tree by this action."
1578 :group 'org-edit-structure
1579 :type 'boolean)
1581 (defcustom org-yank-adjusted-subtrees nil
1582 "Non-nil means when yanking subtrees, adjust the level.
1583 With this setting, `org-paste-subtree' is used to insert the subtree, see
1584 this function for details."
1585 :group 'org-edit-structure
1586 :type 'boolean)
1588 (defcustom org-M-RET-may-split-line '((default . t))
1589 "Non-nil means M-RET will split the line at the cursor position.
1590 When nil, it will go to the end of the line before making a
1591 new line.
1592 You may also set this option in a different way for different
1593 contexts. Valid contexts are:
1595 headline when creating a new headline
1596 item when creating a new item
1597 table in a table field
1598 default the value to be used for all contexts not explicitly
1599 customized"
1600 :group 'org-structure
1601 :group 'org-table
1602 :type '(choice
1603 (const :tag "Always" t)
1604 (const :tag "Never" nil)
1605 (repeat :greedy t :tag "Individual contexts"
1606 (cons
1607 (choice :tag "Context"
1608 (const headline)
1609 (const item)
1610 (const table)
1611 (const default))
1612 (boolean)))))
1615 (defcustom org-insert-heading-respect-content nil
1616 "Non-nil means insert new headings after the current subtree.
1617 When nil, the new heading is created directly after the current line.
1618 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1619 this variable on for the duration of the command."
1620 :group 'org-structure
1621 :type 'boolean)
1623 (defcustom org-blank-before-new-entry '((heading . auto)
1624 (plain-list-item . auto))
1625 "Should `org-insert-heading' leave a blank line before new heading/item?
1626 The value is an alist, with `heading' and `plain-list-item' as CAR,
1627 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1628 which case Org will look at the surrounding headings/items and try to
1629 make an intelligent decision whether to insert a blank line or not."
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 \\<org-mode-map>\
1681 Such highlights are created by `org-occur' and `org-clock-display'.
1682 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1683 to get rid of the highlights.
1684 The highlights created by `org-toggle-latex-fragment' always need
1685 `\\[org-toggle-latex-fragment]' to be removed."
1686 :group 'org-sparse-trees
1687 :group 'org-time
1688 :type 'boolean)
1691 (defcustom org-occur-hook '(org-first-headline-recenter)
1692 "Hook that is run after `org-occur' has constructed a sparse tree.
1693 This can be used to recenter the window to show as much of the structure
1694 as possible."
1695 :group 'org-sparse-trees
1696 :type 'hook)
1698 (defgroup org-imenu-and-speedbar nil
1699 "Options concerning imenu and speedbar in Org-mode."
1700 :tag "Org Imenu and Speedbar"
1701 :group 'org-structure)
1703 (defcustom org-imenu-depth 2
1704 "The maximum level for Imenu access to Org-mode headlines.
1705 This also applied for speedbar access."
1706 :group 'org-imenu-and-speedbar
1707 :type 'integer)
1709 (defgroup org-table nil
1710 "Options concerning tables in Org-mode."
1711 :tag "Org Table"
1712 :group 'org)
1714 (defcustom org-enable-table-editor 'optimized
1715 "Non-nil means lines starting with \"|\" are handled by the table editor.
1716 When nil, such lines will be treated like ordinary lines.
1718 When equal to the symbol `optimized', the table editor will be optimized to
1719 do the following:
1720 - Automatic overwrite mode in front of whitespace in table fields.
1721 This makes the structure of the table stay in tact as long as the edited
1722 field does not exceed the column width.
1723 - Minimize the number of realigns. Normally, the table is aligned each time
1724 TAB or RET are pressed to move to another field. With optimization this
1725 happens only if changes to a field might have changed the column width.
1726 Optimization requires replacing the functions `self-insert-command',
1727 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1728 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1729 very good at guessing when a re-align will be necessary, but you can always
1730 force one with \\[org-ctrl-c-ctrl-c].
1732 If you would like to use the optimized version in Org-mode, but the
1733 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1735 This variable can be used to turn on and off the table editor during a session,
1736 but in order to toggle optimization, a restart is required.
1738 See also the variable `org-table-auto-blank-field'."
1739 :group 'org-table
1740 :type '(choice
1741 (const :tag "off" nil)
1742 (const :tag "on" t)
1743 (const :tag "on, optimized" optimized)))
1745 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1746 (version<= emacs-version "24.1"))
1747 "Non-nil means cluster self-insert commands for undo when possible.
1748 If this is set, then, like in the Emacs command loop, 20 consecutive
1749 characters will be undone together.
1750 This is configurable, because there is some impact on typing performance."
1751 :group 'org-table
1752 :type 'boolean)
1754 (defcustom org-table-tab-recognizes-table.el t
1755 "Non-nil means TAB will automatically notice a table.el table.
1756 When it sees such a table, it moves point into it and - if necessary -
1757 calls `table-recognize-table'."
1758 :group 'org-table-editing
1759 :type 'boolean)
1761 (defgroup org-link nil
1762 "Options concerning links in Org-mode."
1763 :tag "Org Link"
1764 :group 'org)
1766 (defvar-local org-link-abbrev-alist-local nil
1767 "Buffer-local version of `org-link-abbrev-alist', which see.
1768 The value of this is taken from the #+LINK lines.")
1770 (defcustom org-link-abbrev-alist nil
1771 "Alist of link abbreviations.
1772 The car of each element is a string, to be replaced at the start of a link.
1773 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1774 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1776 [[linkkey:tag][description]]
1778 The `linkkey' must be a word word, starting with a letter, followed
1779 by letters, numbers, `-' or `_'.
1781 If REPLACE is a string, the tag will simply be appended to create the link.
1782 If the string contains \"%s\", the tag will be inserted there. If the string
1783 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1784 at that point (see the function `url-hexify-string'). If the string contains
1785 the specifier \"%(my-function)\", then the custom function `my-function' will
1786 be invoked: this function takes the tag as its only argument and must return
1787 a string.
1789 REPLACE may also be a function that will be called with the tag as the
1790 only argument to create the link, which should be returned as a string.
1792 See the manual for examples."
1793 :group 'org-link
1794 :type '(repeat
1795 (cons
1796 (string :tag "Protocol")
1797 (choice
1798 (string :tag "Format")
1799 (function)))))
1801 (defcustom org-descriptive-links t
1802 "Non-nil means Org will display descriptive links.
1803 E.g. [[http://orgmode.org][Org website]] will be displayed as
1804 \"Org Website\", hiding the link itself and just displaying its
1805 description. When set to nil, Org will display the full links
1806 literally.
1808 You can interactively set the value of this variable by calling
1809 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1810 :group 'org-link
1811 :type 'boolean)
1813 (defcustom org-link-file-path-type 'adaptive
1814 "How the path name in file links should be stored.
1815 Valid values are:
1817 relative Relative to the current directory, i.e. the directory of the file
1818 into which the link is being inserted.
1819 absolute Absolute path, if possible with ~ for home directory.
1820 noabbrev Absolute path, no abbreviation of home directory.
1821 adaptive Use relative path for files in the current directory and sub-
1822 directories of it. For other files, use an absolute path."
1823 :group 'org-link
1824 :type '(choice
1825 (const relative)
1826 (const absolute)
1827 (const noabbrev)
1828 (const adaptive)))
1830 (defvaralias 'org-activate-links 'org-highlight-links)
1831 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1832 "Types of links that should be highlighted in Org-mode files.
1834 This is a list of symbols, each one of them leading to the
1835 highlighting of a certain link type.
1837 You can still open links that are not highlighted.
1839 In principle, it does not hurt to turn on highlighting for all
1840 link types. There may be a small gain when turning off unused
1841 link types. The types are:
1843 bracket The recommended [[link][description]] or [[link]] links with hiding.
1844 angle Links in angular brackets that may contain whitespace like
1845 <bbdb:Carsten Dominik>.
1846 plain Plain links in normal text, no whitespace, like http://google.com.
1847 radio Text that is matched by a radio target, see manual for details.
1848 tag Tag settings in a headline (link to tag search).
1849 date Time stamps (link to calendar).
1850 footnote Footnote labels.
1852 If you set this variable during an Emacs session, use `org-mode-restart'
1853 in the Org buffer so that the change takes effect."
1854 :group 'org-link
1855 :group 'org-appearance
1856 :type '(set :greedy t
1857 (const :tag "Double bracket links" bracket)
1858 (const :tag "Angular bracket links" angle)
1859 (const :tag "Plain text links" plain)
1860 (const :tag "Radio target matches" radio)
1861 (const :tag "Tags" tag)
1862 (const :tag "Timestamps" date)
1863 (const :tag "Footnotes" footnote)))
1865 (defcustom org-make-link-description-function nil
1866 "Function to use for generating link descriptions from links.
1867 When nil, the link location will be used. This function must take
1868 two parameters: the first one is the link, the second one is the
1869 description generated by `org-insert-link'. The function should
1870 return the description to use."
1871 :group 'org-link
1872 :type '(choice (const nil) (function)))
1874 (defgroup org-link-store nil
1875 "Options concerning storing links in Org-mode."
1876 :tag "Org Store Link"
1877 :group 'org-link)
1879 (defcustom org-url-hexify-p t
1880 "When non-nil, hexify URL when creating a link."
1881 :type 'boolean
1882 :version "24.3"
1883 :group 'org-link-store)
1885 (defcustom org-email-link-description-format "Email %c: %.30s"
1886 "Format of the description part of a link to an email or usenet message.
1887 The following %-escapes will be replaced by corresponding information:
1889 %F full \"From\" field
1890 %f name, taken from \"From\" field, address if no name
1891 %T full \"To\" field
1892 %t first name in \"To\" field, address if no name
1893 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1894 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1895 %s subject
1896 %d date
1897 %m message-id.
1899 You may use normal field width specification between the % and the letter.
1900 This is for example useful to limit the length of the subject.
1902 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1903 :group 'org-link-store
1904 :type 'string)
1906 (defcustom org-from-is-user-regexp
1907 (let (r1 r2)
1908 (when (and user-mail-address (not (string= user-mail-address "")))
1909 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1910 (when (and user-full-name (not (string= user-full-name "")))
1911 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1912 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1913 "Regexp matched against the \"From:\" header of an email or usenet message.
1914 It should match if the message is from the user him/herself."
1915 :group 'org-link-store
1916 :type 'regexp)
1918 (defcustom org-context-in-file-links t
1919 "Non-nil means file links from `org-store-link' contain context.
1920 A search string will be added to the file name with :: as separator and
1921 used to find the context when the link is activated by the command
1922 `org-open-at-point'. When this option is t, the entire active region
1923 will be placed in the search string of the file link. If set to a
1924 positive integer, only the first n lines of context will be stored.
1926 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1927 negates this setting for the duration of the command."
1928 :group 'org-link-store
1929 :type '(choice boolean integer))
1931 (defcustom org-keep-stored-link-after-insertion nil
1932 "Non-nil means keep link in list for entire session.
1934 The command `org-store-link' adds a link pointing to the current
1935 location to an internal list. These links accumulate during a session.
1936 The command `org-insert-link' can be used to insert links into any
1937 Org-mode file (offering completion for all stored links). When this
1938 option is nil, every link which has been inserted once using \\[org-insert-link]
1939 will be removed from the list, to make completing the unused links
1940 more efficient."
1941 :group 'org-link-store
1942 :type 'boolean)
1944 (defgroup org-link-follow nil
1945 "Options concerning following links in Org-mode."
1946 :tag "Org Follow Link"
1947 :group 'org-link)
1949 (defcustom org-link-translation-function nil
1950 "Function to translate links with different syntax to Org syntax.
1951 This can be used to translate links created for example by the Planner
1952 or emacs-wiki packages to Org syntax.
1953 The function must accept two parameters, a TYPE containing the link
1954 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1955 which is everything after the link protocol. It should return a cons
1956 with possibly modified values of type and path.
1957 Org contains a function for this, so if you set this variable to
1958 `org-translate-link-from-planner', you should be able follow many
1959 links created by planner."
1960 :group 'org-link-follow
1961 :type '(choice (const nil) (function)))
1963 (defcustom org-follow-link-hook nil
1964 "Hook that is run after a link has been followed."
1965 :group 'org-link-follow
1966 :type 'hook)
1968 (defcustom org-tab-follows-link nil
1969 "Non-nil means on links TAB will follow the link.
1970 Needs to be set before org.el is loaded.
1971 This really should not be used, it does not make sense, and the
1972 implementation is bad."
1973 :group 'org-link-follow
1974 :type 'boolean)
1976 (defcustom org-return-follows-link nil
1977 "Non-nil means on links RET will follow the link.
1978 In tables, the special behavior of RET has precedence."
1979 :group 'org-link-follow
1980 :type 'boolean)
1982 (defcustom org-mouse-1-follows-link
1983 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1984 "Non-nil means mouse-1 on a link will follow the link.
1985 A longer mouse click will still set point. Does not work on XEmacs.
1986 Needs to be set before org.el is loaded."
1987 :group 'org-link-follow
1988 :version "24.4"
1989 :package-version '(Org . "8.3")
1990 :type '(choice
1991 (const :tag "A double click follows the link" double)
1992 (const :tag "Unconditionally follow the link with mouse-1" t)
1993 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1995 (defcustom org-mark-ring-length 4
1996 "Number of different positions to be recorded in the ring.
1997 Changing this requires a restart of Emacs to work correctly."
1998 :group 'org-link-follow
1999 :type 'integer)
2001 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2002 "Non-nil means internal links in Org files must exactly match a headline.
2003 When nil, the link search tries to match a phrase with all words
2004 in the search text."
2005 :group 'org-link-follow
2006 :version "24.1"
2007 :type '(choice
2008 (const :tag "Use fuzzy text search" nil)
2009 (const :tag "Match only exact headline" t)
2010 (const :tag "Match exact headline or query to create it"
2011 query-to-create)))
2013 (defcustom org-link-frame-setup
2014 '((vm . vm-visit-folder-other-frame)
2015 (vm-imap . vm-visit-imap-folder-other-frame)
2016 (gnus . org-gnus-no-new-news)
2017 (file . find-file-other-window)
2018 (wl . wl-other-frame))
2019 "Setup the frame configuration for following links.
2020 When following a link with Emacs, it may often be useful to display
2021 this link in another window or frame. This variable can be used to
2022 set this up for the different types of links.
2023 For VM, use any of
2024 `vm-visit-folder'
2025 `vm-visit-folder-other-window'
2026 `vm-visit-folder-other-frame'
2027 For Gnus, use any of
2028 `gnus'
2029 `gnus-other-frame'
2030 `org-gnus-no-new-news'
2031 For FILE, use any of
2032 `find-file'
2033 `find-file-other-window'
2034 `find-file-other-frame'
2035 For Wanderlust use any of
2036 `wl'
2037 `wl-other-frame'
2038 For the calendar, use the variable `calendar-setup'.
2039 For BBDB, it is currently only possible to display the matches in
2040 another window."
2041 :group 'org-link-follow
2042 :type '(list
2043 (cons (const vm)
2044 (choice
2045 (const vm-visit-folder)
2046 (const vm-visit-folder-other-window)
2047 (const vm-visit-folder-other-frame)))
2048 (cons (const vm-imap)
2049 (choice
2050 (const vm-visit-imap-folder)
2051 (const vm-visit-imap-folder-other-window)
2052 (const vm-visit-imap-folder-other-frame)))
2053 (cons (const gnus)
2054 (choice
2055 (const gnus)
2056 (const gnus-other-frame)
2057 (const org-gnus-no-new-news)))
2058 (cons (const file)
2059 (choice
2060 (const find-file)
2061 (const find-file-other-window)
2062 (const find-file-other-frame)))
2063 (cons (const wl)
2064 (choice
2065 (const wl)
2066 (const wl-other-frame)))))
2068 (defcustom org-display-internal-link-with-indirect-buffer nil
2069 "Non-nil means use indirect buffer to display infile links.
2070 Activating internal links (from one location in a file to another location
2071 in the same file) normally just jumps to the location. When the link is
2072 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2073 is displayed in
2074 another window. When this option is set, the other window actually displays
2075 an indirect buffer clone of the current buffer, to avoid any visibility
2076 changes to the current buffer."
2077 :group 'org-link-follow
2078 :type 'boolean)
2080 (defcustom org-open-non-existing-files nil
2081 "Non-nil means `org-open-file' will open non-existing files.
2082 When nil, an error will be generated.
2083 This variable applies only to external applications because they
2084 might choke on non-existing files. If the link is to a file that
2085 will be opened in Emacs, the variable is ignored."
2086 :group 'org-link-follow
2087 :type 'boolean)
2089 (defcustom org-open-directory-means-index-dot-org nil
2090 "Non-nil means a link to a directory really means to index.org.
2091 When nil, following a directory link will run dired or open a finder/explorer
2092 window on that directory."
2093 :group 'org-link-follow
2094 :type 'boolean)
2096 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2097 "Non-nil means ask for confirmation before executing shell links.
2098 Shell links can be dangerous: just think about a link
2100 [[shell:rm -rf ~/*][Google Search]]
2102 This link would show up in your Org-mode document as \"Google Search\",
2103 but really it would remove your entire home directory.
2104 Therefore we advise against setting this variable to nil.
2105 Just change it to `y-or-n-p' if you want to confirm with a
2106 single keystroke rather than having to type \"yes\"."
2107 :group 'org-link-follow
2108 :type '(choice
2109 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2110 (const :tag "with y-or-n (faster)" y-or-n-p)
2111 (const :tag "no confirmation (dangerous)" nil)))
2112 (put 'org-confirm-shell-link-function
2113 'safe-local-variable
2114 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2116 (defcustom org-confirm-shell-link-not-regexp ""
2117 "A regexp to skip confirmation for shell links."
2118 :group 'org-link-follow
2119 :version "24.1"
2120 :type 'regexp)
2122 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2123 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2124 Elisp links can be dangerous: just think about a link
2126 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2128 This link would show up in your Org-mode document as \"Google Search\",
2129 but really it would remove your entire home directory.
2130 Therefore we advise against setting this variable to nil.
2131 Just change it to `y-or-n-p' if you want to confirm with a
2132 single keystroke rather than having to type \"yes\"."
2133 :group 'org-link-follow
2134 :type '(choice
2135 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2136 (const :tag "with y-or-n (faster)" y-or-n-p)
2137 (const :tag "no confirmation (dangerous)" nil)))
2138 (put 'org-confirm-shell-link-function
2139 'safe-local-variable
2140 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2142 (defcustom org-confirm-elisp-link-not-regexp ""
2143 "A regexp to skip confirmation for Elisp links."
2144 :group 'org-link-follow
2145 :version "24.1"
2146 :type 'regexp)
2148 (defconst org-file-apps-defaults-gnu
2149 '((remote . emacs)
2150 (system . mailcap)
2151 (t . mailcap))
2152 "Default file applications on a UNIX or GNU/Linux system.
2153 See `org-file-apps'.")
2155 (defconst org-file-apps-defaults-macosx
2156 '((remote . emacs)
2157 (t . "open %s")
2158 (system . "open %s")
2159 ("ps.gz" . "gv %s")
2160 ("eps.gz" . "gv %s")
2161 ("dvi" . "xdvi %s")
2162 ("fig" . "xfig %s"))
2163 "Default file applications on a MacOS X system.
2164 The system \"open\" is known as a default, but we use X11 applications
2165 for some files for which the OS does not have a good default.
2166 See `org-file-apps'.")
2168 (defconst org-file-apps-defaults-windowsnt
2169 (list
2170 '(remote . emacs)
2171 (cons t
2172 (list (if (featurep 'xemacs)
2173 'mswindows-shell-execute
2174 'w32-shell-execute)
2175 "open" 'file))
2176 (cons 'system
2177 (list (if (featurep 'xemacs)
2178 'mswindows-shell-execute
2179 'w32-shell-execute)
2180 "open" 'file)))
2181 "Default file applications on a Windows NT system.
2182 The system \"open\" is used for most files.
2183 See `org-file-apps'.")
2185 (defcustom org-file-apps
2186 '((auto-mode . emacs)
2187 ("\\.mm\\'" . default)
2188 ("\\.x?html?\\'" . default)
2189 ("\\.pdf\\'" . default))
2190 "External applications for opening `file:path' items in a document.
2191 Org-mode uses system defaults for different file types, but
2192 you can use this variable to set the application for a given file
2193 extension. The entries in this list are cons cells where the car identifies
2194 files and the cdr the corresponding command. Possible values for the
2195 file identifier are
2196 \"string\" A string as a file identifier can be interpreted in different
2197 ways, depending on its contents:
2199 - Alphanumeric characters only:
2200 Match links with this file extension.
2201 Example: (\"pdf\" . \"evince %s\")
2202 to open PDFs with evince.
2204 - Regular expression: Match links where the
2205 filename matches the regexp. If you want to
2206 use groups here, use shy groups.
2208 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2209 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2210 to open *.html and *.xhtml with firefox.
2212 - Regular expression which contains (non-shy) groups:
2213 Match links where the whole link, including \"::\", and
2214 anything after that, matches the regexp.
2215 In a custom command string, %1, %2, etc. are replaced with
2216 the parts of the link that were matched by the groups.
2217 For backwards compatibility, if a command string is given
2218 that does not use any of the group matches, this case is
2219 handled identically to the second one (i.e. match against
2220 file name only).
2221 In a custom lisp form, you can access the group matches with
2222 (match-string n link).
2224 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2225 to open [[file:document.pdf::5]] with evince at page 5.
2227 `directory' Matches a directory
2228 `remote' Matches a remote file, accessible through tramp or efs.
2229 Remote files most likely should be visited through Emacs
2230 because external applications cannot handle such paths.
2231 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2232 so all files Emacs knows how to handle. Using this with
2233 command `emacs' will open most files in Emacs. Beware that this
2234 will also open html files inside Emacs, unless you add
2235 (\"html\" . default) to the list as well.
2236 t Default for files not matched by any of the other options.
2237 `system' The system command to open files, like `open' on Windows
2238 and Mac OS X, and mailcap under GNU/Linux. This is the command
2239 that will be selected if you call `C-c C-o' with a double
2240 \\[universal-argument] \\[universal-argument] prefix.
2242 Possible values for the command are:
2243 `emacs' The file will be visited by the current Emacs process.
2244 `default' Use the default application for this file type, which is the
2245 association for t in the list, most likely in the system-specific
2246 part.
2247 This can be used to overrule an unwanted setting in the
2248 system-specific variable.
2249 `system' Use the system command for opening files, like \"open\".
2250 This command is specified by the entry whose car is `system'.
2251 Most likely, the system-specific version of this variable
2252 does define this command, but you can overrule/replace it
2253 here.
2254 string A command to be executed by a shell; %s will be replaced
2255 by the path to the file.
2256 sexp A Lisp form which will be evaluated. The file path will
2257 be available in the Lisp variable `file'.
2258 For more examples, see the system specific constants
2259 `org-file-apps-defaults-macosx'
2260 `org-file-apps-defaults-windowsnt'
2261 `org-file-apps-defaults-gnu'."
2262 :group 'org-link-follow
2263 :type '(repeat
2264 (cons (choice :value ""
2265 (string :tag "Extension")
2266 (const :tag "System command to open files" system)
2267 (const :tag "Default for unrecognized files" t)
2268 (const :tag "Remote file" remote)
2269 (const :tag "Links to a directory" directory)
2270 (const :tag "Any files that have Emacs modes"
2271 auto-mode))
2272 (choice :value ""
2273 (const :tag "Visit with Emacs" emacs)
2274 (const :tag "Use default" default)
2275 (const :tag "Use the system command" system)
2276 (string :tag "Command")
2277 (sexp :tag "Lisp form")))))
2279 (defcustom org-doi-server-url "http://dx.doi.org/"
2280 "The URL of the DOI server."
2281 :type 'string
2282 :version "24.3"
2283 :group 'org-link-follow)
2285 (defgroup org-refile nil
2286 "Options concerning refiling entries in Org-mode."
2287 :tag "Org Refile"
2288 :group 'org)
2290 (defcustom org-directory "~/org"
2291 "Directory with org files.
2292 This is just a default location to look for Org files. There is no need
2293 at all to put your files into this directory. It is only used in the
2294 following situations:
2296 1. When a capture template specifies a target file that is not an
2297 absolute path. The path will then be interpreted relative to
2298 `org-directory'
2299 2. When a capture note is filed away in an interactive way (when exiting the
2300 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2301 with `org-directory' as the default path."
2302 :group 'org-refile
2303 :group 'org-capture
2304 :type 'directory)
2306 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2307 "Default target for storing notes.
2308 Used as a fall back file for org-capture.el, for templates that
2309 do not specify a target file."
2310 :group 'org-refile
2311 :group 'org-capture
2312 :type 'file)
2314 (defcustom org-goto-interface 'outline
2315 "The default interface to be used for `org-goto'.
2316 Allowed values are:
2317 outline The interface shows an outline of the relevant file
2318 and the correct heading is found by moving through
2319 the outline or by searching with incremental search.
2320 outline-path-completion Headlines in the current buffer are offered via
2321 completion. This is the interface also used by
2322 the refile command."
2323 :group 'org-refile
2324 :type '(choice
2325 (const :tag "Outline" outline)
2326 (const :tag "Outline-path-completion" outline-path-completion)))
2328 (defcustom org-goto-max-level 5
2329 "Maximum target level when running `org-goto' with refile interface."
2330 :group 'org-refile
2331 :type 'integer)
2333 (defcustom org-reverse-note-order nil
2334 "Non-nil means store new notes at the beginning of a file or entry.
2335 When nil, new notes will be filed to the end of a file or entry.
2336 This can also be a list with cons cells of regular expressions that
2337 are matched against file names, and values."
2338 :group 'org-capture
2339 :group 'org-refile
2340 :type '(choice
2341 (const :tag "Reverse always" t)
2342 (const :tag "Reverse never" nil)
2343 (repeat :tag "By file name regexp"
2344 (cons regexp boolean))))
2346 (defcustom org-log-refile nil
2347 "Information to record when a task is refiled.
2349 Possible values are:
2351 nil Don't add anything
2352 time Add a time stamp to the task
2353 note Prompt for a note and add it with template `org-log-note-headings'
2355 This option can also be set with on a per-file-basis with
2357 #+STARTUP: nologrefile
2358 #+STARTUP: logrefile
2359 #+STARTUP: lognoterefile
2361 You can have local logging settings for a subtree by setting the LOGGING
2362 property to one or more of these keywords.
2364 When bulk-refiling from the agenda, the value `note' is forbidden and
2365 will temporarily be changed to `time'."
2366 :group 'org-refile
2367 :group 'org-progress
2368 :version "24.1"
2369 :type '(choice
2370 (const :tag "No logging" nil)
2371 (const :tag "Record timestamp" time)
2372 (const :tag "Record timestamp with note." note)))
2374 (defcustom org-refile-targets nil
2375 "Targets for refiling entries with \\[org-refile].
2376 This is a list of cons cells. Each cell contains:
2377 - a specification of the files to be considered, either a list of files,
2378 or a symbol whose function or variable value will be used to retrieve
2379 a file name or a list of file names. If you use `org-agenda-files' for
2380 that, all agenda files will be scanned for targets. Nil means consider
2381 headings in the current buffer.
2382 - A specification of how to find candidate refile targets. This may be
2383 any of:
2384 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2385 This tag has to be present in all target headlines, inheritance will
2386 not be considered.
2387 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2388 todo keyword.
2389 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2390 headlines that are refiling targets.
2391 - a cons cell (:level . N). Any headline of level N is considered a target.
2392 Note that, when `org-odd-levels-only' is set, level corresponds to
2393 order in hierarchy, not to the number of stars.
2394 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2395 Note that, when `org-odd-levels-only' is set, level corresponds to
2396 order in hierarchy, not to the number of stars.
2398 Each element of this list generates a set of possible targets.
2399 The union of these sets is presented (with completion) to
2400 the user by `org-refile'.
2402 You can set the variable `org-refile-target-verify-function' to a function
2403 to verify each headline found by the simple criteria above.
2405 When this variable is nil, all top-level headlines in the current buffer
2406 are used, equivalent to the value `((nil . (:level . 1))'."
2407 :group 'org-refile
2408 :type '(repeat
2409 (cons
2410 (choice :value org-agenda-files
2411 (const :tag "All agenda files" org-agenda-files)
2412 (const :tag "Current buffer" nil)
2413 (function) (variable) (file))
2414 (choice :tag "Identify target headline by"
2415 (cons :tag "Specific tag" (const :value :tag) (string))
2416 (cons :tag "TODO keyword" (const :value :todo) (string))
2417 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2418 (cons :tag "Level number" (const :value :level) (integer))
2419 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2421 (defcustom org-refile-target-verify-function nil
2422 "Function to verify if the headline at point should be a refile target.
2423 The function will be called without arguments, with point at the
2424 beginning of the headline. It should return t and leave point
2425 where it is if the headline is a valid target for refiling.
2427 If the target should not be selected, the function must return nil.
2428 In addition to this, it may move point to a place from where the search
2429 should be continued. For example, the function may decide that the entire
2430 subtree of the current entry should be excluded and move point to the end
2431 of the subtree."
2432 :group 'org-refile
2433 :type '(choice
2434 (const nil)
2435 (function)))
2437 (defcustom org-refile-use-cache nil
2438 "Non-nil means cache refile targets to speed up the process.
2439 \\<org-mode-map>\
2440 The cache for a particular file will be updated automatically when
2441 the buffer has been killed, or when any of the marker used for flagging
2442 refile targets no longer points at a live buffer.
2443 If you have added new entries to a buffer that might themselves be targets,
2444 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2445 if you find that easier, \
2446 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2447 \\[org-refile]'."
2448 :group 'org-refile
2449 :version "24.1"
2450 :type 'boolean)
2452 (defcustom org-refile-use-outline-path nil
2453 "Non-nil means provide refile targets as paths.
2454 So a level 3 headline will be available as level1/level2/level3.
2456 When the value is `file', also include the file name (without directory)
2457 into the path. In this case, you can also stop the completion after
2458 the file name, to get entries inserted as top level in the file.
2460 When `full-file-path', include the full file path."
2461 :group 'org-refile
2462 :type '(choice
2463 (const :tag "Not" nil)
2464 (const :tag "Yes" t)
2465 (const :tag "Start with file name" file)
2466 (const :tag "Start with full file path" full-file-path)))
2468 (defcustom org-outline-path-complete-in-steps t
2469 "Non-nil means complete the outline path in hierarchical steps.
2470 When Org-mode uses the refile interface to select an outline path
2471 \(see variable `org-refile-use-outline-path'), the completion of
2472 the path can be done in a single go, or it can be done in steps down
2473 the headline hierarchy. Going in steps is probably the best if you
2474 do not use a special completion package like `ido' or `icicles'.
2475 However, when using these packages, going in one step can be very
2476 fast, while still showing the whole path to the entry."
2477 :group 'org-refile
2478 :type 'boolean)
2480 (defcustom org-refile-allow-creating-parent-nodes nil
2481 "Non-nil means allow to create new nodes as refile targets.
2482 New nodes are then created by adding \"/new node name\" to the completion
2483 of an existing node. When the value of this variable is `confirm',
2484 new node creation must be confirmed by the user (recommended).
2485 When nil, the completion must match an existing entry.
2487 Note that, if the new heading is not seen by the criteria
2488 listed in `org-refile-targets', multiple instances of the same
2489 heading would be created by trying again to file under the new
2490 heading."
2491 :group 'org-refile
2492 :type '(choice
2493 (const :tag "Never" nil)
2494 (const :tag "Always" t)
2495 (const :tag "Prompt for confirmation" confirm)))
2497 (defcustom org-refile-active-region-within-subtree nil
2498 "Non-nil means also refile active region within a subtree.
2500 By default `org-refile' doesn't allow refiling regions if they
2501 don't contain a set of subtrees, but it might be convenient to
2502 do so sometimes: in that case, the first line of the region is
2503 converted to a headline before refiling."
2504 :group 'org-refile
2505 :version "24.1"
2506 :type 'boolean)
2508 (defgroup org-todo nil
2509 "Options concerning TODO items in Org-mode."
2510 :tag "Org TODO"
2511 :group 'org)
2513 (defgroup org-progress nil
2514 "Options concerning Progress logging in Org-mode."
2515 :tag "Org Progress"
2516 :group 'org-time)
2518 (defvar org-todo-interpretation-widgets
2519 '((:tag "Sequence (cycling hits every state)" sequence)
2520 (:tag "Type (cycling directly to DONE)" type))
2521 "The available interpretation symbols for customizing `org-todo-keywords'.
2522 Interested libraries should add to this list.")
2524 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2525 "List of TODO entry keyword sequences and their interpretation.
2526 \\<org-mode-map>This is a list of sequences.
2528 Each sequence starts with a symbol, either `sequence' or `type',
2529 indicating if the keywords should be interpreted as a sequence of
2530 action steps, or as different types of TODO items. The first
2531 keywords are states requiring action - these states will select a headline
2532 for inclusion into the global TODO list Org-mode produces. If one of
2533 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2534 signify that no further action is necessary. If \"|\" is not found,
2535 the last keyword is treated as the only DONE state of the sequence.
2537 The command \\[org-todo] cycles an entry through these states, and one
2538 additional state where no keyword is present. For details about this
2539 cycling, see the manual.
2541 TODO keywords and interpretation can also be set on a per-file basis with
2542 the special #+SEQ_TODO and #+TYP_TODO lines.
2544 Each keyword can optionally specify a character for fast state selection
2545 \(in combination with the variable `org-use-fast-todo-selection')
2546 and specifiers for state change logging, using the same syntax that
2547 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2548 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2549 indicates to record a time stamp each time this state is selected.
2551 Each keyword may also specify if a timestamp or a note should be
2552 recorded when entering or leaving the state, by adding additional
2553 characters in the parenthesis after the keyword. This looks like this:
2554 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2555 record only the time of the state change. With X and Y being either
2556 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2557 Y when leaving the state if and only if the *target* state does not
2558 define X. You may omit any of the fast-selection key or X or /Y,
2559 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2561 For backward compatibility, this variable may also be just a list
2562 of keywords. In this case the interpretation (sequence or type) will be
2563 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2564 :group 'org-todo
2565 :group 'org-keywords
2566 :type '(choice
2567 (repeat :tag "Old syntax, just keywords"
2568 (string :tag "Keyword"))
2569 (repeat :tag "New syntax"
2570 (cons
2571 (choice
2572 :tag "Interpretation"
2573 ;;Quick and dirty way to see
2574 ;;`org-todo-interpretations'. This takes the
2575 ;;place of item arguments
2576 :convert-widget
2577 (lambda (widget)
2578 (widget-put widget
2579 :args (mapcar
2580 (lambda (x)
2581 (widget-convert
2582 (cons 'const x)))
2583 org-todo-interpretation-widgets))
2584 widget))
2585 (repeat
2586 (string :tag "Keyword"))))))
2588 (defvar-local org-todo-keywords-1 nil
2589 "All TODO and DONE keywords active in a buffer.")
2590 (defvar org-todo-keywords-for-agenda nil)
2591 (defvar org-done-keywords-for-agenda nil)
2592 (defvar org-todo-keyword-alist-for-agenda nil)
2593 (defvar org-tag-alist-for-agenda nil
2594 "Alist of all tags from all agenda files.")
2595 (defvar org-tag-groups-alist-for-agenda nil
2596 "Alist of all groups tags from all current agenda files.")
2597 (defvar-local org-tag-groups-alist nil)
2598 (defvar org-agenda-contributing-files nil)
2599 (defvar-local org-not-done-keywords nil)
2600 (defvar-local org-done-keywords nil)
2601 (defvar-local org-todo-heads nil)
2602 (defvar-local org-todo-sets nil)
2603 (defvar-local org-todo-log-states nil)
2604 (defvar-local org-todo-kwd-alist nil)
2605 (defvar-local org-todo-key-alist nil)
2606 (defvar-local org-todo-key-trigger nil)
2608 (defcustom org-todo-interpretation 'sequence
2609 "Controls how TODO keywords are interpreted.
2610 This variable is in principle obsolete and is only used for
2611 backward compatibility, if the interpretation of todo keywords is
2612 not given already in `org-todo-keywords'. See that variable for
2613 more information."
2614 :group 'org-todo
2615 :group 'org-keywords
2616 :type '(choice (const sequence)
2617 (const type)))
2619 (defcustom org-use-fast-todo-selection t
2620 "\\<org-mode-map>\
2621 Non-nil means use the fast todo selection scheme with \\[org-todo].
2622 This variable describes if and under what circumstances the cycling
2623 mechanism for TODO keywords will be replaced by a single-key, direct
2624 selection scheme.
2626 When nil, fast selection is never used.
2628 When the symbol `prefix', it will be used when `org-todo' is called
2629 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2630 in an Org-mode buffer, and
2631 `\\[universal-argument] t' in an agenda buffer.
2633 When t, fast selection is used by default. In this case, the prefix
2634 argument forces cycling instead.
2636 In all cases, the special interface is only used if access keys have
2637 actually been assigned by the user, i.e. if keywords in the configuration
2638 are followed by a letter in parenthesis, like TODO(t)."
2639 :group 'org-todo
2640 :type '(choice
2641 (const :tag "Never" nil)
2642 (const :tag "By default" t)
2643 (const :tag "Only with C-u C-c C-t" prefix)))
2645 (defcustom org-provide-todo-statistics t
2646 "Non-nil means update todo statistics after insert and toggle.
2647 ALL-HEADLINES means update todo statistics by including headlines
2648 with no TODO keyword as well, counting them as not done.
2649 A list of TODO keywords means the same, but skip keywords that are
2650 not in this list.
2651 When set to a list of two lists, the first list contains keywords
2652 to consider as TODO keywords, the second list contains keywords
2653 to consider as DONE keywords.
2655 When this is set, todo statistics is updated in the parent of the
2656 current entry each time a todo state is changed."
2657 :group 'org-todo
2658 :type '(choice
2659 (const :tag "Yes, only for TODO entries" t)
2660 (const :tag "Yes, including all entries" all-headlines)
2661 (repeat :tag "Yes, for TODOs in this list"
2662 (string :tag "TODO keyword"))
2663 (list :tag "Yes, for TODOs and DONEs in these lists"
2664 (repeat (string :tag "TODO keyword"))
2665 (repeat (string :tag "DONE keyword")))
2666 (other :tag "No TODO statistics" nil)))
2668 (defcustom org-hierarchical-todo-statistics t
2669 "Non-nil means TODO statistics covers just direct children.
2670 When nil, all entries in the subtree are considered.
2671 This has only an effect if `org-provide-todo-statistics' is set.
2672 To set this to nil for only a single subtree, use a COOKIE_DATA
2673 property and include the word \"recursive\" into the value."
2674 :group 'org-todo
2675 :type 'boolean)
2677 (defcustom org-after-todo-state-change-hook nil
2678 "Hook which is run after the state of a TODO item was changed.
2679 The new state (a string with a TODO keyword, or nil) is available in the
2680 Lisp variable `org-state'."
2681 :group 'org-todo
2682 :type 'hook)
2684 (defvar org-blocker-hook nil
2685 "Hook for functions that are allowed to block a state change.
2687 Functions in this hook should not modify the buffer.
2688 Each function gets as its single argument a property list,
2689 see `org-trigger-hook' for more information about this list.
2691 If any of the functions in this hook returns nil, the state change
2692 is blocked.")
2694 (defvar org-trigger-hook nil
2695 "Hook for functions that are triggered by a state change.
2697 Each function gets as its single argument a property list with at
2698 least the following elements:
2700 (:type type-of-change :position pos-at-entry-start
2701 :from old-state :to new-state)
2703 Depending on the type, more properties may be present.
2705 This mechanism is currently implemented for:
2707 TODO state changes
2708 ------------------
2709 :type todo-state-change
2710 :from previous state (keyword as a string), or nil, or a symbol
2711 `todo' or `done', to indicate the general type of state.
2712 :to new state, like in :from")
2714 (defcustom org-enforce-todo-dependencies nil
2715 "Non-nil means undone TODO entries will block switching the parent to DONE.
2716 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2717 be blocked if any prior sibling is not yet done.
2718 Finally, if the parent is blocked because of ordered siblings of its own,
2719 the child will also be blocked."
2720 :set (lambda (var val)
2721 (set var val)
2722 (if val
2723 (add-hook 'org-blocker-hook
2724 'org-block-todo-from-children-or-siblings-or-parent)
2725 (remove-hook 'org-blocker-hook
2726 'org-block-todo-from-children-or-siblings-or-parent)))
2727 :group 'org-todo
2728 :type 'boolean)
2730 (defcustom org-enforce-todo-checkbox-dependencies nil
2731 "Non-nil means unchecked boxes will block switching the parent to DONE.
2732 When this is nil, checkboxes have no influence on switching TODO states.
2733 When non-nil, you first need to check off all check boxes before the TODO
2734 entry can be switched to DONE.
2735 This variable needs to be set before org.el is loaded, and you need to
2736 restart Emacs after a change to make the change effective. The only way
2737 to change is while Emacs is running is through the customize interface."
2738 :set (lambda (var val)
2739 (set var val)
2740 (if val
2741 (add-hook 'org-blocker-hook
2742 'org-block-todo-from-checkboxes)
2743 (remove-hook 'org-blocker-hook
2744 'org-block-todo-from-checkboxes)))
2745 :group 'org-todo
2746 :type 'boolean)
2748 (defcustom org-treat-insert-todo-heading-as-state-change nil
2749 "Non-nil means inserting a TODO heading is treated as state change.
2750 So when the command \\[org-insert-todo-heading] is used, state change
2751 logging will apply if appropriate. When nil, the new TODO item will
2752 be inserted directly, and no logging will take place."
2753 :group 'org-todo
2754 :type 'boolean)
2756 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2757 "Non-nil means switching TODO states with S-cursor counts as state change.
2758 This is the default behavior. However, setting this to nil allows a
2759 convenient way to select a TODO state and bypass any logging associated
2760 with that."
2761 :group 'org-todo
2762 :type 'boolean)
2764 (defcustom org-todo-state-tags-triggers nil
2765 "Tag changes that should be triggered by TODO state changes.
2766 This is a list. Each entry is
2768 (state-change (tag . flag) .......)
2770 State-change can be a string with a state, and empty string to indicate the
2771 state that has no TODO keyword, or it can be one of the symbols `todo'
2772 or `done', meaning any not-done or done state, respectively."
2773 :group 'org-todo
2774 :group 'org-tags
2775 :type '(repeat
2776 (cons (choice :tag "When changing to"
2777 (const :tag "Not-done state" todo)
2778 (const :tag "Done state" done)
2779 (string :tag "State"))
2780 (repeat
2781 (cons :tag "Tag action"
2782 (string :tag "Tag")
2783 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2785 (defcustom org-log-done nil
2786 "Information to record when a task moves to the DONE state.
2788 Possible values are:
2790 nil Don't add anything, just change the keyword
2791 time Add a time stamp to the task
2792 note Prompt for a note and add it with template `org-log-note-headings'
2794 This option can also be set with on a per-file-basis with
2796 #+STARTUP: nologdone
2797 #+STARTUP: logdone
2798 #+STARTUP: lognotedone
2800 You can have local logging settings for a subtree by setting the LOGGING
2801 property to one or more of these keywords."
2802 :group 'org-todo
2803 :group 'org-progress
2804 :type '(choice
2805 (const :tag "No logging" nil)
2806 (const :tag "Record CLOSED timestamp" time)
2807 (const :tag "Record CLOSED timestamp with note." note)))
2809 ;; Normalize old uses of org-log-done.
2810 (cond
2811 ((eq org-log-done t) (setq org-log-done 'time))
2812 ((and (listp org-log-done) (memq 'done org-log-done))
2813 (setq org-log-done 'note)))
2815 (defcustom org-log-reschedule nil
2816 "Information to record when the scheduling date of a tasks is modified.
2818 Possible values are:
2820 nil Don't add anything, just change the date
2821 time Add a time stamp to the task
2822 note Prompt for a note and add it with template `org-log-note-headings'
2824 This option can also be set with on a per-file-basis with
2826 #+STARTUP: nologreschedule
2827 #+STARTUP: logreschedule
2828 #+STARTUP: lognotereschedule"
2829 :group 'org-todo
2830 :group 'org-progress
2831 :type '(choice
2832 (const :tag "No logging" nil)
2833 (const :tag "Record timestamp" time)
2834 (const :tag "Record timestamp with note." note)))
2836 (defcustom org-log-redeadline nil
2837 "Information to record when the deadline date of a tasks is modified.
2839 Possible values are:
2841 nil Don't add anything, just change the date
2842 time Add a time stamp to the task
2843 note Prompt for a note and add it with template `org-log-note-headings'
2845 This option can also be set with on a per-file-basis with
2847 #+STARTUP: nologredeadline
2848 #+STARTUP: logredeadline
2849 #+STARTUP: lognoteredeadline
2851 You can have local logging settings for a subtree by setting the LOGGING
2852 property to one or more of these keywords."
2853 :group 'org-todo
2854 :group 'org-progress
2855 :type '(choice
2856 (const :tag "No logging" nil)
2857 (const :tag "Record timestamp" time)
2858 (const :tag "Record timestamp with note." note)))
2860 (defcustom org-log-note-clock-out nil
2861 "Non-nil means record a note when clocking out of an item.
2862 This can also be configured on a per-file basis by adding one of
2863 the following lines anywhere in the buffer:
2865 #+STARTUP: lognoteclock-out
2866 #+STARTUP: nolognoteclock-out"
2867 :group 'org-todo
2868 :group 'org-progress
2869 :type 'boolean)
2871 (defcustom org-log-done-with-time t
2872 "Non-nil means the CLOSED time stamp will contain date and time.
2873 When nil, only the date will be recorded."
2874 :group 'org-progress
2875 :type 'boolean)
2877 (defcustom org-log-note-headings
2878 '((done . "CLOSING NOTE %t")
2879 (state . "State %-12s from %-12S %t")
2880 (note . "Note taken on %t")
2881 (reschedule . "Rescheduled from %S on %t")
2882 (delschedule . "Not scheduled, was %S on %t")
2883 (redeadline . "New deadline from %S on %t")
2884 (deldeadline . "Removed deadline, was %S on %t")
2885 (refile . "Refiled on %t")
2886 (clock-out . ""))
2887 "Headings for notes added to entries.
2889 The value is an alist, with the car being a symbol indicating the
2890 note context, and the cdr is the heading to be used. The heading
2891 may also be the empty string. The following placeholders can be
2892 used:
2894 %t a time stamp.
2895 %T an active time stamp instead the default inactive one
2896 %d a short-format time stamp.
2897 %D an active short-format time stamp.
2898 %s the new TODO state or time stamp (inactive), in double quotes.
2899 %S the old TODO state or time stamp (inactive), in double quotes.
2900 %u the user name.
2901 %U full user name.
2903 In fact, it is not a good idea to change the `state' entry,
2904 because Agenda Log mode depends on the format of these entries."
2905 :group 'org-todo
2906 :group 'org-progress
2907 :type '(list :greedy t
2908 (cons (const :tag "Heading when closing an item" done) string)
2909 (cons (const :tag
2910 "Heading when changing todo state (todo sequence only)"
2911 state) string)
2912 (cons (const :tag "Heading when just taking a note" note) string)
2913 (cons (const :tag "Heading when rescheduling" reschedule) string)
2914 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2915 (cons (const :tag "Heading when changing deadline" redeadline) string)
2916 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2917 (cons (const :tag "Heading when refiling" refile) string)
2918 (cons (const :tag "Heading when clocking out" clock-out) string)))
2920 (unless (assq 'note org-log-note-headings)
2921 (push '(note . "%t") org-log-note-headings))
2923 (defcustom org-log-into-drawer nil
2924 "Non-nil means insert state change notes and time stamps into a drawer.
2925 When nil, state changes notes will be inserted after the headline and
2926 any scheduling and clock lines, but not inside a drawer.
2928 The value of this variable should be the name of the drawer to use.
2929 LOGBOOK is proposed as the default drawer for this purpose, you can
2930 also set this to a string to define the drawer of your choice.
2932 A value of t is also allowed, representing \"LOGBOOK\".
2934 A value of t or nil can also be set with on a per-file-basis with
2936 #+STARTUP: logdrawer
2937 #+STARTUP: nologdrawer
2939 If this variable is set, `org-log-state-notes-insert-after-drawers'
2940 will be ignored.
2942 You can set the property LOG_INTO_DRAWER to overrule this setting for
2943 a subtree.
2945 Do not check directly this variable in a Lisp program. Call
2946 function `org-log-into-drawer' instead."
2947 :group 'org-todo
2948 :group 'org-progress
2949 :type '(choice
2950 (const :tag "Not into a drawer" nil)
2951 (const :tag "LOGBOOK" t)
2952 (string :tag "Other")))
2954 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2956 (defun org-log-into-drawer ()
2957 "Name of the log drawer, as a string, or nil.
2958 This is the value of `org-log-into-drawer'. However, if the
2959 current entry has or inherits a LOG_INTO_DRAWER property, it will
2960 be used instead of the default value."
2961 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2962 (cond ((equal p "nil") nil)
2963 ((equal p "t") "LOGBOOK")
2964 ((stringp p) p)
2965 (p "LOGBOOK")
2966 ((stringp org-log-into-drawer) org-log-into-drawer)
2967 (org-log-into-drawer "LOGBOOK"))))
2969 (defcustom org-log-state-notes-insert-after-drawers nil
2970 "Non-nil means insert state change notes after any drawers in entry.
2971 Only the drawers that *immediately* follow the headline and the
2972 deadline/scheduled line are skipped.
2973 When nil, insert notes right after the heading and perhaps the line
2974 with deadline/scheduling if present.
2976 This variable will have no effect if `org-log-into-drawer' is
2977 set."
2978 :group 'org-todo
2979 :group 'org-progress
2980 :type 'boolean)
2982 (defcustom org-log-states-order-reversed t
2983 "Non-nil means the latest state note will be directly after heading.
2984 When nil, the state change notes will be ordered according to time.
2986 This option can also be set with on a per-file-basis with
2988 #+STARTUP: logstatesreversed
2989 #+STARTUP: nologstatesreversed"
2990 :group 'org-todo
2991 :group 'org-progress
2992 :type 'boolean)
2994 (defcustom org-todo-repeat-to-state nil
2995 "The TODO state to which a repeater should return the repeating task.
2996 By default this is the first task in a TODO sequence, or the previous state
2997 in a TODO_TYP set. But you can specify another task here.
2998 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2999 :group 'org-todo
3000 :version "24.1"
3001 :type '(choice (const :tag "Head of sequence" nil)
3002 (string :tag "Specific state")))
3004 (defcustom org-log-repeat 'time
3005 "Non-nil means record moving through the DONE state when triggering repeat.
3006 An auto-repeating task is immediately switched back to TODO when
3007 marked DONE. If you are not logging state changes (by adding \"@\"
3008 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3009 record a closing note, there will be no record of the task moving
3010 through DONE. This variable forces taking a note anyway.
3012 nil Don't force a record
3013 time Record a time stamp
3014 note Prompt for a note and add it with template `org-log-note-headings'
3016 This option can also be set with on a per-file-basis with
3018 #+STARTUP: nologrepeat
3019 #+STARTUP: logrepeat
3020 #+STARTUP: lognoterepeat
3022 You can have local logging settings for a subtree by setting the LOGGING
3023 property to one or more of these keywords."
3024 :group 'org-todo
3025 :group 'org-progress
3026 :type '(choice
3027 (const :tag "Don't force a record" nil)
3028 (const :tag "Force recording the DONE state" time)
3029 (const :tag "Force recording a note with the DONE state" note)))
3032 (defgroup org-priorities nil
3033 "Priorities in Org-mode."
3034 :tag "Org Priorities"
3035 :group 'org-todo)
3037 (defcustom org-enable-priority-commands t
3038 "Non-nil means priority commands are active.
3039 When nil, these commands will be disabled, so that you never accidentally
3040 set a priority."
3041 :group 'org-priorities
3042 :type 'boolean)
3044 (defcustom org-highest-priority ?A
3045 "The highest priority of TODO items. A character like ?A, ?B etc.
3046 Must have a smaller ASCII number than `org-lowest-priority'."
3047 :group 'org-priorities
3048 :type 'character)
3050 (defcustom org-lowest-priority ?C
3051 "The lowest priority of TODO items. A character like ?A, ?B etc.
3052 Must have a larger ASCII number than `org-highest-priority'."
3053 :group 'org-priorities
3054 :type 'character)
3056 (defcustom org-default-priority ?B
3057 "The default priority of TODO items.
3058 This is the priority an item gets if no explicit priority is given.
3059 When starting to cycle on an empty priority the first step in the cycle
3060 depends on `org-priority-start-cycle-with-default'. The resulting first
3061 step priority must not exceed the range from `org-highest-priority' to
3062 `org-lowest-priority' which means that `org-default-priority' has to be
3063 in this range exclusive or inclusive the range boundaries. Else the
3064 first step refuses to set the default and the second will fall back
3065 to (depending on the command used) the highest or lowest priority."
3066 :group 'org-priorities
3067 :type 'character)
3069 (defcustom org-priority-start-cycle-with-default t
3070 "Non-nil means start with default priority when starting to cycle.
3071 When this is nil, the first step in the cycle will be (depending on the
3072 command used) one higher or lower than the default priority.
3073 See also `org-default-priority'."
3074 :group 'org-priorities
3075 :type 'boolean)
3077 (defcustom org-get-priority-function nil
3078 "Function to extract the priority from a string.
3079 The string is normally the headline. If this is nil Org computes the
3080 priority from the priority cookie like [#A] in the headline. It returns
3081 an integer, increasing by 1000 for each priority level.
3082 The user can set a different function here, which should take a string
3083 as an argument and return the numeric priority."
3084 :group 'org-priorities
3085 :version "24.1"
3086 :type '(choice
3087 (const nil)
3088 (function)))
3090 (defgroup org-time nil
3091 "Options concerning time stamps and deadlines in Org-mode."
3092 :tag "Org Time"
3093 :group 'org)
3095 (defcustom org-time-stamp-rounding-minutes '(0 5)
3096 "Number of minutes to round time stamps to.
3097 \\<org-mode-map>\
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 \
3108 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3109 and by using a prefix arg to `S-up/down' to specify the exact number
3110 of minutes to shift."
3111 :group 'org-time
3112 :get (lambda (var) ; Make sure both elements are there
3113 (if (integerp (default-value var))
3114 (list (default-value var) 5)
3115 (default-value var)))
3116 :type '(list
3117 (integer :tag "when inserting times")
3118 (integer :tag "when modifying times")))
3120 ;; Normalize old customizations of this variable.
3121 (when (integerp org-time-stamp-rounding-minutes)
3122 (setq org-time-stamp-rounding-minutes
3123 (list org-time-stamp-rounding-minutes
3124 org-time-stamp-rounding-minutes)))
3126 (defcustom org-display-custom-times nil
3127 "Non-nil means overlay custom formats over all time stamps.
3128 The formats are defined through the variable `org-time-stamp-custom-formats'.
3129 To turn this on on a per-file basis, insert anywhere in the file:
3130 #+STARTUP: customtime"
3131 :group 'org-time
3132 :set 'set-default
3133 :type 'sexp)
3134 (make-variable-buffer-local 'org-display-custom-times)
3136 (defcustom org-time-stamp-custom-formats
3137 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3138 "Custom formats for time stamps. See `format-time-string' for the syntax.
3139 These are overlaid over the default ISO format if the variable
3140 `org-display-custom-times' is set. Time like %H:%M should be at the
3141 end of the second format. The custom formats are also honored by export
3142 commands, if custom time display is turned on at the time of export."
3143 :group 'org-time
3144 :type 'sexp)
3146 (defun org-time-stamp-format (&optional long inactive)
3147 "Get the right format for a time string."
3148 (let ((f (if long (cdr org-time-stamp-formats)
3149 (car org-time-stamp-formats))))
3150 (if inactive
3151 (concat "[" (substring f 1 -1) "]")
3152 f)))
3154 (defcustom org-time-clocksum-format
3155 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3156 "The format string used when creating CLOCKSUM lines.
3157 This is also used when Org mode generates a time duration.
3159 The value can be a single format string containing two
3160 %-sequences, which will be filled with the number of hours and
3161 minutes in that order.
3163 Alternatively, the value can be a plist associating any of the
3164 keys :years, :months, :weeks, :days, :hours or :minutes with
3165 format strings. The time duration is formatted using only the
3166 time components that are needed and concatenating the results.
3167 If a time unit in absent, it falls back to the next smallest
3168 unit.
3170 The keys :require-years, :require-months, :require-days,
3171 :require-weeks, :require-hours, :require-minutes are also
3172 meaningful. A non-nil value for these keys indicates that the
3173 corresponding time component should always be included, even if
3174 its value is 0.
3177 For example,
3179 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3180 :require-minutes t)
3182 means durations longer than a day will be expressed in days,
3183 hours and minutes, and durations less than a day will always be
3184 expressed in hours and minutes (even for durations less than an
3185 hour).
3187 The value
3189 (:days \"%dd\" :minutes \"%dm\")
3191 means durations longer than a day will be expressed in days and
3192 minutes, and durations less than a day will be expressed entirely
3193 in minutes (even for durations longer than an hour)."
3194 :group 'org-time
3195 :group 'org-clock
3196 :version "24.4"
3197 :package-version '(Org . "8.0")
3198 :type '(choice (string :tag "Format string")
3199 (set :tag "Plist"
3200 (group :inline t (const :tag "Years" :years)
3201 (string :tag "Format string"))
3202 (group :inline t
3203 (const :tag "Always show years" :require-years)
3204 (const t))
3205 (group :inline t (const :tag "Months" :months)
3206 (string :tag "Format string"))
3207 (group :inline t
3208 (const :tag "Always show months" :require-months)
3209 (const t))
3210 (group :inline t (const :tag "Weeks" :weeks)
3211 (string :tag "Format string"))
3212 (group :inline t
3213 (const :tag "Always show weeks" :require-weeks)
3214 (const t))
3215 (group :inline t (const :tag "Days" :days)
3216 (string :tag "Format string"))
3217 (group :inline t
3218 (const :tag "Always show days" :require-days)
3219 (const t))
3220 (group :inline t (const :tag "Hours" :hours)
3221 (string :tag "Format string"))
3222 (group :inline t
3223 (const :tag "Always show hours" :require-hours)
3224 (const t))
3225 (group :inline t (const :tag "Minutes" :minutes)
3226 (string :tag "Format string"))
3227 (group :inline t
3228 (const :tag "Always show minutes" :require-minutes)
3229 (const t)))))
3231 (defcustom org-time-clocksum-use-fractional nil
3232 "When non-nil, \\[org-clock-display] uses fractional times.
3233 See `org-time-clocksum-format' for more on time clock formats."
3234 :group 'org-time
3235 :group 'org-clock
3236 :version "24.3"
3237 :type 'boolean)
3239 (defcustom org-time-clocksum-use-effort-durations nil
3240 "When non-nil, \\[org-clock-display] uses effort durations.
3241 E.g. by default, one day is considered to be a 8 hours effort,
3242 so a task that has been clocked for 16 hours will be displayed
3243 as during 2 days in the clock display or in the clocktable.
3245 See `org-effort-durations' on how to set effort durations
3246 and `org-time-clocksum-format' for more on time clock formats."
3247 :group 'org-time
3248 :group 'org-clock
3249 :version "24.4"
3250 :package-version '(Org . "8.0")
3251 :type 'boolean)
3253 (defcustom org-time-clocksum-fractional-format "%.2f"
3254 "The format string used when creating CLOCKSUM lines,
3255 or when Org mode generates a time duration, if
3256 `org-time-clocksum-use-fractional' is enabled.
3258 The value can be a single format string containing one
3259 %-sequence, which will be filled with the number of hours as
3260 a float.
3262 Alternatively, the value can be a plist associating any of the
3263 keys :years, :months, :weeks, :days, :hours or :minutes with
3264 a format string. The time duration is formatted using the
3265 largest time unit which gives a non-zero integer part. If all
3266 specified formats have zero integer part, the smallest time unit
3267 is used."
3268 :group 'org-time
3269 :type '(choice (string :tag "Format string")
3270 (set (group :inline t (const :tag "Years" :years)
3271 (string :tag "Format string"))
3272 (group :inline t (const :tag "Months" :months)
3273 (string :tag "Format string"))
3274 (group :inline t (const :tag "Weeks" :weeks)
3275 (string :tag "Format string"))
3276 (group :inline t (const :tag "Days" :days)
3277 (string :tag "Format string"))
3278 (group :inline t (const :tag "Hours" :hours)
3279 (string :tag "Format string"))
3280 (group :inline t (const :tag "Minutes" :minutes)
3281 (string :tag "Format string")))))
3283 (defcustom org-deadline-warning-days 14
3284 "Number of days before expiration during which a deadline becomes active.
3285 This variable governs the display in sparse trees and in the agenda.
3286 When 0 or negative, it means use this number (the absolute value of it)
3287 even if a deadline has a different individual lead time specified.
3289 Custom commands can set this variable in the options section."
3290 :group 'org-time
3291 :group 'org-agenda-daily/weekly
3292 :type 'integer)
3294 (defcustom org-scheduled-delay-days 0
3295 "Number of days before a scheduled item becomes active.
3296 This variable governs the display in sparse trees and in the agenda.
3297 The default value (i.e. 0) means: don't delay scheduled item.
3298 When negative, it means use this number (the absolute value of it)
3299 even if a scheduled item has a different individual delay time
3300 specified.
3302 Custom commands can set this variable in the options section."
3303 :group 'org-time
3304 :group 'org-agenda-daily/weekly
3305 :version "24.4"
3306 :package-version '(Org . "8.0")
3307 :type 'integer)
3309 (defcustom org-read-date-prefer-future t
3310 "Non-nil means assume future for incomplete date input from user.
3311 This affects the following situations:
3312 1. The user gives a month but not a year.
3313 For example, if it is April and you enter \"feb 2\", this will be read
3314 as Feb 2, *next* year. \"May 5\", however, will be this year.
3315 2. The user gives a day, but no month.
3316 For example, if today is the 15th, and you enter \"3\", Org-mode will
3317 read this as the third of *next* month. However, if you enter \"17\",
3318 it will be considered as *this* month.
3320 If you set this variable to the symbol `time', then also the following
3321 will work:
3323 3. If the user gives a time.
3324 If the time is before now, it will be interpreted as tomorrow.
3326 Currently none of this works for ISO week specifications.
3328 When this option is nil, the current day, month and year will always be
3329 used as defaults.
3331 See also `org-agenda-jump-prefer-future'."
3332 :group 'org-time
3333 :type '(choice
3334 (const :tag "Never" nil)
3335 (const :tag "Check month and day" t)
3336 (const :tag "Check month, day, and time" time)))
3338 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3339 "Should the agenda jump command prefer the future for incomplete dates?
3340 The default is to do the same as configured in `org-read-date-prefer-future'.
3341 But you can also set a deviating value here.
3342 This may t or nil, or the symbol `org-read-date-prefer-future'."
3343 :group 'org-agenda
3344 :group 'org-time
3345 :version "24.1"
3346 :type '(choice
3347 (const :tag "Use org-read-date-prefer-future"
3348 org-read-date-prefer-future)
3349 (const :tag "Never" nil)
3350 (const :tag "Always" t)))
3352 (defcustom org-read-date-force-compatible-dates t
3353 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3355 Depending on the system Emacs is running on, certain dates cannot
3356 be represented with the type used internally to represent time.
3357 Dates between 1970-1-1 and 2038-1-1 can always be represented
3358 correctly. Some systems allow for earlier dates, some for later,
3359 some for both. One way to find out it to insert any date into an
3360 Org buffer, putting the cursor on the year and hitting S-up and
3361 S-down to test the range.
3363 When this variable is set to t, the date/time prompt will not let
3364 you specify dates outside the 1970-2037 range, so it is certain that
3365 these dates will work in whatever version of Emacs you are
3366 running, and also that you can move a file from one Emacs implementation
3367 to another. WHenever Org is forcing the year for you, it will display
3368 a message and beep.
3370 When this variable is nil, Org will check if the date is
3371 representable in the specific Emacs implementation you are using.
3372 If not, it will force a year, usually the current year, and beep
3373 to remind you. Currently this setting is not recommended because
3374 the likelihood that you will open your Org files in an Emacs that
3375 has limited date range is not negligible.
3377 A workaround for this problem is to use diary sexp dates for time
3378 stamps outside of this range."
3379 :group 'org-time
3380 :version "24.1"
3381 :type 'boolean)
3383 (defcustom org-read-date-display-live t
3384 "Non-nil means display current interpretation of date prompt live.
3385 This display will be in an overlay, in the minibuffer."
3386 :group 'org-time
3387 :type 'boolean)
3389 (defcustom org-read-date-popup-calendar t
3390 "Non-nil means pop up a calendar when prompting for a date.
3391 In the calendar, the date can be selected with mouse-1. However, the
3392 minibuffer will also be active, and you can simply enter the date as well.
3393 When nil, only the minibuffer will be available."
3394 :group 'org-time
3395 :type 'boolean)
3396 (org-defvaralias 'org-popup-calendar-for-date-prompt
3397 'org-read-date-popup-calendar)
3399 (make-obsolete-variable
3400 'org-read-date-minibuffer-setup-hook
3401 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3402 (defcustom org-read-date-minibuffer-setup-hook nil
3403 "Hook to be used to set up keys for the date/time interface.
3404 Add key definitions to `minibuffer-local-map', which will be a
3405 temporary copy.
3407 WARNING: This option is obsolete, you should use
3408 `org-read-date-minibuffer-local-map' to set up keys."
3409 :group 'org-time
3410 :type 'hook)
3412 (defcustom org-extend-today-until 0
3413 "The hour when your day really ends. Must be an integer.
3414 This has influence for the following applications:
3415 - When switching the agenda to \"today\". It it is still earlier than
3416 the time given here, the day recognized as TODAY is actually yesterday.
3417 - When a date is read from the user and it is still before the time given
3418 here, the current date and time will be assumed to be yesterday, 23:59.
3419 Also, timestamps inserted in capture templates follow this rule.
3421 IMPORTANT: This is a feature whose implementation is and likely will
3422 remain incomplete. Really, it is only here because past midnight seems to
3423 be the favorite working time of John Wiegley :-)"
3424 :group 'org-time
3425 :type 'integer)
3427 (defcustom org-use-effective-time nil
3428 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3429 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3430 \"effective time\" of any timestamps between midnight and 8am will be
3431 23:59 of the previous day."
3432 :group 'org-time
3433 :version "24.1"
3434 :type 'boolean)
3436 (defcustom org-use-last-clock-out-time-as-effective-time nil
3437 "When non-nil, use the last clock out time for `org-todo'.
3438 Note that this option has precedence over the combined use of
3439 `org-use-effective-time' and `org-extend-today-until'."
3440 :group 'org-time
3441 :version "24.4"
3442 :package-version '(Org . "8.0")
3443 :type 'boolean)
3445 (defcustom org-edit-timestamp-down-means-later nil
3446 "Non-nil means S-down will increase the time in a time stamp.
3447 When nil, S-up will increase."
3448 :group 'org-time
3449 :type 'boolean)
3451 (defcustom org-calendar-follow-timestamp-change t
3452 "Non-nil means make the calendar window follow timestamp changes.
3453 When a timestamp is modified and the calendar window is visible, it will be
3454 moved to the new date."
3455 :group 'org-time
3456 :type 'boolean)
3458 (defgroup org-tags nil
3459 "Options concerning tags in Org-mode."
3460 :tag "Org Tags"
3461 :group 'org)
3463 (defcustom org-tag-alist nil
3464 "List of tags allowed in Org-mode files.
3465 When this list is nil, Org-mode will base TAG input on what is already in the
3466 buffer.
3467 The value of this variable is an alist, the car of each entry must be a
3468 keyword as a string, the cdr may be a character that is used to select
3469 that tag through the fast-tag-selection interface.
3470 See the manual for details."
3471 :group 'org-tags
3472 :type '(repeat
3473 (choice
3474 (cons (string :tag "Tag name")
3475 (character :tag "Access char"))
3476 (list :tag "Start radio group"
3477 (const :startgroup)
3478 (option (string :tag "Group description")))
3479 (list :tag "Start tag group, non distinct"
3480 (const :startgrouptag)
3481 (option (string :tag "Group description")))
3482 (list :tag "Group tags delimiter"
3483 (const :grouptags))
3484 (list :tag "End radio group"
3485 (const :endgroup)
3486 (option (string :tag "Group description")))
3487 (list :tag "End tag group, non distinct"
3488 (const :endgrouptag)
3489 (option (string :tag "Group description")))
3490 (const :tag "New line" (:newline)))))
3492 (defcustom org-tag-persistent-alist nil
3493 "List of tags that will always appear in all Org-mode files.
3494 This is in addition to any in buffer settings or customizations
3495 of `org-tag-alist'.
3496 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3497 The value of this variable is an alist, the car of each entry must be a
3498 keyword as a string, the cdr may be a character that is used to select
3499 that tag through the fast-tag-selection interface.
3500 See the manual for details.
3501 To disable these tags on a per-file basis, insert anywhere in the file:
3502 #+STARTUP: noptag"
3503 :group 'org-tags
3504 :type '(repeat
3505 (choice
3506 (cons (string :tag "Tag name")
3507 (character :tag "Access char"))
3508 (const :tag "Start radio group" (:startgroup))
3509 (const :tag "Group tags delimiter" (:grouptags))
3510 (const :tag "End radio group" (:endgroup))
3511 (const :tag "New line" (:newline)))))
3513 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3514 "If non-nil, always offer completion for all tags of all agenda files.
3515 Instead of customizing this variable directly, you might want to
3516 set it locally for capture buffers, because there no list of
3517 tags in that file can be created dynamically (there are none).
3519 (add-hook \\='org-capture-mode-hook
3520 (lambda ()
3521 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3522 :group 'org-tags
3523 :version "24.1"
3524 :type 'boolean)
3526 (defvar org-file-tags nil
3527 "List of tags that can be inherited by all entries in the file.
3528 The tags will be inherited if the variable `org-use-tag-inheritance'
3529 says they should be.
3530 This variable is populated from #+FILETAGS lines.")
3532 (defcustom org-use-fast-tag-selection 'auto
3533 "Non-nil means use fast tag selection scheme.
3534 This is a special interface to select and deselect tags with single keys.
3535 When nil, fast selection is never used.
3536 When the symbol `auto', fast selection is used if and only if selection
3537 characters for tags have been configured, either through the variable
3538 `org-tag-alist' or through a #+TAGS line in the buffer.
3539 When t, fast selection is always used and selection keys are assigned
3540 automatically if necessary."
3541 :group 'org-tags
3542 :type '(choice
3543 (const :tag "Always" t)
3544 (const :tag "Never" nil)
3545 (const :tag "When selection characters are configured" auto)))
3547 (defcustom org-fast-tag-selection-single-key nil
3548 "Non-nil means fast tag selection exits after first change.
3549 When nil, you have to press RET to exit it.
3550 During fast tag selection, you can toggle this flag with `C-c'.
3551 This variable can also have the value `expert'. In this case, the window
3552 displaying the tags menu is not even shown, until you press C-c again."
3553 :group 'org-tags
3554 :type '(choice
3555 (const :tag "No" nil)
3556 (const :tag "Yes" t)
3557 (const :tag "Expert" expert)))
3559 (defvar org-fast-tag-selection-include-todo nil
3560 "Non-nil means fast tags selection interface will also offer TODO states.
3561 This is an undocumented feature, you should not rely on it.")
3563 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3564 "The column to which tags should be indented in a headline.
3565 If this number is positive, it specifies the column. If it is negative,
3566 it means that the tags should be flushright to that column. For example,
3567 -80 works well for a normal 80 character screen.
3568 When 0, place tags directly after headline text, with only one space in
3569 between."
3570 :group 'org-tags
3571 :type 'integer)
3573 (defcustom org-auto-align-tags t
3574 "Non-nil keeps tags aligned when modifying headlines.
3575 Some operations (i.e. demoting) change the length of a headline and
3576 therefore shift the tags around. With this option turned on, after
3577 each such operation the tags are again aligned to `org-tags-column'."
3578 :group 'org-tags
3579 :type 'boolean)
3581 (defcustom org-use-tag-inheritance t
3582 "Non-nil means tags in levels apply also for sublevels.
3583 When nil, only the tags directly given in a specific line apply there.
3584 This may also be a list of tags that should be inherited, or a regexp that
3585 matches tags that should be inherited. Additional control is possible
3586 with the variable `org-tags-exclude-from-inheritance' which gives an
3587 explicit list of tags to be excluded from inheritance, even if the value of
3588 `org-use-tag-inheritance' would select it for inheritance.
3590 If this option is t, a match early-on in a tree can lead to a large
3591 number of matches in the subtree when constructing the agenda or creating
3592 a sparse tree. If you only want to see the first match in a tree during
3593 a search, check out the variable `org-tags-match-list-sublevels'."
3594 :group 'org-tags
3595 :type '(choice
3596 (const :tag "Not" nil)
3597 (const :tag "Always" t)
3598 (repeat :tag "Specific tags" (string :tag "Tag"))
3599 (regexp :tag "Tags matched by regexp")))
3601 (defcustom org-tags-exclude-from-inheritance nil
3602 "List of tags that should never be inherited.
3603 This is a way to exclude a few tags from inheritance. For way to do
3604 the opposite, to actively allow inheritance for selected tags,
3605 see the variable `org-use-tag-inheritance'."
3606 :group 'org-tags
3607 :type '(repeat (string :tag "Tag")))
3609 (defun org-tag-inherit-p (tag)
3610 "Check if TAG is one that should be inherited."
3611 (cond
3612 ((member tag org-tags-exclude-from-inheritance) nil)
3613 ((eq org-use-tag-inheritance t) t)
3614 ((not org-use-tag-inheritance) nil)
3615 ((stringp org-use-tag-inheritance)
3616 (string-match org-use-tag-inheritance tag))
3617 ((listp org-use-tag-inheritance)
3618 (member tag org-use-tag-inheritance))
3619 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3621 (defcustom org-tags-match-list-sublevels t
3622 "Non-nil means list also sublevels of headlines matching a search.
3623 This variable applies to tags/property searches, and also to stuck
3624 projects because this search is based on a tags match as well.
3626 When set to the symbol `indented', sublevels are indented with
3627 leading dots.
3629 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3630 the sublevels of a headline matching a tag search often also match
3631 the same search. Listing all of them can create very long lists.
3632 Setting this variable to nil causes subtrees of a match to be skipped.
3634 This variable is semi-obsolete and probably should always be true. It
3635 is better to limit inheritance to certain tags using the variables
3636 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3637 :group 'org-tags
3638 :type '(choice
3639 (const :tag "No, don't list them" nil)
3640 (const :tag "Yes, do list them" t)
3641 (const :tag "List them, indented with leading dots" indented)))
3643 (defcustom org-tags-sort-function nil
3644 "When set, tags are sorted using this function as a comparator."
3645 :group 'org-tags
3646 :type '(choice
3647 (const :tag "No sorting" nil)
3648 (const :tag "Alphabetical" string<)
3649 (const :tag "Reverse alphabetical" string>)
3650 (function :tag "Custom function" nil)))
3652 (defvar org-tags-history nil
3653 "History of minibuffer reads for tags.")
3654 (defvar org-last-tags-completion-table nil
3655 "The last used completion table for tags.")
3656 (defvar org-after-tags-change-hook nil
3657 "Hook that is run after the tags in a line have changed.")
3659 (defgroup org-properties nil
3660 "Options concerning properties in Org-mode."
3661 :tag "Org Properties"
3662 :group 'org)
3664 (defcustom org-property-format "%-10s %s"
3665 "How property key/value pairs should be formatted by `indent-line'.
3666 When `indent-line' hits a property definition, it will format the line
3667 according to this format, mainly to make sure that the values are
3668 lined-up with respect to each other."
3669 :group 'org-properties
3670 :type 'string)
3672 (defcustom org-properties-postprocess-alist nil
3673 "Alist of properties and functions to adjust inserted values.
3674 Elements of this alist must be of the form
3676 ([string] [function])
3678 where [string] must be a property name and [function] must be a
3679 lambda expression: this lambda expression must take one argument,
3680 the value to adjust, and return the new value as a string.
3682 For example, this element will allow the property \"Remaining\"
3683 to be updated wrt the relation between the \"Effort\" property
3684 and the clock summary:
3686 ((\"Remaining\" (lambda(value)
3687 (let ((clocksum (org-clock-sum-current-item))
3688 (effort (org-duration-string-to-minutes
3689 (org-entry-get (point) \"Effort\"))))
3690 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3691 :group 'org-properties
3692 :version "24.1"
3693 :type '(alist :key-type (string :tag "Property")
3694 :value-type (function :tag "Function")))
3696 (defcustom org-use-property-inheritance nil
3697 "Non-nil means properties apply also for sublevels.
3699 This setting is chiefly used during property searches. Turning it on can
3700 cause significant overhead when doing a search, which is why it is not
3701 on by default.
3703 When nil, only the properties directly given in the current entry count.
3704 When t, every property is inherited. The value may also be a list of
3705 properties that should have inheritance, or a regular expression matching
3706 properties that should be inherited.
3708 However, note that some special properties use inheritance under special
3709 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3710 and the properties ending in \"_ALL\" when they are used as descriptor
3711 for valid values of a property.
3713 Note for programmers:
3714 When querying an entry with `org-entry-get', you can control if inheritance
3715 should be used. By default, `org-entry-get' looks only at the local
3716 properties. You can request inheritance by setting the inherit argument
3717 to t (to force inheritance) or to `selective' (to respect the setting
3718 in this variable)."
3719 :group 'org-properties
3720 :type '(choice
3721 (const :tag "Not" nil)
3722 (const :tag "Always" t)
3723 (repeat :tag "Specific properties" (string :tag "Property"))
3724 (regexp :tag "Properties matched by regexp")))
3726 (defun org-property-inherit-p (property)
3727 "Check if PROPERTY is one that should be inherited."
3728 (cond
3729 ((eq org-use-property-inheritance t) t)
3730 ((not org-use-property-inheritance) nil)
3731 ((stringp org-use-property-inheritance)
3732 (string-match org-use-property-inheritance property))
3733 ((listp org-use-property-inheritance)
3734 (member property org-use-property-inheritance))
3735 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3737 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3738 "The default column format, if no other format has been defined.
3739 This variable can be set on the per-file basis by inserting a line
3741 #+COLUMNS: %25ITEM ....."
3742 :group 'org-properties
3743 :type 'string)
3745 (defcustom org-columns-ellipses ".."
3746 "The ellipses to be used when a field in column view is truncated.
3747 When this is the empty string, as many characters as possible are shown,
3748 but then there will be no visual indication that the field has been truncated.
3749 When this is a string of length N, the last N characters of a truncated
3750 field are replaced by this string. If the column is narrower than the
3751 ellipses string, only part of the ellipses string will be shown."
3752 :group 'org-properties
3753 :type 'string)
3755 (defcustom org-columns-modify-value-for-display-function nil
3756 "Function that modifies values for display in column view.
3757 For example, it can be used to cut out a certain part from a time stamp.
3758 The function must take 2 arguments:
3760 column-title The title of the column (*not* the property name)
3761 value The value that should be modified.
3763 The function should return the value that should be displayed,
3764 or nil if the normal value should be used."
3765 :group 'org-properties
3766 :type '(choice (const nil) (function)))
3768 (defconst org-global-properties-fixed
3769 '(("VISIBILITY_ALL" . "folded children content all")
3770 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3771 "List of property/value pairs that can be inherited by any entry.
3773 These are fixed values, for the preset properties. The user variable
3774 that can be used to add to this list is `org-global-properties'.
3776 The entries in this list are cons cells where the car is a property
3777 name and cdr is a string with the value. If the value represents
3778 multiple items like an \"_ALL\" property, separate the items by
3779 spaces.")
3781 (defcustom org-global-properties nil
3782 "List of property/value pairs that can be inherited by any entry.
3784 This list will be combined with the constant `org-global-properties-fixed'.
3786 The entries in this list are cons cells where the car is a property
3787 name and cdr is a string with the value.
3789 You can set buffer-local values for the same purpose in the variable
3790 `org-file-properties' this by adding lines like
3792 #+PROPERTY: NAME VALUE"
3793 :group 'org-properties
3794 :type '(repeat
3795 (cons (string :tag "Property")
3796 (string :tag "Value"))))
3798 (defvar-local org-file-properties nil
3799 "List of property/value pairs that can be inherited by any entry.
3800 Valid for the current buffer.
3801 This variable is populated from #+PROPERTY lines.")
3803 (defgroup org-agenda nil
3804 "Options concerning agenda views in Org-mode."
3805 :tag "Org Agenda"
3806 :group 'org)
3808 (defvar-local org-category nil
3809 "Variable used by org files to set a category for agenda display.
3810 Such files should use a file variable to set it, for example
3812 # -*- mode: org; org-category: \"ELisp\"
3814 or contain a special line
3816 #+CATEGORY: ELisp
3818 If the file does not specify a category, then file's base name
3819 is used instead.")
3820 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3822 (defcustom org-agenda-files nil
3823 "The files to be used for agenda display.
3824 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3825 \\[org-remove-file]. You can also use customize to edit the list.
3827 If an entry is a directory, all files in that directory that are matched by
3828 `org-agenda-file-regexp' will be part of the file list.
3830 If the value of the variable is not a list but a single file name, then
3831 the list of agenda files is actually stored and maintained in that file, one
3832 agenda file per line. In this file paths can be given relative to
3833 `org-directory'. Tilde expansion and environment variable substitution
3834 are also made."
3835 :group 'org-agenda
3836 :type '(choice
3837 (repeat :tag "List of files and directories" file)
3838 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3840 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3841 "Regular expression to match files for `org-agenda-files'.
3842 If any element in the list in that variable contains a directory instead
3843 of a normal file, all files in that directory that are matched by this
3844 regular expression will be included."
3845 :group 'org-agenda
3846 :type 'regexp)
3848 (defcustom org-agenda-text-search-extra-files nil
3849 "List of extra files to be searched by text search commands.
3850 These files will be searched in addition to the agenda files by the
3851 commands `org-search-view' (`\\[org-agenda] s') \
3852 and `org-occur-in-agenda-files'.
3853 Note that these files will only be searched for text search commands,
3854 not for the other agenda views like todo lists, tag searches or the weekly
3855 agenda. This variable is intended to list notes and possibly archive files
3856 that should also be searched by these two commands.
3857 In fact, if the first element in the list is the symbol `agenda-archives',
3858 then all archive files of all agenda files will be added to the search
3859 scope."
3860 :group 'org-agenda
3861 :type '(set :greedy t
3862 (const :tag "Agenda Archives" agenda-archives)
3863 (repeat :inline t (file))))
3865 (org-defvaralias 'org-agenda-multi-occur-extra-files
3866 'org-agenda-text-search-extra-files)
3868 (defcustom org-agenda-skip-unavailable-files nil
3869 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3870 A nil value means to remove them, after a query, from the list."
3871 :group 'org-agenda
3872 :type 'boolean)
3874 (defcustom org-calendar-to-agenda-key [?c]
3875 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3876 The command `org-calendar-goto-agenda' will be bound to this key. The
3877 default is the character `c' because then `c' can be used to switch back and
3878 forth between agenda and calendar."
3879 :group 'org-agenda
3880 :type 'sexp)
3882 (defcustom org-calendar-insert-diary-entry-key [?i]
3883 "The key to be installed in `calendar-mode-map' for adding diary entries.
3884 This option is irrelevant until `org-agenda-diary-file' has been configured
3885 to point to an Org-mode file. When that is the case, the command
3886 `org-agenda-diary-entry' will be bound to the key given here, by default
3887 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3888 if you want to continue doing this, you need to change this to a different
3889 key."
3890 :group 'org-agenda
3891 :type 'sexp)
3893 (defcustom org-agenda-diary-file 'diary-file
3894 "File to which to add new entries with the `i' key in agenda and calendar.
3895 When this is the symbol `diary-file', the functionality in the Emacs
3896 calendar will be used to add entries to the `diary-file'. But when this
3897 points to a file, `org-agenda-diary-entry' will be used instead."
3898 :group 'org-agenda
3899 :type '(choice
3900 (const :tag "The standard Emacs diary file" diary-file)
3901 (file :tag "Special Org file diary entries")))
3903 (eval-after-load "calendar"
3904 '(progn
3905 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3906 'org-calendar-goto-agenda)
3907 (add-hook 'calendar-mode-hook
3908 (lambda ()
3909 (unless (eq org-agenda-diary-file 'diary-file)
3910 (define-key calendar-mode-map
3911 org-calendar-insert-diary-entry-key
3912 'org-agenda-diary-entry))))))
3914 (defgroup org-latex nil
3915 "Options for embedding LaTeX code into Org-mode."
3916 :tag "Org LaTeX"
3917 :group 'org)
3919 (defcustom org-format-latex-options
3920 '(:foreground default :background default :scale 1.0
3921 :html-foreground "Black" :html-background "Transparent"
3922 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3923 "Options for creating images from LaTeX fragments.
3924 This is a property list with the following properties:
3925 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3926 `default' means use the foreground of the default face.
3927 `auto' means use the foreground from the text face.
3928 :background the background color, or \"Transparent\".
3929 `default' means use the background of the default face.
3930 `auto' means use the background from the text face.
3931 :scale a scaling factor for the size of the images, to get more pixels
3932 :html-foreground, :html-background, :html-scale
3933 the same numbers for HTML export.
3934 :matchers a list indicating which matchers should be used to
3935 find LaTeX fragments. Valid members of this list are:
3936 \"begin\" find environments
3937 \"$1\" find single characters surrounded by $.$
3938 \"$\" find math expressions surrounded by $...$
3939 \"$$\" find math expressions surrounded by $$....$$
3940 \"\\(\" find math expressions surrounded by \\(...\\)
3941 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3942 :group 'org-latex
3943 :type 'plist)
3945 (defcustom org-format-latex-signal-error t
3946 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3947 When nil, just push out a message."
3948 :group 'org-latex
3949 :version "24.1"
3950 :type 'boolean)
3952 (defcustom org-latex-to-mathml-jar-file nil
3953 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3954 Use this to specify additional executable file say a jar file.
3956 When using MathToWeb as the converter, specify the full-path to
3957 your mathtoweb.jar file."
3958 :group 'org-latex
3959 :version "24.1"
3960 :type '(choice
3961 (const :tag "None" nil)
3962 (file :tag "JAR file" :must-match t)))
3964 (defcustom org-latex-to-mathml-convert-command nil
3965 "Command to convert LaTeX fragments to MathML.
3966 Replace format-specifiers in the command as noted below and use
3967 `shell-command' to convert LaTeX to MathML.
3968 %j: Executable file in fully expanded form as specified by
3969 `org-latex-to-mathml-jar-file'.
3970 %I: Input LaTeX file in fully expanded form.
3971 %i: The latex fragment to be converted.
3972 %o: Output MathML file.
3974 This command is used by `org-create-math-formula'.
3976 When using MathToWeb as the converter, set this option to
3977 \"java -jar %j -unicode -force -df %o %I\".
3979 When using LaTeXML set this option to
3980 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3981 :group 'org-latex
3982 :version "24.1"
3983 :type '(choice
3984 (const :tag "None" nil)
3985 (string :tag "\nShell command")))
3987 (defcustom org-latex-create-formula-image-program 'dvipng
3988 "Program to convert LaTeX fragments with.
3990 dvipng Process the LaTeX fragments to dvi file, then convert
3991 dvi files to png files using dvipng.
3992 This will also include processing of non-math environments.
3993 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3994 to convert pdf files to png files"
3995 :group 'org-latex
3996 :version "24.1"
3997 :type '(choice
3998 (const :tag "dvipng" dvipng)
3999 (const :tag "imagemagick" imagemagick)))
4001 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
4002 "Path to store latex preview images.
4003 A relative path here creates many directories relative to the
4004 processed org files paths. An absolute path puts all preview
4005 images at the same place."
4006 :group 'org-latex
4007 :version "24.3"
4008 :type 'string)
4010 (defun org-format-latex-mathml-available-p ()
4011 "Return t if `org-latex-to-mathml-convert-command' is usable."
4012 (save-match-data
4013 (when (and (boundp 'org-latex-to-mathml-convert-command)
4014 org-latex-to-mathml-convert-command)
4015 (let ((executable (car (split-string
4016 org-latex-to-mathml-convert-command))))
4017 (when (executable-find executable)
4018 (if (string-match
4019 "%j" org-latex-to-mathml-convert-command)
4020 (file-readable-p org-latex-to-mathml-jar-file)
4021 t))))))
4023 (defcustom org-format-latex-header "\\documentclass{article}
4024 \\usepackage[usenames]{color}
4025 \[PACKAGES]
4026 \[DEFAULT-PACKAGES]
4027 \\pagestyle{empty} % do not remove
4028 % The settings below are copied from fullpage.sty
4029 \\setlength{\\textwidth}{\\paperwidth}
4030 \\addtolength{\\textwidth}{-3cm}
4031 \\setlength{\\oddsidemargin}{1.5cm}
4032 \\addtolength{\\oddsidemargin}{-2.54cm}
4033 \\setlength{\\evensidemargin}{\\oddsidemargin}
4034 \\setlength{\\textheight}{\\paperheight}
4035 \\addtolength{\\textheight}{-\\headheight}
4036 \\addtolength{\\textheight}{-\\headsep}
4037 \\addtolength{\\textheight}{-\\footskip}
4038 \\addtolength{\\textheight}{-3cm}
4039 \\setlength{\\topmargin}{1.5cm}
4040 \\addtolength{\\topmargin}{-2.54cm}"
4041 "The document header used for processing LaTeX fragments.
4042 It is imperative that this header make sure that no page number
4043 appears on the page. The package defined in the variables
4044 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4045 will either replace the placeholder \"[PACKAGES]\" in this
4046 header, or they will be appended."
4047 :group 'org-latex
4048 :type 'string)
4050 (defun org-set-packages-alist (var val)
4051 "Set the packages alist and make sure it has 3 elements per entry."
4052 (set var (mapcar (lambda (x)
4053 (if (and (consp x) (= (length x) 2))
4054 (list (car x) (nth 1 x) t)
4056 val)))
4058 (defun org-get-packages-alist (var)
4059 "Get the packages alist and make sure it has 3 elements per entry."
4060 (mapcar (lambda (x)
4061 (if (and (consp x) (= (length x) 2))
4062 (list (car x) (nth 1 x) t)
4064 (default-value var)))
4066 (defcustom org-latex-default-packages-alist
4067 '(("AUTO" "inputenc" t ("pdflatex"))
4068 ("T1" "fontenc" t ("pdflatex"))
4069 ("" "graphicx" t)
4070 ("" "grffile" t)
4071 ("" "longtable" nil)
4072 ("" "wrapfig" nil)
4073 ("" "rotating" nil)
4074 ("normalem" "ulem" t)
4075 ("" "amsmath" t)
4076 ("" "textcomp" t)
4077 ("" "amssymb" t)
4078 ("" "capt-of" nil)
4079 ("" "hyperref" nil))
4080 "Alist of default packages to be inserted in the header.
4082 Change this only if one of the packages here causes an
4083 incompatibility with another package you are using.
4085 The packages in this list are needed by one part or another of
4086 Org mode to function properly:
4088 - inputenc, fontenc: for basic font and character selection
4089 - graphicx: for including images
4090 - grffile: allow periods and spaces in graphics file names
4091 - longtable: For multipage tables
4092 - wrapfig: for figure placement
4093 - rotating: for sideways figures and tables
4094 - ulem: for underline and strike-through
4095 - amsmath: for subscript and superscript and math environments
4096 - textcomp, amssymb: for various symbols used
4097 for interpreting the entities in `org-entities'. You can skip
4098 some of these packages if you don't use any of their symbols.
4099 - capt-of: for captions outside of floats
4100 - hyperref: for cross references
4102 Therefore you should not modify this variable unless you know
4103 what you are doing. The one reason to change it anyway is that
4104 you might be loading some other package that conflicts with one
4105 of the default packages. Each element is either a cell or
4106 a string.
4108 A cell is of the format
4110 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4112 If SNIPPET-FLAG is non-nil, the package also needs to be included
4113 when compiling LaTeX snippets into images for inclusion into
4114 non-LaTeX output. COMPILERS is a list of compilers that should
4115 include the package, see `org-latex-compiler'. If the document
4116 compiler is not in the list, and the list is non-nil, the package
4117 will not be inserted in the final document.
4119 A string will be inserted as-is in the header of the document."
4120 :group 'org-latex
4121 :group 'org-export-latex
4122 :set 'org-set-packages-alist
4123 :get 'org-get-packages-alist
4124 :version "25.1"
4125 :package-version '(Org . "8.3")
4126 :type '(repeat
4127 (choice
4128 (list :tag "options/package pair"
4129 (string :tag "options")
4130 (string :tag "package")
4131 (boolean :tag "Snippet"))
4132 (string :tag "A line of LaTeX"))))
4134 (defcustom org-latex-packages-alist nil
4135 "Alist of packages to be inserted in every LaTeX header.
4137 These will be inserted after `org-latex-default-packages-alist'.
4138 Each element is either a cell or a string.
4140 A cell is of the format:
4142 (\"options\" \"package\" SNIPPET-FLAG)
4144 SNIPPET-FLAG, when non-nil, indicates that this package is also
4145 needed when turning LaTeX snippets into images for inclusion into
4146 non-LaTeX output.
4148 A string will be inserted as-is in the header of the document.
4150 Make sure that you only list packages here which:
4152 - you want in every file;
4153 - do not conflict with the setup in `org-format-latex-header';
4154 - do not conflict with the default packages in
4155 `org-latex-default-packages-alist'."
4156 :group 'org-latex
4157 :group 'org-export-latex
4158 :set 'org-set-packages-alist
4159 :get 'org-get-packages-alist
4160 :type '(repeat
4161 (choice
4162 (list :tag "options/package pair"
4163 (string :tag "options")
4164 (string :tag "package")
4165 (boolean :tag "Snippet"))
4166 (string :tag "A line of LaTeX"))))
4168 (defgroup org-appearance nil
4169 "Settings for Org-mode appearance."
4170 :tag "Org Appearance"
4171 :group 'org)
4173 (defcustom org-level-color-stars-only nil
4174 "Non-nil means fontify only the stars in each headline.
4175 When nil, the entire headline is fontified.
4176 Changing it requires restart of `font-lock-mode' to become effective
4177 also in regions already fontified."
4178 :group 'org-appearance
4179 :type 'boolean)
4181 (defcustom org-hide-leading-stars nil
4182 "Non-nil means hide the first N-1 stars in a headline.
4183 This works by using the face `org-hide' for these stars. This
4184 face is white for a light background, and black for a dark
4185 background. You may have to customize the face `org-hide' to
4186 make this work.
4187 Changing it requires restart of `font-lock-mode' to become effective
4188 also in regions already fontified.
4189 You may also set this on a per-file basis by adding one of the following
4190 lines to the buffer:
4192 #+STARTUP: hidestars
4193 #+STARTUP: showstars"
4194 :group 'org-appearance
4195 :type 'boolean)
4197 (defcustom org-hidden-keywords nil
4198 "List of symbols corresponding to keywords to be hidden the org buffer.
4199 For example, a value \\='(title) for this list will make the document's title
4200 appear in the buffer without the initial #+TITLE: keyword."
4201 :group 'org-appearance
4202 :version "24.1"
4203 :type '(set (const :tag "#+AUTHOR" author)
4204 (const :tag "#+DATE" date)
4205 (const :tag "#+EMAIL" email)
4206 (const :tag "#+TITLE" title)))
4208 (defcustom org-custom-properties nil
4209 "List of properties (as strings) with a special meaning.
4210 The default use of these custom properties is to let the user
4211 hide them with `org-toggle-custom-properties-visibility'."
4212 :group 'org-properties
4213 :group 'org-appearance
4214 :version "24.3"
4215 :type '(repeat (string :tag "Property Name")))
4217 (defcustom org-fontify-done-headline nil
4218 "Non-nil means change the face of a headline if it is marked DONE.
4219 Normally, only the TODO/DONE keyword indicates the state of a headline.
4220 When this is non-nil, the headline after the keyword is set to the
4221 `org-headline-done' as an additional indication."
4222 :group 'org-appearance
4223 :type 'boolean)
4225 (defcustom org-fontify-emphasized-text t
4226 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4227 Changing this variable requires a restart of Emacs to take effect."
4228 :group 'org-appearance
4229 :type 'boolean)
4231 (defcustom org-fontify-whole-heading-line nil
4232 "Non-nil means fontify the whole line for headings.
4233 This is useful when setting a background color for the
4234 org-level-* faces."
4235 :group 'org-appearance
4236 :type 'boolean)
4238 (defcustom org-highlight-latex-and-related nil
4239 "Non-nil means highlight LaTeX related syntax in the buffer.
4240 When non nil, the value should be a list containing any of the
4241 following symbols:
4242 `latex' Highlight LaTeX snippets and environments.
4243 `script' Highlight subscript and superscript.
4244 `entities' Highlight entities."
4245 :group 'org-appearance
4246 :version "24.4"
4247 :package-version '(Org . "8.0")
4248 :type '(choice
4249 (const :tag "No highlighting" nil)
4250 (set :greedy t :tag "Highlight"
4251 (const :tag "LaTeX snippets and environments" latex)
4252 (const :tag "Subscript and superscript" script)
4253 (const :tag "Entities" entities))))
4255 (defcustom org-hide-emphasis-markers nil
4256 "Non-nil mean font-lock should hide the emphasis marker characters."
4257 :group 'org-appearance
4258 :type 'boolean)
4260 (defcustom org-hide-macro-markers nil
4261 "Non-nil mean font-lock should hide the brackets marking macro calls."
4262 :group 'org-appearance
4263 :type 'boolean)
4265 (defcustom org-pretty-entities nil
4266 "Non-nil means show entities as UTF8 characters.
4267 When nil, the \\name form remains in the buffer."
4268 :group 'org-appearance
4269 :version "24.1"
4270 :type 'boolean)
4272 (defcustom org-pretty-entities-include-sub-superscripts t
4273 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4274 :group 'org-appearance
4275 :version "24.1"
4276 :type 'boolean)
4278 (defvar org-emph-re nil
4279 "Regular expression for matching emphasis.
4280 After a match, the match groups contain these elements:
4281 0 The match of the full regular expression, including the characters
4282 before and after the proper match
4283 1 The character before the proper match, or empty at beginning of line
4284 2 The proper match, including the leading and trailing markers
4285 3 The leading marker like * or /, indicating the type of highlighting
4286 4 The text between the emphasis markers, not including the markers
4287 5 The character after the match, empty at the end of a line")
4288 (defvar org-verbatim-re nil
4289 "Regular expression for matching verbatim text.")
4290 (defvar org-emphasis-regexp-components) ; defined just below
4291 (defvar org-emphasis-alist) ; defined just below
4292 (defun org-set-emph-re (var val)
4293 "Set variable and compute the emphasis regular expression."
4294 (set var val)
4295 (when (and (boundp 'org-emphasis-alist)
4296 (boundp 'org-emphasis-regexp-components)
4297 org-emphasis-alist org-emphasis-regexp-components)
4298 (let* ((e org-emphasis-regexp-components)
4299 (pre (car e))
4300 (post (nth 1 e))
4301 (border (nth 2 e))
4302 (body (nth 3 e))
4303 (nl (nth 4 e))
4304 (body1 (concat body "*?"))
4305 (markers (mapconcat 'car org-emphasis-alist ""))
4306 (vmarkers (mapconcat
4307 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4308 org-emphasis-alist "")))
4309 ;; make sure special characters appear at the right position in the class
4310 (if (string-match "\\^" markers)
4311 (setq markers (concat (replace-match "" t t markers) "^")))
4312 (if (string-match "-" markers)
4313 (setq markers (concat (replace-match "" t t markers) "-")))
4314 (if (string-match "\\^" vmarkers)
4315 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4316 (if (string-match "-" vmarkers)
4317 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4318 (if (> nl 0)
4319 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4320 (int-to-string nl) "\\}")))
4321 ;; Make the regexp
4322 (setq org-emph-re
4323 (concat "\\([" pre "]\\|^\\)"
4324 "\\("
4325 "\\([" markers "]\\)"
4326 "\\("
4327 "[^" border "]\\|"
4328 "[^" border "]"
4329 body1
4330 "[^" border "]"
4331 "\\)"
4332 "\\3\\)"
4333 "\\([" post "]\\|$\\)"))
4334 (setq org-verbatim-re
4335 (concat "\\([" pre "]\\|^\\)"
4336 "\\("
4337 "\\([" vmarkers "]\\)"
4338 "\\("
4339 "[^" border "]\\|"
4340 "[^" border "]"
4341 body1
4342 "[^" border "]"
4343 "\\)"
4344 "\\3\\)"
4345 "\\([" post "]\\|$\\)")))))
4347 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4348 ;; set this option proved cumbersome. See this message/thread:
4349 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4350 (defvar org-emphasis-regexp-components
4351 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4352 "Components used to build the regular expression for emphasis.
4353 This is a list with five entries. Terminology: In an emphasis string
4354 like \" *strong word* \", we call the initial space PREMATCH, the final
4355 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4356 and \"trong wor\" is the body. The different components in this variable
4357 specify what is allowed/forbidden in each part:
4359 pre Chars allowed as prematch. Beginning of line will be allowed too.
4360 post Chars allowed as postmatch. End of line will be allowed too.
4361 border The chars *forbidden* as border characters.
4362 body-regexp A regexp like \".\" to match a body character. Don't use
4363 non-shy groups here, and don't allow newline here.
4364 newline The maximum number of newlines allowed in an emphasis exp.
4366 You need to reload Org or to restart Emacs after customizing this.")
4368 (defcustom org-emphasis-alist
4369 `(("*" bold)
4370 ("/" italic)
4371 ("_" underline)
4372 ("=" org-verbatim verbatim)
4373 ("~" org-code verbatim)
4374 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4375 "Alist of characters and faces to emphasize text.
4376 Text starting and ending with a special character will be emphasized,
4377 for example *bold*, _underlined_ and /italic/. This variable sets the
4378 marker characters and the face to be used by font-lock for highlighting
4379 in Org-mode Emacs buffers.
4381 You need to reload Org or to restart Emacs after customizing this."
4382 :group 'org-appearance
4383 :set 'org-set-emph-re
4384 :version "24.4"
4385 :package-version '(Org . "8.0")
4386 :type '(repeat
4387 (list
4388 (string :tag "Marker character")
4389 (choice
4390 (face :tag "Font-lock-face")
4391 (plist :tag "Face property list"))
4392 (option (const verbatim)))))
4394 (defvar org-protecting-blocks
4395 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4396 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4397 This is needed for font-lock setup.")
4399 ;;; Miscellaneous options
4401 (defgroup org-completion nil
4402 "Completion in Org-mode."
4403 :tag "Org Completion"
4404 :group 'org)
4406 (defcustom org-completion-use-ido nil
4407 "Non-nil means use ido completion wherever possible.
4408 Note that `ido-mode' must be active for this variable to be relevant.
4409 If you decide to turn this variable on, you might well want to turn off
4410 `org-outline-path-complete-in-steps'.
4411 See also `org-completion-use-iswitchb'."
4412 :group 'org-completion
4413 :type 'boolean)
4415 (defcustom org-completion-use-iswitchb nil
4416 "Non-nil means use iswitchb completion wherever possible.
4417 Note that `iswitchb-mode' must be active for this variable to be relevant.
4418 If you decide to turn this variable on, you might well want to turn off
4419 `org-outline-path-complete-in-steps'.
4420 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4421 :group 'org-completion
4422 :type 'boolean)
4424 (defcustom org-completion-fallback-command 'hippie-expand
4425 "The expansion command called by \\[pcomplete] in normal context.
4426 Normal means, no org-mode-specific context."
4427 :group 'org-completion
4428 :type 'function)
4430 ;;; Functions and variables from their packages
4431 ;; Declared here to avoid compiler warnings
4433 ;; XEmacs only
4434 (defvar outline-mode-menu-heading)
4435 (defvar outline-mode-menu-show)
4436 (defvar outline-mode-menu-hide)
4437 (defvar zmacs-regions) ; XEmacs regions
4439 ;; Emacs only
4440 (defvar mark-active)
4442 ;; Various packages
4443 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4444 (declare-function calendar-forward-day "cal-move" (arg))
4445 (declare-function calendar-goto-date "cal-move" (date))
4446 (declare-function calendar-goto-today "cal-move" ())
4447 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4448 (defvar calc-embedded-close-formula)
4449 (defvar calc-embedded-open-formula)
4450 (declare-function cdlatex-tab "ext:cdlatex" ())
4451 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4452 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4453 (defvar font-lock-unfontify-region-function)
4454 (declare-function iswitchb-read-buffer "iswitchb"
4455 (prompt &optional default require-match start matches-set))
4456 (defvar iswitchb-temp-buflist)
4457 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4458 (defvar org-agenda-tags-todo-honor-ignore-options)
4459 (declare-function org-agenda-skip "org-agenda" ())
4460 (declare-function
4461 org-agenda-format-item "org-agenda"
4462 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4463 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4464 (declare-function org-agenda-change-all-lines "org-agenda"
4465 (newhead hdmarker &optional fixface just-this))
4466 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4467 (declare-function org-agenda-maybe-redo "org-agenda" ())
4468 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4469 (beg end))
4470 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4471 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4472 "org-agenda" (&optional end))
4473 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4474 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4475 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4476 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4477 (declare-function org-indent-mode "org-indent" (&optional arg))
4478 (declare-function parse-time-string "parse-time" (string))
4479 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4480 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4481 (defvar remember-data-file)
4482 (defvar texmathp-why)
4483 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4484 (declare-function table--at-cell-p "table" (position &optional object at-column))
4485 (declare-function calc-eval "calc" (str &optional separator &rest args))
4487 ;;;###autoload
4488 (defun turn-on-orgtbl ()
4489 "Unconditionally turn on `orgtbl-mode'."
4490 (require 'org-table)
4491 (orgtbl-mode 1))
4493 (defun org-at-table-p (&optional table-type)
4494 "Non-nil if the cursor is inside an Org table.
4495 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4496 If `org-enable-table-editor' is nil, return nil unconditionally."
4497 (and
4498 org-enable-table-editor
4499 (save-excursion
4500 (beginning-of-line)
4501 (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4502 (or (not (derived-mode-p 'org-mode))
4503 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4504 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4505 (defsubst org-table-p () (org-at-table-p))
4507 (defun org-at-table.el-p ()
4508 "Non-nil when point is at a table.el table."
4509 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4510 (let ((element (org-element-at-point)))
4511 (and (eq (org-element-type element) 'table)
4512 (eq (org-element-property :type element) 'table.el)))))
4514 (defun org-table-recognize-table.el ()
4515 "If there is a table.el table nearby, recognize it and move into it."
4516 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4517 (beginning-of-line)
4518 (unless (or (looking-at org-table-dataline-regexp)
4519 (not (looking-at org-table1-hline-regexp)))
4520 (forward-line)
4521 (when (looking-at org-table-any-border-regexp)
4522 (forward-line -2)))
4523 (if (re-search-forward "|" (org-table-end t) t)
4524 (progn
4525 (require 'table)
4526 (if (table--at-cell-p (point)) t
4527 (message "recognizing table.el table...")
4528 (table-recognize-table)
4529 (message "recognizing table.el table...done")))
4530 (error "This should not happen"))))
4532 (defun org-at-table-hline-p ()
4533 "Non-nil when point is inside a hline in a table.
4534 Assume point is already in a table. If `org-enable-table-editor'
4535 is nil, return nil unconditionally."
4536 (and org-enable-table-editor
4537 (save-excursion
4538 (beginning-of-line)
4539 (looking-at org-table-hline-regexp))))
4541 (defun org-table-map-tables (function &optional quietly)
4542 "Apply FUNCTION to the start of all tables in the buffer."
4543 (save-excursion
4544 (save-restriction
4545 (widen)
4546 (goto-char (point-min))
4547 (while (re-search-forward org-table-any-line-regexp nil t)
4548 (unless quietly
4549 (message "Mapping tables: %d%%"
4550 (floor (* 100.0 (point)) (buffer-size))))
4551 (beginning-of-line 1)
4552 (when (and (looking-at org-table-line-regexp)
4553 ;; Exclude tables in src/example/verbatim/clocktable blocks
4554 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4555 (save-excursion (funcall function))
4556 (or (looking-at org-table-line-regexp)
4557 (forward-char 1)))
4558 (re-search-forward org-table-any-border-regexp nil 1))))
4559 (unless quietly (message "Mapping tables: done")))
4561 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4562 (declare-function org-clock-update-mode-line "org-clock" ())
4563 (declare-function org-resolve-clocks "org-clock"
4564 (&optional also-non-dangling-p prompt last-valid))
4566 (defun org-at-TBLFM-p (&optional pos)
4567 "Non-nil when point (or POS) is in #+TBLFM line."
4568 (save-excursion
4569 (goto-char (or pos (point)))
4570 (beginning-of-line)
4571 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4572 (eq (org-element-type (org-element-at-point)) 'table))))
4574 (defvar org-clock-start-time)
4575 (defvar org-clock-marker (make-marker)
4576 "Marker recording the last clock-in.")
4577 (defvar org-clock-hd-marker (make-marker)
4578 "Marker recording the last clock-in, but the headline position.")
4579 (defvar org-clock-heading ""
4580 "The heading of the current clock entry.")
4581 (defun org-clock-is-active ()
4582 "Return the buffer where the clock is currently running.
4583 Return nil if no clock is running."
4584 (marker-buffer org-clock-marker))
4586 (defun org-check-running-clock ()
4587 "Check if the current buffer contains the running clock.
4588 If yes, offer to stop it and to save the buffer with the changes."
4589 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4590 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4591 (buffer-name))))
4592 (org-clock-out)
4593 (when (y-or-n-p "Save changed buffer?")
4594 (save-buffer))))
4596 (defun org-clocktable-try-shift (dir n)
4597 "Check if this line starts a clock table, if yes, shift the time block."
4598 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4599 (org-clocktable-shift dir n)))
4601 ;;;###autoload
4602 (defun org-clock-persistence-insinuate ()
4603 "Set up hooks for clock persistence."
4604 (require 'org-clock)
4605 (add-hook 'org-mode-hook 'org-clock-load)
4606 (add-hook 'kill-emacs-hook 'org-clock-save))
4608 (defgroup org-archive nil
4609 "Options concerning archiving in Org-mode."
4610 :tag "Org Archive"
4611 :group 'org-structure)
4613 (defcustom org-archive-location "%s_archive::"
4614 "The location where subtrees should be archived.
4616 The value of this variable is a string, consisting of two parts,
4617 separated by a double-colon. The first part is a filename and
4618 the second part is a headline.
4620 When the filename is omitted, archiving happens in the same file.
4621 %s in the filename will be replaced by the current file
4622 name (without the directory part). Archiving to a different file
4623 is useful to keep archived entries from contributing to the
4624 Org-mode Agenda.
4626 The archived entries will be filed as subtrees of the specified
4627 headline. When the headline is omitted, the subtrees are simply
4628 filed away at the end of the file, as top-level entries. Also in
4629 the heading you can use %s to represent the file name, this can be
4630 useful when using the same archive for a number of different files.
4632 Here are a few examples:
4633 \"%s_archive::\"
4634 If the current file is Projects.org, archive in file
4635 Projects.org_archive, as top-level trees. This is the default.
4637 \"::* Archived Tasks\"
4638 Archive in the current file, under the top-level headline
4639 \"* Archived Tasks\".
4641 \"~/org/archive.org::\"
4642 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4644 \"~/org/archive.org::* From %s\"
4645 Archive in file ~/org/archive.org (absolute path), under headlines
4646 \"From FILENAME\" where file name is the current file name.
4648 \"~/org/datetree.org::datetree/* Finished Tasks\"
4649 The \"datetree/\" string is special, signifying to archive
4650 items to the datetree. Items are placed in either the CLOSED
4651 date of the item, or the current date if there is no CLOSED date.
4652 The heading will be a subentry to the current date. There doesn't
4653 need to be a heading, but there always needs to be a slash after
4654 datetree. For example, to store archived items directly in the
4655 datetree, use \"~/org/datetree.org::datetree/\".
4657 \"basement::** Finished Tasks\"
4658 Archive in file ./basement (relative path), as level 3 trees
4659 below the level 2 heading \"** Finished Tasks\".
4661 You may set this option on a per-file basis by adding to the buffer a
4662 line like
4664 #+ARCHIVE: basement::** Finished Tasks
4666 You may also define it locally for a subtree by setting an ARCHIVE property
4667 in the entry. If such a property is found in an entry, or anywhere up
4668 the hierarchy, it will be used."
4669 :group 'org-archive
4670 :type 'string)
4672 (defcustom org-agenda-skip-archived-trees t
4673 "Non-nil means the agenda will skip any items located in archived trees.
4674 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4675 variable is no longer recommended, you should leave it at the value t.
4676 Instead, use the key `v' to cycle the archives-mode in the agenda."
4677 :group 'org-archive
4678 :group 'org-agenda-skip
4679 :type 'boolean)
4681 (defcustom org-columns-skip-archived-trees t
4682 "Non-nil means ignore archived trees when creating column view."
4683 :group 'org-archive
4684 :group 'org-properties
4685 :type 'boolean)
4687 (defcustom org-cycle-open-archived-trees nil
4688 "Non-nil means `org-cycle' will open archived trees.
4689 An archived tree is a tree marked with the tag ARCHIVE.
4690 When nil, archived trees will stay folded. You can still open them with
4691 normal outline commands like `show-all', but not with the cycling commands."
4692 :group 'org-archive
4693 :group 'org-cycle
4694 :type 'boolean)
4696 (defcustom org-sparse-tree-open-archived-trees nil
4697 "Non-nil means sparse tree construction shows matches in archived trees.
4698 When nil, matches in these trees are highlighted, but the trees are kept in
4699 collapsed state."
4700 :group 'org-archive
4701 :group 'org-sparse-trees
4702 :type 'boolean)
4704 (defcustom org-sparse-tree-default-date-type nil
4705 "The default date type when building a sparse tree.
4706 When this is nil, a date is a scheduled or a deadline timestamp.
4707 Otherwise, these types are allowed:
4709 all: all timestamps
4710 active: only active timestamps (<...>)
4711 inactive: only inactive timestamps ([...])
4712 scheduled: only scheduled timestamps
4713 deadline: only deadline timestamps"
4714 :type '(choice (const :tag "Scheduled or deadline" nil)
4715 (const :tag "All timestamps" all)
4716 (const :tag "Only active timestamps" active)
4717 (const :tag "Only inactive timestamps" inactive)
4718 (const :tag "Only scheduled timestamps" scheduled)
4719 (const :tag "Only deadline timestamps" deadline)
4720 (const :tag "Only closed timestamps" closed))
4721 :version "25.1"
4722 :package-version '(Org . "8.3")
4723 :group 'org-sparse-trees)
4725 (defun org-cycle-hide-archived-subtrees (state)
4726 "Re-hide all archived subtrees after a visibility state change."
4727 (when (and (not org-cycle-open-archived-trees)
4728 (not (memq state '(overview folded))))
4729 (save-excursion
4730 (let* ((globalp (memq state '(contents all)))
4731 (beg (if globalp (point-min) (point)))
4732 (end (if globalp (point-max) (org-end-of-subtree t))))
4733 (org-hide-archived-subtrees beg end)
4734 (goto-char beg)
4735 (if (looking-at (concat ".*:" org-archive-tag ":"))
4736 (message "%s" (substitute-command-keys
4737 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4739 (defun org-force-cycle-archived ()
4740 "Cycle subtree even if it is archived."
4741 (interactive)
4742 (setq this-command 'org-cycle)
4743 (let ((org-cycle-open-archived-trees t))
4744 (call-interactively 'org-cycle)))
4746 (defun org-hide-archived-subtrees (beg end)
4747 "Re-hide all archived subtrees after a visibility state change."
4748 (org-with-wide-buffer
4749 (let ((case-fold-search nil)
4750 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4751 (goto-char beg)
4752 ;; Include headline point is currently on.
4753 (beginning-of-line)
4754 (while (and (< (point) end) (re-search-forward re end t))
4755 (when (member org-archive-tag (org-get-tags))
4756 (org-flag-subtree t)
4757 (org-end-of-subtree t))))))
4759 (declare-function outline-end-of-heading "outline" ())
4760 (declare-function outline-flag-region "outline" (from to flag))
4761 (defun org-flag-subtree (flag)
4762 (save-excursion
4763 (org-back-to-heading t)
4764 (outline-end-of-heading)
4765 (outline-flag-region (point)
4766 (progn (org-end-of-subtree t) (point))
4767 flag)))
4769 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4771 ;; Declare Column View Code
4773 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4774 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4775 (declare-function org-columns-compute "org-colview" (property))
4777 ;; Declare ID code
4779 (declare-function org-id-store-link "org-id")
4780 (declare-function org-id-locations-load "org-id")
4781 (declare-function org-id-locations-save "org-id")
4782 (defvar org-id-track-globally)
4784 ;;; Variables for pre-computed regular expressions, all buffer local
4786 (defvar-local org-todo-regexp nil
4787 "Matches any of the TODO state keywords.")
4788 (defvar-local org-not-done-regexp nil
4789 "Matches any of the TODO state keywords except the last one.")
4790 (defvar-local org-not-done-heading-regexp nil
4791 "Matches a TODO headline that is not done.")
4792 (defvar-local org-todo-line-regexp nil
4793 "Matches a headline and puts TODO state into group 2 if present.")
4794 (defvar-local org-complex-heading-regexp nil
4795 "Matches a headline and puts everything into groups:
4796 group 1: the stars
4797 group 2: The todo keyword, maybe
4798 group 3: Priority cookie
4799 group 4: True headline
4800 group 5: Tags")
4801 (defvar-local org-complex-heading-regexp-format nil
4802 "Printf format to make regexp to match an exact headline.
4803 This regexp will match the headline of any node which has the
4804 exact headline text that is put into the format, but may have any
4805 TODO state, priority and tags.")
4806 (defvar-local org-todo-line-tags-regexp nil
4807 "Matches a headline and puts TODO state into group 2 if present.
4808 Also put tags into group 4 if tags are present.")
4810 (defconst org-plain-time-of-day-regexp
4811 (concat
4812 "\\(\\<[012]?[0-9]"
4813 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4814 "\\(--?"
4815 "\\(\\<[012]?[0-9]"
4816 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4817 "\\)?")
4818 "Regular expression to match a plain time or time range.
4819 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4820 groups carry important information:
4821 0 the full match
4822 1 the first time, range or not
4823 8 the second time, if it is a range.")
4825 (defconst org-plain-time-extension-regexp
4826 (concat
4827 "\\(\\<[012]?[0-9]"
4828 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4829 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4830 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4831 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4832 groups carry important information:
4833 0 the full match
4834 7 hours of duration
4835 9 minutes of duration")
4837 (defconst org-stamp-time-of-day-regexp
4838 (concat
4839 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4840 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4841 "\\(--?"
4842 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4843 "Regular expression to match a timestamp time or time range.
4844 After a match, the following groups carry important information:
4845 0 the full match
4846 1 date plus weekday, for back referencing to make sure both times are on the same day
4847 2 the first time, range or not
4848 4 the second time, if it is a range.")
4850 (defconst org-startup-options
4851 '(("fold" org-startup-folded t)
4852 ("overview" org-startup-folded t)
4853 ("nofold" org-startup-folded nil)
4854 ("showall" org-startup-folded nil)
4855 ("showeverything" org-startup-folded showeverything)
4856 ("content" org-startup-folded content)
4857 ("indent" org-startup-indented t)
4858 ("noindent" org-startup-indented nil)
4859 ("hidestars" org-hide-leading-stars t)
4860 ("showstars" org-hide-leading-stars nil)
4861 ("odd" org-odd-levels-only t)
4862 ("oddeven" org-odd-levels-only nil)
4863 ("align" org-startup-align-all-tables t)
4864 ("noalign" org-startup-align-all-tables nil)
4865 ("inlineimages" org-startup-with-inline-images t)
4866 ("noinlineimages" org-startup-with-inline-images nil)
4867 ("latexpreview" org-startup-with-latex-preview t)
4868 ("nolatexpreview" org-startup-with-latex-preview nil)
4869 ("customtime" org-display-custom-times t)
4870 ("logdone" org-log-done time)
4871 ("lognotedone" org-log-done note)
4872 ("nologdone" org-log-done nil)
4873 ("lognoteclock-out" org-log-note-clock-out t)
4874 ("nolognoteclock-out" org-log-note-clock-out nil)
4875 ("logrepeat" org-log-repeat state)
4876 ("lognoterepeat" org-log-repeat note)
4877 ("logdrawer" org-log-into-drawer t)
4878 ("nologdrawer" org-log-into-drawer nil)
4879 ("logstatesreversed" org-log-states-order-reversed t)
4880 ("nologstatesreversed" org-log-states-order-reversed nil)
4881 ("nologrepeat" org-log-repeat nil)
4882 ("logreschedule" org-log-reschedule time)
4883 ("lognotereschedule" org-log-reschedule note)
4884 ("nologreschedule" org-log-reschedule nil)
4885 ("logredeadline" org-log-redeadline time)
4886 ("lognoteredeadline" org-log-redeadline note)
4887 ("nologredeadline" org-log-redeadline nil)
4888 ("logrefile" org-log-refile time)
4889 ("lognoterefile" org-log-refile note)
4890 ("nologrefile" org-log-refile nil)
4891 ("fninline" org-footnote-define-inline t)
4892 ("nofninline" org-footnote-define-inline nil)
4893 ("fnlocal" org-footnote-section nil)
4894 ("fnauto" org-footnote-auto-label t)
4895 ("fnprompt" org-footnote-auto-label nil)
4896 ("fnconfirm" org-footnote-auto-label confirm)
4897 ("fnplain" org-footnote-auto-label plain)
4898 ("fnadjust" org-footnote-auto-adjust t)
4899 ("nofnadjust" org-footnote-auto-adjust nil)
4900 ("constcgs" constants-unit-system cgs)
4901 ("constSI" constants-unit-system SI)
4902 ("noptag" org-tag-persistent-alist nil)
4903 ("hideblocks" org-hide-block-startup t)
4904 ("nohideblocks" org-hide-block-startup nil)
4905 ("beamer" org-startup-with-beamer-mode t)
4906 ("entitiespretty" org-pretty-entities t)
4907 ("entitiesplain" org-pretty-entities nil))
4908 "Variable associated with STARTUP options for org-mode.
4909 Each element is a list of three items: the startup options (as written
4910 in the #+STARTUP line), the corresponding variable, and the value to set
4911 this variable to if the option is found. An optional forth element PUSH
4912 means to push this value onto the list in the variable.")
4914 (defcustom org-group-tags t
4915 "When non-nil (the default), use group tags.
4916 This can be turned on/off through `org-toggle-tags-groups'."
4917 :group 'org-tags
4918 :group 'org-startup
4919 :type 'boolean)
4921 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4923 (defun org-toggle-tags-groups ()
4924 "Toggle support for group tags.
4925 Support for group tags is controlled by the option
4926 `org-group-tags', which is non-nil by default."
4927 (interactive)
4928 (setq org-group-tags (not org-group-tags))
4929 (cond ((and (derived-mode-p 'org-agenda-mode)
4930 org-group-tags)
4931 (org-agenda-redo))
4932 ((derived-mode-p 'org-mode)
4933 (let ((org-inhibit-startup t)) (org-mode))))
4934 (message "Groups tags support has been turned %s"
4935 (if org-group-tags "on" "off")))
4937 (defun org-set-regexps-and-options (&optional tags-only)
4938 "Precompute regular expressions used in the current buffer.
4939 When optional argument TAGS-ONLY is non-nil, only compute tags
4940 related expressions."
4941 (when (derived-mode-p 'org-mode)
4942 (let ((alist (org--setup-collect-keywords
4943 (org-make-options-regexp
4944 (append '("FILETAGS" "TAGS" "SETUPFILE")
4945 (and (not tags-only)
4946 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4947 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4948 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4949 (org--setup-process-tags
4950 (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
4951 (unless tags-only
4952 ;; File properties.
4953 (setq-local org-file-properties (cdr (assq 'property alist)))
4954 ;; Archive location.
4955 (let ((archive (cdr (assq 'archive alist))))
4956 (when archive (setq-local org-archive-location archive)))
4957 ;; Category.
4958 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4959 (when cat
4960 (setq-local org-category (intern cat))
4961 (setq-local org-file-properties
4962 (org--update-property-plist
4963 "CATEGORY" cat org-file-properties))))
4964 ;; Columns.
4965 (let ((column (cdr (assq 'columns alist))))
4966 (when column (setq-local org-columns-default-format column)))
4967 ;; Constants.
4968 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4969 ;; Link abbreviations.
4970 (let ((links (cdr (assq 'link alist))))
4971 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4972 ;; Priorities.
4973 (let ((priorities (cdr (assq 'priorities alist))))
4974 (when priorities
4975 (setq-local org-highest-priority (nth 0 priorities))
4976 (setq-local org-lowest-priority (nth 1 priorities))
4977 (setq-local org-default-priority (nth 2 priorities))))
4978 ;; Scripts.
4979 (let ((scripts (assq 'scripts alist)))
4980 (when scripts
4981 (setq-local org-use-sub-superscripts (cdr scripts))))
4982 ;; Startup options.
4983 (let ((startup (cdr (assq 'startup alist))))
4984 (dolist (option startup)
4985 (let ((entry (assoc-string option org-startup-options t)))
4986 (when entry
4987 (let ((var (nth 1 entry))
4988 (val (nth 2 entry)))
4989 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4990 (unless (listp (symbol-value var))
4991 (set (make-local-variable var) nil))
4992 (add-to-list var val)))))))
4993 ;; TODO keywords.
4994 (setq-local org-todo-kwd-alist nil)
4995 (setq-local org-todo-key-alist nil)
4996 (setq-local org-todo-key-trigger nil)
4997 (setq-local org-todo-keywords-1 nil)
4998 (setq-local org-done-keywords nil)
4999 (setq-local org-todo-heads nil)
5000 (setq-local org-todo-sets nil)
5001 (setq-local org-todo-log-states nil)
5002 (let ((todo-sequences
5003 (or (nreverse (cdr (assq 'todo alist)))
5004 (let ((d (default-value 'org-todo-keywords)))
5005 (if (not (stringp (car d))) d
5006 ;; XXX: Backward compatibility code.
5007 (list (cons org-todo-interpretation d)))))))
5008 (dolist (sequence todo-sequences)
5009 (let* ((sequence (or (run-hook-with-args-until-success
5010 'org-todo-setup-filter-hook sequence)
5011 sequence))
5012 (sequence-type (car sequence))
5013 (keywords (cdr sequence))
5014 (sep (member "|" keywords))
5015 names alist)
5016 (dolist (k (remove "|" keywords))
5017 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5019 (error "Invalid TODO keyword %s" k))
5020 (let ((name (match-string 1 k))
5021 (key (match-string 2 k))
5022 (log (org-extract-log-state-settings k)))
5023 (push name names)
5024 (push (cons name (and key (string-to-char key))) alist)
5025 (when log (push log org-todo-log-states))))
5026 (let* ((names (nreverse names))
5027 (done (if sep (org-remove-keyword-keys (cdr sep))
5028 (last names)))
5029 (head (car names))
5030 (tail (list sequence-type head (car done) (org-last done))))
5031 (add-to-list 'org-todo-heads head 'append)
5032 (push names org-todo-sets)
5033 (setq org-done-keywords (append org-done-keywords done nil))
5034 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5035 (setq org-todo-key-alist
5036 (append org-todo-key-alist
5037 (and alist
5038 (append '((:startgroup))
5039 (nreverse alist)
5040 '((:endgroup))))))
5041 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5042 (setq org-todo-sets (nreverse org-todo-sets)
5043 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5044 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5045 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5046 ;; Compute the regular expressions and other local variables.
5047 ;; Using `org-outline-regexp-bol' would complicate them much,
5048 ;; because of the fixed white space at the end of that string.
5049 (if (not org-done-keywords)
5050 (setq org-done-keywords
5051 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5052 (setq org-not-done-keywords
5053 (org-delete-all org-done-keywords
5054 (copy-sequence org-todo-keywords-1))
5055 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5056 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5057 org-not-done-heading-regexp
5058 (format org-heading-keyword-regexp-format org-not-done-regexp)
5059 org-todo-line-regexp
5060 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5061 org-complex-heading-regexp
5062 (concat "^\\(\\*+\\)"
5063 "\\(?: +" org-todo-regexp "\\)?"
5064 "\\(?: +\\(\\[#.\\]\\)\\)?"
5065 "\\(?: +\\(.*?\\)\\)??"
5066 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5067 "[ \t]*$")
5068 org-complex-heading-regexp-format
5069 (concat "^\\(\\*+\\)"
5070 "\\(?: +" org-todo-regexp "\\)?"
5071 "\\(?: +\\(\\[#.\\]\\)\\)?"
5072 "\\(?: +"
5073 ;; Stats cookies can be stuck to body.
5074 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5075 "\\(%s\\)"
5076 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5077 "\\)"
5078 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5079 "[ \t]*$")
5080 org-todo-line-tags-regexp
5081 (concat "^\\(\\*+\\)"
5082 "\\(?: +" org-todo-regexp "\\)?"
5083 "\\(?: +\\(.*?\\)\\)??"
5084 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5085 "[ \t]*$"))
5086 (org-compute-latex-and-related-regexp)))))
5088 (defun org--setup-collect-keywords (regexp &optional files alist)
5089 "Return setup keywords values as an alist.
5091 REGEXP matches a subset of setup keywords. FILES is a list of
5092 file names already visited. It is used to avoid circular setup
5093 files. ALIST, when non-nil, is the alist computed so far.
5095 Return value contains the following keys: `archive', `category',
5096 `columns', `constants', `filetags', `link', `priorities',
5097 `property', `scripts', `startup', `tags' and `todo'."
5098 (org-with-wide-buffer
5099 (goto-char (point-min))
5100 (let ((case-fold-search t))
5101 (while (re-search-forward regexp nil t)
5102 (let ((element (org-element-at-point)))
5103 (when (eq (org-element-type element) 'keyword)
5104 (let ((key (org-element-property :key element))
5105 (value (org-element-property :value element)))
5106 (cond
5107 ((equal key "ARCHIVE")
5108 (when (org-string-nw-p value)
5109 (push (cons 'archive value) alist)))
5110 ((equal key "CATEGORY") (push (cons 'category value) alist))
5111 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5112 ((equal key "CONSTANTS")
5113 (let* ((constants (assq 'constants alist))
5114 (store (cdr constants)))
5115 (dolist (pair (org-split-string value))
5116 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5117 pair)
5118 (let* ((name (match-string 1 pair))
5119 (value (match-string 2 pair))
5120 (old (assoc name store)))
5121 (if old (setcdr old value)
5122 (push (cons name value) store)))))
5123 (if constants (setcdr constants store)
5124 (push (cons 'constants store) alist))))
5125 ((equal key "FILETAGS")
5126 (when (org-string-nw-p value)
5127 (let ((old (assq 'filetags alist))
5128 (new (apply #'nconc
5129 (mapcar (lambda (x) (org-split-string x ":"))
5130 (org-split-string value)))))
5131 (if old (setcdr old (append new (cdr old)))
5132 (push (cons 'filetags new) alist)))))
5133 ((equal key "LINK")
5134 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5135 (let ((links (assq 'link alist))
5136 (pair (cons (org-match-string-no-properties 1 value)
5137 (org-match-string-no-properties 2 value))))
5138 (if links (push pair (cdr links))
5139 (push (list 'link pair) alist)))))
5140 ((equal key "OPTIONS")
5141 (when (and (org-string-nw-p value)
5142 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5143 (push (cons 'scripts (read (match-string 1 value))) alist)))
5144 ((equal key "PRIORITIES")
5145 (push (cons 'priorities
5146 (let ((prio (org-split-string value)))
5147 (if (< (length prio) 3) '(?A ?C ?B)
5148 (mapcar #'string-to-char prio))))
5149 alist))
5150 ((equal key "PROPERTY")
5151 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5152 (let* ((property (assq 'property alist))
5153 (value (org--update-property-plist
5154 (org-match-string-no-properties 1 value)
5155 (org-match-string-no-properties 2 value)
5156 (cdr property))))
5157 (if property (setcdr property value)
5158 (push (cons 'property value) alist)))))
5159 ((equal key "STARTUP")
5160 (let ((startup (assq 'startup alist)))
5161 (if startup
5162 (setcdr startup
5163 (append (cdr startup) (org-split-string value)))
5164 (push (cons 'startup (org-split-string value)) alist))))
5165 ((equal key "TAGS")
5166 (let ((tag-cell (assq 'tags alist)))
5167 (if tag-cell
5168 (setcdr tag-cell
5169 (append (cdr tag-cell)
5170 '("\\n")
5171 (org-split-string value)))
5172 (push (cons 'tags (org-split-string value)) alist))))
5173 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5174 (let ((todo (assq 'todo alist))
5175 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5176 (org-split-string value))))
5177 (if todo (push value (cdr todo))
5178 (push (list 'todo value) alist))))
5179 ((equal key "SETUPFILE")
5180 (unless buffer-read-only ; Do not check in Gnus messages.
5181 (let ((f (and (org-string-nw-p value)
5182 (expand-file-name
5183 (org-remove-double-quotes value)))))
5184 (when (and f (file-readable-p f) (not (member f files)))
5185 (with-temp-buffer
5186 (setq default-directory (file-name-directory f))
5187 (insert-file-contents f)
5188 (setq alist
5189 ;; Fake Org mode to benefit from cache
5190 ;; without recurring needlessly.
5191 (let ((major-mode 'org-mode))
5192 (org--setup-collect-keywords
5193 regexp (cons f files) alist)))))))))))))))
5194 alist)
5196 (defun org--setup-process-tags (tags filetags)
5197 "Precompute variables used for tags.
5198 TAGS is a list of tags and tag group symbols, as strings.
5199 FILETAGS is a list of tags, as strings."
5200 ;; Process the file tags.
5201 (setq-local org-file-tags
5202 (mapcar #'org-add-prop-inherited filetags))
5203 ;; Provide default tags if no local tags are found.
5204 (when (and (not tags) org-tag-alist)
5205 (setq tags
5206 (mapcar (lambda (tag)
5207 (case (car tag)
5208 (:startgroup "{")
5209 (:endgroup "}")
5210 (:startgrouptag "[")
5211 (:endgrouptag "]")
5212 (:grouptags ":")
5213 (:newline "\\n")
5214 (otherwise (concat (car tag)
5215 (and (characterp (cdr tag))
5216 (format "(%c)" (cdr tag)))))))
5217 org-tag-alist)))
5218 ;; Process the tags.
5219 (setq-local org-tag-groups-alist nil)
5220 (setq-local org-tag-alist nil)
5221 (let (group-flag)
5222 (while tags
5223 (let ((e (car tags)))
5224 (setq tags (cdr tags))
5225 (cond
5226 ((equal e "{")
5227 (push '(:startgroup) org-tag-alist)
5228 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5229 ((equal e "}")
5230 (push '(:endgroup) org-tag-alist)
5231 (setq group-flag nil))
5232 ((equal e "[")
5233 (push '(:startgrouptag) org-tag-alist)
5234 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5235 ((equal e "]")
5236 (push '(:endgrouptag) org-tag-alist)
5237 (setq group-flag nil))
5238 ((equal e ":")
5239 (push '(:grouptags) org-tag-alist)
5240 (setq group-flag 'append))
5241 ((equal e "\\n") (push '(:newline) org-tag-alist))
5242 ((string-match
5243 (org-re (concat "\\`\\([[:alnum:]_@#%]+"
5244 "\\|{.+?}\\)" ; regular expression
5245 "\\(?:(\\(.\\))\\)?\\'")) e)
5246 (let ((tag (match-string 1 e))
5247 (key (and (match-beginning 2)
5248 (string-to-char (match-string 2 e)))))
5249 (cond ((eq group-flag 'append)
5250 (setcar org-tag-groups-alist
5251 (append (car org-tag-groups-alist) (list tag))))
5252 (group-flag (push (list tag) org-tag-groups-alist)))
5253 ;; Push all tags in groups, no matter if they already exist.
5254 (unless (and (not group-flag) (assoc tag org-tag-alist))
5255 (push (cons tag key) org-tag-alist))))))))
5256 (setq org-tag-alist (nreverse org-tag-alist)))
5258 (defun org-file-contents (file &optional noerror)
5259 "Return the contents of FILE, as a string."
5260 (if (and file (file-readable-p file))
5261 (with-temp-buffer
5262 (insert-file-contents file)
5263 (buffer-string))
5264 (funcall (if noerror 'message 'error)
5265 "Cannot read file \"%s\"%s"
5266 file
5267 (let ((from (buffer-file-name (buffer-base-buffer))))
5268 (if from (concat " (referenced in file \"" from "\")") "")))))
5270 (defun org-extract-log-state-settings (x)
5271 "Extract the log state setting from a TODO keyword string.
5272 This will extract info from a string like \"WAIT(w@/!)\"."
5273 (let (kw key log1 log2)
5274 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5275 (setq kw (match-string 1 x)
5276 key (and (match-end 2) (match-string 2 x))
5277 log1 (and (match-end 3) (match-string 3 x))
5278 log2 (and (match-end 4) (match-string 4 x)))
5279 (and (or log1 log2)
5280 (list kw
5281 (and log1 (if (equal log1 "!") 'time 'note))
5282 (and log2 (if (equal log2 "!") 'time 'note)))))))
5284 (defun org-remove-keyword-keys (list)
5285 "Remove a pair of parenthesis at the end of each string in LIST."
5286 (mapcar (lambda (x)
5287 (if (string-match "(.*)$" x)
5288 (substring x 0 (match-beginning 0))
5290 list))
5292 (defun org-assign-fast-keys (alist)
5293 "Assign fast keys to a keyword-key alist.
5294 Respect keys that are already there."
5295 (let (new e (alt ?0))
5296 (while (setq e (pop alist))
5297 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5298 (cdr e)) ;; Key already assigned.
5299 (push e new)
5300 (let ((clist (string-to-list (downcase (car e))))
5301 (used (append new alist)))
5302 (when (= (car clist) ?@)
5303 (pop clist))
5304 (while (and clist (rassoc (car clist) used))
5305 (pop clist))
5306 (unless clist
5307 (while (rassoc alt used)
5308 (incf alt)))
5309 (push (cons (car e) (or (car clist) alt)) new))))
5310 (nreverse new)))
5312 ;;; Some variables used in various places
5314 (defvar org-window-configuration nil
5315 "Used in various places to store a window configuration.")
5316 (defvar org-selected-window nil
5317 "Used in various places to store a window configuration.")
5318 (defvar org-finish-function nil
5319 "Function to be called when `C-c C-c' is used.
5320 This is for getting out of special buffers like capture.")
5323 ;; FIXME: Occasionally check by commenting these, to make sure
5324 ;; no other functions uses these, forgetting to let-bind them.
5325 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5326 (defvar org-last-state)
5327 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5329 ;; Defined somewhere in this file, but used before definition.
5330 (defvar org-entities) ;; defined in org-entities.el
5331 (defvar org-struct-menu)
5332 (defvar org-org-menu)
5333 (defvar org-tbl-menu)
5335 ;;;; Define the Org-mode
5337 ;; We use a before-change function to check if a table might need
5338 ;; an update.
5339 (defvar org-table-may-need-update t
5340 "Indicates that a table might need an update.
5341 This variable is set by `org-before-change-function'.
5342 `org-table-align' sets it back to nil.")
5343 (defun org-before-change-function (beg end)
5344 "Every change indicates that a table might need an update."
5345 (setq org-table-may-need-update t))
5346 (defvar org-mode-map)
5347 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5348 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5349 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5350 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5351 (defvar org-table-buffer-is-an nil)
5353 (defvar bidi-paragraph-direction)
5354 (defvar buffer-face-mode-face)
5356 (require 'outline)
5357 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5358 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
5359 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5361 ;; Other stuff we need.
5362 (require 'time-date)
5363 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5364 (require 'easymenu)
5365 (autoload 'easy-menu-add "easymenu")
5366 (require 'overlay)
5368 ;; (require 'org-macs) moved higher up in the file before it is first used
5369 (require 'org-entities)
5370 ;; (require 'org-compat) moved higher up in the file before it is first used
5371 (require 'org-faces)
5372 (require 'org-list)
5373 (require 'org-pcomplete)
5374 (require 'org-src)
5375 (require 'org-footnote)
5376 (require 'org-macro)
5378 ;; babel
5379 (require 'ob)
5381 ;;;###autoload
5382 (define-derived-mode org-mode outline-mode "Org"
5383 "Outline-based notes management and organizer, alias
5384 \"Carsten's outline-mode for keeping track of everything.\"
5386 Org-mode develops organizational tasks around a NOTES file which
5387 contains information about projects as plain text. Org-mode is
5388 implemented on top of outline-mode, which is ideal to keep the content
5389 of large files well structured. It supports ToDo items, deadlines and
5390 time stamps, which magically appear in the diary listing of the Emacs
5391 calendar. Tables are easily created with a built-in table editor.
5392 Plain text URL-like links connect to websites, emails (VM), Usenet
5393 messages (Gnus), BBDB entries, and any files related to the project.
5394 For printing and sharing of notes, an Org-mode file (or a part of it)
5395 can be exported as a structured ASCII or HTML file.
5397 The following commands are available:
5399 \\{org-mode-map}"
5401 ;; Get rid of Outline menus, they are not needed
5402 ;; Need to do this here because define-derived-mode sets up
5403 ;; the keymap so late. Still, it is a waste to call this each time
5404 ;; we switch another buffer into org-mode.
5405 (if (featurep 'xemacs)
5406 (when (boundp 'outline-mode-menu-heading)
5407 ;; Assume this is Greg's port, it uses easymenu
5408 (easy-menu-remove outline-mode-menu-heading)
5409 (easy-menu-remove outline-mode-menu-show)
5410 (easy-menu-remove outline-mode-menu-hide))
5411 (define-key org-mode-map [menu-bar headings] 'undefined)
5412 (define-key org-mode-map [menu-bar hide] 'undefined)
5413 (define-key org-mode-map [menu-bar show] 'undefined))
5415 (org-load-modules-maybe)
5416 (when (featurep 'xemacs)
5417 (easy-menu-add org-org-menu)
5418 (easy-menu-add org-tbl-menu))
5419 (org-install-agenda-files-menu)
5420 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5421 (add-to-invisibility-spec '(org-cwidth))
5422 (add-to-invisibility-spec '(org-hide-block . t))
5423 (when (featurep 'xemacs)
5424 (setq-local line-move-ignore-invisible t))
5425 (setq-local outline-regexp org-outline-regexp)
5426 (setq-local outline-level 'org-outline-level)
5427 (setq bidi-paragraph-direction 'left-to-right)
5428 (when (and org-ellipsis
5429 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5430 (fboundp 'make-glyph-code))
5431 (unless org-display-table
5432 (setq org-display-table (make-display-table)))
5433 (set-display-table-slot
5434 org-display-table 4
5435 (vconcat (mapcar
5436 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5437 org-ellipsis)))
5438 (if (stringp org-ellipsis) org-ellipsis "..."))))
5439 (setq buffer-display-table org-display-table))
5440 (org-set-regexps-and-options)
5441 (org-set-font-lock-defaults)
5442 (when (and org-tag-faces (not org-tags-special-faces-re))
5443 ;; tag faces set outside customize.... force initialization.
5444 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5445 ;; Calc embedded
5446 (setq-local calc-embedded-open-mode "# ")
5447 ;; Modify a few syntax entries
5448 (modify-syntax-entry ?@ "w")
5449 (modify-syntax-entry ?\" "\"")
5450 (modify-syntax-entry ?\\ "_")
5451 (modify-syntax-entry ?~ "_")
5452 (if org-startup-truncated (setq truncate-lines t))
5453 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5454 (setq-local font-lock-unfontify-region-function
5455 'org-unfontify-region)
5456 ;; Activate before-change-function
5457 (setq-local org-table-may-need-update t)
5458 (org-add-hook 'before-change-functions 'org-before-change-function nil
5459 'local)
5460 ;; Check for running clock before killing a buffer
5461 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5462 ;; Initialize macros templates.
5463 (org-macro-initialize-templates)
5464 ;; Initialize radio targets.
5465 (org-update-radio-target-regexp)
5466 ;; Indentation.
5467 (setq-local indent-line-function 'org-indent-line)
5468 (setq-local indent-region-function 'org-indent-region)
5469 ;; Filling and auto-filling.
5470 (org-setup-filling)
5471 ;; Comments.
5472 (org-setup-comments-handling)
5473 ;; Initialize cache.
5474 (org-element-cache-reset)
5475 ;; Beginning/end of defun
5476 (setq-local beginning-of-defun-function 'org-backward-element)
5477 (setq-local end-of-defun-function
5478 (lambda ()
5479 (if (not (org-at-heading-p))
5480 (org-forward-element)
5481 (org-forward-element)
5482 (forward-char -1))))
5483 ;; Next error for sparse trees
5484 (setq-local next-error-function 'org-occur-next-match)
5485 ;; Make sure dependence stuff works reliably, even for users who set it
5486 ;; too late :-(
5487 (if org-enforce-todo-dependencies
5488 (add-hook 'org-blocker-hook
5489 'org-block-todo-from-children-or-siblings-or-parent)
5490 (remove-hook 'org-blocker-hook
5491 'org-block-todo-from-children-or-siblings-or-parent))
5492 (if org-enforce-todo-checkbox-dependencies
5493 (add-hook 'org-blocker-hook
5494 'org-block-todo-from-checkboxes)
5495 (remove-hook 'org-blocker-hook
5496 'org-block-todo-from-checkboxes))
5498 ;; Align options lines
5499 (setq-local
5500 align-mode-rules-list
5501 '((org-in-buffer-settings
5502 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5503 (modes . '(org-mode)))))
5505 ;; Imenu
5506 (setq-local imenu-create-index-function
5507 'org-imenu-get-tree)
5509 ;; Make isearch reveal context
5510 (if (or (featurep 'xemacs)
5511 (not (boundp 'outline-isearch-open-invisible-function)))
5512 ;; Emacs 21 and XEmacs make use of the hook
5513 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5514 ;; Emacs 22 deals with this through a special variable
5515 (setq-local outline-isearch-open-invisible-function
5516 (lambda (&rest ignore) (org-show-context 'isearch))))
5518 ;; Setup the pcomplete hooks
5519 (setq-local pcomplete-command-completion-function
5520 'org-pcomplete-initial)
5521 (setq-local pcomplete-command-name-function
5522 'org-command-at-point)
5523 (setq-local pcomplete-default-completion-function
5524 'ignore)
5525 (setq-local pcomplete-parse-arguments-function
5526 'org-parse-arguments)
5527 (setq-local pcomplete-termination-string "")
5528 (setq-local buffer-face-mode-face 'org-default)
5530 ;; If empty file that did not turn on org-mode automatically, make it to.
5531 (if (and org-insert-mode-line-in-empty-file
5532 (org-called-interactively-p 'any)
5533 (= (point-min) (point-max)))
5534 (insert "# -*- mode: org -*-\n\n"))
5535 (unless org-inhibit-startup
5536 (org-unmodified
5537 (and org-startup-with-beamer-mode (org-beamer-mode))
5538 (when org-startup-align-all-tables
5539 (org-table-map-tables 'org-table-align 'quietly))
5540 (when org-startup-with-inline-images
5541 (org-display-inline-images))
5542 (when org-startup-with-latex-preview
5543 (org-toggle-latex-fragment))
5544 (unless org-inhibit-startup-visibility-stuff
5545 (org-set-startup-visibility))
5546 (org-refresh-effort-properties)))
5547 ;; Try to set org-hide correctly
5548 (let ((foreground (org-find-invisible-foreground)))
5549 (if foreground
5550 (set-face-foreground 'org-hide foreground))))
5552 ;; Update `customize-package-emacs-version-alist'
5553 (add-to-list 'customize-package-emacs-version-alist
5554 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5555 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5556 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5558 (defvar org-mode-transpose-word-syntax-table
5559 (let ((st (make-syntax-table text-mode-syntax-table)))
5560 (mapc (lambda(c) (modify-syntax-entry
5561 (string-to-char (car c)) "w p" st))
5562 org-emphasis-alist)
5563 st))
5565 (when (fboundp 'abbrev-table-put)
5566 (abbrev-table-put org-mode-abbrev-table
5567 :parents (list text-mode-abbrev-table)))
5569 (defun org-find-invisible-foreground ()
5570 (let ((candidates (remove
5571 "unspecified-bg"
5572 (nconc
5573 (list (face-background 'default)
5574 (face-background 'org-default))
5575 (mapcar
5576 (lambda (alist)
5577 (when (boundp alist)
5578 (cdr (assoc 'background-color (symbol-value alist)))))
5579 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5580 (list (face-foreground 'org-hide))))))
5581 (car (remove nil candidates))))
5583 (defun org-current-time (&optional rounding-minutes past)
5584 "Current time, possibly rounded to ROUNDING-MINUTES.
5585 When ROUNDING-MINUTES is not an integer, fall back on the car of
5586 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5587 the rounding returns a past time."
5588 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5589 (car org-time-stamp-rounding-minutes)))
5590 (time (decode-time)) res)
5591 (if (< r 1)
5592 (current-time)
5593 (setq res
5594 (apply 'encode-time
5595 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5596 (nthcdr 2 time))))
5597 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5598 (seconds-to-time (- (org-float-time res) (* r 60)))
5599 res))))
5601 (defun org-today ()
5602 "Return today date, considering `org-extend-today-until'."
5603 (time-to-days
5604 (time-subtract (current-time)
5605 (list 0 (* 3600 org-extend-today-until) 0))))
5607 ;;;; Font-Lock stuff, including the activators
5609 (defvar org-mouse-map (make-sparse-keymap))
5610 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5611 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5612 (when org-mouse-1-follows-link
5613 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5614 (when org-tab-follows-link
5615 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5616 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5618 (require 'font-lock)
5620 (defconst org-non-link-chars "]\t\n\r<>")
5621 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5622 "file+sys" "news" "shell" "elisp" "doi" "message"
5623 "help"))
5624 (defvar org-link-types-re nil
5625 "Matches a link that has a url-like prefix like \"http:\"")
5626 (defvar org-link-re-with-space nil
5627 "Matches a link with spaces, optional angular brackets around it.")
5628 (defvar org-link-re-with-space2 nil
5629 "Matches a link with spaces, optional angular brackets around it.")
5630 (defvar org-link-re-with-space3 nil
5631 "Matches a link with spaces, only for internal part in bracket links.")
5632 (defvar org-angle-link-re nil
5633 "Matches link with angular brackets, spaces are allowed.")
5634 (defvar org-plain-link-re nil
5635 "Matches plain link, without spaces.")
5636 (defvar org-bracket-link-regexp nil
5637 "Matches a link in double brackets.")
5638 (defvar org-bracket-link-analytic-regexp nil
5639 "Regular expression used to analyze links.
5640 Here is what the match groups contain after a match:
5641 1: http:
5642 2: http
5643 3: path
5644 4: [desc]
5645 5: desc")
5646 (defvar org-bracket-link-analytic-regexp++ nil
5647 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5648 (defvar org-any-link-re nil
5649 "Regular expression matching any link.")
5651 (defconst org-match-sexp-depth 3
5652 "Number of stacked braces for sub/superscript matching.")
5654 (defun org-create-multibrace-regexp (left right n)
5655 "Create a regular expression which will match a balanced sexp.
5656 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5657 as single character strings.
5658 The regexp returned will match the entire expression including the
5659 delimiters. It will also define a single group which contains the
5660 match except for the outermost delimiters. The maximum depth of
5661 stacked delimiters is N. Escaping delimiters is not possible."
5662 (let* ((nothing (concat "[^" left right "]*?"))
5663 (or "\\|")
5664 (re nothing)
5665 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5666 (while (> n 1)
5667 (setq n (1- n)
5668 re (concat re or next)
5669 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5670 (concat left "\\(" re "\\)" right)))
5672 (defconst org-match-substring-regexp
5673 (concat
5674 "\\(\\S-\\)\\([_^]\\)\\("
5675 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5676 "\\|"
5677 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5678 "\\|"
5679 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5680 "The regular expression matching a sub- or superscript.")
5682 (defconst org-match-substring-with-braces-regexp
5683 (concat
5684 "\\(\\S-\\)\\([_^]\\)"
5685 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5686 "The regular expression matching a sub- or superscript, forcing braces.")
5688 (defun org-make-link-regexps ()
5689 "Update the link regular expressions.
5690 This should be called after the variable `org-link-types' has changed."
5691 (let ((types-re (regexp-opt org-link-types t)))
5692 (setq org-link-types-re
5693 (concat "\\`" types-re ":")
5694 org-link-re-with-space
5695 (concat "<?" types-re ":"
5696 "\\([^" org-non-link-chars " ]"
5697 "[^" org-non-link-chars "]*"
5698 "[^" org-non-link-chars " ]\\)>?")
5699 org-link-re-with-space2
5700 (concat "<?" types-re ":"
5701 "\\([^" org-non-link-chars " ]"
5702 "[^\t\n\r]*"
5703 "[^" org-non-link-chars " ]\\)>?")
5704 org-link-re-with-space3
5705 (concat "<?" types-re ":"
5706 "\\([^" org-non-link-chars " ]"
5707 "[^\t\n\r]*\\)")
5708 org-angle-link-re
5709 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5710 types-re)
5711 org-plain-link-re
5712 (concat
5713 "\\<" types-re ":"
5714 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5715 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5716 org-bracket-link-regexp
5717 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5718 org-bracket-link-analytic-regexp
5719 (concat
5720 "\\[\\["
5721 "\\(" types-re ":\\)?"
5722 "\\([^]]+\\)"
5723 "\\]"
5724 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5725 "\\]")
5726 org-bracket-link-analytic-regexp++
5727 (concat
5728 "\\[\\["
5729 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5730 "\\([^]]+\\)"
5731 "\\]"
5732 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5733 "\\]")
5734 org-any-link-re
5735 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5736 org-angle-link-re "\\)\\|\\("
5737 org-plain-link-re "\\)"))))
5739 (org-make-link-regexps)
5741 (defvar org-emph-face nil)
5743 (defun org-do-emphasis-faces (limit)
5744 "Run through the buffer and emphasize strings."
5745 (let (rtn a)
5746 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5747 (let* ((border (char-after (match-beginning 3)))
5748 (bre (regexp-quote (char-to-string border))))
5749 (if (and (not (= border (char-after (match-beginning 4))))
5750 (not (save-match-data
5751 (string-match (concat bre ".*" bre)
5752 (replace-regexp-in-string
5753 "\n" " "
5754 (substring (match-string 2) 1 -1))))))
5755 (progn
5756 (setq rtn t)
5757 (setq a (assoc (match-string 3) org-emphasis-alist))
5758 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5759 'face
5760 (nth 1 a))
5761 (and (nth 2 a)
5762 (org-remove-flyspell-overlays-in
5763 (match-beginning 0) (match-end 0)))
5764 (add-text-properties (match-beginning 2) (match-end 2)
5765 '(font-lock-multiline t org-emphasis t))
5766 (when org-hide-emphasis-markers
5767 (add-text-properties (match-end 4) (match-beginning 5)
5768 '(invisible org-link))
5769 (add-text-properties (match-beginning 3) (match-end 3)
5770 '(invisible org-link))))))
5771 (goto-char (1+ (match-beginning 0))))
5772 rtn))
5774 (defun org-emphasize (&optional char)
5775 "Insert or change an emphasis, i.e. a font like bold or italic.
5776 If there is an active region, change that region to a new emphasis.
5777 If there is no region, just insert the marker characters and position
5778 the cursor between them.
5779 CHAR should be the marker character. If it is a space, it means to
5780 remove the emphasis of the selected region.
5781 If CHAR is not given (for example in an interactive call) it will be
5782 prompted for."
5783 (interactive)
5784 (let ((erc org-emphasis-regexp-components)
5785 (prompt "")
5786 (string "") beg end move c s)
5787 (if (org-region-active-p)
5788 (setq beg (region-beginning) end (region-end)
5789 string (buffer-substring beg end))
5790 (setq move t))
5792 (unless char
5793 (message "Emphasis marker or tag: [%s]"
5794 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5795 (setq char (read-char-exclusive)))
5796 (if (equal char ?\ )
5797 (setq s "" move nil)
5798 (unless (assoc (char-to-string char) org-emphasis-alist)
5799 (user-error "No such emphasis marker: \"%c\"" char))
5800 (setq s (char-to-string char)))
5801 (while (and (> (length string) 1)
5802 (equal (substring string 0 1) (substring string -1))
5803 (assoc (substring string 0 1) org-emphasis-alist))
5804 (setq string (substring string 1 -1)))
5805 (setq string (concat s string s))
5806 (if beg (delete-region beg end))
5807 (unless (or (bolp)
5808 (string-match (concat "[" (nth 0 erc) "\n]")
5809 (char-to-string (char-before (point)))))
5810 (insert " "))
5811 (unless (or (eobp)
5812 (string-match (concat "[" (nth 1 erc) "\n]")
5813 (char-to-string (char-after (point)))))
5814 (insert " ") (backward-char 1))
5815 (insert string)
5816 (and move (backward-char 1))))
5818 (defconst org-nonsticky-props
5819 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5821 (defsubst org-rear-nonsticky-at (pos)
5822 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5824 (defun org-activate-plain-links (limit)
5825 "Add link properties for plain links."
5826 (let (f hl)
5827 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5828 (not (member 'org-tag
5829 (get-text-property (1- (match-beginning 0)) 'face)))
5830 (not (org-in-src-block-p)))
5831 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5832 (setq f (get-text-property (match-beginning 0) 'face))
5833 (setq hl (org-match-string-no-properties 0))
5834 (if (or (eq f 'org-tag)
5835 (and (listp f) (memq 'org-tag f)))
5837 (add-text-properties (match-beginning 0) (match-end 0)
5838 (list 'mouse-face 'highlight
5839 'face 'org-link
5840 'htmlize-link `(:uri ,hl)
5841 'keymap org-mouse-map))
5842 (org-rear-nonsticky-at (match-end 0)))
5843 t)))
5845 (defun org-activate-code (limit)
5846 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5847 (progn
5848 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5849 (remove-text-properties (match-beginning 0) (match-end 0)
5850 '(display t invisible t intangible t))
5851 t)))
5853 (defcustom org-src-fontify-natively t
5854 "When non-nil, fontify code in code blocks."
5855 :type 'boolean
5856 :version "24.4"
5857 :package-version '(Org . "8.3")
5858 :group 'org-appearance
5859 :group 'org-babel)
5861 (defcustom org-allow-promoting-top-level-subtree nil
5862 "When non-nil, allow promoting a top level subtree.
5863 The leading star of the top level headline will be replaced
5864 by a #."
5865 :type 'boolean
5866 :version "24.1"
5867 :group 'org-appearance)
5869 (defun org-fontify-meta-lines-and-blocks (limit)
5870 (condition-case nil
5871 (org-fontify-meta-lines-and-blocks-1 limit)
5872 (error (message "org-mode fontification error"))))
5874 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5875 "Fontify #+ lines and blocks."
5876 (let ((case-fold-search t))
5877 (if (re-search-forward
5878 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5879 limit t)
5880 (let ((beg (match-beginning 0))
5881 (block-start (match-end 0))
5882 (block-end nil)
5883 (lang (match-string 7))
5884 (beg1 (line-beginning-position 2))
5885 (dc1 (downcase (match-string 2)))
5886 (dc3 (downcase (match-string 3)))
5887 end end1 quoting block-type ovl)
5888 (cond
5889 ((and (match-end 4) (equal dc3 "+begin"))
5890 ;; Truly a block
5891 (setq block-type (downcase (match-string 5))
5892 quoting (member block-type org-protecting-blocks))
5893 (when (re-search-forward
5894 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5895 nil t) ;; on purpose, we look further than LIMIT
5896 (setq end (min (point-max) (match-end 0))
5897 end1 (min (point-max) (1- (match-beginning 0))))
5898 (setq block-end (match-beginning 0))
5899 (when quoting
5900 (org-remove-flyspell-overlays-in beg1 end1)
5901 (remove-text-properties beg end
5902 '(display t invisible t intangible t)))
5903 (add-text-properties
5904 beg end '(font-lock-fontified t font-lock-multiline t))
5905 (add-text-properties beg beg1 '(face org-meta-line))
5906 (org-remove-flyspell-overlays-in beg beg1)
5907 (add-text-properties ; For end_src
5908 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5909 (org-remove-flyspell-overlays-in end1 end)
5910 (cond
5911 ((and lang (not (string= lang "")) org-src-fontify-natively)
5912 (org-src-font-lock-fontify-block lang block-start block-end)
5913 (add-text-properties beg1 block-end '(src-block t)))
5914 (quoting
5915 (add-text-properties beg1 (min (point-max) (1+ end1))
5916 '(face org-block))) ; end of source block
5917 ((not org-fontify-quote-and-verse-blocks))
5918 ((string= block-type "quote")
5919 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5920 ((string= block-type "verse")
5921 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5922 (add-text-properties beg beg1 '(face org-block-begin-line))
5923 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5924 '(face org-block-end-line))
5926 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5927 (org-remove-flyspell-overlays-in
5928 (match-beginning 0)
5929 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5930 (add-text-properties
5931 beg (match-end 3)
5932 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5933 '(font-lock-fontified t invisible t)
5934 '(font-lock-fontified t face org-document-info-keyword)))
5935 (add-text-properties
5936 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5937 (if (string-equal dc1 "+title:")
5938 '(font-lock-fontified t face org-document-title)
5939 '(font-lock-fontified t face org-document-info))))
5940 ((equal dc1 "+caption:")
5941 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5942 (remove-text-properties (match-beginning 0) (match-end 0)
5943 '(display t invisible t intangible t))
5944 (add-text-properties (match-beginning 1) (match-end 3)
5945 '(font-lock-fontified t face org-meta-line))
5946 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5947 '(font-lock-fontified t face org-block))
5949 ((member dc3 '(" " ""))
5950 (org-remove-flyspell-overlays-in beg (match-end 0))
5951 (add-text-properties
5952 beg (match-end 0)
5953 '(font-lock-fontified t face font-lock-comment-face)))
5954 (t ;; just any other in-buffer setting, but not indented
5955 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5956 (remove-text-properties (match-beginning 0) (match-end 0)
5957 '(display t invisible t intangible t))
5958 (add-text-properties beg (match-end 0)
5959 '(font-lock-fontified t face org-meta-line))
5960 t))))))
5962 (defun org-fontify-drawers (limit)
5963 "Fontify drawers."
5964 (when (re-search-forward org-drawer-regexp limit t)
5965 (add-text-properties
5966 (match-beginning 0) (match-end 0)
5967 '(font-lock-fontified t face org-special-keyword))
5968 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5971 (defun org-fontify-macros (limit)
5972 "Fontify macros."
5973 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5974 (add-text-properties
5975 (match-beginning 0) (match-end 0)
5976 '(font-lock-fontified t face org-macro))
5977 (when org-hide-macro-markers
5978 (add-text-properties (match-end 2) (match-beginning 2)
5979 '(invisible t))
5980 (add-text-properties (match-beginning 1) (match-end 1)
5981 '(invisible t)))
5982 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5985 (defun org-activate-angle-links (limit)
5986 "Add text properties for angle links."
5987 (if (and (re-search-forward org-angle-link-re limit t)
5988 (not (org-in-src-block-p)))
5989 (progn
5990 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5991 (add-text-properties (match-beginning 0) (match-end 0)
5992 (list 'mouse-face 'highlight
5993 'keymap org-mouse-map
5994 'font-lock-multiline t))
5995 (org-rear-nonsticky-at (match-end 0))
5996 t)))
5998 (defun org-activate-footnote-links (limit)
5999 "Add text properties for footnotes."
6000 (let ((fn (org-footnote-next-reference-or-definition limit)))
6001 (when fn
6002 (let* ((beg (nth 1 fn))
6003 (end (nth 2 fn))
6004 (label (car fn))
6005 (referencep (/= (line-beginning-position) beg)))
6006 (when (and referencep (nth 3 fn))
6007 (save-excursion
6008 (goto-char beg)
6009 (search-forward (or label "fn:"))
6010 (org-remove-flyspell-overlays-in beg (match-end 0))))
6011 (add-text-properties beg end
6012 (list 'mouse-face 'highlight
6013 'keymap org-mouse-map
6014 'help-echo
6015 (if referencep "Footnote reference"
6016 "Footnote definition")
6017 'font-lock-fontified t
6018 'font-lock-multiline t
6019 'face 'org-footnote))))))
6021 (defun org-activate-bracket-links (limit)
6022 "Add text properties for bracketed links."
6023 (if (and (re-search-forward org-bracket-link-regexp limit t)
6024 (not (org-in-src-block-p)))
6025 (let* ((hl (org-match-string-no-properties 1))
6026 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6027 (ip (org-maybe-intangible
6028 (list 'invisible 'org-link
6029 'keymap org-mouse-map 'mouse-face 'highlight
6030 'font-lock-multiline t 'help-echo help
6031 'htmlize-link `(:uri ,hl))))
6032 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6033 'font-lock-multiline t 'help-echo help
6034 'htmlize-link `(:uri ,hl))))
6035 ;; We need to remove the invisible property here. Table narrowing
6036 ;; may have made some of this invisible.
6037 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6038 (remove-text-properties (match-beginning 0) (match-end 0)
6039 '(invisible nil))
6040 (if (match-end 3)
6041 (progn
6042 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6043 (org-rear-nonsticky-at (match-beginning 3))
6044 (add-text-properties (match-beginning 3) (match-end 3) vp)
6045 (org-rear-nonsticky-at (match-end 3))
6046 (add-text-properties (match-end 3) (match-end 0) ip)
6047 (org-rear-nonsticky-at (match-end 0)))
6048 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6049 (org-rear-nonsticky-at (match-beginning 1))
6050 (add-text-properties (match-beginning 1) (match-end 1) vp)
6051 (org-rear-nonsticky-at (match-end 1))
6052 (add-text-properties (match-end 1) (match-end 0) ip)
6053 (org-rear-nonsticky-at (match-end 0)))
6054 t)))
6056 (defun org-activate-dates (limit)
6057 "Add text properties for dates."
6058 (if (and (re-search-forward org-tsr-regexp-both limit t)
6059 (not (equal (char-before (match-beginning 0)) 91)))
6060 (progn
6061 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6062 (add-text-properties (match-beginning 0) (match-end 0)
6063 (list 'mouse-face 'highlight
6064 'keymap org-mouse-map))
6065 (org-rear-nonsticky-at (match-end 0))
6066 (when org-display-custom-times
6067 (if (match-end 3)
6068 (org-display-custom-time (match-beginning 3) (match-end 3)))
6069 (org-display-custom-time (match-beginning 1) (match-end 1)))
6070 t)))
6072 (defvar-local org-target-link-regexp nil
6073 "Regular expression matching radio targets in plain text.")
6075 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6076 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6077 border border border))
6078 "Regular expression matching a link target.")
6080 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6081 "Regular expression matching a radio target.")
6083 (defconst org-any-target-regexp
6084 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6085 "Regular expression matching any target.")
6087 (defun org-activate-target-links (limit)
6088 "Add text properties for target matches."
6089 (when org-target-link-regexp
6090 (let ((case-fold-search t))
6091 (if (re-search-forward org-target-link-regexp limit t)
6092 (progn
6093 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6094 (add-text-properties (match-beginning 1) (match-end 1)
6095 (list 'mouse-face 'highlight
6096 'keymap org-mouse-map
6097 'help-echo "Radio target link"
6098 'org-linked-text t))
6099 (org-rear-nonsticky-at (match-end 1))
6100 t)))))
6102 (defun org-update-radio-target-regexp ()
6103 "Find all radio targets in this file and update the regular expression.
6104 Also refresh fontification if needed."
6105 (interactive)
6106 (let ((old-regexp org-target-link-regexp)
6107 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6108 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6109 (targets
6110 (org-with-wide-buffer
6111 (goto-char (point-min))
6112 (let (rtn)
6113 (while (re-search-forward org-radio-target-regexp nil t)
6114 ;; Make sure point is really within the object.
6115 (backward-char)
6116 (let ((obj (org-element-context)))
6117 (when (eq (org-element-type obj) 'radio-target)
6118 (add-to-list 'rtn (org-element-property :value obj)))))
6119 rtn))))
6120 (setq org-target-link-regexp
6121 (and targets
6122 (concat before-re
6123 (mapconcat
6124 (lambda (x)
6125 (replace-regexp-in-string
6126 " +" "\\s-+" (regexp-quote x) t t))
6127 targets
6128 "\\|")
6129 after-re)))
6130 (unless (equal old-regexp org-target-link-regexp)
6131 ;; Clean-up cache.
6132 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6133 ((not org-target-link-regexp) old-regexp)
6135 (concat before-re
6136 (mapconcat
6137 (lambda (re)
6138 (substring re (length before-re)
6139 (- (length after-re))))
6140 (list old-regexp org-target-link-regexp)
6141 "\\|")
6142 after-re)))))
6143 (org-with-wide-buffer
6144 (goto-char (point-min))
6145 (while (re-search-forward regexp nil t)
6146 (org-element-cache-refresh (match-beginning 1)))))
6147 ;; Re fontify buffer.
6148 (when (memq 'radio org-highlight-links)
6149 (org-restart-font-lock)))))
6151 (defun org-hide-wide-columns (limit)
6152 (let (s e)
6153 (setq s (text-property-any (point) (or limit (point-max))
6154 'org-cwidth t))
6155 (when s
6156 (setq e (next-single-property-change s 'org-cwidth))
6157 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6158 (goto-char e)
6159 t)))
6161 (defvar org-latex-and-related-regexp nil
6162 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6164 (defun org-compute-latex-and-related-regexp ()
6165 "Compute regular expression for LaTeX, entities and sub/superscript.
6166 Result depends on variable `org-highlight-latex-and-related'."
6167 (setq-local
6168 org-latex-and-related-regexp
6169 (let* ((re-sub
6170 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6171 ((eq org-use-sub-superscripts '{})
6172 (list org-match-substring-with-braces-regexp))
6173 (org-use-sub-superscripts (list org-match-substring-regexp))))
6174 (re-latex
6175 (when (memq 'latex org-highlight-latex-and-related)
6176 (let ((matchers (plist-get org-format-latex-options :matchers)))
6177 (delq nil
6178 (mapcar (lambda (x)
6179 (and (member (car x) matchers) (nth 1 x)))
6180 org-latex-regexps)))))
6181 (re-entities
6182 (when (memq 'entities org-highlight-latex-and-related)
6183 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6184 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6186 (defun org-do-latex-and-related (limit)
6187 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6188 LIMIT bounds the search for syntax to highlight. Stop at first
6189 highlighted object, if any. Return t if some highlighting was
6190 done, nil otherwise."
6191 (when (org-string-nw-p org-latex-and-related-regexp)
6192 (catch 'found
6193 (while (re-search-forward org-latex-and-related-regexp limit t)
6194 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6195 'face))
6196 '(org-code org-verbatim underline))
6197 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6198 '(?_ ?^))
6200 0)))
6201 (font-lock-prepend-text-property
6202 (+ offset (match-beginning 0)) (match-end 0)
6203 'face 'org-latex-and-related)
6204 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6205 '(font-lock-multiline t)))
6206 (throw 'found t)))
6207 nil)))
6209 (defun org-restart-font-lock ()
6210 "Restart `font-lock-mode', to force refontification."
6211 (when (and (boundp 'font-lock-mode) font-lock-mode)
6212 (font-lock-mode -1)
6213 (font-lock-mode 1)))
6215 (defun org-activate-tags (limit)
6216 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6217 (progn
6218 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6219 (add-text-properties (match-beginning 1) (match-end 1)
6220 (list 'mouse-face 'highlight
6221 'keymap org-mouse-map))
6222 (org-rear-nonsticky-at (match-end 1))
6223 t)))
6225 (defun org-outline-level ()
6226 "Compute the outline level of the heading at point.
6228 If this is called at a normal headline, the level is the number
6229 of stars. Use `org-reduced-level' to remove the effect of
6230 `org-odd-levels'. Unlike to `org-current-level', this function
6231 takes into consideration inlinetasks."
6232 (org-with-wide-buffer
6233 (end-of-line)
6234 (if (re-search-backward org-outline-regexp-bol nil t)
6235 (1- (- (match-end 0) (match-beginning 0)))
6236 0)))
6238 (defvar org-font-lock-keywords nil)
6240 (defsubst org-re-property (property &optional literal allow-null value)
6241 "Return a regexp matching a PROPERTY line.
6243 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6244 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6245 non-nil, match properties even without a value.
6247 Match group 3 is set to the value when it exists. If there is no
6248 value and ALLOW-NULL is non-nil, it is set to the empty string.
6250 With optional argument VALUE, match only property lines with
6251 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6252 unless LITERAL is non-nil."
6253 (concat
6254 "^\\(?4:[ \t]*\\)"
6255 (format "\\(?1::\\(?2:%s\\):\\)"
6256 (if literal property (regexp-quote property)))
6257 (cond (value
6258 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6259 (if literal value (regexp-quote value))))
6260 (allow-null
6261 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6263 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6265 (defconst org-property-re
6266 (org-re-property "\\S-+" 'literal t)
6267 "Regular expression matching a property line.
6268 There are four matching groups:
6269 1: :PROPKEY: including the leading and trailing colon,
6270 2: PROPKEY without the leading and trailing colon,
6271 3: PROPVAL without leading or trailing spaces,
6272 4: the indentation of the current line,
6273 5: trailing whitespace.")
6275 (defvar org-font-lock-hook nil
6276 "Functions to be called for special font lock stuff.")
6278 (defvar org-font-lock-set-keywords-hook nil
6279 "Functions that can manipulate `org-font-lock-extra-keywords'.
6280 This is called after `org-font-lock-extra-keywords' is defined, but before
6281 it is installed to be used by font lock. This can be useful if something
6282 needs to be inserted at a specific position in the font-lock sequence.")
6284 (defun org-font-lock-hook (limit)
6285 "Run `org-font-lock-hook' within LIMIT."
6286 (run-hook-with-args 'org-font-lock-hook limit))
6288 (defun org-set-font-lock-defaults ()
6289 "Set font lock defaults for the current buffer."
6290 (let* ((em org-fontify-emphasized-text)
6291 (lk org-highlight-links)
6292 (org-font-lock-extra-keywords
6293 (list
6294 ;; Call the hook
6295 '(org-font-lock-hook)
6296 ;; Headlines
6297 `(,(if org-fontify-whole-heading-line
6298 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6299 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6300 (1 (org-get-level-face 1))
6301 (2 (org-get-level-face 2))
6302 (3 (org-get-level-face 3)))
6303 ;; Table lines
6304 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6305 (1 'org-table t))
6306 ;; Table internals
6307 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6308 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6309 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6310 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6311 ;; Drawers
6312 '(org-fontify-drawers)
6313 ;; Properties
6314 (list org-property-re
6315 '(1 'org-special-keyword t)
6316 '(3 'org-property-value t))
6317 ;; Links
6318 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6319 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6320 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6321 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6322 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6323 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6324 (if (memq 'footnote lk) '(org-activate-footnote-links))
6325 ;; Targets.
6326 (list org-any-target-regexp '(0 'org-target t))
6327 ;; Diary sexps.
6328 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6329 ;; Macro
6330 '(org-fontify-macros)
6331 '(org-hide-wide-columns (0 nil append))
6332 ;; TODO keyword
6333 (list (format org-heading-keyword-regexp-format
6334 org-todo-regexp)
6335 '(2 (org-get-todo-face 2) t))
6336 ;; DONE
6337 (if org-fontify-done-headline
6338 (list (format org-heading-keyword-regexp-format
6339 (concat
6340 "\\(?:"
6341 (mapconcat 'regexp-quote org-done-keywords "\\|")
6342 "\\)"))
6343 '(2 'org-headline-done t))
6344 nil)
6345 ;; Priorities
6346 '(org-font-lock-add-priority-faces)
6347 ;; Tags
6348 '(org-font-lock-add-tag-faces)
6349 ;; Tags groups
6350 (if (and org-group-tags org-tag-groups-alist)
6351 (list (concat org-outline-regexp-bol ".+\\(:"
6352 (regexp-opt (mapcar 'car org-tag-groups-alist))
6353 ":\\).*$")
6354 '(1 'org-tag-group prepend)))
6355 ;; Special keywords
6356 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6357 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6358 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6359 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6360 ;; Emphasis
6361 (if em
6362 (if (featurep 'xemacs)
6363 '(org-do-emphasis-faces (0 nil append))
6364 '(org-do-emphasis-faces)))
6365 ;; Checkboxes
6366 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6367 1 'org-checkbox prepend)
6368 (if (cdr (assq 'checkbox org-list-automatic-rules))
6369 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6370 (0 (org-get-checkbox-statistics-face) t)))
6371 ;; Description list items
6372 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6373 1 'org-list-dt prepend)
6374 ;; ARCHIVEd headings
6375 (list (concat
6376 org-outline-regexp-bol
6377 "\\(.*:" org-archive-tag ":.*\\)")
6378 '(1 'org-archived prepend))
6379 ;; Specials
6380 '(org-do-latex-and-related)
6381 '(org-fontify-entities)
6382 '(org-raise-scripts)
6383 ;; Code
6384 '(org-activate-code (1 'org-code t))
6385 ;; COMMENT
6386 (list (format
6387 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6388 org-todo-regexp
6389 org-comment-string)
6390 '(9 'org-special-keyword t))
6391 ;; Blocks and meta lines
6392 '(org-fontify-meta-lines-and-blocks))))
6393 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6394 (run-hooks 'org-font-lock-set-keywords-hook)
6395 ;; Now set the full font-lock-keywords
6396 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6397 (setq-local font-lock-defaults
6398 '(org-font-lock-keywords t nil nil backward-paragraph))
6399 (kill-local-variable 'font-lock-keywords) nil))
6401 (defun org-toggle-pretty-entities ()
6402 "Toggle the composition display of entities as UTF8 characters."
6403 (interactive)
6404 (setq-local org-pretty-entities (not org-pretty-entities))
6405 (org-restart-font-lock)
6406 (if org-pretty-entities
6407 (message "Entities are now displayed as UTF8 characters")
6408 (save-restriction
6409 (widen)
6410 (org-decompose-region (point-min) (point-max))
6411 (message "Entities are now displayed as plain text"))))
6413 (defvar-local org-custom-properties-overlays nil
6414 "List of overlays used for custom properties.")
6416 (defun org-toggle-custom-properties-visibility ()
6417 "Display or hide properties in `org-custom-properties'."
6418 (interactive)
6419 (if org-custom-properties-overlays
6420 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6421 (setq org-custom-properties-overlays nil))
6422 (when org-custom-properties
6423 (org-with-wide-buffer
6424 (goto-char (point-min))
6425 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6426 (while (re-search-forward regexp nil t)
6427 (let ((end (cdr (save-match-data (org-get-property-block)))))
6428 (when (and end (< (point) end))
6429 ;; Hide first custom property in current drawer.
6430 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6431 (overlay-put o 'invisible t)
6432 (overlay-put o 'org-custom-property t)
6433 (push o org-custom-properties-overlays))
6434 ;; Hide additional custom properties in the same drawer.
6435 (while (re-search-forward regexp end t)
6436 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6437 (overlay-put o 'invisible t)
6438 (overlay-put o 'org-custom-property t)
6439 (push o org-custom-properties-overlays)))))
6440 ;; Each entry is limited to a single property drawer.
6441 (outline-next-heading)))))))
6443 (defun org-fontify-entities (limit)
6444 "Find an entity to fontify."
6445 (let (ee)
6446 (when org-pretty-entities
6447 (catch 'match
6448 ;; "\_ "-family is left out on purpose. Only the first one,
6449 ;; i.e., "\_ ", could be fontified anyway, and it would be
6450 ;; confusing when adding a second white space character.
6451 (while (re-search-forward
6452 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6453 limit t)
6454 (if (and (not (org-at-comment-p))
6455 (setq ee (org-entity-get (match-string 1)))
6456 (= (length (nth 6 ee)) 1))
6457 (let*
6458 ((end (if (equal (match-string 2) "{}")
6459 (match-end 2)
6460 (match-end 1))))
6461 (add-text-properties
6462 (match-beginning 0) end
6463 (list 'font-lock-fontified t))
6464 (compose-region (match-beginning 0) end
6465 (nth 6 ee) nil)
6466 (backward-char 1)
6467 (throw 'match t))))
6468 nil))))
6470 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6471 "Fontify string S like in Org-mode."
6472 (with-temp-buffer
6473 (insert s)
6474 (let ((org-odd-levels-only odd-levels))
6475 (org-mode)
6476 (font-lock-ensure)
6477 (buffer-string))))
6479 (defvar org-m nil)
6480 (defvar org-l nil)
6481 (defvar org-f nil)
6482 (defun org-get-level-face (n)
6483 "Get the right face for match N in font-lock matching of headlines."
6484 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6485 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6486 (if org-cycle-level-faces
6487 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6488 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6489 (cond
6490 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6491 ((eq n 2) org-f)
6492 (t (if org-level-color-stars-only nil org-f))))
6494 (defun org-face-from-face-or-color (context inherit face-or-color)
6495 "Create a face list that inherits INHERIT, but sets the foreground color.
6496 When FACE-OR-COLOR is not a string, just return it."
6497 (if (stringp face-or-color)
6498 (list :inherit inherit
6499 (cdr (assoc context org-faces-easy-properties))
6500 face-or-color)
6501 face-or-color))
6503 (defun org-get-todo-face (kwd)
6504 "Get the right face for a TODO keyword KWD.
6505 If KWD is a number, get the corresponding match group."
6506 (if (numberp kwd) (setq kwd (match-string kwd)))
6507 (or (org-face-from-face-or-color
6508 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6509 (and (member kwd org-done-keywords) 'org-done)
6510 'org-todo))
6512 (defun org-get-priority-face (priority)
6513 "Get the right face for PRIORITY.
6514 PRIORITY is a character."
6515 (or (org-face-from-face-or-color
6516 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6517 'org-priority))
6519 (defun org-get-tag-face (tag)
6520 "Get the right face for TAG.
6521 If TAG is a number, get the corresponding match group."
6522 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6523 (or (org-face-from-face-or-color
6524 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6525 'org-tag)))
6527 (defun org-font-lock-add-priority-faces (limit)
6528 "Add the special priority faces."
6529 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6530 (add-text-properties
6531 (match-beginning 1) (match-end 1)
6532 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6533 'font-lock-fontified t))))
6535 (defun org-font-lock-add-tag-faces (limit)
6536 "Add the special tag faces."
6537 (when (and org-tag-faces org-tags-special-faces-re)
6538 (while (re-search-forward org-tags-special-faces-re limit t)
6539 (add-text-properties (match-beginning 1) (match-end 1)
6540 (list 'face (org-get-tag-face 1)
6541 'font-lock-fontified t))
6542 (backward-char 1))))
6544 (defun org-unfontify-region (beg end &optional maybe_loudly)
6545 "Remove fontification and activation overlays from links."
6546 (font-lock-default-unfontify-region beg end)
6547 (let* ((buffer-undo-list t)
6548 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6549 (inhibit-modification-hooks t)
6550 deactivate-mark buffer-file-name buffer-file-truename)
6551 (org-decompose-region beg end)
6552 (remove-text-properties beg end
6553 '(mouse-face t keymap t org-linked-text t
6554 invisible t intangible t
6555 org-emphasis t))
6556 (org-remove-font-lock-display-properties beg end)))
6558 (defconst org-script-display '(((raise -0.3) (height 0.7))
6559 ((raise 0.3) (height 0.7))
6560 ((raise -0.5))
6561 ((raise 0.5)))
6562 "Display properties for showing superscripts and subscripts.")
6564 (defun org-remove-font-lock-display-properties (beg end)
6565 "Remove specific display properties that have been added by font lock.
6566 The will remove the raise properties that are used to show superscripts
6567 and subscripts."
6568 (let (next prop)
6569 (while (< beg end)
6570 (setq next (next-single-property-change beg 'display nil end)
6571 prop (get-text-property beg 'display))
6572 (if (member prop org-script-display)
6573 (put-text-property beg next 'display nil))
6574 (setq beg next))))
6576 (defun org-raise-scripts (limit)
6577 "Add raise properties to sub/superscripts."
6578 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6579 (if (re-search-forward
6580 (if (eq org-use-sub-superscripts t)
6581 org-match-substring-regexp
6582 org-match-substring-with-braces-regexp)
6583 limit t)
6584 (let* ((pos (point)) table-p comment-p
6585 (mpos (match-beginning 3))
6586 (emph-p (get-text-property mpos 'org-emphasis))
6587 (link-p (get-text-property mpos 'mouse-face))
6588 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6589 (goto-char (point-at-bol))
6590 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6591 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6592 (goto-char pos)
6593 ;; Handle a_b^c
6594 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6595 (if (or comment-p emph-p link-p keyw-p)
6597 (put-text-property (match-beginning 3) (match-end 0)
6598 'display
6599 (if (equal (char-after (match-beginning 2)) ?^)
6600 (nth (if table-p 3 1) org-script-display)
6601 (nth (if table-p 2 0) org-script-display)))
6602 (add-text-properties (match-beginning 2) (match-end 2)
6603 (list 'invisible t
6604 'org-dwidth t 'org-dwidth-n 1))
6605 (if (and (eq (char-after (match-beginning 3)) ?{)
6606 (eq (char-before (match-end 3)) ?}))
6607 (progn
6608 (add-text-properties
6609 (match-beginning 3) (1+ (match-beginning 3))
6610 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6611 (add-text-properties
6612 (1- (match-end 3)) (match-end 3)
6613 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6614 t)))))
6616 ;;;; Visibility cycling, including org-goto and indirect buffer
6618 ;;; Cycling
6620 (defvar-local org-cycle-global-status nil)
6621 (put 'org-cycle-global-status 'org-state t)
6622 (defvar-local org-cycle-subtree-status nil)
6623 (put 'org-cycle-subtree-status 'org-state t)
6625 (defvar org-inlinetask-min-level)
6627 (defun org-unlogged-message (&rest args)
6628 "Display a message, but avoid logging it in the *Messages* buffer."
6629 (let ((message-log-max nil))
6630 (apply 'message args)))
6632 ;;;###autoload
6633 (defun org-cycle (&optional arg)
6634 "TAB-action and visibility cycling for Org-mode.
6636 This is the command invoked in Org-mode by the TAB key. Its main purpose
6637 is outline visibility cycling, but it also invokes other actions
6638 in special contexts.
6640 - When this function is called with a prefix argument, rotate the entire
6641 buffer through 3 states (global cycling)
6642 1. OVERVIEW: Show only top-level headlines.
6643 2. CONTENTS: Show all headlines of all levels, but no body text.
6644 3. SHOW ALL: Show everything.
6645 With a double \\[universal-argument] prefix argument, \
6646 switch to the startup visibility,
6647 determined by the variable `org-startup-folded', and by any VISIBILITY
6648 properties in the buffer.
6649 With a triple \\[universal-argument] prefix argument, \
6650 show the entire buffer, including any drawers.
6652 - When inside a table, re-align the table and move to the next field.
6654 - When point is at the beginning of a headline, rotate the subtree started
6655 by this line through 3 different states (local cycling)
6656 1. FOLDED: Only the main headline is shown.
6657 2. CHILDREN: The main headline and the direct children are shown.
6658 From this state, you can move to one of the children
6659 and zoom in further.
6660 3. SUBTREE: Show the entire subtree, including body text.
6661 If there is no subtree, switch directly from CHILDREN to FOLDED.
6663 - When point is at the beginning of an empty headline and the variable
6664 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6665 of the headline by demoting and promoting it to likely levels. This
6666 speeds up creation document structure by pressing TAB once or several
6667 times right after creating a new headline.
6669 - When there is a numeric prefix, go up to a heading with level ARG, do
6670 a `show-subtree' and return to the previous cursor position. If ARG
6671 is negative, go up that many levels.
6673 - When point is not at the beginning of a headline, execute the global
6674 binding for TAB, which is re-indenting the line. See the option
6675 `org-cycle-emulate-tab' for details.
6677 - Special case: if point is at the beginning of the buffer and there is
6678 no headline in line 1, this function will act as if called with prefix arg
6679 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6680 But only if also the variable `org-cycle-global-at-bob' is t."
6681 (interactive "P")
6682 (org-load-modules-maybe)
6683 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6684 (and org-cycle-level-after-item/entry-creation
6685 (or (org-cycle-level)
6686 (org-cycle-item-indentation))))
6687 (let* ((limit-level
6688 (or org-cycle-max-level
6689 (and (boundp 'org-inlinetask-min-level)
6690 org-inlinetask-min-level
6691 (1- org-inlinetask-min-level))))
6692 (nstars (and limit-level
6693 (if org-odd-levels-only
6694 (and limit-level (1- (* limit-level 2)))
6695 limit-level)))
6696 (org-outline-regexp
6697 (if (not (derived-mode-p 'org-mode))
6698 outline-regexp
6699 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6700 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6701 (not (looking-at org-outline-regexp))))
6702 (org-cycle-hook
6703 (if bob-special
6704 (delq 'org-optimize-window-after-visibility-change
6705 (copy-sequence org-cycle-hook))
6706 org-cycle-hook))
6707 (pos (point)))
6709 (if (or bob-special (equal arg '(4)))
6710 ;; special case: use global cycling
6711 (setq arg t))
6713 (cond
6715 ((equal arg '(16))
6716 (setq last-command 'dummy)
6717 (org-set-startup-visibility)
6718 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6720 ((equal arg '(64))
6721 (outline-show-all)
6722 (org-unlogged-message "Entire buffer visible, including drawers"))
6724 ;; Try cdlatex TAB completion
6725 ((org-try-cdlatex-tab))
6727 ;; Table: enter it or move to the next field.
6728 ((org-at-table-p 'any)
6729 (if (org-at-table.el-p)
6730 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6731 Use \\[org-edit-special] to edit table.el tables"))
6732 (if arg (org-table-edit-field t)
6733 (org-table-justify-field-maybe)
6734 (call-interactively 'org-table-next-field))))
6736 ((run-hook-with-args-until-success
6737 'org-tab-after-check-for-table-hook))
6739 ;; Global cycling: delegate to `org-cycle-internal-global'.
6740 ((eq arg t) (org-cycle-internal-global))
6742 ;; Drawers: delegate to `org-flag-drawer'.
6743 ((save-excursion
6744 (beginning-of-line 1)
6745 (looking-at org-drawer-regexp))
6746 (org-flag-drawer ; toggle block visibility
6747 (not (get-char-property (match-end 0) 'invisible))))
6749 ;; Show-subtree, ARG levels up from here.
6750 ((integerp arg)
6751 (save-excursion
6752 (org-back-to-heading)
6753 (outline-up-heading (if (< arg 0) (- arg)
6754 (- (funcall outline-level) arg)))
6755 (org-show-subtree)))
6757 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6758 ((and (featurep 'org-inlinetask)
6759 (org-inlinetask-at-task-p)
6760 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6761 (org-inlinetask-toggle-visibility))
6763 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6764 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6765 (save-excursion (move-beginning-of-line 1)
6766 (looking-at org-outline-regexp)))
6767 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6768 (org-cycle-internal-local))
6770 ;; From there: TAB emulation and template completion.
6771 (buffer-read-only (org-back-to-heading))
6773 ((run-hook-with-args-until-success
6774 'org-tab-after-check-for-cycling-hook))
6776 ((org-try-structure-completion))
6778 ((run-hook-with-args-until-success
6779 'org-tab-before-tab-emulation-hook))
6781 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6782 (or (not (bolp))
6783 (not (looking-at org-outline-regexp))))
6784 (call-interactively (global-key-binding "\t")))
6786 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6787 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6788 (or (and (eq org-cycle-emulate-tab 'white)
6789 (= (match-end 0) (point-at-eol)))
6790 (and (eq org-cycle-emulate-tab 'whitestart)
6791 (>= (match-end 0) pos))))
6793 (eq org-cycle-emulate-tab t))
6794 (call-interactively (global-key-binding "\t")))
6796 (t (save-excursion
6797 (org-back-to-heading)
6798 (org-cycle)))))))
6800 (defun org-cycle-internal-global ()
6801 "Do the global cycling action."
6802 ;; Hack to avoid display of messages for .org attachments in Gnus
6803 (let ((ga (string-match "\\*fontification" (buffer-name))))
6804 (cond
6805 ((and (eq last-command this-command)
6806 (eq org-cycle-global-status 'overview))
6807 ;; We just created the overview - now do table of contents
6808 ;; This can be slow in very large buffers, so indicate action
6809 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6810 (unless ga (org-unlogged-message "CONTENTS..."))
6811 (org-content)
6812 (unless ga (org-unlogged-message "CONTENTS...done"))
6813 (setq org-cycle-global-status 'contents)
6814 (run-hook-with-args 'org-cycle-hook 'contents))
6816 ((and (eq last-command this-command)
6817 (eq org-cycle-global-status 'contents))
6818 ;; We just showed the table of contents - now show everything
6819 (run-hook-with-args 'org-pre-cycle-hook 'all)
6820 (outline-show-all)
6821 (unless ga (org-unlogged-message "SHOW ALL"))
6822 (setq org-cycle-global-status 'all)
6823 (run-hook-with-args 'org-cycle-hook 'all))
6826 ;; Default action: go to overview
6827 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6828 (org-overview)
6829 (unless ga (org-unlogged-message "OVERVIEW"))
6830 (setq org-cycle-global-status 'overview)
6831 (run-hook-with-args 'org-cycle-hook 'overview)))))
6833 (defvar org-called-with-limited-levels nil
6834 "Non-nil when `org-with-limited-levels' is currently active.")
6836 (defun org-cycle-internal-local ()
6837 "Do the local cycling action."
6838 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6839 ;; First, determine end of headline (EOH), end of subtree or item
6840 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6841 (save-excursion
6842 (if (org-at-item-p)
6843 (progn
6844 (beginning-of-line)
6845 (setq struct (org-list-struct))
6846 (setq eoh (point-at-eol))
6847 (setq eos (org-list-get-item-end-before-blank (point) struct))
6848 (setq has-children (org-list-has-child-p (point) struct)))
6849 (org-back-to-heading)
6850 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6851 (setq eos (save-excursion (org-end-of-subtree t t)
6852 (when (bolp) (backward-char)) (point)))
6853 (setq has-children
6854 (or (save-excursion
6855 (let ((level (funcall outline-level)))
6856 (outline-next-heading)
6857 (and (org-at-heading-p t)
6858 (> (funcall outline-level) level))))
6859 (save-excursion
6860 (org-list-search-forward (org-item-beginning-re) eos t)))))
6861 ;; Determine end invisible part of buffer (EOL)
6862 (beginning-of-line 2)
6863 ;; XEmacs doesn't have `next-single-char-property-change'
6864 (if (featurep 'xemacs)
6865 (while (and (not (eobp)) ;; this is like `next-line'
6866 (get-char-property (1- (point)) 'invisible))
6867 (beginning-of-line 2))
6868 (while (and (not (eobp)) ;; this is like `next-line'
6869 (get-char-property (1- (point)) 'invisible))
6870 (goto-char (next-single-char-property-change (point) 'invisible))
6871 (and (eolp) (beginning-of-line 2))))
6872 (setq eol (point)))
6873 ;; Find out what to do next and set `this-command'
6874 (cond
6875 ((= eos eoh)
6876 ;; Nothing is hidden behind this heading
6877 (unless (org-before-first-heading-p)
6878 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6879 (org-unlogged-message "EMPTY ENTRY")
6880 (setq org-cycle-subtree-status nil)
6881 (save-excursion
6882 (goto-char eos)
6883 (outline-next-heading)
6884 (if (outline-invisible-p) (org-flag-heading nil))))
6885 ((and (or (>= eol eos)
6886 (not (string-match "\\S-" (buffer-substring eol eos))))
6887 (or has-children
6888 (not (setq children-skipped
6889 org-cycle-skip-children-state-if-no-children))))
6890 ;; Entire subtree is hidden in one line: children view
6891 (unless (org-before-first-heading-p)
6892 (run-hook-with-args 'org-pre-cycle-hook 'children))
6893 (if (org-at-item-p)
6894 (org-list-set-item-visibility (point-at-bol) struct 'children)
6895 (org-show-entry)
6896 (org-with-limited-levels (org-show-children))
6897 ;; FIXME: This slows down the func way too much.
6898 ;; How keep drawers hidden in subtree anyway?
6899 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6900 ;; (org-cycle-hide-drawers 'subtree))
6902 ;; Fold every list in subtree to top-level items.
6903 (when (eq org-cycle-include-plain-lists 'integrate)
6904 (save-excursion
6905 (org-back-to-heading)
6906 (while (org-list-search-forward (org-item-beginning-re) eos t)
6907 (beginning-of-line 1)
6908 (let* ((struct (org-list-struct))
6909 (prevs (org-list-prevs-alist struct))
6910 (end (org-list-get-bottom-point struct)))
6911 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6912 (org-list-get-all-items (point) struct prevs))
6913 (goto-char (if (< end eos) end eos)))))))
6914 (org-unlogged-message "CHILDREN")
6915 (save-excursion
6916 (goto-char eos)
6917 (outline-next-heading)
6918 (if (outline-invisible-p) (org-flag-heading nil)))
6919 (setq org-cycle-subtree-status 'children)
6920 (unless (org-before-first-heading-p)
6921 (run-hook-with-args 'org-cycle-hook 'children)))
6922 ((or children-skipped
6923 (and (eq last-command this-command)
6924 (eq org-cycle-subtree-status 'children)))
6925 ;; We just showed the children, or no children are there,
6926 ;; now show everything.
6927 (unless (org-before-first-heading-p)
6928 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6929 (outline-flag-region eoh eos nil)
6930 (org-unlogged-message
6931 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6932 (setq org-cycle-subtree-status 'subtree)
6933 (unless (org-before-first-heading-p)
6934 (run-hook-with-args 'org-cycle-hook 'subtree)))
6936 ;; Default action: hide the subtree.
6937 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6938 (outline-flag-region eoh eos t)
6939 (org-unlogged-message "FOLDED")
6940 (setq org-cycle-subtree-status 'folded)
6941 (unless (org-before-first-heading-p)
6942 (run-hook-with-args 'org-cycle-hook 'folded))))))
6944 ;;;###autoload
6945 (defun org-global-cycle (&optional arg)
6946 "Cycle the global visibility. For details see `org-cycle'.
6947 With \\[universal-argument] prefix arg, switch to startup visibility.
6948 With a numeric prefix, show all headlines up to that level."
6949 (interactive "P")
6950 (let ((org-cycle-include-plain-lists
6951 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6952 (cond
6953 ((integerp arg)
6954 (outline-show-all)
6955 (outline-hide-sublevels arg)
6956 (setq org-cycle-global-status 'contents))
6957 ((equal arg '(4))
6958 (org-set-startup-visibility)
6959 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6961 (org-cycle '(4))))))
6963 (defun org-set-startup-visibility ()
6964 "Set the visibility required by startup options and properties."
6965 (cond
6966 ((eq org-startup-folded t)
6967 (org-overview))
6968 ((eq org-startup-folded 'content)
6969 (org-content))
6970 ((or (eq org-startup-folded 'showeverything)
6971 (eq org-startup-folded nil))
6972 (outline-show-all)))
6973 (unless (eq org-startup-folded 'showeverything)
6974 (if org-hide-block-startup (org-hide-block-all))
6975 (org-set-visibility-according-to-property 'no-cleanup)
6976 (org-cycle-hide-archived-subtrees 'all)
6977 (org-cycle-hide-drawers 'all)
6978 (org-cycle-show-empty-lines t)))
6980 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6981 "Switch subtree visibilities according to :VISIBILITY: property."
6982 (interactive)
6983 (let (org-show-entry-below)
6984 (org-with-wide-buffer
6985 (goto-char (point-min))
6986 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6987 (if (not (org-at-property-p)) (outline-next-heading)
6988 (let ((state (match-string 3)))
6989 (save-excursion
6990 (org-back-to-heading t)
6991 (outline-hide-subtree)
6992 (org-reveal)
6993 (cond
6994 ((equal state "folded")
6995 (outline-hide-subtree))
6996 ((equal state "children")
6997 (org-show-hidden-entry)
6998 (org-show-children))
6999 ((equal state "content")
7000 (save-excursion
7001 (save-restriction
7002 (org-narrow-to-subtree)
7003 (org-content))))
7004 ((member state '("all" "showall"))
7005 (outline-show-subtree)))))))
7006 (unless no-cleanup
7007 (org-cycle-hide-archived-subtrees 'all)
7008 (org-cycle-hide-drawers 'all)
7009 (org-cycle-show-empty-lines 'all)))))
7011 ;; This function uses outline-regexp instead of the more fundamental
7012 ;; org-outline-regexp so that org-cycle-global works outside of Org
7013 ;; buffers, where outline-regexp is needed.
7014 (defun org-overview ()
7015 "Switch to overview mode, showing only top-level headlines.
7016 This shows all headlines with a level equal or greater than the level
7017 of the first headline in the buffer. This is important, because if the
7018 first headline is not level one, then (hide-sublevels 1) gives confusing
7019 results."
7020 (interactive)
7021 (save-excursion
7022 (let ((level
7023 (save-excursion
7024 (goto-char (point-min))
7025 (if (re-search-forward (concat "^" outline-regexp) nil t)
7026 (progn
7027 (goto-char (match-beginning 0))
7028 (funcall outline-level))))))
7029 (and level (outline-hide-sublevels level)))))
7031 (defun org-content (&optional arg)
7032 "Show all headlines in the buffer, like a table of contents.
7033 With numerical argument N, show content up to level N."
7034 (interactive "P")
7035 (org-overview)
7036 (save-excursion
7037 ;; Visit all headings and show their offspring
7038 (and (integerp arg) (org-overview))
7039 (goto-char (point-max))
7040 (catch 'exit
7041 (while (and (progn (condition-case nil
7042 (outline-previous-visible-heading 1)
7043 (error (goto-char (point-min))))
7045 (looking-at org-outline-regexp))
7046 (if (integerp arg)
7047 (org-show-children (1- arg))
7048 (outline-show-branches))
7049 (if (bobp) (throw 'exit nil))))))
7051 (defun org-optimize-window-after-visibility-change (state)
7052 "Adjust the window after a change in outline visibility.
7053 This function is the default value of the hook `org-cycle-hook'."
7054 (when (get-buffer-window (current-buffer))
7055 (cond
7056 ((eq state 'content) nil)
7057 ((eq state 'all) nil)
7058 ((eq state 'folded) nil)
7059 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7060 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7062 (defun org-remove-empty-overlays-at (pos)
7063 "Remove outline overlays that do not contain non-white stuff."
7064 (mapc
7065 (lambda (o)
7066 (and (eq 'outline (overlay-get o 'invisible))
7067 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7068 (overlay-end o))))
7069 (delete-overlay o)))
7070 (overlays-at pos)))
7072 (defun org-clean-visibility-after-subtree-move ()
7073 "Fix visibility issues after moving a subtree."
7074 ;; First, find a reasonable region to look at:
7075 ;; Start two siblings above, end three below
7076 (let* ((beg (save-excursion
7077 (and (org-get-last-sibling)
7078 (org-get-last-sibling))
7079 (point)))
7080 (end (save-excursion
7081 (and (org-get-next-sibling)
7082 (org-get-next-sibling)
7083 (org-get-next-sibling))
7084 (if (org-at-heading-p)
7085 (point-at-eol)
7086 (point))))
7087 (level (looking-at "\\*+"))
7088 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7089 (save-excursion
7090 (save-restriction
7091 (narrow-to-region beg end)
7092 (when re
7093 ;; Properly fold already folded siblings
7094 (goto-char (point-min))
7095 (while (re-search-forward re nil t)
7096 (if (and (not (outline-invisible-p))
7097 (save-excursion
7098 (goto-char (point-at-eol)) (outline-invisible-p)))
7099 (outline-hide-entry))))
7100 (org-cycle-show-empty-lines 'overview)
7101 (org-cycle-hide-drawers 'overview)))))
7103 (defun org-cycle-show-empty-lines (state)
7104 "Show empty lines above all visible headlines.
7105 The region to be covered depends on STATE when called through
7106 `org-cycle-hook'. Lisp program can use t for STATE to get the
7107 entire buffer covered. Note that an empty line is only shown if there
7108 are at least `org-cycle-separator-lines' empty lines before the headline."
7109 (when (/= org-cycle-separator-lines 0)
7110 (save-excursion
7111 (let* ((n (abs org-cycle-separator-lines))
7112 (re (cond
7113 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7114 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7115 (t (let ((ns (number-to-string (- n 2))))
7116 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7117 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7118 beg end)
7119 (cond
7120 ((memq state '(overview contents t))
7121 (setq beg (point-min) end (point-max)))
7122 ((memq state '(children folded))
7123 (setq beg (point)
7124 end (progn (org-end-of-subtree t t)
7125 (line-beginning-position 2)))))
7126 (when beg
7127 (goto-char beg)
7128 (while (re-search-forward re end t)
7129 (unless (get-char-property (match-end 1) 'invisible)
7130 (let ((e (match-end 1))
7131 (b (if (>= org-cycle-separator-lines 0)
7132 (match-beginning 1)
7133 (save-excursion
7134 (goto-char (match-beginning 0))
7135 (skip-chars-backward " \t\n")
7136 (line-end-position)))))
7137 (outline-flag-region b e nil))))))))
7138 ;; Never hide empty lines at the end of the file.
7139 (save-excursion
7140 (goto-char (point-max))
7141 (outline-previous-heading)
7142 (outline-end-of-heading)
7143 (if (and (looking-at "[ \t\n]+")
7144 (= (match-end 0) (point-max)))
7145 (outline-flag-region (point) (match-end 0) nil))))
7147 (defun org-show-empty-lines-in-parent ()
7148 "Move to the parent and re-show empty lines before visible headlines."
7149 (save-excursion
7150 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7151 (org-cycle-show-empty-lines context))))
7153 (defun org-files-list ()
7154 "Return `org-agenda-files' list, plus all open org-mode files.
7155 This is useful for operations that need to scan all of a user's
7156 open and agenda-wise Org files."
7157 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7158 (dolist (buf (buffer-list))
7159 (with-current-buffer buf
7160 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7161 (let ((file (expand-file-name (buffer-file-name))))
7162 (unless (member file files)
7163 (push file files))))))
7164 files))
7166 (defsubst org-entry-beginning-position ()
7167 "Return the beginning position of the current entry."
7168 (save-excursion (outline-back-to-heading t) (point)))
7170 (defsubst org-entry-end-position ()
7171 "Return the end position of the current entry."
7172 (save-excursion (outline-next-heading) (point)))
7174 (defun org-cycle-hide-drawers (state &optional exceptions)
7175 "Re-hide all drawers after a visibility state change.
7176 When non-nil, optional argument EXCEPTIONS is a list of strings
7177 specifying which drawers should not be hidden."
7178 (when (and (derived-mode-p 'org-mode)
7179 (not (memq state '(overview folded contents))))
7180 (save-excursion
7181 (let* ((globalp (memq state '(contents all)))
7182 (beg (if globalp (point-min) (point)))
7183 (end (if globalp (point-max)
7184 (if (eq state 'children)
7185 (save-excursion (outline-next-heading) (point))
7186 (org-end-of-subtree t)))))
7187 (goto-char beg)
7188 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7189 (unless (member-ignore-case (match-string 1) exceptions)
7190 (let ((drawer (org-element-at-point)))
7191 (when (memq (org-element-type drawer) '(drawer property-drawer))
7192 (org-flag-drawer t drawer)
7193 ;; Make sure to skip drawer entirely or we might flag
7194 ;; it another time when matching its ending line with
7195 ;; `org-drawer-regexp'.
7196 (goto-char (org-element-property :end drawer))))))))))
7198 (defun org-flag-drawer (flag &optional element)
7199 "When FLAG is non-nil, hide the drawer we are at.
7200 Otherwise make it visible. When optional argument ELEMENT is
7201 a parsed drawer, as returned by `org-element-at-point', hide or
7202 show that drawer instead."
7203 (when (save-excursion
7204 (beginning-of-line)
7205 (org-looking-at-p org-drawer-regexp))
7206 (let ((drawer (or element (org-element-at-point))))
7207 (when (memq (org-element-type drawer) '(drawer property-drawer))
7208 (let ((post (org-element-property :post-affiliated drawer)))
7209 (save-excursion
7210 (outline-flag-region
7211 (progn (goto-char post) (line-end-position))
7212 (progn (goto-char (org-element-property :end drawer))
7213 (skip-chars-backward " \r\t\n")
7214 (line-end-position))
7215 flag))
7216 ;; When the drawer is hidden away, make sure point lies in
7217 ;; a visible part of the buffer.
7218 (when (and flag (> (line-beginning-position) post))
7219 (goto-char post)))))))
7221 (defun org-subtree-end-visible-p ()
7222 "Is the end of the current subtree visible?"
7223 (pos-visible-in-window-p
7224 (save-excursion (org-end-of-subtree t) (point))))
7226 (defun org-first-headline-recenter ()
7227 "Move cursor to the first headline and recenter the headline."
7228 (goto-char (point-min))
7229 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7230 (set-window-start (selected-window) (point-at-bol))))
7232 ;;; Saving and restoring visibility
7234 (defun org-outline-overlay-data (&optional use-markers)
7235 "Return a list of the locations of all outline overlays.
7236 These are overlays with the `invisible' property value `outline'.
7237 The return value is a list of cons cells, with start and stop
7238 positions for each overlay.
7239 If USE-MARKERS is set, return the positions as markers."
7240 (let (beg end)
7241 (save-excursion
7242 (save-restriction
7243 (widen)
7244 (delq nil
7245 (mapcar (lambda (o)
7246 (when (eq (overlay-get o 'invisible) 'outline)
7247 (setq beg (overlay-start o)
7248 end (overlay-end o))
7249 (and beg end (> end beg)
7250 (if use-markers
7251 (cons (copy-marker beg)
7252 (copy-marker end t))
7253 (cons beg end)))))
7254 (overlays-in (point-min) (point-max))))))))
7256 (defun org-set-outline-overlay-data (data)
7257 "Create visibility overlays for all positions in DATA.
7258 DATA should have been made by `org-outline-overlay-data'."
7259 (let (o)
7260 (save-excursion
7261 (save-restriction
7262 (widen)
7263 (outline-show-all)
7264 (mapc (lambda (c)
7265 (outline-flag-region (car c) (cdr c) t))
7266 data)))))
7268 ;;; Folding of blocks
7270 (defvar-local org-hide-block-overlays nil
7271 "Overlays hiding blocks.")
7273 (defun org-block-map (function &optional start end)
7274 "Call FUNCTION at the head of all source blocks in the current buffer.
7275 Optional arguments START and END can be used to limit the range."
7276 (let ((start (or start (point-min)))
7277 (end (or end (point-max))))
7278 (save-excursion
7279 (goto-char start)
7280 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7281 (save-excursion
7282 (save-match-data
7283 (goto-char (match-beginning 0))
7284 (funcall function)))))))
7286 (defun org-hide-block-toggle-all ()
7287 "Toggle the visibility of all blocks in the current buffer."
7288 (org-block-map 'org-hide-block-toggle))
7290 (defun org-hide-block-all ()
7291 "Fold all blocks in the current buffer."
7292 (interactive)
7293 (org-show-block-all)
7294 (org-block-map 'org-hide-block-toggle-maybe))
7296 (defun org-show-block-all ()
7297 "Unfold all blocks in the current buffer."
7298 (interactive)
7299 (mapc 'delete-overlay org-hide-block-overlays)
7300 (setq org-hide-block-overlays nil))
7302 (defun org-hide-block-toggle-maybe ()
7303 "Toggle visibility of block at point.
7304 Unlike to `org-hide-block-toggle', this function does not throw
7305 an error. Return a non-nil value when toggling is successful."
7306 (interactive)
7307 (ignore-errors (org-hide-block-toggle)))
7309 (defun org-hide-block-toggle (&optional force)
7310 "Toggle the visibility of the current block.
7311 When optional argument FORCE is `off', make block visible. If it
7312 is non-nil, hide it unconditionally. Throw an error when not at
7313 a block. Return a non-nil value when toggling is successful."
7314 (interactive)
7315 (let ((element (org-element-at-point)))
7316 (unless (memq (org-element-type element)
7317 '(center-block comment-block dynamic-block example-block
7318 export-block quote-block special-block
7319 src-block verse-block))
7320 (user-error "Not at a block"))
7321 (let* ((start (save-excursion
7322 (goto-char (org-element-property :post-affiliated element))
7323 (line-end-position)))
7324 (end (save-excursion
7325 (goto-char (org-element-property :end element))
7326 (skip-chars-backward " \r\t\n")
7327 (line-end-position)))
7328 (overlays (overlays-at start)))
7329 (cond
7330 ;; Do nothing when not before or at the block opening line or
7331 ;; at the block closing line.
7332 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7333 ((and (not (eq force 'off))
7334 (not (memq t (mapcar
7335 (lambda (o)
7336 (eq (overlay-get o 'invisible) 'org-hide-block))
7337 overlays))))
7338 (let ((ov (make-overlay start end)))
7339 (overlay-put ov 'invisible 'org-hide-block)
7340 ;; Make the block accessible to `isearch'.
7341 (overlay-put
7342 ov 'isearch-open-invisible
7343 (lambda (ov)
7344 (when (memq ov org-hide-block-overlays)
7345 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7346 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7347 (delete-overlay ov))))
7348 (push ov org-hide-block-overlays)
7349 ;; When the block is hidden away, make sure point is left in
7350 ;; a visible part of the buffer.
7351 (when (> (line-beginning-position) start)
7352 (goto-char start)
7353 (beginning-of-line))
7354 ;; Signal successful toggling.
7356 ((or (not force) (eq force 'off))
7357 (dolist (ov overlays t)
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))))))))
7363 ;; org-tab-after-check-for-cycling-hook
7364 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7365 ;; Remove overlays when changing major mode
7366 (add-hook 'org-mode-hook
7367 (lambda () (org-add-hook 'change-major-mode-hook
7368 'org-show-block-all 'append 'local)))
7370 ;;; Org-goto
7372 (defvar org-goto-window-configuration nil)
7373 (defvar org-goto-marker nil)
7374 (defvar org-goto-map)
7375 (defun org-goto-map ()
7376 "Set the keymap `org-goto'."
7377 (setq org-goto-map
7378 (let ((map (make-sparse-keymap)))
7379 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7380 mouse-drag-region universal-argument org-occur)))
7381 (dolist (cmd cmds)
7382 (substitute-key-definition cmd cmd map global-map)))
7383 (suppress-keymap map)
7384 (org-defkey map "\C-m" 'org-goto-ret)
7385 (org-defkey map [(return)] 'org-goto-ret)
7386 (org-defkey map [(left)] 'org-goto-left)
7387 (org-defkey map [(right)] 'org-goto-right)
7388 (org-defkey map [(control ?g)] 'org-goto-quit)
7389 (org-defkey map "\C-i" 'org-cycle)
7390 (org-defkey map [(tab)] 'org-cycle)
7391 (org-defkey map [(down)] 'outline-next-visible-heading)
7392 (org-defkey map [(up)] 'outline-previous-visible-heading)
7393 (if org-goto-auto-isearch
7394 (if (fboundp 'define-key-after)
7395 (define-key-after map [t] 'org-goto-local-auto-isearch)
7396 nil)
7397 (org-defkey map "q" 'org-goto-quit)
7398 (org-defkey map "n" 'outline-next-visible-heading)
7399 (org-defkey map "p" 'outline-previous-visible-heading)
7400 (org-defkey map "f" 'outline-forward-same-level)
7401 (org-defkey map "b" 'outline-backward-same-level)
7402 (org-defkey map "u" 'outline-up-heading))
7403 (org-defkey map "/" 'org-occur)
7404 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7405 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7406 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7407 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7408 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7409 map)))
7411 (defconst org-goto-help
7412 "Browse buffer copy, to find location or copy text.%s
7413 RET=jump to location C-g=quit and return to previous location
7414 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7416 (defvar org-goto-start-pos) ; dynamically scoped parameter
7418 (defun org-goto (&optional alternative-interface)
7419 "Look up a different location in the current file, keeping current visibility.
7421 When you want look-up or go to a different location in a
7422 document, the fastest way is often to fold the entire buffer and
7423 then dive into the tree. This method has the disadvantage, that
7424 the previous location will be folded, which may not be what you
7425 want.
7427 This command works around this by showing a copy of the current
7428 buffer in an indirect buffer, in overview mode. You can dive
7429 into the tree in that copy, use org-occur and incremental search
7430 to find a location. When pressing RET or `Q', the command
7431 returns to the original buffer in which the visibility is still
7432 unchanged. After RET it will also jump to the location selected
7433 in the indirect buffer and expose the headline hierarchy above.
7435 With a prefix argument, use the alternative interface: e.g. if
7436 `org-goto-interface' is 'outline use 'outline-path-completion."
7437 (interactive "P")
7438 (org-goto-map)
7439 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7440 (org-refile-use-outline-path t)
7441 (org-refile-target-verify-function nil)
7442 (interface
7443 (if (not alternative-interface)
7444 org-goto-interface
7445 (if (eq org-goto-interface 'outline)
7446 'outline-path-completion
7447 'outline)))
7448 (org-goto-start-pos (point))
7449 (selected-point
7450 (if (eq interface 'outline)
7451 (car (org-get-location (current-buffer) org-goto-help))
7452 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7453 (org-refile-check-position pa)
7454 (nth 3 pa)))))
7455 (if selected-point
7456 (progn
7457 (org-mark-ring-push org-goto-start-pos)
7458 (goto-char selected-point)
7459 (if (or (outline-invisible-p) (org-invisible-p2))
7460 (org-show-context 'org-goto)))
7461 (message "Quit"))))
7463 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7464 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7465 (defvar org-goto-local-auto-isearch-map) ; defined below
7467 (defun org-get-location (buf help)
7468 "Let the user select a location in the Org-mode buffer BUF.
7469 This function uses a recursive edit. It returns the selected position
7470 or nil."
7471 (org-no-popups
7472 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7473 (isearch-hide-immediately nil)
7474 (isearch-search-fun-function
7475 (lambda () 'org-goto-local-search-headings))
7476 (org-goto-selected-point org-goto-exit-command))
7477 (save-excursion
7478 (save-window-excursion
7479 (delete-other-windows)
7480 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7481 (org-pop-to-buffer-same-window
7482 (condition-case nil
7483 (make-indirect-buffer (current-buffer) "*org-goto*")
7484 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7485 (with-output-to-temp-buffer "*Org Help*"
7486 (princ (format help (if org-goto-auto-isearch
7487 " Just type for auto-isearch."
7488 " n/p/f/b/u to navigate, q to quit."))))
7489 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7490 (setq buffer-read-only nil)
7491 (let ((org-startup-truncated t)
7492 (org-startup-folded nil)
7493 (org-startup-align-all-tables nil))
7494 (org-mode)
7495 (org-overview))
7496 (setq buffer-read-only t)
7497 (if (and (boundp 'org-goto-start-pos)
7498 (integer-or-marker-p org-goto-start-pos))
7499 (progn (goto-char org-goto-start-pos)
7500 (when (outline-invisible-p)
7501 (org-show-set-visibility 'lineage)))
7502 (goto-char (point-min)))
7503 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7504 (message "Select location and press RET")
7505 (use-local-map org-goto-map)
7506 (recursive-edit)))
7507 (kill-buffer "*org-goto*")
7508 (cons org-goto-selected-point org-goto-exit-command))))
7510 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7511 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7512 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7513 (if (fboundp 'isearch-other-control-char)
7514 (progn
7515 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7516 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7517 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7518 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7519 (define-key org-goto-local-auto-isearch-map [return] nil))
7521 (defun org-goto-local-search-headings (string bound noerror)
7522 "Search and make sure that any matches are in headlines."
7523 (catch 'return
7524 (while (if isearch-forward
7525 (search-forward string bound noerror)
7526 (search-backward string bound noerror))
7527 (when (save-match-data
7528 (and (save-excursion
7529 (beginning-of-line)
7530 (looking-at org-complex-heading-regexp))
7531 (or (not (match-beginning 5))
7532 (< (point) (match-beginning 5)))))
7533 (throw 'return (point))))))
7535 (defun org-goto-local-auto-isearch ()
7536 "Start isearch."
7537 (interactive)
7538 (goto-char (point-min))
7539 (let ((keys (this-command-keys)))
7540 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7541 (isearch-mode t)
7542 (isearch-process-search-char (string-to-char keys)))))
7544 (defun org-goto-ret (&optional arg)
7545 "Finish `org-goto' by going to the new location."
7546 (interactive "P")
7547 (setq org-goto-selected-point (point)
7548 org-goto-exit-command 'return)
7549 (throw 'exit nil))
7551 (defun org-goto-left ()
7552 "Finish `org-goto' by going to the new location."
7553 (interactive)
7554 (if (org-at-heading-p)
7555 (progn
7556 (beginning-of-line 1)
7557 (setq org-goto-selected-point (point)
7558 org-goto-exit-command 'left)
7559 (throw 'exit nil))
7560 (user-error "Not on a heading")))
7562 (defun org-goto-right ()
7563 "Finish `org-goto' by going to the new location."
7564 (interactive)
7565 (if (org-at-heading-p)
7566 (progn
7567 (setq org-goto-selected-point (point)
7568 org-goto-exit-command 'right)
7569 (throw 'exit nil))
7570 (user-error "Not on a heading")))
7572 (defun org-goto-quit ()
7573 "Finish `org-goto' without cursor motion."
7574 (interactive)
7575 (setq org-goto-selected-point nil)
7576 (setq org-goto-exit-command 'quit)
7577 (throw 'exit nil))
7579 ;;; Indirect buffer display of subtrees
7581 (defvar org-indirect-dedicated-frame nil
7582 "This is the frame being used for indirect tree display.")
7583 (defvar org-last-indirect-buffer nil)
7585 (defun org-tree-to-indirect-buffer (&optional arg)
7586 "Create indirect buffer and narrow it to current subtree.
7587 With a numerical prefix ARG, go up to this level and then take that tree.
7588 If ARG is negative, go up that many levels.
7590 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7591 indirect buffer previously made with this command, to avoid proliferation of
7592 indirect buffers. However, when you call the command with a \
7593 \\[universal-argument] prefix, or
7594 when `org-indirect-buffer-display' is `new-frame', the last buffer
7595 is kept so that you can work with several indirect buffers at the same time.
7596 If `org-indirect-buffer-display' is `dedicated-frame', the \
7597 \\[universal-argument] prefix also
7598 requests that a new frame be made for the new buffer, so that the dedicated
7599 frame is not changed."
7600 (interactive "P")
7601 (let ((cbuf (current-buffer))
7602 (cwin (selected-window))
7603 (pos (point))
7604 beg end level heading ibuf)
7605 (save-excursion
7606 (org-back-to-heading t)
7607 (when (numberp arg)
7608 (setq level (org-outline-level))
7609 (if (< arg 0) (setq arg (+ level arg)))
7610 (while (> (setq level (org-outline-level)) arg)
7611 (org-up-heading-safe)))
7612 (setq beg (point)
7613 heading (org-get-heading))
7614 (org-end-of-subtree t t)
7615 (if (org-at-heading-p) (backward-char 1))
7616 (setq end (point)))
7617 (if (and (buffer-live-p org-last-indirect-buffer)
7618 (not (eq org-indirect-buffer-display 'new-frame))
7619 (not arg))
7620 (kill-buffer org-last-indirect-buffer))
7621 (setq ibuf (org-get-indirect-buffer cbuf heading)
7622 org-last-indirect-buffer ibuf)
7623 (cond
7624 ((or (eq org-indirect-buffer-display 'new-frame)
7625 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7626 (select-frame (make-frame))
7627 (delete-other-windows)
7628 (org-pop-to-buffer-same-window ibuf)
7629 (org-set-frame-title heading))
7630 ((eq org-indirect-buffer-display 'dedicated-frame)
7631 (raise-frame
7632 (select-frame (or (and org-indirect-dedicated-frame
7633 (frame-live-p org-indirect-dedicated-frame)
7634 org-indirect-dedicated-frame)
7635 (setq org-indirect-dedicated-frame (make-frame)))))
7636 (delete-other-windows)
7637 (org-pop-to-buffer-same-window ibuf)
7638 (org-set-frame-title (concat "Indirect: " heading)))
7639 ((eq org-indirect-buffer-display 'current-window)
7640 (org-pop-to-buffer-same-window ibuf))
7641 ((eq org-indirect-buffer-display 'other-window)
7642 (pop-to-buffer ibuf))
7643 (t (error "Invalid value")))
7644 (if (featurep 'xemacs)
7645 (save-excursion (org-mode) (turn-on-font-lock)))
7646 (narrow-to-region beg end)
7647 (outline-show-all)
7648 (goto-char pos)
7649 (run-hook-with-args 'org-cycle-hook 'all)
7650 (and (window-live-p cwin) (select-window cwin))))
7652 (defun org-get-indirect-buffer (&optional buffer heading)
7653 (setq buffer (or buffer (current-buffer)))
7654 (let ((n 1) (base (buffer-name buffer)) bname)
7655 (while (buffer-live-p
7656 (get-buffer
7657 (setq bname
7658 (concat base "-"
7659 (if heading (concat heading "-" (number-to-string n))
7660 (number-to-string n))))))
7661 (setq n (1+ n)))
7662 (condition-case nil
7663 (make-indirect-buffer buffer bname 'clone)
7664 (error (make-indirect-buffer buffer bname)))))
7666 (defun org-set-frame-title (title)
7667 "Set the title of the current frame to the string TITLE."
7668 ;; FIXME: how to name a single frame in XEmacs???
7669 (unless (featurep 'xemacs)
7670 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7672 ;;;; Structure editing
7674 ;;; Inserting headlines
7676 (defun org-previous-line-empty-p (&optional next)
7677 "Is the previous line a blank line?
7678 When NEXT is non-nil, check the next line instead."
7679 (save-excursion
7680 (and (not (bobp))
7681 (or (beginning-of-line (if next 2 0)) t)
7682 (save-match-data
7683 (looking-at "[ \t]*$")))))
7685 (defun org-insert-heading (&optional arg invisible-ok top-level)
7686 "Insert a new heading or an item with the same depth at point.
7688 If point is at the beginning of a heading or a list item, insert
7689 a new heading or a new item above the current one. If point is
7690 at the beginning of a normal line, turn the line into a heading.
7692 If point is in the middle of a headline or a list item, split the
7693 headline or the item and create a new headline/item with the text
7694 in the current line after point \(see `org-M-RET-may-split-line'
7695 on how to modify this behavior).
7697 With one universal prefix argument, set the user option
7698 `org-insert-heading-respect-content' to t for the duration of
7699 the command. This modifies the behavior described above in this
7700 ways: on list items and at the beginning of normal lines, force
7701 the insertion of a heading after the current subtree.
7703 With two universal prefix arguments, insert the heading at the
7704 end of the grandparent subtree. For example, if point is within
7705 a 2nd-level heading, then it will insert a 2nd-level heading at
7706 the end of the 1st-level parent heading.
7708 If point is at the beginning of a headline, insert a sibling
7709 before the current headline. If point is not at the beginning,
7710 split the line and create a new headline with the text in the
7711 current line after point \(see `org-M-RET-may-split-line' on how
7712 to modify this behavior).
7714 If point is at the beginning of a normal line, turn this line
7715 into a heading.
7717 When INVISIBLE-OK is set, stop at invisible headlines when going
7718 back. This is important for non-interactive uses of the
7719 command.
7721 When optional argument TOP-LEVEL is non-nil, insert a level 1
7722 heading, unconditionally."
7723 (interactive "P")
7724 (if (org-called-interactively-p 'any) (org-reveal))
7725 (let ((itemp (and (not top-level) (org-in-item-p)))
7726 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7727 (respect-content (or org-insert-heading-respect-content
7728 (equal arg '(4))))
7729 (initial-content ""))
7731 (cond
7733 ((or (= (buffer-size) 0)
7734 (and (not (save-excursion
7735 (and (ignore-errors (org-back-to-heading invisible-ok))
7736 (org-at-heading-p))))
7737 (or arg (not itemp))))
7738 ;; At beginning of buffer or so high up that only a heading
7739 ;; makes sense.
7740 (cond ((and (bolp) (not respect-content)) (insert "* "))
7741 ((not respect-content)
7742 (unless may-split (end-of-line))
7743 (insert "\n* "))
7744 ((re-search-forward org-outline-regexp-bol nil t)
7745 (beginning-of-line)
7746 (insert "* \n")
7747 (backward-char))
7748 (t (goto-char (point-max))
7749 (insert "\n* ")))
7750 (run-hooks 'org-insert-heading-hook))
7752 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7755 ;; Maybe move at the end of the subtree
7756 (when (equal arg '(16))
7757 (org-up-heading-safe)
7758 (org-end-of-subtree t))
7759 ;; Insert a heading
7760 (save-restriction
7761 (widen)
7762 (let* ((level nil)
7763 (on-heading (org-at-heading-p))
7764 (empty-line-p (if on-heading
7765 (org-previous-line-empty-p)
7766 ;; We will decide later
7767 nil))
7768 ;; Get a level string to fall back on.
7769 (fix-level
7770 (if (org-before-first-heading-p) "*"
7771 (save-excursion
7772 (org-back-to-heading t)
7773 (if (org-previous-line-empty-p) (setq empty-line-p t))
7774 (looking-at org-outline-regexp)
7775 (make-string (1- (length (match-string 0))) ?*))))
7776 (stars
7777 (save-excursion
7778 (condition-case nil
7779 (if top-level "* "
7780 (org-back-to-heading invisible-ok)
7781 (when (and (not on-heading)
7782 (featurep 'org-inlinetask)
7783 (integerp org-inlinetask-min-level)
7784 (>= (length (match-string 0))
7785 org-inlinetask-min-level))
7786 ;; Find a heading level before the inline
7787 ;; task.
7788 (while (and (setq level (org-up-heading-safe))
7789 (>= level org-inlinetask-min-level)))
7790 (if (org-at-heading-p)
7791 (org-back-to-heading invisible-ok)
7792 (error "This should not happen")))
7793 (unless (and (save-excursion
7794 (save-match-data
7795 (org-backward-heading-same-level
7796 1 invisible-ok))
7797 (= (point) (match-beginning 0)))
7798 (not (org-previous-line-empty-p t)))
7799 (setq empty-line-p (or empty-line-p
7800 (org-previous-line-empty-p))))
7801 (match-string 0))
7802 (error (or fix-level "* ")))))
7803 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7804 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7805 pos hide-previous previous-pos)
7807 ;; If we insert after content, move there and clean up
7808 ;; whitespace.
7809 (when (and respect-content
7810 (not (org-looking-at-p org-outline-regexp-bol)))
7811 (if (not (org-before-first-heading-p))
7812 (org-end-of-subtree nil t)
7813 (re-search-forward org-outline-regexp-bol)
7814 (beginning-of-line 0))
7815 (skip-chars-backward " \r\t\n")
7816 (and (not (org-looking-back "^\\*+" (line-beginning-position)))
7817 (looking-at "[ \t]+") (replace-match ""))
7818 (unless (eobp) (forward-char 1))
7819 (when (looking-at "^\\*")
7820 (unless (bobp) (backward-char 1))
7821 (insert "\n")))
7823 ;; If we are splitting, grab the text that should be moved
7824 ;; to the new headline.
7825 (when may-split
7826 (if (org-on-heading-p)
7827 ;; This is a heading: split intelligently (keeping
7828 ;; tags).
7829 (let ((pos (point)))
7830 (beginning-of-line)
7831 (unless (looking-at org-complex-heading-regexp)
7832 (error "This should not happen"))
7833 (when (and (match-beginning 4)
7834 (> pos (match-beginning 4))
7835 (< pos (match-end 4)))
7836 (setq initial-content (buffer-substring pos (match-end 4)))
7837 (goto-char pos)
7838 (delete-region (point) (match-end 4))
7839 (if (looking-at "[ \t]*$")
7840 (replace-match "")
7841 (insert (make-string (length initial-content) ?\s)))
7842 (setq initial-content (org-trim initial-content)))
7843 (goto-char pos))
7844 ;; A normal line.
7845 (setq initial-content
7846 (org-trim
7847 (delete-and-extract-region (point) (line-end-position))))))
7849 ;; If we are at the beginning of the line, insert before it.
7850 ;; Otherwise, after it.
7851 (cond
7852 ((and (bolp) (looking-at "[ \t]*$")))
7853 ((bolp) (save-excursion (insert "\n")))
7854 (t (end-of-line)
7855 (insert "\n")))
7857 ;; Insert the new heading
7858 (insert stars)
7859 (just-one-space)
7860 (insert initial-content)
7861 (unless (and blank (org-previous-line-empty-p))
7862 (org-N-empty-lines-before-current (if blank 1 0)))
7863 ;; Adjust visibility, which may be messed up if we removed
7864 ;; blank lines while previous entry was hidden.
7865 (let ((bol (line-beginning-position)))
7866 (dolist (o (overlays-at (1- bol)))
7867 (when (and (eq (overlay-get o 'invisible) 'outline)
7868 (eq (overlay-end o) bol))
7869 (move-overlay o (overlay-start o) (1- bol)))))
7870 (run-hooks 'org-insert-heading-hook)))))))
7872 (defun org-N-empty-lines-before-current (N)
7873 "Make the number of empty lines before current exactly N.
7874 So this will delete or add empty lines."
7875 (save-excursion
7876 (beginning-of-line)
7877 (let ((p (point)))
7878 (skip-chars-backward " \r\t\n")
7879 (unless (bolp) (forward-line))
7880 (delete-region (point) p))
7881 (when (> N 0) (insert (make-string N ?\n)))))
7883 (defun org-get-heading (&optional no-tags no-todo)
7884 "Return the heading of the current entry, without the stars.
7885 When NO-TAGS is non-nil, don't include tags.
7886 When NO-TODO is non-nil, don't include TODO keywords."
7887 (save-excursion
7888 (org-back-to-heading t)
7889 (cond
7890 ((and no-tags no-todo)
7891 (looking-at org-complex-heading-regexp)
7892 (match-string 4))
7893 (no-tags
7894 (looking-at (concat org-outline-regexp
7895 "\\(.*?\\)"
7896 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7897 (match-string 1))
7898 (no-todo
7899 (looking-at org-todo-line-regexp)
7900 (match-string 3))
7901 (t (looking-at org-heading-regexp)
7902 (match-string 2)))))
7904 (defvar orgstruct-mode) ; defined below
7906 (defun org-heading-components ()
7907 "Return the components of the current heading.
7908 This is a list with the following elements:
7909 - the level as an integer
7910 - the reduced level, different if `org-odd-levels-only' is set.
7911 - the TODO keyword, or nil
7912 - the priority character, like ?A, or nil if no priority is given
7913 - the headline text itself, or the tags string if no headline text
7914 - the tags string, or nil."
7915 (save-excursion
7916 (org-back-to-heading t)
7917 (if (let (case-fold-search)
7918 (looking-at
7919 (if orgstruct-mode
7920 org-heading-regexp
7921 org-complex-heading-regexp)))
7922 (if orgstruct-mode
7923 (list (length (match-string 1))
7924 (org-reduced-level (length (match-string 1)))
7927 (match-string 2)
7928 nil)
7929 (list (length (match-string 1))
7930 (org-reduced-level (length (match-string 1)))
7931 (org-match-string-no-properties 2)
7932 (and (match-end 3) (aref (match-string 3) 2))
7933 (org-match-string-no-properties 4)
7934 (org-match-string-no-properties 5))))))
7936 (defun org-get-entry ()
7937 "Get the entry text, after heading, entire subtree."
7938 (save-excursion
7939 (org-back-to-heading t)
7940 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7942 (defun org-insert-heading-after-current ()
7943 "Insert a new heading with same level as current, after current subtree."
7944 (interactive)
7945 (org-back-to-heading)
7946 (org-insert-heading)
7947 (org-move-subtree-down)
7948 (end-of-line 1))
7950 (defun org-insert-heading-respect-content (&optional invisible-ok)
7951 "Insert heading with `org-insert-heading-respect-content' set to t."
7952 (interactive)
7953 (org-insert-heading '(4) invisible-ok))
7955 (defun org-insert-todo-heading-respect-content (&optional force-state)
7956 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7957 (interactive)
7958 (org-insert-todo-heading force-state '(4)))
7960 (defun org-insert-todo-heading (arg &optional force-heading)
7961 "Insert a new heading with the same level and TODO state as current heading.
7962 If the heading has no TODO state, or if the state is DONE, use the first
7963 state (TODO by default). Also with one prefix arg, force first state. With
7964 two prefix args, force inserting at the end of the parent subtree."
7965 (interactive "P")
7966 (when (or force-heading (not (org-insert-item 'checkbox)))
7967 (org-insert-heading (or (and (equal arg '(16)) '(16))
7968 force-heading))
7969 (save-excursion
7970 (org-back-to-heading)
7971 (outline-previous-heading)
7972 (looking-at org-todo-line-regexp))
7973 (let*
7974 ((new-mark-x
7975 (if (or (equal arg '(4))
7976 (not (match-beginning 2))
7977 (member (match-string 2) org-done-keywords))
7978 (car org-todo-keywords-1)
7979 (match-string 2)))
7980 (new-mark
7982 (run-hook-with-args-until-success
7983 'org-todo-get-default-hook new-mark-x nil)
7984 new-mark-x)))
7985 (beginning-of-line 1)
7986 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7987 (if org-treat-insert-todo-heading-as-state-change
7988 (org-todo new-mark)
7989 (insert new-mark " "))))
7990 (when org-provide-todo-statistics
7991 (org-update-parent-todo-statistics))))
7993 (defun org-insert-subheading (arg)
7994 "Insert a new subheading and demote it.
7995 Works for outline headings and for plain lists alike."
7996 (interactive "P")
7997 (org-insert-heading arg)
7998 (cond
7999 ((org-at-heading-p) (org-do-demote))
8000 ((org-at-item-p) (org-indent-item))))
8002 (defun org-insert-todo-subheading (arg)
8003 "Insert a new subheading with TODO keyword or checkbox and demote it.
8004 Works for outline headings and for plain lists alike."
8005 (interactive "P")
8006 (org-insert-todo-heading arg)
8007 (cond
8008 ((org-at-heading-p) (org-do-demote))
8009 ((org-at-item-p) (org-indent-item))))
8011 ;;; Promotion and Demotion
8013 (defvar org-after-demote-entry-hook nil
8014 "Hook run after an entry has been demoted.
8015 The cursor will be at the beginning of the entry.
8016 When a subtree is being demoted, the hook will be called for each node.")
8018 (defvar org-after-promote-entry-hook nil
8019 "Hook run after an entry has been promoted.
8020 The cursor will be at the beginning of the entry.
8021 When a subtree is being promoted, the hook will be called for each node.")
8023 (defun org-promote-subtree ()
8024 "Promote the entire subtree.
8025 See also `org-promote'."
8026 (interactive)
8027 (save-excursion
8028 (org-with-limited-levels (org-map-tree 'org-promote)))
8029 (org-fix-position-after-promote))
8031 (defun org-demote-subtree ()
8032 "Demote the entire subtree.
8033 See `org-demote' and `org-promote'."
8034 (interactive)
8035 (save-excursion
8036 (org-with-limited-levels (org-map-tree 'org-demote)))
8037 (org-fix-position-after-promote))
8039 (defun org-do-promote ()
8040 "Promote the current heading higher up the tree.
8041 If the region is active in `transient-mark-mode', promote all
8042 headings in the region."
8043 (interactive)
8044 (save-excursion
8045 (if (org-region-active-p)
8046 (org-map-region 'org-promote (region-beginning) (region-end))
8047 (org-promote)))
8048 (org-fix-position-after-promote))
8050 (defun org-do-demote ()
8051 "Demote the current heading lower down the tree.
8052 If the region is active in `transient-mark-mode', demote all
8053 headings in the region."
8054 (interactive)
8055 (save-excursion
8056 (if (org-region-active-p)
8057 (org-map-region 'org-demote (region-beginning) (region-end))
8058 (org-demote)))
8059 (org-fix-position-after-promote))
8061 (defun org-fix-position-after-promote ()
8062 "Fix cursor position and indentation after demoting/promoting."
8063 (let ((pos (point)))
8064 (when (save-excursion
8065 (beginning-of-line 1)
8066 (looking-at org-todo-line-regexp)
8067 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8068 (cond ((eobp) (insert " "))
8069 ((eolp) (insert " "))
8070 ((equal (char-after) ?\ ) (forward-char 1))))))
8072 (defun org-current-level ()
8073 "Return the level of the current entry, or nil if before the first headline.
8074 The level is the number of stars at the beginning of the
8075 headline. Use `org-reduced-level' to remove the effect of
8076 `org-odd-levels'. Unlike to `org-outline-level', this function
8077 ignores inlinetasks."
8078 (let ((level (org-with-limited-levels (org-outline-level))))
8079 (and (> level 0) level)))
8081 (defun org-get-previous-line-level ()
8082 "Return the outline depth of the last headline before the current line.
8083 Returns 0 for the first headline in the buffer, and nil if before the
8084 first headline."
8085 (and (org-current-level)
8086 (or (and (/= (line-beginning-position) (point-min))
8087 (save-excursion (beginning-of-line 0) (org-current-level)))
8088 0)))
8090 (defun org-reduced-level (l)
8091 "Compute the effective level of a heading.
8092 This takes into account the setting of `org-odd-levels-only'."
8093 (cond
8094 ((zerop l) 0)
8095 (org-odd-levels-only (1+ (floor (/ l 2))))
8096 (t l)))
8098 (defun org-level-increment ()
8099 "Return the number of stars that will be added or removed at a
8100 time to headlines when structure editing, based on the value of
8101 `org-odd-levels-only'."
8102 (if org-odd-levels-only 2 1))
8104 (defun org-get-valid-level (level &optional change)
8105 "Rectify a level change under the influence of `org-odd-levels-only'
8106 LEVEL is a current level, CHANGE is by how much the level should be
8107 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8108 even level numbers will become the next higher odd number."
8109 (if org-odd-levels-only
8110 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8111 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8112 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8113 (max 1 (+ level (or change 0)))))
8115 (if (boundp 'define-obsolete-function-alias)
8116 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8117 (define-obsolete-function-alias 'org-get-legal-level
8118 'org-get-valid-level)
8119 (define-obsolete-function-alias 'org-get-legal-level
8120 'org-get-valid-level "23.1")))
8122 (defun org-promote ()
8123 "Promote the current heading higher up the tree."
8124 (org-with-wide-buffer
8125 (org-back-to-heading t)
8126 (let* ((after-change-functions (remq 'flyspell-after-change-function
8127 after-change-functions))
8128 (level (save-match-data (funcall outline-level)))
8129 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8130 (diff (abs (- level (length up-head) -1))))
8131 (cond
8132 ((and (= level 1) org-allow-promoting-top-level-subtree)
8133 (replace-match "# " nil t))
8134 ((= level 1)
8135 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8136 (t (replace-match up-head nil t)))
8137 (unless (= level 1)
8138 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8139 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8140 (run-hooks 'org-after-promote-entry-hook))))
8142 (defun org-demote ()
8143 "Demote the current heading lower down the tree."
8144 (org-with-wide-buffer
8145 (org-back-to-heading t)
8146 (let* ((after-change-functions (remq 'flyspell-after-change-function
8147 after-change-functions))
8148 (level (save-match-data (funcall outline-level)))
8149 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8150 (diff (abs (- level (length down-head) -1))))
8151 (replace-match down-head nil t)
8152 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8153 (when org-adapt-indentation (org-fixup-indentation diff))
8154 (run-hooks 'org-after-demote-entry-hook))))
8156 (defun org-cycle-level ()
8157 "Cycle the level of an empty headline through possible states.
8158 This goes first to child, then to parent, level, then up the hierarchy.
8159 After top level, it switches back to sibling level."
8160 (interactive)
8161 (let ((org-adapt-indentation nil))
8162 (when (org-point-at-end-of-empty-headline)
8163 (setq this-command 'org-cycle-level) ; Only needed for caching
8164 (let ((cur-level (org-current-level))
8165 (prev-level (org-get-previous-line-level)))
8166 (cond
8167 ;; If first headline in file, promote to top-level.
8168 ((= prev-level 0)
8169 (loop repeat (/ (- cur-level 1) (org-level-increment))
8170 do (org-do-promote)))
8171 ;; If same level as prev, demote one.
8172 ((= prev-level cur-level)
8173 (org-do-demote))
8174 ;; If parent is top-level, promote to top level if not already.
8175 ((= prev-level 1)
8176 (loop repeat (/ (- cur-level 1) (org-level-increment))
8177 do (org-do-promote)))
8178 ;; If top-level, return to prev-level.
8179 ((= cur-level 1)
8180 (loop repeat (/ (- prev-level 1) (org-level-increment))
8181 do (org-do-demote)))
8182 ;; If less than prev-level, promote one.
8183 ((< cur-level prev-level)
8184 (org-do-promote))
8185 ;; If deeper than prev-level, promote until higher than
8186 ;; prev-level.
8187 ((> cur-level prev-level)
8188 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8189 do (org-do-promote))))
8190 t))))
8192 (defun org-map-tree (fun)
8193 "Call FUN for every heading underneath the current one."
8194 (org-back-to-heading)
8195 (let ((level (funcall outline-level)))
8196 (save-excursion
8197 (funcall fun)
8198 (while (and (progn
8199 (outline-next-heading)
8200 (> (funcall outline-level) level))
8201 (not (eobp)))
8202 (funcall fun)))))
8204 (defun org-map-region (fun beg end)
8205 "Call FUN for every heading between BEG and END."
8206 (let ((org-ignore-region t))
8207 (save-excursion
8208 (setq end (copy-marker end))
8209 (goto-char beg)
8210 (if (and (re-search-forward org-outline-regexp-bol nil t)
8211 (< (point) end))
8212 (funcall fun))
8213 (while (and (progn
8214 (outline-next-heading)
8215 (< (point) end))
8216 (not (eobp)))
8217 (funcall fun)))))
8219 (defun org-fixup-indentation (diff)
8220 "Change the indentation in the current entry by DIFF.
8222 DIFF is an integer. Indentation is done according to the
8223 following rules:
8225 - Planning information and property drawers are always indented
8226 according to the new level of the headline;
8228 - Footnote definitions and their contents are ignored;
8230 - Inlinetasks' boundaries are not shifted;
8232 - Empty lines are ignored;
8234 - Other lines' indentation are shifted by DIFF columns, unless
8235 it would introduce a structural change in the document, in
8236 which case no shifting is done at all.
8238 Assume point is at a heading or an inlinetask beginning."
8239 (org-with-wide-buffer
8240 (narrow-to-region (line-beginning-position)
8241 (save-excursion
8242 (if (org-with-limited-levels (org-at-heading-p))
8243 (org-with-limited-levels (outline-next-heading))
8244 (org-inlinetask-goto-end))
8245 (point)))
8246 (forward-line)
8247 ;; Indent properly planning info and property drawer.
8248 (when (org-looking-at-p org-planning-line-re)
8249 (org-indent-line)
8250 (forward-line))
8251 (when (looking-at org-property-drawer-re)
8252 (goto-char (match-end 0))
8253 (forward-line)
8254 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8255 (catch 'no-shift
8256 (when (zerop diff) (throw 'no-shift nil))
8257 ;; If DIFF is negative, first check if a shift is possible at all
8258 ;; (e.g., it doesn't break structure). This can only happen if
8259 ;; some contents are not properly indented.
8260 (let ((case-fold-search t))
8261 (when (< diff 0)
8262 (let ((diff (- diff))
8263 (forbidden-re (concat org-outline-regexp
8264 "\\|"
8265 (substring org-footnote-definition-re 1))))
8266 (save-excursion
8267 (while (not (eobp))
8268 (cond
8269 ((org-looking-at-p "[ \t]*$") (forward-line))
8270 ((and (org-looking-at-p org-footnote-definition-re)
8271 (let ((e (org-element-at-point)))
8272 (and (eq (org-element-type e) 'footnote-definition)
8273 (goto-char (org-element-property :end e))))))
8274 ((org-looking-at-p org-outline-regexp) (forward-line))
8275 ;; Give up if shifting would move before column 0 or
8276 ;; if it would introduce a headline or a footnote
8277 ;; definition.
8279 (skip-chars-forward " \t")
8280 (let ((ind (current-column)))
8281 (when (or (< ind diff)
8282 (and (= ind diff) (org-looking-at-p forbidden-re)))
8283 (throw 'no-shift nil)))
8284 ;; Ignore contents of example blocks and source
8285 ;; blocks if their indentation is meant to be
8286 ;; preserved. Jump to block's closing line.
8287 (beginning-of-line)
8288 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8289 (let ((e (org-element-at-point)))
8290 (and (memq (org-element-type e)
8291 '(example-block src-block))
8292 (or org-src-preserve-indentation
8293 (org-element-property :preserve-indent e))
8294 (goto-char (org-element-property :end e))
8295 (progn (skip-chars-backward " \r\t\n")
8296 (beginning-of-line)
8297 t))))
8298 (forward-line))))))))
8299 ;; Shift lines but footnote definitions, inlinetasks boundaries
8300 ;; by DIFF. Also skip contents of source or example blocks
8301 ;; when indentation is meant to be preserved.
8302 (while (not (eobp))
8303 (cond
8304 ((and (org-looking-at-p org-footnote-definition-re)
8305 (let ((e (org-element-at-point)))
8306 (and (eq (org-element-type e) 'footnote-definition)
8307 (goto-char (org-element-property :end e))))))
8308 ((org-looking-at-p org-outline-regexp) (forward-line))
8309 ((org-looking-at-p "[ \t]*$") (forward-line))
8311 (org-indent-line-to (+ (org-get-indentation) diff))
8312 (beginning-of-line)
8313 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8314 (let ((e (org-element-at-point)))
8315 (and (memq (org-element-type e)
8316 '(example-block src-block))
8317 (or org-src-preserve-indentation
8318 (org-element-property :preserve-indent e))
8319 (goto-char (org-element-property :end e))
8320 (progn (skip-chars-backward " \r\t\n")
8321 (beginning-of-line)
8322 t))))
8323 (forward-line)))))))))
8325 (defun org-convert-to-odd-levels ()
8326 "Convert an org-mode file with all levels allowed to one with odd levels.
8327 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8328 level 5 etc."
8329 (interactive)
8330 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8331 (let ((outline-level 'org-outline-level)
8332 (org-odd-levels-only nil) n)
8333 (save-excursion
8334 (goto-char (point-min))
8335 (while (re-search-forward "^\\*\\*+ " nil t)
8336 (setq n (- (length (match-string 0)) 2))
8337 (while (>= (setq n (1- n)) 0)
8338 (org-demote))
8339 (end-of-line 1))))))
8341 (defun org-convert-to-oddeven-levels ()
8342 "Convert an org-mode file with only odd levels to one with odd/even levels.
8343 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8344 file contains a section with an even level, conversion would
8345 destroy the structure of the file. An error is signaled in this
8346 case."
8347 (interactive)
8348 (goto-char (point-min))
8349 ;; First check if there are no even levels
8350 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8351 (org-show-set-visibility 'canonical)
8352 (error "Not all levels are odd in this file. Conversion not possible"))
8353 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8354 (let ((outline-regexp org-outline-regexp)
8355 (outline-level 'org-outline-level)
8356 (org-odd-levels-only nil) n)
8357 (save-excursion
8358 (goto-char (point-min))
8359 (while (re-search-forward "^\\*\\*+ " nil t)
8360 (setq n (/ (1- (length (match-string 0))) 2))
8361 (while (>= (setq n (1- n)) 0)
8362 (org-promote))
8363 (end-of-line 1))))))
8365 (defun org-tr-level (n)
8366 "Make N odd if required."
8367 (if org-odd-levels-only (1+ (/ n 2)) n))
8369 ;;; Vertical tree motion, cutting and pasting of subtrees
8371 (defun org-move-subtree-up (&optional arg)
8372 "Move the current subtree up past ARG headlines of the same level."
8373 (interactive "p")
8374 (org-move-subtree-down (- (prefix-numeric-value arg))))
8376 (defun org-move-subtree-down (&optional arg)
8377 "Move the current subtree down past ARG headlines of the same level."
8378 (interactive "p")
8379 (setq arg (prefix-numeric-value arg))
8380 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8381 'org-get-last-sibling))
8382 (ins-point (make-marker))
8383 (cnt (abs arg))
8384 (col (current-column))
8385 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8386 ;; Select the tree
8387 (org-back-to-heading)
8388 (setq beg0 (point))
8389 (save-excursion
8390 (setq ne-beg (org-back-over-empty-lines))
8391 (setq beg (point)))
8392 (save-match-data
8393 (save-excursion (outline-end-of-heading)
8394 (setq folded (outline-invisible-p)))
8395 (progn (org-end-of-subtree nil t)
8396 (unless (eobp) (backward-char))))
8397 (outline-next-heading)
8398 (setq ne-end (org-back-over-empty-lines))
8399 (setq end (point))
8400 (goto-char beg0)
8401 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8402 ;; include less whitespace
8403 (save-excursion
8404 (goto-char beg)
8405 (forward-line (- ne-beg ne-end))
8406 (setq beg (point))))
8407 ;; Find insertion point, with error handling
8408 (while (> cnt 0)
8409 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8410 (progn (goto-char beg0)
8411 (user-error "Cannot move past superior level or buffer limit")))
8412 (setq cnt (1- cnt)))
8413 (if (> arg 0)
8414 ;; Moving forward - still need to move over subtree
8415 (progn (org-end-of-subtree t t)
8416 (save-excursion
8417 (org-back-over-empty-lines)
8418 (or (bolp) (newline)))))
8419 (setq ne-ins (org-back-over-empty-lines))
8420 (move-marker ins-point (point))
8421 (setq txt (buffer-substring beg end))
8422 (org-save-markers-in-region beg end)
8423 (delete-region beg end)
8424 (org-remove-empty-overlays-at beg)
8425 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8426 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8427 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8428 (let ((bbb (point)))
8429 (insert-before-markers txt)
8430 (org-reinstall-markers-in-region bbb)
8431 (move-marker ins-point bbb))
8432 (or (bolp) (insert "\n"))
8433 (setq ins-end (point))
8434 (goto-char ins-point)
8435 (org-skip-whitespace)
8436 (when (and (< arg 0)
8437 (org-first-sibling-p)
8438 (> ne-ins ne-beg))
8439 ;; Move whitespace back to beginning
8440 (save-excursion
8441 (goto-char ins-end)
8442 (let ((kill-whole-line t))
8443 (kill-line (- ne-ins ne-beg)) (point)))
8444 (insert (make-string (- ne-ins ne-beg) ?\n)))
8445 (move-marker ins-point nil)
8446 (if folded
8447 (outline-hide-subtree)
8448 (org-show-entry)
8449 (org-show-children)
8450 (org-cycle-hide-drawers 'children))
8451 (org-clean-visibility-after-subtree-move)
8452 ;; move back to the initial column we were at
8453 (move-to-column col)))
8455 (defvar org-subtree-clip ""
8456 "Clipboard for cut and paste of subtrees.
8457 This is actually only a copy of the kill, because we use the normal kill
8458 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8460 (defvar org-subtree-clip-folded nil
8461 "Was the last copied subtree folded?
8462 This is used to fold the tree back after pasting.")
8464 (defun org-cut-subtree (&optional n)
8465 "Cut the current subtree into the clipboard.
8466 With prefix arg N, cut this many sequential subtrees.
8467 This is a short-hand for marking the subtree and then cutting it."
8468 (interactive "p")
8469 (org-copy-subtree n 'cut))
8471 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8472 "Copy the current subtree it in the clipboard.
8473 With prefix arg N, copy this many sequential subtrees.
8474 This is a short-hand for marking the subtree and then copying it.
8475 If CUT is non-nil, actually cut the subtree.
8476 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8477 of some markers in the region, even if CUT is non-nil. This is
8478 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8479 (interactive "p")
8480 (let (beg end folded (beg0 (point)))
8481 (if (org-called-interactively-p 'any)
8482 (org-back-to-heading nil) ; take what looks like a subtree
8483 (org-back-to-heading t)) ; take what is really there
8484 (setq beg (point))
8485 (skip-chars-forward " \t\r\n")
8486 (save-match-data
8487 (if nosubtrees
8488 (outline-next-heading)
8489 (save-excursion (outline-end-of-heading)
8490 (setq folded (outline-invisible-p)))
8491 (ignore-errors (org-forward-heading-same-level (1- n) t))
8492 (org-end-of-subtree t t)))
8493 ;; Include the end of an inlinetask
8494 (when (and (featurep 'org-inlinetask)
8495 (looking-at-p (concat (org-inlinetask-outline-regexp)
8496 "END[ \t]*$")))
8497 (end-of-line))
8498 (setq end (point))
8499 (goto-char beg0)
8500 (when (> end beg)
8501 (setq org-subtree-clip-folded folded)
8502 (when (or cut force-store-markers)
8503 (org-save-markers-in-region beg end))
8504 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8505 (setq org-subtree-clip (current-kill 0))
8506 (message "%s: Subtree(s) with %d characters"
8507 (if cut "Cut" "Copied")
8508 (length org-subtree-clip)))))
8510 (defun org-paste-subtree (&optional level tree for-yank remove)
8511 "Paste the clipboard as a subtree, with modification of headline level.
8512 The entire subtree is promoted or demoted in order to match a new headline
8513 level.
8515 If the cursor is at the beginning of a headline, the same level as
8516 that headline is used to paste the tree.
8518 If not, the new level is derived from the *visible* headings
8519 before and after the insertion point, and taken to be the inferior headline
8520 level of the two. So if the previous visible heading is level 3 and the
8521 next is level 4 (or vice versa), level 4 will be used for insertion.
8522 This makes sure that the subtree remains an independent subtree and does
8523 not swallow low level entries.
8525 You can also force a different level, either by using a numeric prefix
8526 argument, or by inserting the heading marker by hand. For example, if the
8527 cursor is after \"*****\", then the tree will be shifted to level 5.
8529 If optional TREE is given, use this text instead of the kill ring.
8531 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8532 move back over whitespace before inserting, and move point to the end of
8533 the inserted text when done.
8535 When REMOVE is non-nil, remove the subtree from the clipboard."
8536 (interactive "P")
8537 (setq tree (or tree (and kill-ring (current-kill 0))))
8538 (unless (org-kill-is-subtree-p tree)
8539 (user-error "%s"
8540 (substitute-command-keys
8541 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8542 (org-with-limited-levels
8543 (let* ((visp (not (outline-invisible-p)))
8544 (txt tree)
8545 (^re_ "\\(\\*+\\)[ \t]*")
8546 (old-level (if (string-match org-outline-regexp-bol txt)
8547 (- (match-end 0) (match-beginning 0) 1)
8548 -1))
8549 (force-level (cond (level (prefix-numeric-value level))
8550 ((and (looking-at "[ \t]*$")
8551 (string-match
8552 "^\\*+$" (buffer-substring
8553 (point-at-bol) (point))))
8554 (- (match-end 0) (match-beginning 0)))
8555 ((and (bolp)
8556 (looking-at org-outline-regexp))
8557 (- (match-end 0) (point) 1))))
8558 (previous-level (save-excursion
8559 (condition-case nil
8560 (progn
8561 (outline-previous-visible-heading 1)
8562 (if (looking-at ^re_)
8563 (- (match-end 0) (match-beginning 0) 1)
8565 (error 1))))
8566 (next-level (save-excursion
8567 (condition-case nil
8568 (progn
8569 (or (looking-at org-outline-regexp)
8570 (outline-next-visible-heading 1))
8571 (if (looking-at ^re_)
8572 (- (match-end 0) (match-beginning 0) 1)
8574 (error 1))))
8575 (new-level (or force-level (max previous-level next-level)))
8576 (shift (if (or (= old-level -1)
8577 (= new-level -1)
8578 (= old-level new-level))
8580 (- new-level old-level)))
8581 (delta (if (> shift 0) -1 1))
8582 (func (if (> shift 0) 'org-demote 'org-promote))
8583 (org-odd-levels-only nil)
8584 beg end newend)
8585 ;; Remove the forced level indicator
8586 (if force-level
8587 (delete-region (point-at-bol) (point)))
8588 ;; Paste
8589 (beginning-of-line (if (bolp) 1 2))
8590 (setq beg (point))
8591 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8592 (insert-before-markers txt)
8593 (unless (string-match "\n\\'" txt) (insert "\n"))
8594 (setq newend (point))
8595 (org-reinstall-markers-in-region beg)
8596 (setq end (point))
8597 (goto-char beg)
8598 (skip-chars-forward " \t\n\r")
8599 (setq beg (point))
8600 (if (and (outline-invisible-p) visp)
8601 (save-excursion (outline-show-heading)))
8602 ;; Shift if necessary
8603 (unless (= shift 0)
8604 (save-restriction
8605 (narrow-to-region beg end)
8606 (while (not (= shift 0))
8607 (org-map-region func (point-min) (point-max))
8608 (setq shift (+ delta shift)))
8609 (goto-char (point-min))
8610 (setq newend (point-max))))
8611 (when (or (org-called-interactively-p 'interactive) for-yank)
8612 (message "Clipboard pasted as level %d subtree" new-level))
8613 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8614 kill-ring
8615 (eq org-subtree-clip (current-kill 0))
8616 org-subtree-clip-folded)
8617 ;; The tree was folded before it was killed/copied
8618 (outline-hide-subtree))
8619 (and for-yank (goto-char newend))
8620 (and remove (setq kill-ring (cdr kill-ring))))))
8622 (defun org-kill-is-subtree-p (&optional txt)
8623 "Check if the current kill is an outline subtree, or a set of trees.
8624 Returns nil if kill does not start with a headline, or if the first
8625 headline level is not the largest headline level in the tree.
8626 So this will actually accept several entries of equal levels as well,
8627 which is OK for `org-paste-subtree'.
8628 If optional TXT is given, check this string instead of the current kill."
8629 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8630 (re (org-get-limited-outline-regexp))
8631 (^re (concat "^" re))
8632 (start-level (and kill
8633 (string-match
8634 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8635 kill)
8636 (- (match-end 2) (match-beginning 2) 1)))
8637 (start (1+ (or (match-beginning 2) -1))))
8638 (if (not start-level)
8639 (progn
8640 nil) ;; does not even start with a heading
8641 (catch 'exit
8642 (while (setq start (string-match ^re kill (1+ start)))
8643 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8644 (throw 'exit nil)))
8645 t))))
8647 (defvar org-markers-to-move nil
8648 "Markers that should be moved with a cut-and-paste operation.
8649 Those markers are stored together with their positions relative to
8650 the start of the region.")
8652 (defun org-save-markers-in-region (beg end)
8653 "Check markers in region.
8654 If these markers are between BEG and END, record their position relative
8655 to BEG, so that after moving the block of text, we can put the markers back
8656 into place.
8657 This function gets called just before an entry or tree gets cut from the
8658 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8659 called immediately, to move the markers with the entries."
8660 (setq org-markers-to-move nil)
8661 (when (featurep 'org-clock)
8662 (org-clock-save-markers-for-cut-and-paste beg end))
8663 (when (featurep 'org-agenda)
8664 (org-agenda-save-markers-for-cut-and-paste beg end)))
8666 (defun org-check-and-save-marker (marker beg end)
8667 "Check if MARKER is between BEG and END.
8668 If yes, remember the marker and the distance to BEG."
8669 (when (and (marker-buffer marker)
8670 (equal (marker-buffer marker) (current-buffer)))
8671 (if (and (>= marker beg) (< marker end))
8672 (push (cons marker (- marker beg)) org-markers-to-move))))
8674 (defun org-reinstall-markers-in-region (beg)
8675 "Move all remembered markers to their position relative to BEG."
8676 (mapc (lambda (x)
8677 (move-marker (car x) (+ beg (cdr x))))
8678 org-markers-to-move)
8679 (setq org-markers-to-move nil))
8681 (defun org-narrow-to-subtree ()
8682 "Narrow buffer to the current subtree."
8683 (interactive)
8684 (save-excursion
8685 (save-match-data
8686 (org-with-limited-levels
8687 (narrow-to-region
8688 (progn (org-back-to-heading t) (point))
8689 (progn (org-end-of-subtree t t)
8690 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8691 (point)))))))
8693 (defun org-narrow-to-block ()
8694 "Narrow buffer to the current block."
8695 (interactive)
8696 (let* ((case-fold-search t)
8697 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8698 "^[ \t]*#\\+end_.*")))
8699 (if blockp
8700 (narrow-to-region (car blockp) (cdr blockp))
8701 (user-error "Not in a block"))))
8703 (defun org-clone-subtree-with-time-shift (n &optional shift)
8704 "Clone the task (subtree) at point N times.
8705 The clones will be inserted as siblings.
8707 In interactive use, the user will be prompted for the number of
8708 clones to be produced. If the entry has a timestamp, the user
8709 will also be prompted for a time shift, which may be a repeater
8710 as used in time stamps, for example `+3d'. To disable this,
8711 you can call the function with a universal prefix argument.
8713 When a valid repeater is given and the entry contains any time
8714 stamps, the clones will become a sequence in time, with time
8715 stamps in the subtree shifted for each clone produced. If SHIFT
8716 is nil or the empty string, time stamps will be left alone. The
8717 ID property of the original subtree is removed.
8719 If the original subtree did contain time stamps with a repeater,
8720 the following will happen:
8721 - the repeater will be removed in each clone
8722 - an additional clone will be produced, with the current, unshifted
8723 date(s) in the entry.
8724 - the original entry will be placed *after* all the clones, with
8725 repeater intact.
8726 - the start days in the repeater in the original entry will be shifted
8727 to past the last clone.
8728 In this way you can spell out a number of instances of a repeating task,
8729 and still retain the repeater to cover future instances of the task.
8731 As described above, N+1 clones are produced when the original
8732 subtree has a repeater. Setting N to 0, then, can be used to
8733 remove the repeater from a subtree and create a shifted clone
8734 with the original repeater."
8735 (interactive "nNumber of clones to produce: ")
8736 (let ((shift
8737 (or shift
8738 (if (and (not (equal current-prefix-arg '(4)))
8739 (save-excursion
8740 (re-search-forward org-ts-regexp-both
8741 (save-excursion
8742 (org-end-of-subtree t)
8743 (point)) t)))
8744 (read-from-minibuffer
8745 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8746 ""))) ;; No time shift
8747 (n-no-remove -1)
8748 (drawer-re org-drawer-regexp)
8749 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8750 beg end template task idprop
8751 shift-n shift-what doshift nmin nmax)
8752 (unless (wholenump n)
8753 (user-error "Invalid number of replications %s" n))
8754 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8755 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8756 shift)))
8757 (user-error "Invalid shift specification %s" shift))
8758 (when doshift
8759 (setq shift-n (string-to-number (match-string 1 shift))
8760 shift-what (cdr (assoc (match-string 2 shift)
8761 '(("d" . day) ("w" . week)
8762 ("m" . month) ("y" . year))))))
8763 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8764 (setq nmin 1 nmax n)
8765 (org-back-to-heading t)
8766 (setq beg (point))
8767 (setq idprop (org-entry-get nil "ID"))
8768 (org-end-of-subtree t t)
8769 (or (bolp) (insert "\n"))
8770 (setq end (point))
8771 (setq template (buffer-substring beg end))
8772 (when (and doshift
8773 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8774 (delete-region beg end)
8775 (setq end beg)
8776 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8777 (goto-char end)
8778 (loop for n from nmin to nmax do
8779 ;; prepare clone
8780 (with-temp-buffer
8781 (insert template)
8782 (org-mode)
8783 (goto-char (point-min))
8784 (org-show-subtree)
8785 (and idprop (if org-clone-delete-id
8786 (org-entry-delete nil "ID")
8787 (org-id-get-create t)))
8788 (unless (= n 0)
8789 (while (re-search-forward org-clock-re nil t)
8790 (kill-whole-line))
8791 (goto-char (point-min))
8792 (while (re-search-forward drawer-re nil t)
8793 (org-remove-empty-drawer-at (point))))
8794 (goto-char (point-min))
8795 (when doshift
8796 (while (re-search-forward org-ts-regexp-both nil t)
8797 (org-timestamp-change (* n shift-n) shift-what))
8798 (unless (= n n-no-remove)
8799 (goto-char (point-min))
8800 (while (re-search-forward org-ts-regexp nil t)
8801 (save-excursion
8802 (goto-char (match-beginning 0))
8803 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8804 (delete-region (match-beginning 1) (match-end 1)))))))
8805 (setq task (buffer-string)))
8806 (insert task))
8807 (goto-char beg)))
8809 ;;; Outline Sorting
8811 (defun org-sort (with-case)
8812 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8813 Optional argument WITH-CASE means sort case-sensitively."
8814 (interactive "P")
8815 (cond
8816 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8817 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8819 (org-call-with-arg 'org-sort-entries with-case))))
8821 (defun org-sort-remove-invisible (s)
8822 "Remove invisible links from string S."
8823 (remove-text-properties 0 (length s) org-rm-props s)
8824 (while (string-match org-bracket-link-regexp s)
8825 (setq s (replace-match (if (match-end 2)
8826 (match-string 3 s)
8827 (match-string 1 s))
8828 t t s)))
8829 (let ((st (format " %s " s)))
8830 (while (string-match org-emph-re st)
8831 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8832 (setq s (substring st 1 -1)))
8835 (defvar org-priority-regexp) ; defined later in the file
8837 (defvar org-after-sorting-entries-or-items-hook nil
8838 "Hook that is run after a bunch of entries or items have been sorted.
8839 When children are sorted, the cursor is in the parent line when this
8840 hook gets called. When a region or a plain list is sorted, the cursor
8841 will be in the first entry of the sorted region/list.")
8843 (defun org-sort-entries
8844 (&optional with-case sorting-type getkey-func compare-func property)
8845 "Sort entries on a certain level of an outline tree.
8846 If there is an active region, the entries in the region are sorted.
8847 Else, if the cursor is before the first entry, sort the top-level items.
8848 Else, the children of the entry at point are sorted.
8850 Sorting can be alphabetically, numerically, by date/time as given by
8851 a time stamp, by a property, by priority order, or by a custom function.
8853 The command prompts for the sorting type unless it has been given to the
8854 function through the SORTING-TYPE argument, which needs to be a character,
8855 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8856 the precise meaning of each character:
8858 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8859 c By creation time, which is assumed to be the first inactive time stamp
8860 at the beginning of a line.
8861 d By deadline date/time.
8862 k By clocking time.
8863 n Numerically, by converting the beginning of the entry/item to a number.
8864 o By order of TODO keywords.
8865 p By priority according to the cookie.
8866 r By the value of a property.
8867 s By scheduled date/time.
8868 t By date/time, either the first active time stamp in the entry, or, if
8869 none exist, by the first inactive one.
8871 Capital letters will reverse the sort order.
8873 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8874 called with point at the beginning of the record. It must return either
8875 a string or a number that should serve as the sorting key for that record.
8877 Comparing entries ignores case by default. However, with an optional argument
8878 WITH-CASE, the sorting considers case as well.
8880 Sorting is done against the visible part of the headlines, it ignores hidden
8881 links.
8883 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8884 (interactive "P")
8885 (let ((case-func (if with-case 'identity 'downcase))
8886 (cmstr
8887 ;; The clock marker is lost when using `sort-subr', let's
8888 ;; store the clocking string.
8889 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8890 (save-excursion
8891 (goto-char org-clock-marker)
8892 (buffer-substring-no-properties (line-beginning-position)
8893 (point)))))
8894 start beg end stars re re2
8895 txt what tmp)
8896 ;; Find beginning and end of region to sort
8897 (cond
8898 ((org-region-active-p)
8899 ;; we will sort the region
8900 (setq end (region-end)
8901 what "region")
8902 (goto-char (region-beginning))
8903 (if (not (org-at-heading-p)) (outline-next-heading))
8904 (setq start (point)))
8905 ((or (org-at-heading-p)
8906 (ignore-errors (progn (org-back-to-heading) t)))
8907 ;; we will sort the children of the current headline
8908 (org-back-to-heading)
8909 (setq start (point)
8910 end (progn (org-end-of-subtree t t)
8911 (or (bolp) (insert "\n"))
8912 (when (>= (org-back-over-empty-lines) 1)
8913 (forward-line 1))
8914 (point))
8915 what "children")
8916 (goto-char start)
8917 (outline-show-subtree)
8918 (outline-next-heading))
8920 ;; we will sort the top-level entries in this file
8921 (goto-char (point-min))
8922 (or (org-at-heading-p) (outline-next-heading))
8923 (setq start (point))
8924 (goto-char (point-max))
8925 (beginning-of-line 1)
8926 (when (looking-at ".*?\\S-")
8927 ;; File ends in a non-white line
8928 (end-of-line 1)
8929 (insert "\n"))
8930 (setq end (point-max))
8931 (setq what "top-level")
8932 (goto-char start)
8933 (outline-show-all)))
8935 (setq beg (point))
8936 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8938 (looking-at "\\(\\*+\\)")
8939 (setq stars (match-string 1)
8940 re (concat "^" (regexp-quote stars) " +")
8941 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8942 txt (buffer-substring beg end))
8943 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8944 (if (and (not (equal stars "*")) (string-match re2 txt))
8945 (user-error "Region to sort contains a level above the first entry"))
8947 (unless sorting-type
8948 (message
8949 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8950 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8951 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8952 what)
8953 (setq sorting-type (read-char-exclusive))
8955 (unless getkey-func
8956 (and (= (downcase sorting-type) ?f)
8957 (setq getkey-func
8958 (org-icompleting-read "Sort using function: "
8959 obarray 'fboundp t nil nil))
8960 (setq getkey-func (intern getkey-func))))
8962 (and (= (downcase sorting-type) ?r)
8963 (not property)
8964 (setq property
8965 (org-icompleting-read "Property: "
8966 (mapcar 'list (org-buffer-property-keys t))
8967 nil t))))
8969 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8970 (message "Sorting entries...")
8972 (save-restriction
8973 (narrow-to-region start end)
8974 (let ((dcst (downcase sorting-type))
8975 (case-fold-search nil)
8976 (now (current-time)))
8977 (sort-subr
8978 (/= dcst sorting-type)
8979 ;; This function moves to the beginning character of the "record" to
8980 ;; be sorted.
8981 (lambda nil
8982 (if (re-search-forward re nil t)
8983 (goto-char (match-beginning 0))
8984 (goto-char (point-max))))
8985 ;; This function moves to the last character of the "record" being
8986 ;; sorted.
8987 (lambda nil
8988 (save-match-data
8989 (condition-case nil
8990 (outline-forward-same-level 1)
8991 (error
8992 (goto-char (point-max))))))
8993 ;; This function returns the value that gets sorted against.
8994 (lambda nil
8995 (cond
8996 ((= dcst ?n)
8997 (if (looking-at org-complex-heading-regexp)
8998 (string-to-number (org-sort-remove-invisible (match-string 4)))
8999 nil))
9000 ((= dcst ?a)
9001 (if (looking-at org-complex-heading-regexp)
9002 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9003 nil))
9004 ((= dcst ?k)
9005 (or (get-text-property (point) :org-clock-minutes) 0))
9006 ((= dcst ?t)
9007 (let ((end (save-excursion (outline-next-heading) (point))))
9008 (if (or (re-search-forward org-ts-regexp end t)
9009 (re-search-forward org-ts-regexp-both end t))
9010 (org-time-string-to-seconds (match-string 0))
9011 (org-float-time now))))
9012 ((= dcst ?c)
9013 (let ((end (save-excursion (outline-next-heading) (point))))
9014 (if (re-search-forward
9015 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9016 end t)
9017 (org-time-string-to-seconds (match-string 0))
9018 (org-float-time now))))
9019 ((= dcst ?s)
9020 (let ((end (save-excursion (outline-next-heading) (point))))
9021 (if (re-search-forward org-scheduled-time-regexp end t)
9022 (org-time-string-to-seconds (match-string 1))
9023 (org-float-time now))))
9024 ((= dcst ?d)
9025 (let ((end (save-excursion (outline-next-heading) (point))))
9026 (if (re-search-forward org-deadline-time-regexp end t)
9027 (org-time-string-to-seconds (match-string 1))
9028 (org-float-time now))))
9029 ((= dcst ?p)
9030 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9031 (string-to-char (match-string 2))
9032 org-default-priority))
9033 ((= dcst ?r)
9034 (or (org-entry-get nil property) ""))
9035 ((= dcst ?o)
9036 (if (looking-at org-complex-heading-regexp)
9037 (let* ((m (match-string 2))
9038 (s (if (member m org-done-keywords) '- '+)))
9039 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9040 ((= dcst ?f)
9041 (if getkey-func
9042 (progn
9043 (setq tmp (funcall getkey-func))
9044 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
9045 tmp)
9046 (error "Invalid key function `%s'" getkey-func)))
9047 (t (error "Invalid sorting type `%c'" sorting-type))))
9049 (cond
9050 ((= dcst ?a) 'string<)
9051 ((= dcst ?f) compare-func)
9052 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9053 (run-hooks 'org-after-sorting-entries-or-items-hook)
9054 ;; Reset the clock marker if needed
9055 (when cmstr
9056 (save-excursion
9057 (goto-char start)
9058 (search-forward cmstr nil t)
9059 (move-marker org-clock-marker (point))))
9060 (message "Sorting entries...done")))
9062 ;;; The orgstruct minor mode
9064 ;; Define a minor mode which can be used in other modes in order to
9065 ;; integrate the org-mode structure editing commands.
9067 ;; This is really a hack, because the org-mode structure commands use
9068 ;; keys which normally belong to the major mode. Here is how it
9069 ;; works: The minor mode defines all the keys necessary to operate the
9070 ;; structure commands, but wraps the commands into a function which
9071 ;; tests if the cursor is currently at a headline or a plain list
9072 ;; item. If that is the case, the structure command is used,
9073 ;; temporarily setting many Org-mode variables like regular
9074 ;; expressions for filling etc. However, when any of those keys is
9075 ;; used at a different location, function uses `key-binding' to look
9076 ;; up if the key has an associated command in another currently active
9077 ;; keymap (minor modes, major mode, global), and executes that
9078 ;; command. There might be problems if any of the keys is otherwise
9079 ;; used as a prefix key.
9081 (defcustom orgstruct-heading-prefix-regexp ""
9082 "Regexp that matches the custom prefix of Org headlines in
9083 orgstruct(++)-mode."
9084 :group 'org
9085 :version "24.4"
9086 :package-version '(Org . "8.3")
9087 :type 'regexp)
9088 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9090 (defcustom orgstruct-setup-hook nil
9091 "Hook run after orgstruct-mode-map is filled."
9092 :group 'org
9093 :version "24.4"
9094 :package-version '(Org . "8.0")
9095 :type 'hook)
9097 (defvar orgstruct-initialized nil)
9099 (defvar org-local-vars nil
9100 "List of local variables, for use by `orgstruct-mode'.")
9102 ;;;###autoload
9103 (define-minor-mode orgstruct-mode
9104 "Toggle the minor mode `orgstruct-mode'.
9105 This mode is for using Org-mode structure commands in other
9106 modes. The following keys behave as if Org-mode were active, if
9107 the cursor is on a headline, or on a plain list item (both as
9108 defined by Org-mode)."
9109 nil " OrgStruct" (make-sparse-keymap)
9110 (funcall (if orgstruct-mode
9111 'add-to-invisibility-spec
9112 'remove-from-invisibility-spec)
9113 '(outline . t))
9114 (when orgstruct-mode
9115 (org-load-modules-maybe)
9116 (unless orgstruct-initialized
9117 (orgstruct-setup)
9118 (setq orgstruct-initialized t))))
9120 ;;;###autoload
9121 (defun turn-on-orgstruct ()
9122 "Unconditionally turn on `orgstruct-mode'."
9123 (orgstruct-mode 1))
9125 (defvar-local org-fb-vars nil)
9126 (defun orgstruct++-mode (&optional arg)
9127 "Toggle `orgstruct-mode', the enhanced version of it.
9128 In addition to setting orgstruct-mode, this also exports all
9129 indentation and autofilling variables from org-mode into the
9130 buffer. It will also recognize item context in multiline items."
9131 (interactive "P")
9132 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9133 (if (< arg 1)
9134 (progn (orgstruct-mode -1)
9135 (mapc (lambda(v)
9136 (set (make-local-variable (car v))
9137 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9138 org-fb-vars))
9139 (orgstruct-mode 1)
9140 (setq org-fb-vars nil)
9141 (unless org-local-vars
9142 (setq org-local-vars (org-get-local-variables)))
9143 (let (var val)
9144 (mapc
9145 (lambda (x)
9146 (when (string-match
9147 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9148 (symbol-name (car x)))
9149 (setq var (car x) val (nth 1 x))
9150 (push (list var `(quote ,(eval var))) org-fb-vars)
9151 (set (make-local-variable var)
9152 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9153 org-local-vars)
9154 (setq-local orgstruct-is-++ t))))
9156 (defvar-local orgstruct-is-++ nil
9157 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9159 ;;;###autoload
9160 (defun turn-on-orgstruct++ ()
9161 "Unconditionally turn on `orgstruct++-mode'."
9162 (orgstruct++-mode 1))
9164 (defun orgstruct-error ()
9165 "Error when there is no default binding for a structure key."
9166 (interactive)
9167 (funcall (if (fboundp 'user-error)
9168 'user-error
9169 'error)
9170 "This key has no function outside structure elements"))
9172 (defun orgstruct-setup ()
9173 "Setup orgstruct keymap."
9174 (dolist (cell '((org-demote . t)
9175 (org-metaleft . t)
9176 (org-metaright . t)
9177 (org-promote . t)
9178 (org-shiftmetaleft . t)
9179 (org-shiftmetaright . t)
9180 org-backward-element
9181 org-backward-heading-same-level
9182 org-ctrl-c-ret
9183 org-ctrl-c-minus
9184 org-ctrl-c-star
9185 org-cycle
9186 org-forward-heading-same-level
9187 org-insert-heading
9188 org-insert-heading-respect-content
9189 org-kill-note-or-show-branches
9190 org-mark-subtree
9191 org-meta-return
9192 org-metadown
9193 org-metaup
9194 org-narrow-to-subtree
9195 org-promote-subtree
9196 org-reveal
9197 org-shiftdown
9198 org-shiftleft
9199 org-shiftmetadown
9200 org-shiftmetaup
9201 org-shiftright
9202 org-shifttab
9203 org-shifttab
9204 org-shiftup
9205 org-show-children
9206 org-show-subtree
9207 org-sort
9208 org-up-element
9209 outline-demote
9210 outline-next-visible-heading
9211 outline-previous-visible-heading
9212 outline-promote
9213 outline-up-heading))
9214 (let ((f (or (car-safe cell) cell))
9215 (disable-when-heading-prefix (cdr-safe cell)))
9216 (when (fboundp f)
9217 (let ((new-bindings))
9218 (dolist (binding (nconc (where-is-internal f org-mode-map)
9219 (where-is-internal f outline-mode-map)))
9220 (push binding new-bindings)
9221 ;; TODO use local-function-key-map
9222 (dolist (rep '(("<tab>" . "TAB")
9223 ("<return>" . "RET")
9224 ("<escape>" . "ESC")
9225 ("<delete>" . "DEL")))
9226 (setq binding (read-kbd-macro
9227 (let ((case-fold-search))
9228 (replace-regexp-in-string
9229 (regexp-quote (cdr rep))
9230 (car rep)
9231 (key-description binding)))))
9232 (pushnew binding new-bindings :test 'equal)))
9233 (dolist (binding new-bindings)
9234 (let ((key (lookup-key orgstruct-mode-map binding)))
9235 (when (or (not key) (numberp key))
9236 (ignore-errors
9237 (org-defkey orgstruct-mode-map
9238 binding
9239 (orgstruct-make-binding
9240 f binding disable-when-heading-prefix))))))))))
9241 (run-hooks 'orgstruct-setup-hook))
9243 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9244 "Create a function for binding in the structure minor mode.
9245 FUN is the command to call inside a table. KEY is the key that
9246 should be checked in for a command to execute outside of tables.
9247 Non-nil `disable-when-heading-prefix' means to disable the command
9248 if `orgstruct-heading-prefix-regexp' is not empty."
9249 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9250 (let ((nname name)
9251 (i 0))
9252 (while (fboundp (intern nname))
9253 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9254 (setq name (intern nname)))
9255 (eval
9256 (let ((bindings '((org-heading-regexp
9257 (concat "^"
9258 orgstruct-heading-prefix-regexp
9259 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9260 (org-outline-regexp
9261 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9262 (org-outline-regexp-bol
9263 (concat "^" org-outline-regexp))
9264 (outline-regexp org-outline-regexp)
9265 (outline-heading-end-regexp "\n")
9266 (outline-level 'org-outline-level)
9267 (outline-heading-alist))))
9268 `(defun ,name (arg)
9269 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9270 "Outside of structure, run the binding of `"
9271 (key-description key) "'."
9272 (when disable-when-heading-prefix
9273 (concat
9274 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9275 "back to the default binding due to limitations of Org's implementation of\n"
9276 "`" (symbol-name fun) "'.")))
9277 (interactive "p")
9278 (let* ((disable
9279 ,(and disable-when-heading-prefix
9280 '(not (string= orgstruct-heading-prefix-regexp ""))))
9281 (fallback
9282 (or disable
9283 (not
9284 (let* ,bindings
9285 (org-context-p 'headline 'item
9286 ,(when (memq fun
9287 '(org-insert-heading
9288 org-insert-heading-respect-content
9289 org-meta-return))
9290 '(when orgstruct-is-++
9291 'item-body))))))))
9292 (if fallback
9293 (let* ((orgstruct-mode)
9294 (binding
9295 (let ((key ,key))
9296 (catch 'exit
9297 (dolist
9298 (rep
9299 '(nil
9300 ("<\\([^>]*\\)tab>" . "\\1TAB")
9301 ("<\\([^>]*\\)return>" . "\\1RET")
9302 ("<\\([^>]*\\)escape>" . "\\1ESC")
9303 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9304 nil)
9305 (when rep
9306 (setq key (read-kbd-macro
9307 (let ((case-fold-search))
9308 (replace-regexp-in-string
9309 (car rep)
9310 (cdr rep)
9311 (key-description key))))))
9312 (when (key-binding key)
9313 (throw 'exit (key-binding key))))))))
9314 (if (keymapp binding)
9315 (org-set-transient-map binding)
9316 (let ((func (or binding
9317 (unless disable
9318 'orgstruct-error))))
9319 (when func
9320 (call-interactively func)))))
9321 (org-run-like-in-org-mode
9322 (lambda ()
9323 (interactive)
9324 (let* ,bindings
9325 (call-interactively ',fun)))))))))
9326 name))
9328 (defun org-contextualize-keys (alist contexts)
9329 "Return valid elements in ALIST depending on CONTEXTS.
9331 `org-agenda-custom-commands' or `org-capture-templates' are the
9332 values used for ALIST, and `org-agenda-custom-commands-contexts'
9333 or `org-capture-templates-contexts' are the associated contexts
9334 definitions."
9335 (let ((contexts
9336 ;; normalize contexts
9337 (mapcar
9338 (lambda(c) (cond ((listp (cadr c))
9339 (list (car c) (car c) (cadr c)))
9340 ((string= "" (cadr c))
9341 (list (car c) (car c) (caddr c)))
9342 (t c)))
9343 contexts))
9344 (a alist) r s)
9345 ;; loop over all commands or templates
9346 (dolist (c a)
9347 (let (vrules repl)
9348 (cond
9349 ((not (assoc (car c) contexts))
9350 (push c r))
9351 ((and (assoc (car c) contexts)
9352 (setq vrules (org-contextualize-validate-key
9353 (car c) contexts)))
9354 (mapc (lambda (vr)
9355 (when (not (equal (car vr) (cadr vr)))
9356 (setq repl vr)))
9357 vrules)
9358 (if (not repl) (push c r)
9359 (push (cadr repl) s)
9360 (push
9361 (cons (car c)
9362 (cdr (or (assoc (cadr repl) alist)
9363 (error "Undefined key `%s' as contextual replacement for `%s'"
9364 (cadr repl) (car c)))))
9365 r))))))
9366 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9367 (delq
9369 (delete-dups
9370 (mapcar (lambda (x)
9371 (let ((tpl (car x)))
9372 (when (not (delq
9374 (mapcar (lambda (y)
9375 (equal y tpl))
9376 s)))
9377 x)))
9378 (reverse r))))))
9380 (defun org-contextualize-validate-key (key contexts)
9381 "Check CONTEXTS for agenda or capture KEY."
9382 (let (rr res)
9383 (dolist (r contexts)
9384 (mapc
9385 (lambda (rr)
9386 (when
9387 (and (equal key (car r))
9388 (if (functionp rr) (funcall rr)
9389 (or (and (eq (car rr) 'in-file)
9390 (buffer-file-name)
9391 (string-match (cdr rr) (buffer-file-name)))
9392 (and (eq (car rr) 'in-mode)
9393 (string-match (cdr rr) (symbol-name major-mode)))
9394 (and (eq (car rr) 'in-buffer)
9395 (string-match (cdr rr) (buffer-name)))
9396 (when (and (eq (car rr) 'not-in-file)
9397 (buffer-file-name))
9398 (not (string-match (cdr rr) (buffer-file-name))))
9399 (when (eq (car rr) 'not-in-mode)
9400 (not (string-match (cdr rr) (symbol-name major-mode))))
9401 (when (eq (car rr) 'not-in-buffer)
9402 (not (string-match (cdr rr) (buffer-name)))))))
9403 (push r res)))
9404 (car (last r))))
9405 (delete-dups (delq nil res))))
9407 (defun org-context-p (&rest contexts)
9408 "Check if local context is any of CONTEXTS.
9409 Possible values in the list of contexts are `table', `headline', and `item'."
9410 (let ((pos (point)))
9411 (goto-char (point-at-bol))
9412 (prog1 (or (and (memq 'table contexts)
9413 (looking-at "[ \t]*|"))
9414 (and (memq 'headline contexts)
9415 (looking-at org-outline-regexp))
9416 (and (memq 'item contexts)
9417 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9418 (and (memq 'item-body contexts)
9419 (org-in-item-p)))
9420 (goto-char pos))))
9422 (defun org-get-local-variables ()
9423 "Return a list of all local variables in an Org mode buffer."
9424 (let (varlist)
9425 (with-current-buffer (get-buffer-create "*Org tmp*")
9426 (erase-buffer)
9427 (org-mode)
9428 (setq varlist (buffer-local-variables)))
9429 (kill-buffer "*Org tmp*")
9430 (delq nil
9431 (mapcar
9432 (lambda (x)
9433 (setq x
9434 (if (symbolp x)
9435 (list x)
9436 (list (car x) (cdr x))))
9437 (if (and (not (get (car x) 'org-state))
9438 (string-match
9439 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9440 (symbol-name (car x))))
9441 x nil))
9442 varlist))))
9444 (defun org-clone-local-variables (from-buffer &optional regexp)
9445 "Clone local variables from FROM-BUFFER.
9446 Optional argument REGEXP selects variables to clone."
9447 (mapc
9448 (lambda (pair)
9449 (and (symbolp (car pair))
9450 (or (null regexp)
9451 (string-match regexp (symbol-name (car pair))))
9452 (set (make-local-variable (car pair))
9453 (cdr pair))))
9454 (buffer-local-variables from-buffer)))
9456 ;;;###autoload
9457 (defun org-run-like-in-org-mode (cmd)
9458 "Run a command, pretending that the current buffer is in Org-mode.
9459 This will temporarily bind local variables that are typically bound in
9460 Org-mode to the values they have in Org-mode, and then interactively
9461 call CMD."
9462 (org-load-modules-maybe)
9463 (unless org-local-vars
9464 (setq org-local-vars (org-get-local-variables)))
9465 (let (binds)
9466 (dolist (var org-local-vars)
9467 (when (or (not (boundp (car var)))
9468 (eq (symbol-value (car var))
9469 (default-value (car var))))
9470 (push (list (car var) `(quote ,(cadr var))) binds)))
9471 (eval `(let ,binds
9472 (call-interactively (quote ,cmd))))))
9474 (defun org-get-category (&optional pos force-refresh)
9475 "Get the category applying to position POS."
9476 (save-match-data
9477 (if force-refresh (org-refresh-category-properties))
9478 (let ((pos (or pos (point))))
9479 (or (get-text-property pos 'org-category)
9480 (progn (org-refresh-category-properties)
9481 (get-text-property pos 'org-category))))))
9483 ;;; Refresh properties
9485 (defun org-refresh-properties (dprop tprop)
9486 "Refresh buffer text properties.
9487 DPROP is the drawer property and TPROP is either the
9488 corresponding text property to set, or an alist with each element
9489 being a text property (as a symbol) and a function to apply to
9490 the value of the drawer property."
9491 (let ((case-fold-search t)
9492 (inhibit-read-only t))
9493 (org-with-silent-modifications
9494 (save-excursion
9495 (save-restriction
9496 (widen)
9497 (goto-char (point-min))
9498 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9499 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9501 (defun org-refresh-property (tprop p)
9502 "Refresh the buffer text property TPROP from the drawer property P.
9503 The refresh happens only for the current tree (not subtree)."
9504 (unless (org-before-first-heading-p)
9505 (save-excursion
9506 (org-back-to-heading t)
9507 (if (symbolp tprop)
9508 ;; TPROP is a text property symbol
9509 (put-text-property
9510 (point) (or (outline-next-heading) (point-max)) tprop p)
9511 ;; TPROP is an alist with (properties . function) elements
9512 (dolist (al tprop)
9513 (save-excursion
9514 (put-text-property
9515 (line-beginning-position) (or (outline-next-heading) (point-max))
9516 (car al)
9517 (funcall (cdr al) p))))))))
9519 (defun org-refresh-category-properties ()
9520 "Refresh category text properties in the buffer."
9521 (let ((case-fold-search t)
9522 (inhibit-read-only t)
9523 (default-category
9524 (cond ((null org-category)
9525 (if buffer-file-name
9526 (file-name-sans-extension
9527 (file-name-nondirectory buffer-file-name))
9528 "???"))
9529 ((symbolp org-category) (symbol-name org-category))
9530 (t org-category))))
9531 (org-with-silent-modifications
9532 (org-with-wide-buffer
9533 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9534 ;; This is the default category for the buffer. If none is
9535 ;; found, fall-back to `org-category' or buffer file name.
9536 (put-text-property
9537 (point-min) (point-max)
9538 'org-category
9539 (catch 'buffer-category
9540 (goto-char (point-max))
9541 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9542 (let ((element (org-element-at-point)))
9543 (when (eq (org-element-type element) 'keyword)
9544 (throw 'buffer-category
9545 (org-element-property :value element)))))
9546 default-category))
9547 ;; Set sub-tree specific categories.
9548 (goto-char (point-min))
9549 (let ((regexp (org-re-property "CATEGORY")))
9550 (while (re-search-forward regexp nil t)
9551 (let ((value (org-match-string-no-properties 3)))
9552 (when (org-at-property-p)
9553 (put-text-property
9554 (save-excursion (org-back-to-heading t) (point))
9555 (save-excursion (org-end-of-subtree t t) (point))
9556 'org-category
9557 value)))))))))
9559 (defun org-refresh-stats-properties ()
9560 "Refresh stats text properties in the buffer."
9561 (let (stats)
9562 (org-with-silent-modifications
9563 (save-excursion
9564 (save-restriction
9565 (widen)
9566 (goto-char (point-min))
9567 (while (re-search-forward
9568 (concat org-outline-regexp-bol ".*"
9569 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9570 nil t)
9571 (setq stats (cond ((equal (match-string 3) "0") 0)
9572 ((match-string 2)
9573 (/ (* (string-to-number (match-string 2)) 100)
9574 (string-to-number (match-string 3))))
9575 (t (string-to-number (match-string 1)))))
9576 (org-back-to-heading t)
9577 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9578 'org-stats stats)))))))
9580 (defun org-refresh-effort-properties ()
9581 "Refresh effort properties"
9582 (org-refresh-properties
9583 org-effort-property
9584 '((effort . identity)
9585 (effort-minutes . org-duration-string-to-minutes))))
9587 ;;;; Link Stuff
9589 ;;; Link abbreviations
9591 (defun org-link-expand-abbrev (link)
9592 "Apply replacements as defined in `org-link-abbrev-alist'."
9593 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9594 (let* ((key (match-string 1 link))
9595 (as (or (assoc key org-link-abbrev-alist-local)
9596 (assoc key org-link-abbrev-alist)))
9597 (tag (and (match-end 2) (match-string 3 link)))
9598 rpl)
9599 (if (not as)
9600 link
9601 (setq rpl (cdr as))
9602 (cond
9603 ((symbolp rpl) (funcall rpl tag))
9604 ((string-match "%(\\([^)]+\\))" rpl)
9605 (replace-match
9606 (save-match-data
9607 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9608 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9609 ((string-match "%h" rpl)
9610 (replace-match (url-hexify-string (or tag "")) t t rpl))
9611 (t (concat rpl tag)))))
9612 link))
9614 ;;; Storing and inserting links
9616 (defvar org-insert-link-history nil
9617 "Minibuffer history for links inserted with `org-insert-link'.")
9619 (defvar org-stored-links nil
9620 "Contains the links stored with `org-store-link'.")
9622 (defvar org-store-link-plist nil
9623 "Plist with info about the most recently link created with `org-store-link'.")
9625 (defvar org-link-protocols nil
9626 "Link protocols added to Org-mode using `org-add-link-type'.")
9628 (defvar org-store-link-functions nil
9629 "List of functions that are called to create and store a link.
9630 Each function will be called in turn until one returns a non-nil
9631 value. Each function should check if it is responsible for creating
9632 this link (for example by looking at the major mode).
9633 If not, it must exit and return nil.
9634 If yes, it should return a non-nil value after a calling
9635 `org-store-link-props' with a list of properties and values.
9636 Special properties are:
9638 :type The link prefix, like \"http\". This must be given.
9639 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9640 This is obligatory as well.
9641 :description Optional default description for the second pair
9642 of brackets in an Org-mode link. The user can still change
9643 this when inserting this link into an Org-mode buffer.
9645 In addition to these, any additional properties can be specified
9646 and then used in capture templates.")
9648 (defun org-add-link-type (type &optional follow export)
9649 "Add TYPE to the list of `org-link-types'.
9650 Re-compute all regular expressions depending on `org-link-types'
9652 FOLLOW and EXPORT are two functions.
9654 FOLLOW should take the link path as the single argument and do whatever
9655 is necessary to follow the link, for example find a file or display
9656 a mail message.
9658 EXPORT should format the link path for export to one of the export formats.
9659 It should be a function accepting three arguments:
9661 path the path of the link, the text after the prefix (like \"http:\")
9662 desc the description of the link, if any
9663 format the export format, a symbol like `html' or `latex' or `ascii'.
9665 The function may use the FORMAT information to return different values
9666 depending on the format. The return value will be put literally into
9667 the exported file. If the return value is nil, this means Org should
9668 do what it normally does with links which do not have EXPORT defined.
9670 Org mode has a built-in default for exporting links. If you are happy with
9671 this default, there is no need to define an export function for the link
9672 type. For a simple example of an export function, see `org-bbdb.el'."
9673 (add-to-list 'org-link-types type t)
9674 (org-make-link-regexps)
9675 (org-element-update-syntax)
9676 (if (assoc type org-link-protocols)
9677 (setcdr (assoc type org-link-protocols) (list follow export))
9678 (push (list type follow export) org-link-protocols)))
9680 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9681 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9683 ;;;###autoload
9684 (defun org-store-link (arg)
9685 "\\<org-mode-map>Store an org-link to the current location.
9686 This link is added to `org-stored-links' and can later be inserted
9687 into an Org buffer with \\[org-insert-link].
9689 For some link types, a prefix ARG is interpreted.
9690 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9691 For file links, ARG negates `org-context-in-file-links'.
9693 A double prefix ARG force skipping storing functions that are not
9694 part of Org's core.
9696 A triple prefix ARG force storing a link for each line in the
9697 active region."
9698 (interactive "P")
9699 (org-load-modules-maybe)
9700 (if (and (equal arg '(64)) (org-region-active-p))
9701 (save-excursion
9702 (let ((end (region-end)))
9703 (goto-char (region-beginning))
9704 (set-mark (point))
9705 (while (< (point-at-eol) end)
9706 (move-end-of-line 1) (activate-mark)
9707 (let (current-prefix-arg)
9708 (call-interactively 'org-store-link))
9709 (move-beginning-of-line 2)
9710 (set-mark (point)))))
9711 (org-with-limited-levels
9712 (setq org-store-link-plist nil)
9713 (let (link cpltxt desc description search
9714 txt custom-id agenda-link sfuns sfunsn)
9715 (cond
9717 ;; Store a link using an external link type
9718 ((and (not (equal arg '(16)))
9719 (setq sfuns
9720 (delq
9721 nil (mapcar (lambda (f)
9722 (let (fs) (if (funcall f) (push f fs))))
9723 org-store-link-functions))
9724 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9725 (or (and (cdr sfuns)
9726 (funcall (intern
9727 (completing-read
9728 "Which function for creating the link? "
9729 sfunsn nil t (car sfunsn)))))
9730 (funcall (caar sfuns)))
9731 (setq link (plist-get org-store-link-plist :link)
9732 desc (or (plist-get org-store-link-plist
9733 :description)
9734 link))))
9736 ;; Store a link from a source code buffer.
9737 ((org-src-edit-buffer-p)
9738 (cond
9739 ((save-excursion
9740 (beginning-of-line)
9741 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9742 "[ \t]*$")))
9743 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9744 ((org-called-interactively-p 'any)
9745 (let (label)
9746 (while (or (not label)
9747 (org-with-wide-buffer
9748 (goto-char (point-min))
9749 (re-search-forward
9750 (regexp-quote (format org-coderef-label-format label))
9751 nil t)))
9752 (when label (message "Label exists already") (sit-for 2))
9753 (setq label (read-string "Code line label: " label)))
9754 (end-of-line)
9755 (setq link (format org-coderef-label-format label))
9756 (let ((gc (- 79 (length link))))
9757 (if (< (current-column) gc) (org-move-to-column gc t)
9758 (insert " ")))
9759 (insert link)
9760 (setq link (concat "(" label ")") desc nil)))
9761 (t (setq link nil))))
9763 ;; We are in the agenda, link to referenced location
9764 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9765 (let ((m (or (get-text-property (point) 'org-hd-marker)
9766 (get-text-property (point) 'org-marker))))
9767 (when m
9768 (org-with-point-at m
9769 (setq agenda-link
9770 (if (org-called-interactively-p 'any)
9771 (call-interactively 'org-store-link)
9772 (org-store-link nil)))))))
9774 ((eq major-mode 'calendar-mode)
9775 (let ((cd (calendar-cursor-to-date)))
9776 (setq link
9777 (format-time-string
9778 (car org-time-stamp-formats)
9779 (apply 'encode-time
9780 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9781 nil nil nil))))
9782 (org-store-link-props :type "calendar" :date cd)))
9784 ((eq major-mode 'help-mode)
9785 (setq link (concat "help:" (save-excursion
9786 (goto-char (point-min))
9787 (looking-at "^[^ ]+")
9788 (match-string 0))))
9789 (org-store-link-props :type "help"))
9791 ((eq major-mode 'w3-mode)
9792 (setq cpltxt (if (and (buffer-name)
9793 (not (string-match "Untitled" (buffer-name))))
9794 (buffer-name)
9795 (url-view-url t))
9796 link (url-view-url t))
9797 (org-store-link-props :type "w3" :url (url-view-url t)))
9799 ((eq major-mode 'image-mode)
9800 (setq cpltxt (concat "file:"
9801 (abbreviate-file-name buffer-file-name))
9802 link cpltxt)
9803 (org-store-link-props :type "image" :file buffer-file-name))
9805 ;; In dired, store a link to the file of the current line
9806 ((derived-mode-p 'dired-mode)
9807 (let ((file (dired-get-filename nil t)))
9808 (setq file (if file
9809 (abbreviate-file-name
9810 (expand-file-name (dired-get-filename nil t)))
9811 ;; otherwise, no file so use current directory.
9812 default-directory))
9813 (setq cpltxt (concat "file:" file)
9814 link cpltxt)))
9816 ((setq search (run-hook-with-args-until-success
9817 'org-create-file-search-functions))
9818 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9819 "::" search))
9820 (setq cpltxt (or description link)))
9822 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9823 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9824 (cond
9825 ;; Store a link using the target at point
9826 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9827 (setq cpltxt
9828 (concat "file:"
9829 (abbreviate-file-name
9830 (buffer-file-name (buffer-base-buffer)))
9831 "::" (match-string 1))
9832 link cpltxt))
9833 ((and (featurep 'org-id)
9834 (or (eq org-id-link-to-org-use-id t)
9835 (and (org-called-interactively-p 'any)
9836 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9837 (and (eq org-id-link-to-org-use-id
9838 'create-if-interactive-and-no-custom-id)
9839 (not custom-id))))
9840 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9841 ;; Store a link using the ID at point
9842 (setq link (condition-case nil
9843 (prog1 (org-id-store-link)
9844 (setq desc (or (plist-get org-store-link-plist
9845 :description)
9846 "")))
9847 (error
9848 ;; Probably before first headline, link only to file
9849 (concat "file:"
9850 (abbreviate-file-name
9851 (buffer-file-name (buffer-base-buffer))))))))
9853 ;; Just link to current headline
9854 (setq cpltxt (concat "file:"
9855 (abbreviate-file-name
9856 (buffer-file-name (buffer-base-buffer)))))
9857 ;; Add a context search string
9858 (when (org-xor org-context-in-file-links arg)
9859 (let* ((ee (org-element-at-point))
9860 (et (org-element-type ee))
9861 (ev (plist-get (cadr ee) :value))
9862 (ek (plist-get (cadr ee) :key))
9863 (eok (and (stringp ek) (string-match "name" ek))))
9864 (setq txt (cond
9865 ((org-at-heading-p) nil)
9866 ((and (eq et 'keyword) eok) ev)
9867 ((org-region-active-p)
9868 (buffer-substring (region-beginning) (region-end)))))
9869 (when (or (null txt) (string-match "\\S-" txt))
9870 (setq cpltxt
9871 (concat cpltxt "::"
9872 (condition-case nil
9873 (org-make-org-heading-search-string txt)
9874 (error "")))
9875 desc (or (and (eq et 'keyword) eok ev)
9876 (nth 4 (ignore-errors (org-heading-components)))
9877 "NONE")))))
9878 (if (string-match "::\\'" cpltxt)
9879 (setq cpltxt (substring cpltxt 0 -2)))
9880 (setq link cpltxt))))
9882 ((buffer-file-name (buffer-base-buffer))
9883 ;; Just link to this file here.
9884 (setq cpltxt (concat "file:"
9885 (abbreviate-file-name
9886 (buffer-file-name (buffer-base-buffer)))))
9887 ;; Add a context string.
9888 (when (org-xor org-context-in-file-links arg)
9889 (setq txt (if (org-region-active-p)
9890 (buffer-substring (region-beginning) (region-end))
9891 (buffer-substring (point-at-bol) (point-at-eol))))
9892 ;; Only use search option if there is some text.
9893 (when (string-match "\\S-" txt)
9894 (setq cpltxt
9895 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9896 desc "NONE")))
9897 (setq link cpltxt))
9899 ((org-called-interactively-p 'interactive)
9900 (user-error "No method for storing a link from this buffer"))
9902 (t (setq link nil)))
9904 ;; We're done setting link and desc, clean up
9905 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9906 (setq link (or link cpltxt)
9907 desc (or desc cpltxt))
9908 (cond ((equal desc "NONE") (setq desc nil))
9909 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9910 (let ((d0 (match-string 3 desc))
9911 (p0 (match-string 5 desc)))
9912 (setq desc
9913 (replace-regexp-in-string
9914 org-bracket-link-regexp
9915 (concat (or p0 d0)
9916 (if (equal (length (match-string 0 desc))
9917 (length desc)) "*" "")) desc)))))
9919 ;; Return the link
9920 (if (not (and (or (org-called-interactively-p 'any)
9921 executing-kbd-macro)
9922 link))
9923 (or agenda-link (and link (org-make-link-string link desc)))
9924 (push (list link desc) org-stored-links)
9925 (message "Stored: %s" (or desc link))
9926 (when custom-id
9927 (setq link (concat "file:" (abbreviate-file-name
9928 (buffer-file-name)) "::#" custom-id))
9929 (push (list link desc) org-stored-links))
9930 (car org-stored-links))))))
9932 (defun org-store-link-props (&rest plist)
9933 "Store link properties, extract names and addresses."
9934 (let (x adr)
9935 (when (setq x (plist-get plist :from))
9936 (setq adr (mail-extract-address-components x))
9937 (setq plist (plist-put plist :fromname (car adr)))
9938 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9939 (when (setq x (plist-get plist :to))
9940 (setq adr (mail-extract-address-components x))
9941 (setq plist (plist-put plist :toname (car adr)))
9942 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9943 (let ((from (plist-get plist :from))
9944 (to (plist-get plist :to)))
9945 (when (and from to org-from-is-user-regexp)
9946 (setq plist
9947 (plist-put plist :fromto
9948 (if (string-match org-from-is-user-regexp from)
9949 (concat "to %t")
9950 (concat "from %f"))))))
9951 (setq org-store-link-plist plist))
9953 (defun org-add-link-props (&rest plist)
9954 "Add these properties to the link property list."
9955 (let (key value)
9956 (while plist
9957 (setq key (pop plist) value (pop plist))
9958 (setq org-store-link-plist
9959 (plist-put org-store-link-plist key value)))))
9961 (defun org-email-link-description (&optional fmt)
9962 "Return the description part of an email link.
9963 This takes information from `org-store-link-plist' and formats it
9964 according to FMT (default from `org-email-link-description-format')."
9965 (setq fmt (or fmt org-email-link-description-format))
9966 (let* ((p org-store-link-plist)
9967 (to (plist-get p :toaddress))
9968 (from (plist-get p :fromaddress))
9969 (table
9970 (list
9971 (cons "%c" (plist-get p :fromto))
9972 (cons "%F" (plist-get p :from))
9973 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9974 (cons "%T" (plist-get p :to))
9975 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9976 (cons "%s" (plist-get p :subject))
9977 (cons "%d" (plist-get p :date))
9978 (cons "%m" (plist-get p :message-id)))))
9979 (when (string-match "%c" fmt)
9980 ;; Check if the user wrote this message
9981 (if (and org-from-is-user-regexp from to
9982 (save-match-data (string-match org-from-is-user-regexp from)))
9983 (setq fmt (replace-match "to %t" t t fmt))
9984 (setq fmt (replace-match "from %f" t t fmt))))
9985 (org-replace-escapes fmt table)))
9987 (defun org-make-org-heading-search-string (&optional string)
9988 "Make search string for the current headline or STRING."
9989 (let ((s (or string
9990 (and (derived-mode-p 'org-mode)
9991 (save-excursion
9992 (org-back-to-heading t)
9993 (org-element-property :raw-value (org-element-at-point))))))
9994 (lines org-context-in-file-links))
9995 (or string (setq s (concat "*" s))) ; Add * for headlines
9996 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9997 (when (and string (integerp lines) (> lines 0))
9998 (let ((slines (org-split-string s "\n")))
9999 (when (< lines (length slines))
10000 (setq s (mapconcat
10001 'identity
10002 (reverse (nthcdr (- (length slines) lines)
10003 (reverse slines))) "\n")))))
10004 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10006 (defun org-make-link-string (link &optional description)
10007 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10008 (unless (org-string-nw-p link) (error "Empty link"))
10009 (let ((uri (cond ((string-match org-link-types-re link)
10010 (concat (match-string 1 link)
10011 (org-link-escape (substring link (match-end 1)))))
10012 ;; For readability, url-encode internal links only
10013 ;; when absolutely needed (i.e, when they contain
10014 ;; square brackets). File links however, are
10015 ;; encoded since, e.g., spaces are significant.
10016 ((or (file-name-absolute-p link)
10017 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
10018 (org-link-escape link))
10019 (t link)))
10020 (description
10021 (and (org-string-nw-p description)
10022 ;; Remove brackets from description, as they are fatal.
10023 (replace-regexp-in-string
10024 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10025 (org-trim description)))))
10026 (format "[[%s]%s]"
10028 (if description (format "[%s]" description) ""))))
10030 (defconst org-link-escape-chars
10031 ;;%20 %5B %5D %25
10032 '(?\s ?\[ ?\] ?%)
10033 "List of characters that should be escaped in a link when stored to Org.
10034 This is the list that is used for internal purposes.")
10036 (defconst org-link-escape-chars-browser
10037 ;;%20 %22
10038 '(?\s ?\")
10039 "List of characters to be escaped before handing over to the browser.
10040 If you consider using this constant then you probably want to use
10041 the function `org-link-escape-browser' instead. See there why
10042 this constant is a candidate to be removed once Org drops support
10043 for Emacs 24.1 and 24.2.")
10045 (defun org-link-escape (text &optional table merge)
10046 "Return percent escaped representation of TEXT.
10047 TEXT is a string with the text to escape.
10048 Optional argument TABLE is a list with characters that should be
10049 escaped. When nil, `org-link-escape-chars' is used.
10050 If optional argument MERGE is set, merge TABLE into
10051 `org-link-escape-chars'."
10052 (let ((characters-to-encode
10053 (cond ((null table) org-link-escape-chars)
10054 (merge (append org-link-escape-chars table))
10055 (t table))))
10056 (mapconcat
10057 (lambda (c)
10058 (if (or (memq c characters-to-encode)
10059 (and org-url-hexify-p (or (< c 32) (> c 126))))
10060 (mapconcat (lambda (e) (format "%%%.2X" e))
10061 (or (encode-coding-char c 'utf-8)
10062 (error "Unable to percent escape character: %c" c))
10064 (char-to-string c)))
10065 text "")))
10067 (defun org-link-escape-browser (text)
10068 "Escape some characters before handing over to the browser.
10069 This function is a candidate to be removed together with the
10070 constant `org-link-escape-chars-browser' once Org drops support
10071 for Emacs 24.1 and 24.2. All calls to this function will have to
10072 be replaced with `url-encode-url' which is available since Emacs
10073 24.3.1."
10074 ;; Example with the Org link
10075 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10076 ;; to open the browser with +subject:"Release 8.2" filled into the
10077 ;; query field: In this case the variable TEXT contains the
10078 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10079 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10080 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10081 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10082 (if (fboundp 'url-encode-url)
10083 (url-encode-url text)
10084 (if (org-string-match-p
10085 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10086 text)
10087 (org-link-escape text org-link-escape-chars-browser)
10088 text)))
10090 (defun org-link-unescape (str)
10091 "Unhex hexified Unicode parts in string STR.
10092 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10093 reciprocal of `org-link-escape', which see."
10094 (if (org-string-nw-p str)
10095 (replace-regexp-in-string
10096 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10097 str))
10099 (defun org-link-unescape-compound (hex)
10100 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10101 Note: this function also decodes single byte encodings like
10102 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10103 (save-match-data
10104 (let* ((bytes (cdr (split-string hex "%")))
10105 (ret "")
10106 (eat 0)
10107 (sum 0))
10108 (while bytes
10109 (let* ((val (string-to-number (pop bytes) 16))
10110 (shift-xor
10111 (if (= 0 eat)
10112 (cond
10113 ((>= val 252) (cons 6 252))
10114 ((>= val 248) (cons 5 248))
10115 ((>= val 240) (cons 4 240))
10116 ((>= val 224) (cons 3 224))
10117 ((>= val 192) (cons 2 192))
10118 (t (cons 0 0)))
10119 (cons 6 128))))
10120 (if (>= val 192) (setq eat (car shift-xor)))
10121 (setq val (logxor val (cdr shift-xor)))
10122 (setq sum (+ (lsh sum (car shift-xor)) val))
10123 (if (> eat 0) (setq eat (- eat 1)))
10124 (cond
10125 ((= 0 eat) ;multi byte
10126 (setq ret (concat ret (org-char-to-string sum)))
10127 (setq sum 0))
10128 ((not bytes) ; single byte(s)
10129 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10130 ret)))
10132 (defun org-link-unescape-single-byte-sequence (hex)
10133 "Unhexify hex-encoded single byte character sequences."
10134 (mapconcat (lambda (byte)
10135 (char-to-string (string-to-number byte 16)))
10136 (cdr (split-string hex "%")) ""))
10138 (defun org-xor (a b)
10139 "Exclusive or."
10140 (if a (not b) b))
10142 (defun org-fixup-message-id-for-http (s)
10143 "Replace special characters in a message id, so it can be used in an http query."
10144 (when (string-match "%" s)
10145 (setq s (mapconcat (lambda (c)
10146 (if (eq c ?%)
10147 "%25"
10148 (char-to-string c)))
10149 s "")))
10150 (while (string-match "<" s)
10151 (setq s (replace-match "%3C" t t s)))
10152 (while (string-match ">" s)
10153 (setq s (replace-match "%3E" t t s)))
10154 (while (string-match "@" s)
10155 (setq s (replace-match "%40" t t s)))
10158 (defun org-link-prettify (link)
10159 "Return a human-readable representation of LINK.
10160 The car of LINK must be a raw link.
10161 The cdr of LINK must be either a link description or nil."
10162 (let ((desc (or (cadr link) "<no description>")))
10163 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10164 "<" (car link) ">")))
10166 ;;;###autoload
10167 (defun org-insert-link-global ()
10168 "Insert a link like Org-mode does.
10169 This command can be called in any mode to insert a link in Org-mode syntax."
10170 (interactive)
10171 (org-load-modules-maybe)
10172 (org-run-like-in-org-mode 'org-insert-link))
10174 (defun org-insert-all-links (arg &optional pre post)
10175 "Insert all links in `org-stored-links'.
10176 When a universal prefix, do not delete the links from `org-stored-links'.
10177 When `ARG' is a number, insert the last N link(s).
10178 `PRE' and `POST' are optional arguments to define a string to
10179 prepend or to append."
10180 (interactive "P")
10181 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10182 (links (copy-seq org-stored-links))
10183 (pr (or pre "- "))
10184 (po (or post "\n"))
10185 (cnt 1) l)
10186 (if (null org-stored-links)
10187 (message "No link to insert")
10188 (while (and (or (listp arg) (>= arg cnt))
10189 (setq l (if (listp arg)
10190 (pop links)
10191 (pop org-stored-links))))
10192 (setq cnt (1+ cnt))
10193 (insert pr)
10194 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10195 (insert po)))))
10197 (defun org-insert-last-stored-link (arg)
10198 "Insert the last link stored in `org-stored-links'."
10199 (interactive "p")
10200 (org-insert-all-links arg "" "\n"))
10202 (defun org-link-fontify-links-to-this-file ()
10203 "Fontify links to the current file in `org-stored-links'."
10204 (let ((f (buffer-file-name)) a b)
10205 (setq a (mapcar (lambda(l)
10206 (let ((ll (car l)))
10207 (when (and (string-match "^file:\\(.+\\)::" ll)
10208 (equal f (expand-file-name (match-string 1 ll))))
10209 ll)))
10210 org-stored-links))
10211 (when (featurep 'org-id)
10212 (setq b (mapcar (lambda(l)
10213 (let ((ll (car l)))
10214 (when (and (string-match "^id:\\(.+\\)$" ll)
10215 (equal f (expand-file-name
10216 (or (org-id-find-id-file
10217 (match-string 1 ll)) ""))))
10218 ll)))
10219 org-stored-links)))
10220 (mapcar (lambda(l)
10221 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10222 (delq nil (append a b)))))
10224 (defvar org-link-links-in-this-file nil)
10225 (defun org-insert-link (&optional complete-file link-location default-description)
10226 "Insert a link. At the prompt, enter the link.
10228 Completion can be used to insert any of the link protocol prefixes like
10229 http or ftp in use.
10231 The history can be used to select a link previously stored with
10232 `org-store-link'. When the empty string is entered (i.e. if you just
10233 press RET at the prompt), the link defaults to the most recently
10234 stored link. As SPC triggers completion in the minibuffer, you need to
10235 use M-SPC or C-q SPC to force the insertion of a space character.
10237 You will also be prompted for a description, and if one is given, it will
10238 be displayed in the buffer instead of the link.
10240 If there is already a link at point, this command will allow you to edit link
10241 and description parts.
10243 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10244 be selected using completion. The path to the file will be relative to the
10245 current directory if the file is in the current directory or a subdirectory.
10246 Otherwise, the link will be the absolute path as completed in the minibuffer
10247 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10248 option `org-link-file-path-type'.
10250 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10251 the current directory or below.
10253 With three \\[universal-argument] prefixes, negate the meaning of
10254 `org-keep-stored-link-after-insertion'.
10256 If `org-make-link-description-function' is non-nil, this function will be
10257 called with the link target, and the result will be the default
10258 link description.
10260 If the LINK-LOCATION parameter is non-nil, this value will be
10261 used as the link location instead of reading one interactively.
10263 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10264 be used as the default description."
10265 (interactive "P")
10266 (let* ((wcf (current-window-configuration))
10267 (origbuf (current-buffer))
10268 (region (if (org-region-active-p)
10269 (buffer-substring (region-beginning) (region-end))))
10270 (remove (and region (list (region-beginning) (region-end))))
10271 (desc region)
10272 tmphist ; byte-compile incorrectly complains about this
10273 (link link-location)
10274 (abbrevs org-link-abbrev-alist-local)
10275 entry file all-prefixes auto-desc)
10276 (cond
10277 (link-location) ; specified by arg, just use it.
10278 ((org-in-regexp org-bracket-link-regexp 1)
10279 ;; We do have a link at point, and we are going to edit it.
10280 (setq remove (list (match-beginning 0) (match-end 0)))
10281 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10282 (setq link (read-string "Link: "
10283 (org-link-unescape
10284 (org-match-string-no-properties 1)))))
10285 ((or (org-in-regexp org-angle-link-re)
10286 (org-in-regexp org-plain-link-re))
10287 ;; Convert to bracket link
10288 (setq remove (list (match-beginning 0) (match-end 0))
10289 link (read-string "Link: "
10290 (org-remove-angle-brackets (match-string 0)))))
10291 ((member complete-file '((4) (16)))
10292 ;; Completing read for file names.
10293 (setq link (org-file-complete-link complete-file)))
10295 ;; Read link, with completion for stored links.
10296 (org-link-fontify-links-to-this-file)
10297 (org-switch-to-buffer-other-window "*Org Links*")
10298 (with-current-buffer "*Org Links*"
10299 (erase-buffer)
10300 (insert "Insert a link.
10301 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10302 (when org-stored-links
10303 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10304 (insert (mapconcat 'org-link-prettify
10305 (reverse org-stored-links) "\n")))
10306 (goto-char (point-min)))
10307 (let ((cw (selected-window)))
10308 (select-window (get-buffer-window "*Org Links*" 'visible))
10309 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10310 (unless (pos-visible-in-window-p (point-max))
10311 (org-fit-window-to-buffer))
10312 (and (window-live-p cw) (select-window cw)))
10313 ;; Fake a link history, containing the stored links.
10314 (setq tmphist (append (mapcar 'car org-stored-links)
10315 org-insert-link-history))
10316 (setq all-prefixes (append (mapcar 'car abbrevs)
10317 (mapcar 'car org-link-abbrev-alist)
10318 org-link-types))
10319 (unwind-protect
10320 (progn
10321 (setq link
10322 (org-completing-read
10323 "Link: "
10324 (append
10325 (mapcar (lambda (x) (concat x ":"))
10326 all-prefixes)
10327 (mapcar 'car org-stored-links))
10328 nil nil nil
10329 'tmphist
10330 (caar org-stored-links)))
10331 (if (not (string-match "\\S-" link))
10332 (user-error "No link selected"))
10333 (mapc (lambda(l)
10334 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10335 org-stored-links)
10336 (if (or (member link all-prefixes)
10337 (and (equal ":" (substring link -1))
10338 (member (substring link 0 -1) all-prefixes)
10339 (setq link (substring link 0 -1))))
10340 (setq link (with-current-buffer origbuf
10341 (org-link-try-special-completion link)))))
10342 (set-window-configuration wcf)
10343 (kill-buffer "*Org Links*"))
10344 (setq entry (assoc link org-stored-links))
10345 (or entry (push link org-insert-link-history))
10346 (setq desc (or desc (nth 1 entry)))))
10348 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10349 (not org-keep-stored-link-after-insertion))
10350 (setq org-stored-links (delq (assoc link org-stored-links)
10351 org-stored-links)))
10353 (if (and (string-match org-plain-link-re link)
10354 (not (string-match org-ts-regexp link)))
10355 ;; URL-like link, normalize the use of angular brackets.
10356 (setq link (org-remove-angle-brackets link)))
10358 ;; Check if we are linking to the current file with a search
10359 ;; option If yes, simplify the link by using only the search
10360 ;; option.
10361 (when (and buffer-file-name
10362 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10363 (let* ((path (match-string 1 link))
10364 (case-fold-search nil)
10365 (search (match-string 2 link)))
10366 (save-match-data
10367 (if (equal (file-truename buffer-file-name) (file-truename path))
10368 ;; We are linking to this same file, with a search option
10369 (setq link search)))))
10371 ;; Check if we can/should use a relative path. If yes, simplify the link
10372 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10373 (let* ((type (match-string 1 link))
10374 (path (match-string 2 link))
10375 (origpath path)
10376 (case-fold-search nil))
10377 (cond
10378 ((or (eq org-link-file-path-type 'absolute)
10379 (equal complete-file '(16)))
10380 (setq path (abbreviate-file-name (expand-file-name path))))
10381 ((eq org-link-file-path-type 'noabbrev)
10382 (setq path (expand-file-name path)))
10383 ((eq org-link-file-path-type 'relative)
10384 (setq path (file-relative-name path)))
10386 (save-match-data
10387 (if (string-match (concat "^" (regexp-quote
10388 (expand-file-name
10389 (file-name-as-directory
10390 default-directory))))
10391 (expand-file-name path))
10392 ;; We are linking a file with relative path name.
10393 (setq path (substring (expand-file-name path)
10394 (match-end 0)))
10395 (setq path (abbreviate-file-name (expand-file-name path)))))))
10396 (setq link (concat type path))
10397 (if (equal desc origpath)
10398 (setq desc path))))
10400 (if org-make-link-description-function
10401 (setq desc
10402 (or (condition-case nil
10403 (funcall org-make-link-description-function link desc)
10404 (error (progn (message "Can't get link description from `%s'"
10405 (symbol-name org-make-link-description-function))
10406 (sit-for 2) nil)))
10407 (read-string "Description: " default-description)))
10408 (if default-description (setq desc default-description)
10409 (setq desc (or (and auto-desc desc)
10410 (read-string "Description: " desc)))))
10412 (unless (string-match "\\S-" desc) (setq desc nil))
10413 (if remove (apply 'delete-region remove))
10414 (insert (org-make-link-string link desc))
10415 ;; Redisplay so as the new link has proper invisible characters.
10416 (sit-for 0)))
10418 (defun org-link-try-special-completion (type)
10419 "If there is completion support for link type TYPE, offer it."
10420 (let ((fun (intern (concat "org-" type "-complete-link"))))
10421 (if (functionp fun)
10422 (funcall fun)
10423 (read-string "Link (no completion support): " (concat type ":")))))
10425 (defun org-file-complete-link (&optional arg)
10426 "Create a file link using completion."
10427 (let ((file (org-iread-file-name "File: "))
10428 (pwd (file-name-as-directory (expand-file-name ".")))
10429 (pwd1 (file-name-as-directory (abbreviate-file-name
10430 (expand-file-name ".")))))
10431 (cond ((equal arg '(16))
10432 (concat "file:"
10433 (abbreviate-file-name (expand-file-name file))))
10434 ((string-match
10435 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10436 (concat "file:" (match-string 1 file)))
10437 ((string-match
10438 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10439 (expand-file-name file))
10440 (concat "file:"
10441 (match-string 1 (expand-file-name file))))
10442 (t (concat "file:" file)))))
10444 (defun org-iread-file-name (&rest args)
10445 "Read-file-name using `ido-mode' speedup if available.
10446 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10447 See `read-file-name' for a description of parameters."
10448 (org-without-partial-completion
10449 (if (and org-completion-use-ido
10450 (fboundp 'ido-read-file-name)
10451 (org-bound-and-true-p ido-mode)
10452 (listp (nth 1 args)))
10453 (let ((ido-enter-matching-directory nil))
10454 (apply #'ido-read-file-name args))
10455 (apply #'read-file-name args))))
10457 (defun org-completing-read (&rest args)
10458 "Completing-read with SPACE being a normal character."
10459 (let ((enable-recursive-minibuffers t)
10460 (minibuffer-local-completion-map
10461 (copy-keymap minibuffer-local-completion-map)))
10462 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10463 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10464 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10465 (apply 'org-icompleting-read args)))
10467 (defun org-completing-read-no-i (&rest args)
10468 (let (org-completion-use-ido org-completion-use-iswitchb)
10469 (apply 'org-completing-read args)))
10471 (defun org-iswitchb-completing-read (prompt choices &rest args)
10472 "Use iswitch as a completing-read replacement to choose from choices.
10473 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10474 from."
10475 (let* ((iswitchb-use-virtual-buffers nil)
10476 (iswitchb-make-buflist-hook
10477 (lambda ()
10478 (setq iswitchb-temp-buflist choices))))
10479 (iswitchb-read-buffer prompt)))
10481 (defun org-icompleting-read (&rest args)
10482 "Completing-read using `ido-mode' or `iswitchb' speedups if available.
10483 Should be called like `completing-read'."
10484 (org-without-partial-completion
10485 (if (not (listp (nth 1 args)))
10486 ;; Ido only supports lists as the COLLECTION argument. Use
10487 ;; default completion function when second argument is not
10488 ;; a list.
10489 (apply #'completing-read args)
10490 (let ((ido-enter-matching-directory nil))
10491 (apply (cond ((and org-completion-use-ido
10492 (fboundp 'ido-completing-read)
10493 (org-bound-and-true-p ido-mode))
10494 #'ido-completing-read)
10495 ((and org-completion-use-iswitchb
10496 (org-bound-and-true-p iswitchb-mode))
10497 #'org-iswitchb-completing-read)
10498 (t #'completing-read))
10499 args)))))
10501 ;;; Opening/following a link
10503 (defvar org-link-search-failed nil)
10505 (defvar org-open-link-functions nil
10506 "Hook for functions finding a plain text link.
10507 These functions must take a single argument, the link content.
10508 They will be called for links that look like [[link text][description]]
10509 when LINK TEXT does not have a protocol like \"http:\" and does not look
10510 like a filename (e.g. \"./blue.png\").
10512 These functions will be called *before* Org attempts to resolve the
10513 link by doing text searches in the current buffer - so if you want a
10514 link \"[[target]]\" to still find \"<<target>>\", your function should
10515 handle this as a special case.
10517 When the function does handle the link, it must return a non-nil value.
10518 If it decides that it is not responsible for this link, it must return
10519 nil to indicate that that Org-mode can continue with other options
10520 like exact and fuzzy text search.")
10522 (defun org-next-link (&optional search-backward)
10523 "Move forward to the next link.
10524 If the link is in hidden text, expose it."
10525 (interactive "P")
10526 (when (and org-link-search-failed (eq this-command last-command))
10527 (goto-char (point-min))
10528 (message "Link search wrapped back to beginning of buffer"))
10529 (setq org-link-search-failed nil)
10530 (let* ((pos (point))
10531 (ct (org-context))
10532 (a (assoc :link ct))
10533 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10534 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10535 ((looking-at org-any-link-re)
10536 ;; Don't stay stuck at link without an org-link face
10537 (forward-char (if search-backward -1 1))))
10538 (if (funcall srch-fun org-any-link-re nil t)
10539 (progn
10540 (goto-char (match-beginning 0))
10541 (if (outline-invisible-p) (org-show-context)))
10542 (goto-char pos)
10543 (setq org-link-search-failed t)
10544 (message "No further link found"))))
10546 (defun org-previous-link ()
10547 "Move backward to the previous link.
10548 If the link is in hidden text, expose it."
10549 (interactive)
10550 (funcall 'org-next-link t))
10552 (defun org-translate-link (s)
10553 "Translate a link string if a translation function has been defined."
10554 (with-temp-buffer
10555 (insert (org-trim s))
10556 (org-trim (org-element-interpret-data (org-element-context)))))
10558 (defun org-translate-link-from-planner (type path)
10559 "Translate a link from Emacs Planner syntax so that Org can follow it.
10560 This is still an experimental function, your mileage may vary."
10561 (cond
10562 ((member type '("http" "https" "news" "ftp"))
10563 ;; standard Internet links are the same.
10564 nil)
10565 ((and (equal type "irc") (string-match "^//" path))
10566 ;; Planner has two / at the beginning of an irc link, we have 1.
10567 ;; We should have zero, actually....
10568 (setq path (substring path 1)))
10569 ((and (equal type "lisp") (string-match "^/" path))
10570 ;; Planner has a slash, we do not.
10571 (setq type "elisp" path (substring path 1)))
10572 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10573 ;; A typical message link. Planner has the id after the final slash,
10574 ;; we separate it with a hash mark
10575 (setq path (concat (match-string 1 path) "#"
10576 (org-remove-angle-brackets (match-string 2 path))))))
10577 (cons type path))
10579 (defun org-find-file-at-mouse (ev)
10580 "Open file link or URL at mouse."
10581 (interactive "e")
10582 (mouse-set-point ev)
10583 (org-open-at-point 'in-emacs))
10585 (defun org-open-at-mouse (ev)
10586 "Open file link or URL at mouse.
10587 See the docstring of `org-open-file' for details."
10588 (interactive "e")
10589 (mouse-set-point ev)
10590 (if (eq major-mode 'org-agenda-mode)
10591 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10592 (org-open-at-point))
10594 (defvar org-window-config-before-follow-link nil
10595 "The window configuration before following a link.
10596 This is saved in case the need arises to restore it.")
10598 ;;;###autoload
10599 (defun org-open-at-point-global ()
10600 "Follow a link like Org-mode does.
10601 This command can be called in any mode to follow a link that has
10602 Org-mode syntax."
10603 (interactive)
10604 (org-run-like-in-org-mode 'org-open-at-point))
10606 ;;;###autoload
10607 (defun org-open-link-from-string (s &optional arg reference-buffer)
10608 "Open a link in the string S, as if it was in Org-mode."
10609 (interactive "sLink: \nP")
10610 (let ((reference-buffer (or reference-buffer (current-buffer))))
10611 (with-temp-buffer
10612 (let ((org-inhibit-startup (not reference-buffer)))
10613 (org-mode)
10614 (insert s)
10615 (goto-char (point-min))
10616 (when reference-buffer
10617 (setq org-link-abbrev-alist-local
10618 (with-current-buffer reference-buffer
10619 org-link-abbrev-alist-local)))
10620 (org-open-at-point arg reference-buffer)))))
10622 (defvar org-open-at-point-functions nil
10623 "Hook that is run when following a link at point.
10625 Functions in this hook must return t if they identify and follow
10626 a link at point. If they don't find anything interesting at point,
10627 they must return nil.")
10629 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10630 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10631 (defun org-open-at-point (&optional arg reference-buffer)
10632 "Open link, timestamp, footnote or tags at point.
10634 When point is on a link, follow it. Normally, files will be
10635 opened by an appropriate application. If the optional prefix
10636 argument ARG is non-nil, Emacs will visit the file. With
10637 a double prefix argument, try to open outside of Emacs, in the
10638 application the system uses for this file type.
10640 When point is on a timestamp, open the agenda at the day
10641 specified.
10643 When point is a footnote definition, move to the first reference
10644 found. If it is on a reference, move to the associated
10645 definition.
10647 When point is on a headline, display a list of every link in the
10648 entry, so it is possible to pick one, or all, of them. If point
10649 is on a tag, call `org-tags-view' instead.
10651 When optional argument REFERENCE-BUFFER is non-nil, it should
10652 specify a buffer from where the link search should happen. This
10653 is used internally by `org-open-link-from-string'.
10655 On top of syntactically correct links, this function will open
10656 the link at point in comments or comment blocks and the first
10657 link in a property drawer line."
10658 (interactive "P")
10659 ;; On a code block, open block's results.
10660 (unless (call-interactively 'org-babel-open-src-block-result)
10661 (org-load-modules-maybe)
10662 (setq org-window-config-before-follow-link (current-window-configuration))
10663 (org-remove-occur-highlights nil nil t)
10664 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10665 (let* ((context
10666 ;; Only consider supported types, even if they are not
10667 ;; the closest one.
10668 (org-element-lineage
10669 (org-element-context)
10670 '(clock comment comment-block footnote-definition
10671 footnote-reference headline inlinetask keyword link
10672 node-property timestamp)
10674 (type (org-element-type context))
10675 (value (org-element-property :value context)))
10676 (cond
10677 ((not context) (user-error "No link found"))
10678 ;; Exception: open timestamps and links in properties
10679 ;; drawers, keywords and comments.
10680 ((memq type '(comment comment-block keyword node-property))
10681 (cond ((org-in-regexp org-any-link-re)
10682 (org-open-link-from-string (match-string-no-properties 0)))
10683 ((or (org-in-regexp org-ts-regexp-both nil t)
10684 (org-in-regexp org-tsr-regexp-both nil t))
10685 (org-follow-timestamp-link))
10686 (t (user-error "No link found"))))
10687 ;; On a headline or an inlinetask, but not on a timestamp,
10688 ;; a link, a footnote reference or on tags.
10689 ((and (memq type '(headline inlinetask))
10690 ;; Not on tags.
10691 (progn (save-excursion (beginning-of-line)
10692 (looking-at org-complex-heading-regexp))
10693 (or (not (match-beginning 5))
10694 (< (point) (match-beginning 5)))))
10695 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10696 (links (car data))
10697 (links-end (cdr data)))
10698 (if links
10699 (dolist (link (if (stringp links) (list links) links))
10700 (search-forward link nil links-end)
10701 (goto-char (match-beginning 0))
10702 (org-open-at-point))
10703 (require 'org-attach)
10704 (org-attach-reveal 'if-exists))))
10705 ;; On a clock line, make sure point is on the timestamp
10706 ;; before opening it.
10707 ((and (eq type 'clock)
10708 value
10709 (>= (point) (org-element-property :begin value))
10710 (<= (point) (org-element-property :end value)))
10711 (org-follow-timestamp-link))
10712 ;; Do nothing on white spaces after an object.
10713 ((>= (point)
10714 (save-excursion
10715 (goto-char (org-element-property :end context))
10716 (skip-chars-backward " \t")
10717 (point)))
10718 (user-error "No link found"))
10719 ((eq type 'timestamp) (org-follow-timestamp-link))
10720 ;; On tags within a headline or an inlinetask.
10721 ((and (memq type '(headline inlinetask))
10722 (progn (save-excursion (beginning-of-line)
10723 (looking-at org-complex-heading-regexp))
10724 (and (match-beginning 5)
10725 (>= (point) (match-beginning 5)))))
10726 (org-tags-view arg (substring (match-string 5) 0 -1)))
10727 ((eq type 'link)
10728 ;; When link is located within the description of another
10729 ;; link (e.g., an inline image), always open the parent
10730 ;; link.
10731 (let*((link (let ((up (org-element-property :parent context)))
10732 (if (eq (org-element-type up) 'link) up context)))
10733 (type (org-element-property :type link))
10734 (path (org-link-unescape (org-element-property :path link))))
10735 ;; Switch back to REFERENCE-BUFFER needed when called in
10736 ;; a temporary buffer through `org-open-link-from-string'.
10737 (with-current-buffer (or reference-buffer (current-buffer))
10738 (cond
10739 ((equal type "file")
10740 (if (string-match "[*?{]" (file-name-nondirectory path))
10741 (dired path)
10742 ;; Look into `org-link-protocols' in order to find
10743 ;; a DEDICATED-FUNCTION to open file. The function
10744 ;; will be applied on raw link instead of parsed
10745 ;; link due to the limitation in `org-add-link-type'
10746 ;; ("open" function called with a single argument).
10747 ;; If no such function is found, fallback to
10748 ;; `org-open-file'.
10750 ;; Note : "file+emacs" and "file+sys" types are
10751 ;; hard-coded in order to escape the previous
10752 ;; limitation.
10753 (let* ((option (org-element-property :search-option link))
10754 (app (org-element-property :application link))
10755 (dedicated-function
10756 (nth 1 (assoc app org-link-protocols))))
10757 (if dedicated-function
10758 (funcall dedicated-function
10759 (concat path
10760 (and option (concat "::" option))))
10761 (apply #'org-open-file
10762 path
10763 (cond (arg)
10764 ((equal app "emacs") 'emacs)
10765 ((equal app "sys") 'system))
10766 (cond ((not option) nil)
10767 ((org-string-match-p "\\`[0-9]+\\'" option)
10768 (list (string-to-number option)))
10769 (t (list nil
10770 (org-link-unescape option)))))))))
10771 ((assoc type org-link-protocols)
10772 (funcall (nth 1 (assoc type org-link-protocols)) path))
10773 ((equal type "help")
10774 (let ((f-or-v (intern path)))
10775 (cond ((fboundp f-or-v) (describe-function f-or-v))
10776 ((boundp f-or-v) (describe-variable f-or-v))
10777 (t (error "Not a known function or variable")))))
10778 ((member type '("http" "https" "ftp" "mailto" "news"))
10779 (browse-url (org-link-escape-browser (concat type ":" path))))
10780 ((equal type "doi")
10781 (browse-url
10782 (org-link-escape-browser (concat org-doi-server-url path))))
10783 ((equal type "message") (browse-url (concat type ":" path)))
10784 ((equal type "shell")
10785 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10786 (cmd path))
10787 (if (or (and (org-string-nw-p
10788 org-confirm-shell-link-not-regexp)
10789 (string-match
10790 org-confirm-shell-link-not-regexp cmd))
10791 (not org-confirm-shell-link-function)
10792 (funcall org-confirm-shell-link-function
10793 (format "Execute \"%s\" in shell? "
10794 (org-add-props cmd nil
10795 'face 'org-warning))))
10796 (progn
10797 (message "Executing %s" cmd)
10798 (shell-command cmd buf)
10799 (when (featurep 'midnight)
10800 (setq clean-buffer-list-kill-buffer-names
10801 (cons (buffer-name buf)
10802 clean-buffer-list-kill-buffer-names))))
10803 (user-error "Abort"))))
10804 ((equal type "elisp")
10805 (let ((cmd path))
10806 (if (or (and (org-string-nw-p
10807 org-confirm-elisp-link-not-regexp)
10808 (org-string-match-p
10809 org-confirm-elisp-link-not-regexp cmd))
10810 (not org-confirm-elisp-link-function)
10811 (funcall org-confirm-elisp-link-function
10812 (format "Execute \"%s\" as elisp? "
10813 (org-add-props cmd nil
10814 'face 'org-warning))))
10815 (message "%s => %s" cmd
10816 (if (eq (string-to-char cmd) ?\()
10817 (eval (read cmd))
10818 (call-interactively (read cmd))))
10819 (user-error "Abort"))))
10820 ((equal type "id")
10821 (require 'org-id)
10822 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10823 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10824 (unless (run-hook-with-args-until-success
10825 'org-open-link-functions path)
10826 (if (not arg) (org-mark-ring-push)
10827 (switch-to-buffer-other-window
10828 (org-get-buffer-for-internal-link (current-buffer))))
10829 (let ((destination
10830 (org-with-wide-buffer
10831 (if (equal type "radio")
10832 (org-search-radio-target
10833 (org-element-property :path link))
10834 (org-link-search
10835 (if (member type '("custom-id" "coderef"))
10836 (org-element-property :raw-link link)
10837 path)
10838 ;; Prevent fuzzy links from matching
10839 ;; themselves.
10840 (and (equal type "fuzzy")
10841 (+ 2 (org-element-property :begin link)))))
10842 (point))))
10843 (unless (and (<= (point-min) destination)
10844 (>= (point-max) destination))
10845 (widen))
10846 (goto-char destination))))
10847 (t (browse-url-at-point))))))
10848 ;; On a footnote reference or at a footnote definition's label.
10849 ((or (eq type 'footnote-reference)
10850 (and (eq type 'footnote-definition)
10851 (save-excursion
10852 ;; Do not validate action when point is on the
10853 ;; spaces right after the footnote label, in
10854 ;; order to be on par with behaviour on links.
10855 (skip-chars-forward " \t")
10856 (let ((begin
10857 (org-element-property :contents-begin context)))
10858 (if begin (< (point) begin)
10859 (= (org-element-property :post-affiliated context)
10860 (line-beginning-position)))))))
10861 (org-footnote-action))
10862 (t (user-error "No link found")))))
10863 (run-hook-with-args 'org-follow-link-hook)))
10865 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10866 "Offer links in the current entry and return the selected link.
10867 If there is only one link, return it.
10868 If NTH is an integer, return the NTH link found.
10869 If ZERO is a string, check also this string for a link, and if
10870 there is one, return it."
10871 (with-current-buffer buffer
10872 (save-excursion
10873 (save-restriction
10874 (widen)
10875 (goto-char marker)
10876 (let ((cnt ?0)
10877 (in-emacs (if (integerp nth) nil nth))
10878 have-zero end links link c)
10879 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10880 (push (match-string 0 zero) links)
10881 (setq cnt (1- cnt) have-zero t))
10882 (save-excursion
10883 (org-back-to-heading t)
10884 (setq end (save-excursion (outline-next-heading) (point)))
10885 (while (re-search-forward org-any-link-re end t)
10886 (push (match-string 0) links))
10887 (setq links (org-uniquify (reverse links))))
10888 (cond
10889 ((null links)
10890 (message "No links"))
10891 ((equal (length links) 1)
10892 (setq link (car links)))
10893 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10894 (setq link (nth (if have-zero nth (1- nth)) links)))
10895 (t ; we have to select a link
10896 (save-excursion
10897 (save-window-excursion
10898 (delete-other-windows)
10899 (with-output-to-temp-buffer "*Select Link*"
10900 (mapc (lambda (l)
10901 (if (not (string-match org-bracket-link-regexp l))
10902 (princ (format "[%c] %s\n" (incf cnt)
10903 (org-remove-angle-brackets l)))
10904 (if (match-end 3)
10905 (princ (format "[%c] %s (%s)\n" (incf cnt)
10906 (match-string 3 l) (match-string 1 l)))
10907 (princ (format "[%c] %s\n" (incf cnt)
10908 (match-string 1 l))))))
10909 links))
10910 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10911 (message "Select link to open, RET to open all:")
10912 (setq c (read-char-exclusive))
10913 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10914 (when (equal c ?q) (user-error "Abort"))
10915 (if (equal c ?\C-m)
10916 (setq link links)
10917 (setq nth (- c ?0))
10918 (if have-zero (setq nth (1+ nth)))
10919 (unless (and (integerp nth) (>= (length links) nth))
10920 (user-error "Invalid link selection"))
10921 (setq link (nth (1- nth) links)))))
10922 (cons link end))))))
10924 ;; TODO: These functions are deprecated since `org-open-at-point'
10925 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10926 (defun org-open-file-with-system (path)
10927 "Open file at PATH using the system way of opening it."
10928 (org-open-file path 'system))
10929 (defun org-open-file-with-emacs (path)
10930 "Open file at PATH in Emacs."
10931 (org-open-file path 'emacs))
10934 ;;; File search
10936 (defvar org-create-file-search-functions nil
10937 "List of functions to construct the right search string for a file link.
10938 These functions are called in turn with point at the location to
10939 which the link should point.
10941 A function in the hook should first test if it would like to
10942 handle this file type, for example by checking the `major-mode'
10943 or the file extension. If it decides not to handle this file, it
10944 should just return nil to give other functions a chance. If it
10945 does handle the file, it must return the search string to be used
10946 when following the link. The search string will be part of the
10947 file link, given after a double colon, and `org-open-at-point'
10948 will automatically search for it. If special measures must be
10949 taken to make the search successful, another function should be
10950 added to the companion hook `org-execute-file-search-functions',
10951 which see.
10953 A function in this hook may also use `setq' to set the variable
10954 `description' to provide a suggestion for the descriptive text to
10955 be used for this link when it gets inserted into an Org-mode
10956 buffer with \\[org-insert-link].")
10958 (defvar org-execute-file-search-functions nil
10959 "List of functions to execute a file search triggered by a link.
10961 Functions added to this hook must accept a single argument, the
10962 search string that was part of the file link, the part after the
10963 double colon. The function must first check if it would like to
10964 handle this search, for example by checking the `major-mode' or
10965 the file extension. If it decides not to handle this search, it
10966 should just return nil to give other functions a chance. If it
10967 does handle the search, it must return a non-nil value to keep
10968 other functions from trying.
10970 Each function can access the current prefix argument through the
10971 variable `current-prefix-arg'. Note that a single prefix is used
10972 to force opening a link in Emacs, so it may be good to only use a
10973 numeric or double prefix to guide the search function.
10975 In case this is needed, a function in this hook can also restore
10976 the window configuration before `org-open-at-point' was called using:
10978 (set-window-configuration org-window-config-before-follow-link)")
10980 (defun org-search-radio-target (target)
10981 "Search a radio target matching TARGET in current buffer.
10982 White spaces are not significant."
10983 (let ((re (format "<<<%s>>>"
10984 (mapconcat #'regexp-quote
10985 (org-split-string target "[ \t\n]+")
10986 "[ \t]+\\(?:\n[ \t]*\\)?")))
10987 (origin (point)))
10988 (goto-char (point-min))
10989 (catch :radio-match
10990 (while (re-search-forward re nil t)
10991 (backward-char)
10992 (let ((object (org-element-context)))
10993 (when (eq (org-element-type object) 'radio-target)
10994 (goto-char (org-element-property :begin object))
10995 (org-show-context 'link-search)
10996 (throw :radio-match nil))))
10997 (goto-char origin)
10998 (user-error "No match for radio target: %s" target))))
11000 (defun org-link-search (s &optional avoid-pos stealth)
11001 "Search for a search string S.
11003 If S starts with \"#\", it triggers a custom ID search.
11005 If S is enclosed within parenthesis, it initiates a coderef
11006 search.
11008 If S is surrounded by forward slashes, it is interpreted as
11009 a regular expression. In Org mode files, this will create an
11010 `org-occur' sparse tree. In ordinary files, `occur' will be used
11011 to list matches. If the current buffer is in `dired-mode', grep
11012 will be used to search in all files.
11014 When AVOID-POS is given, ignore matches near that position.
11016 When optional argument STEALTH is non-nil, do not modify
11017 visibility around point, thus ignoring `org-show-context-detail'
11018 variable.
11020 Search is case-insensitive and ignores white spaces. Return type
11021 of matched result, with is either `dedicated' or `fuzzy'."
11022 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11023 (let* ((case-fold-search t)
11024 (origin (point))
11025 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11026 (words (org-split-string s "[ \t\n]+"))
11027 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11028 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11029 type)
11030 (cond
11031 ;; Check if there are any special search functions.
11032 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11033 ((eq (string-to-char s) ?#)
11034 ;; Look for a custom ID S if S starts with "#".
11035 (let* ((id (substring normalized 1))
11036 (match (org-find-property "CUSTOM_ID" id)))
11037 (if match (progn (goto-char match) (setf type 'dedicated))
11038 (error "No match for custom ID: %s" id))))
11039 ((string-match "\\`(\\(.*\\))\\'" normalized)
11040 ;; Look for coderef targets if S is enclosed within parenthesis.
11041 (let ((coderef (match-string-no-properties 1 normalized))
11042 (re (substring s-single-re 1 -1)))
11043 (goto-char (point-min))
11044 (catch :coderef-match
11045 (while (re-search-forward re nil t)
11046 (let ((element (org-element-at-point)))
11047 (when (and (memq (org-element-type element)
11048 '(example-block src-block))
11049 ;; Build proper regexp according to current
11050 ;; block's label format.
11051 (let ((label-fmt
11052 (regexp-quote
11053 (or (org-element-property :label-fmt element)
11054 org-coderef-label-format))))
11055 (save-excursion
11056 (beginning-of-line)
11057 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11058 (format label-fmt coderef))))))
11059 (setq type 'dedicated)
11060 (goto-char (match-beginning 1))
11061 (throw :coderef-match nil))))
11062 (goto-char origin)
11063 (error "No match for coderef: %s" coderef))))
11064 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11065 ;; Look for a regular expression.
11066 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11067 (match-string 1 s)))
11068 ;; Fuzzy links.
11070 (let* ((starred (eq (string-to-char normalized) ?*))
11071 (headline-search (and (derived-mode-p 'org-mode)
11072 (or org-link-search-must-match-exact-headline
11073 starred))))
11074 (cond
11075 ;; Look for targets, only if not in a headline search.
11076 ((and (not starred)
11077 (let ((target (format "<<%s>>" s-multi-re)))
11078 (catch :target-match
11079 (goto-char (point-min))
11080 (while (re-search-forward target nil t)
11081 (backward-char)
11082 (let ((context (org-element-context)))
11083 (when (eq (org-element-type context) 'target)
11084 (setq type 'dedicated)
11085 (goto-char (org-element-property :begin context))
11086 (throw :target-match t))))
11087 nil))))
11088 ;; Look for elements named after S, only if not in a headline
11089 ;; search.
11090 ((and (not starred)
11091 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11092 (catch :name-match
11093 (goto-char (point-min))
11094 (while (re-search-forward name nil t)
11095 (let ((element (org-element-at-point)))
11096 (when (equal (org-split-string
11097 (org-element-property :name element)
11098 "[ \t]+")
11099 words)
11100 (setq type 'dedicated)
11101 (beginning-of-line)
11102 (throw :name-match t))))
11103 nil))))
11104 ;; Regular text search. Prefer headlines in Org mode
11105 ;; buffers.
11106 ((and (derived-mode-p 'org-mode)
11107 (let* ((wspace "[ \t]")
11108 (wspaceopt (concat wspace "*"))
11109 (cookie (concat "\\(?:"
11110 wspaceopt
11111 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11112 wspaceopt
11113 "\\)"))
11114 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11115 (re (concat
11116 org-outline-regexp-bol
11117 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11118 "\\(?:\\[#.\\][ \t]+\\)?"
11119 "\\(?:" org-comment-string "[ \t]+\\)?"
11120 sep "?"
11121 (let ((title (mapconcat #'regexp-quote
11122 words
11123 sep)))
11124 (if starred (substring title 1) title))
11125 sep "?"
11126 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11127 "[ \t]*$")))
11128 (goto-char (point-min))
11129 (re-search-forward re nil t)))
11130 (goto-char (match-beginning 0))
11131 (setq type 'dedicated))
11132 ;; Offer to create non-existent headline depending on
11133 ;; `org-link-search-must-match-exact-headline'.
11134 ((and (derived-mode-p 'org-mode)
11135 (not org-link-search-inhibit-query)
11136 (eq org-link-search-must-match-exact-headline 'query-to-create)
11137 (yes-or-no-p "No match - create this as a new heading? "))
11138 (goto-char (point-max))
11139 (unless (bolp) (newline))
11140 (org-insert-heading nil t t)
11141 (insert s "\n")
11142 (beginning-of-line 0))
11143 ;; Only headlines are looked after. No need to process
11144 ;; further: throw an error.
11145 ((and (derived-mode-p 'org-mode)
11146 (or starred org-link-search-must-match-exact-headline))
11147 (goto-char origin)
11148 (error "No match for fuzzy expression: %s" normalized))
11149 ;; Regular text search.
11150 ((catch :fuzzy-match
11151 (goto-char (point-min))
11152 (while (re-search-forward s-multi-re nil t)
11153 ;; Skip match if it contains AVOID-POS or it is included
11154 ;; in a link with a description but outside the
11155 ;; description.
11156 (unless (or (and avoid-pos
11157 (<= (match-beginning 0) avoid-pos)
11158 (> (match-end 0) avoid-pos))
11159 (and (save-match-data
11160 (org-in-regexp org-bracket-link-regexp))
11161 (match-beginning 3)
11162 (or (> (match-beginning 3) (point))
11163 (<= (match-end 3) (point)))
11164 (org-element-lineage
11165 (save-match-data (org-element-context))
11166 '(link) t)))
11167 (goto-char (match-beginning 0))
11168 (setq type 'fuzzy)
11169 (throw :fuzzy-match t)))
11170 nil))
11171 ;; All failed. Throw an error.
11172 (t (goto-char origin)
11173 (error "No match for fuzzy expression: %s" normalized))))))
11174 ;; Disclose surroundings of match, if appropriate.
11175 (when (and (derived-mode-p 'org-mode) (not stealth))
11176 (org-show-context 'link-search))
11177 type))
11179 (defun org-get-buffer-for-internal-link (buffer)
11180 "Return a buffer to be used for displaying the link target of internal links."
11181 (cond
11182 ((not org-display-internal-link-with-indirect-buffer)
11183 buffer)
11184 ((string-match "(Clone)$" (buffer-name buffer))
11185 (message "Buffer is already a clone, not making another one")
11186 ;; we also do not modify visibility in this case
11187 buffer)
11188 (t ; make a new indirect buffer for displaying the link
11189 (let* ((bn (buffer-name buffer))
11190 (ibn (concat bn "(Clone)"))
11191 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11192 (with-current-buffer ib (org-overview))
11193 ib))))
11195 (defun org-do-occur (regexp &optional cleanup)
11196 "Call the Emacs command `occur'.
11197 If CLEANUP is non-nil, remove the printout of the regular expression
11198 in the *Occur* buffer. This is useful if the regex is long and not useful
11199 to read."
11200 (occur regexp)
11201 (when cleanup
11202 (let ((cwin (selected-window)) win beg end)
11203 (when (setq win (get-buffer-window "*Occur*"))
11204 (select-window win))
11205 (goto-char (point-min))
11206 (when (re-search-forward "match[a-z]+" nil t)
11207 (setq beg (match-end 0))
11208 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11209 (setq end (1- (match-beginning 0)))))
11210 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11211 (goto-char (point-min))
11212 (select-window cwin))))
11214 ;;; The mark ring for links jumps
11216 (defvar org-mark-ring nil
11217 "Mark ring for positions before jumps in Org-mode.")
11218 (defvar org-mark-ring-last-goto nil
11219 "Last position in the mark ring used to go back.")
11220 ;; Fill and close the ring
11221 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11222 (loop for i from 1 to org-mark-ring-length do
11223 (push (make-marker) org-mark-ring))
11224 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11225 org-mark-ring)
11227 (defun org-mark-ring-push (&optional pos buffer)
11228 "Put the current position or POS into the mark ring and rotate it."
11229 (interactive)
11230 (setq pos (or pos (point)))
11231 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11232 (move-marker (car org-mark-ring)
11233 (or pos (point))
11234 (or buffer (current-buffer)))
11235 (message "%s"
11236 (substitute-command-keys
11237 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11239 (defun org-mark-ring-goto (&optional n)
11240 "Jump to the previous position in the mark ring.
11241 With prefix arg N, jump back that many stored positions. When
11242 called several times in succession, walk through the entire ring.
11243 Org-mode commands jumping to a different position in the current file,
11244 or to another Org-mode file, automatically push the old position
11245 onto the ring."
11246 (interactive "p")
11247 (let (p m)
11248 (if (eq last-command this-command)
11249 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11250 (setq p org-mark-ring))
11251 (setq org-mark-ring-last-goto p)
11252 (setq m (car p))
11253 (org-pop-to-buffer-same-window (marker-buffer m))
11254 (goto-char m)
11255 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11257 (defun org-remove-angle-brackets (s)
11258 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11259 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11261 (defun org-add-angle-brackets (s)
11262 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11263 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11265 (defun org-remove-double-quotes (s)
11266 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11267 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11270 ;;; Following specific links
11272 (defun org-follow-timestamp-link ()
11273 "Open an agenda view for the time-stamp date/range at point."
11274 (cond
11275 ((org-at-date-range-p t)
11276 (let ((org-agenda-start-on-weekday)
11277 (t1 (match-string 1))
11278 (t2 (match-string 2)) tt1 tt2)
11279 (setq tt1 (time-to-days (org-time-string-to-time t1))
11280 tt2 (time-to-days (org-time-string-to-time t2)))
11281 (let ((org-agenda-buffer-tmp-name
11282 (format "*Org Agenda(a:%s)"
11283 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11284 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11285 ((org-at-timestamp-p t)
11286 (let ((org-agenda-buffer-tmp-name
11287 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11288 (org-agenda-list nil (time-to-days (org-time-string-to-time
11289 (substring (match-string 1) 0 10)))
11290 1)))
11291 (t (error "This should not happen"))))
11294 ;;; Following file links
11295 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11296 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11297 (declare-function mailcap-mime-info
11298 "mailcap" (string &optional request no-decode))
11299 (defvar org-wait nil)
11300 (defun org-open-file (path &optional in-emacs line search)
11301 "Open the file at PATH.
11302 First, this expands any special file name abbreviations. Then the
11303 configuration variable `org-file-apps' is checked if it contains an
11304 entry for this file type, and if yes, the corresponding command is launched.
11306 If no application is found, Emacs simply visits the file.
11308 With optional prefix argument IN-EMACS, Emacs will visit the file.
11309 With a double \\[universal-argument] \\[universal-argument] \
11310 prefix arg, Org tries to avoid opening in Emacs
11311 and to use an external application to visit the file.
11313 Optional LINE specifies a line to go to, optional SEARCH a string
11314 to search for. If LINE or SEARCH is given, the file will be
11315 opened in Emacs, unless an entry from org-file-apps that makes
11316 use of groups in a regexp matches.
11318 If you want to change the way frames are used when following a
11319 link, please customize `org-link-frame-setup'.
11321 If the file does not exist, an error is thrown."
11322 (let* ((file (if (equal path "")
11323 buffer-file-name
11324 (substitute-in-file-name (expand-file-name path))))
11325 (file-apps (append org-file-apps (org-default-apps)))
11326 (apps (org-remove-if
11327 'org-file-apps-entry-match-against-dlink-p file-apps))
11328 (apps-dlink (org-remove-if-not
11329 'org-file-apps-entry-match-against-dlink-p file-apps))
11330 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11331 (dirp (if remp nil (file-directory-p file)))
11332 (file (if (and dirp org-open-directory-means-index-dot-org)
11333 (concat (file-name-as-directory file) "index.org")
11334 file))
11335 (a-m-a-p (assq 'auto-mode apps))
11336 (dfile (downcase file))
11337 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11338 (link (cond ((and (eq line nil)
11339 (eq search nil))
11340 file)
11341 (line
11342 (concat file "::" (number-to-string line)))
11343 (search
11344 (concat file "::" search))))
11345 (dlink (downcase link))
11346 (old-buffer (current-buffer))
11347 (old-pos (point))
11348 (old-mode major-mode)
11349 ext cmd link-match-data)
11350 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11351 (setq ext (match-string 1 dfile))
11352 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11353 (setq ext (match-string 1 dfile))))
11354 (cond
11355 ((member in-emacs '((16) system))
11356 (setq cmd (cdr (assoc 'system apps))))
11357 (in-emacs (setq cmd 'emacs))
11359 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11360 (and dirp (cdr (assoc 'directory apps)))
11361 ; first, try matching against apps-dlink
11362 ; if we get a match here, store the match data for later
11363 (let ((match (assoc-default dlink apps-dlink
11364 'string-match)))
11365 (if match
11366 (progn (setq link-match-data (match-data))
11367 match)
11368 (progn (setq in-emacs (or in-emacs line search))
11369 nil))) ; if we have no match in apps-dlink,
11370 ; always open the file in emacs if line or search
11371 ; is given (for backwards compatibility)
11372 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11373 'string-match)
11374 (cdr (assoc ext apps))
11375 (cdr (assoc t apps))))))
11376 (when (eq cmd 'system)
11377 (setq cmd (cdr (assoc 'system apps))))
11378 (when (eq cmd 'default)
11379 (setq cmd (cdr (assoc t apps))))
11380 (when (eq cmd 'mailcap)
11381 (require 'mailcap)
11382 (mailcap-parse-mailcaps)
11383 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11384 (command (mailcap-mime-info mime-type)))
11385 (if (stringp command)
11386 (setq cmd command)
11387 (setq cmd 'emacs))))
11388 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11389 (not (file-exists-p file))
11390 (not org-open-non-existing-files))
11391 (user-error "No such file: %s" file))
11392 (cond
11393 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11394 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11395 (while (string-match "['\"]%s['\"]" cmd)
11396 (setq cmd (replace-match "%s" t t cmd)))
11397 (while (string-match "%s" cmd)
11398 (setq cmd (replace-match
11399 (save-match-data
11400 (shell-quote-argument
11401 (convert-standard-filename file)))
11402 t t cmd)))
11404 ;; Replace "%1", "%2" etc. in command with group matches from regex
11405 (save-match-data
11406 (let ((match-index 1)
11407 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11408 (set-match-data link-match-data)
11409 (while (<= match-index number-of-groups)
11410 (let ((regex (concat "%" (number-to-string match-index)))
11411 (replace-with (match-string match-index dlink)))
11412 (while (string-match regex cmd)
11413 (setq cmd (replace-match replace-with t t cmd))))
11414 (setq match-index (+ match-index 1)))))
11416 (save-window-excursion
11417 (message "Running %s...done" cmd)
11418 (start-process-shell-command cmd nil cmd)
11419 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11420 ((or (stringp cmd)
11421 (eq cmd 'emacs))
11422 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11423 (widen)
11424 (if line (progn (org-goto-line line)
11425 (if (derived-mode-p 'org-mode)
11426 (org-reveal)))
11427 (if search (org-link-search search))))
11428 ((consp cmd)
11429 (let ((file (convert-standard-filename file)))
11430 (save-match-data
11431 (set-match-data link-match-data)
11432 (eval cmd))))
11433 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11434 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11435 (or (not (equal old-buffer (current-buffer)))
11436 (not (equal old-pos (point))))
11437 (org-mark-ring-push old-pos old-buffer))))
11439 (defun org-file-apps-entry-match-against-dlink-p (entry)
11440 "This function returns non-nil if `entry' uses a regular
11441 expression which should be matched against the whole link by
11442 org-open-file.
11444 It assumes that is the case when the entry uses a regular
11445 expression which has at least one grouping construct and the
11446 action is either a lisp form or a command string containing
11447 `%1', i.e. using at least one subexpression match as a
11448 parameter."
11449 (let ((selector (car entry))
11450 (action (cdr entry)))
11451 (if (stringp selector)
11452 (and (> (regexp-opt-depth selector) 0)
11453 (or (and (stringp action)
11454 (string-match "%[0-9]" action))
11455 (consp action)))
11456 nil)))
11458 (defun org-default-apps ()
11459 "Return the default applications for this operating system."
11460 (cond
11461 ((eq system-type 'darwin)
11462 org-file-apps-defaults-macosx)
11463 ((eq system-type 'windows-nt)
11464 org-file-apps-defaults-windowsnt)
11465 (t org-file-apps-defaults-gnu)))
11467 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11468 "Convert extensions to regular expressions in the cars of LIST.
11469 Also, weed out any non-string entries, because the return value is used
11470 only for regexp matching.
11471 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11472 point to the symbol `emacs', indicating that the file should
11473 be opened in Emacs."
11474 (append
11475 (delq nil
11476 (mapcar (lambda (x)
11477 (if (not (stringp (car x)))
11479 (if (string-match "\\W" (car x))
11481 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11482 list))
11483 (if add-auto-mode
11484 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11486 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11487 (defun org-file-remote-p (file)
11488 "Test whether FILE specifies a location on a remote system.
11489 Return non-nil if the location is indeed remote.
11491 For example, the filename \"/user@host:/foo\" specifies a location
11492 on the system \"/user@host:\"."
11493 (cond ((fboundp 'file-remote-p)
11494 (file-remote-p file))
11495 ((fboundp 'tramp-handle-file-remote-p)
11496 (tramp-handle-file-remote-p file))
11497 ((and (boundp 'ange-ftp-name-format)
11498 (string-match (car ange-ftp-name-format) file))
11499 t)))
11502 ;;;; Refiling
11504 (defun org-get-org-file ()
11505 "Read a filename, with default directory `org-directory'."
11506 (let ((default (or org-default-notes-file remember-data-file)))
11507 (read-file-name (format "File name [%s]: " default)
11508 (file-name-as-directory org-directory)
11509 default)))
11511 (defun org-notes-order-reversed-p ()
11512 "Check if the current file should receive notes in reversed order."
11513 (cond
11514 ((not org-reverse-note-order) nil)
11515 ((eq t org-reverse-note-order) t)
11516 ((not (listp org-reverse-note-order)) nil)
11517 (t (catch 'exit
11518 (dolist (entry org-reverse-note-order)
11519 (if (string-match (car entry) buffer-file-name)
11520 (throw 'exit (cdr entry))))))))
11522 (defvar org-refile-target-table nil
11523 "The list of refile targets, created by `org-refile'.")
11525 (defvar org-agenda-new-buffers nil
11526 "Buffers created to visit agenda files.")
11528 (defvar org-refile-cache nil
11529 "Cache for refile targets.")
11531 (defvar org-refile-markers nil
11532 "All the markers used for caching refile locations.")
11534 (defun org-refile-marker (pos)
11535 "Get a new refile marker, but only if caching is in use."
11536 (if (not org-refile-use-cache)
11538 (let ((m (make-marker)))
11539 (move-marker m pos)
11540 (push m org-refile-markers)
11541 m)))
11543 (defun org-refile-cache-clear ()
11544 "Clear the refile cache and disable all the markers."
11545 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11546 (setq org-refile-markers nil)
11547 (setq org-refile-cache nil)
11548 (message "Refile cache has been cleared"))
11550 (defun org-refile-cache-check-set (set)
11551 "Check if all the markers in the cache still have live buffers."
11552 (let (marker)
11553 (catch 'exit
11554 (while (and set (setq marker (nth 3 (pop set))))
11555 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11556 (when (and marker (null (marker-buffer marker)))
11557 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11558 (sit-for 3)
11559 (throw 'exit nil)))
11560 t)))
11562 (defun org-refile-cache-put (set &rest identifiers)
11563 "Push the refile targets SET into the cache, under IDENTIFIERS."
11564 (let* ((key (sha1 (prin1-to-string identifiers)))
11565 (entry (assoc key org-refile-cache)))
11566 (if entry
11567 (setcdr entry set)
11568 (push (cons key set) org-refile-cache))))
11570 (defun org-refile-cache-get (&rest identifiers)
11571 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11572 (cond
11573 ((not org-refile-cache) nil)
11574 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11576 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11577 org-refile-cache))))
11578 (and set (org-refile-cache-check-set set) set)))))
11580 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11581 "Produce a table with refile targets."
11582 (let ((case-fold-search nil)
11583 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11584 (entries (or org-refile-targets '((nil . (:level . 1)))))
11585 targets tgs txt re files desc descre fast-path-p level pos0)
11586 (message "Getting targets...")
11587 (with-current-buffer (or default-buffer (current-buffer))
11588 (dolist (entry entries)
11589 (setq files (car entry) desc (cdr entry))
11590 (setq fast-path-p nil)
11591 (cond
11592 ((null files) (setq files (list (current-buffer))))
11593 ((eq files 'org-agenda-files)
11594 (setq files (org-agenda-files 'unrestricted)))
11595 ((and (symbolp files) (fboundp files))
11596 (setq files (funcall files)))
11597 ((and (symbolp files) (boundp files))
11598 (setq files (symbol-value files))))
11599 (if (stringp files) (setq files (list files)))
11600 (cond
11601 ((eq (car desc) :tag)
11602 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11603 ((eq (car desc) :todo)
11604 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11605 ((eq (car desc) :regexp)
11606 (setq descre (cdr desc)))
11607 ((eq (car desc) :level)
11608 (setq descre (concat "^\\*\\{" (number-to-string
11609 (if org-odd-levels-only
11610 (1- (* 2 (cdr desc)))
11611 (cdr desc)))
11612 "\\}[ \t]")))
11613 ((eq (car desc) :maxlevel)
11614 (setq fast-path-p t)
11615 (setq descre (concat "^\\*\\{1," (number-to-string
11616 (if org-odd-levels-only
11617 (1- (* 2 (cdr desc)))
11618 (cdr desc)))
11619 "\\}[ \t]")))
11620 (t (error "Bad refiling target description %s" desc)))
11621 (dolist (f files)
11622 (with-current-buffer
11623 (if (bufferp f) f (org-get-agenda-file-buffer f))
11625 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11626 (progn
11627 (if (bufferp f) (setq f (buffer-file-name
11628 (buffer-base-buffer f))))
11629 (setq f (and f (expand-file-name f)))
11630 (if (eq org-refile-use-outline-path 'file)
11631 (push (list (file-name-nondirectory f) f nil nil) tgs))
11632 (save-excursion
11633 (save-restriction
11634 (widen)
11635 (goto-char (point-min))
11636 (while (re-search-forward descre nil t)
11637 (goto-char (setq pos0 (point-at-bol)))
11638 (catch 'next
11639 (when org-refile-target-verify-function
11640 (save-match-data
11641 (or (funcall org-refile-target-verify-function)
11642 (throw 'next t))))
11643 (when (and (looking-at org-complex-heading-regexp)
11644 (not (member (match-string 4) excluded-entries))
11645 (match-string 4))
11646 (setq level (org-reduced-level
11647 (- (match-end 1) (match-beginning 1)))
11648 txt (org-link-display-format (match-string 4))
11649 txt (replace-regexp-in-string "\\( *[[0-9]+/?[0-9]*%?]\\)+$" "" txt)
11650 re (format org-complex-heading-regexp-format
11651 (regexp-quote (match-string 4))))
11652 (when org-refile-use-outline-path
11653 (setq txt (mapconcat
11654 'org-protect-slash
11655 (append
11656 (if (eq org-refile-use-outline-path
11657 'file)
11658 (list (file-name-nondirectory
11659 (buffer-file-name
11660 (buffer-base-buffer))))
11661 (if (eq org-refile-use-outline-path
11662 'full-file-path)
11663 (list (buffer-file-name
11664 (buffer-base-buffer)))))
11665 (org-get-outline-path fast-path-p
11666 level txt)
11667 (list txt))
11668 "/")))
11669 (push (list txt f re (org-refile-marker (point)))
11670 tgs)))
11671 (when (= (point) pos0)
11672 ;; verification function has not moved point
11673 (goto-char (point-at-eol))))))))
11674 (when org-refile-use-cache
11675 (org-refile-cache-put tgs (buffer-file-name) descre))
11676 (setq targets (append tgs targets))))))
11677 (message "Getting targets...done")
11678 (nreverse targets)))
11680 (defun org-protect-slash (s)
11681 (while (string-match "/" s)
11682 (setq s (replace-match "\\" t t s)))
11685 (defvar org-olpa (make-vector 20 nil))
11687 (defun org-get-outline-path (&optional fastp level heading)
11688 "Return the outline path to the current entry, as a list.
11690 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11691 routine which makes outline path derivations for an entire file,
11692 avoiding backtracing. Refile target collection makes use of that."
11693 (if fastp
11694 (progn
11695 (if (> level 19)
11696 (error "Outline path failure, more than 19 levels"))
11697 (loop for i from level upto 19 do
11698 (aset org-olpa i nil))
11699 (prog1
11700 (delq nil (append org-olpa nil))
11701 (aset org-olpa level heading)))
11702 (let (rtn case-fold-search)
11703 (save-excursion
11704 (save-restriction
11705 (widen)
11706 (while (org-up-heading-safe)
11707 (when (looking-at org-complex-heading-regexp)
11708 (push (org-trim
11709 (replace-regexp-in-string
11710 ;; Remove statistical/checkboxes cookies
11711 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11712 (org-match-string-no-properties 4)))
11713 rtn)))
11714 rtn)))))
11716 (defun org-format-outline-path (path &optional width prefix separator)
11717 "Format the outline path PATH for display.
11718 WIDTH is the maximum number of characters that is available.
11719 PREFIX is a prefix to be included in the returned string,
11720 such as the file name.
11721 SEPARATOR is inserted between the different parts of the path,
11722 the default is \"/\"."
11723 (setq width (or width 79))
11724 (setq path (delq nil path))
11725 (unless (> width 0)
11726 (user-error "Argument `width' must be positive"))
11727 (setq separator (or separator "/"))
11728 (let* ((org-odd-levels-only nil)
11729 (fpath (concat
11730 prefix (and prefix path separator)
11731 (mapconcat
11732 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11733 (loop for head in path
11734 for n from 0
11735 collect (org-add-props
11736 head nil 'face
11737 (nth (% n org-n-level-faces) org-level-faces)))
11738 separator))))
11739 (when (> (length fpath) width)
11740 (if (< width 7)
11741 ;; It's unlikely that `width' will be this small, but don't
11742 ;; waste characters by adding ".." if it is.
11743 (setq fpath (substring fpath 0 width))
11744 (setf (substring fpath (- width 2)) "..")))
11745 fpath))
11747 (defun org-display-outline-path (&optional file current separator just-return-string)
11748 "Display the current outline path in the echo area.
11750 If FILE is non-nil, prepend the output with the file name.
11751 If CURRENT is non-nil, append the current heading to the output.
11752 SEPARATOR is passed through to `org-format-outline-path'. It separates
11753 the different parts of the path and defaults to \"/\".
11754 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11755 (interactive "P")
11756 (let* (case-fold-search
11757 (bfn (buffer-file-name (buffer-base-buffer)))
11758 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11759 res)
11760 (if current (setq path (append path
11761 (save-excursion
11762 (org-back-to-heading t)
11763 (if (looking-at org-complex-heading-regexp)
11764 (list (match-string 4)))))))
11765 (setq res
11766 (org-format-outline-path
11767 path
11768 (1- (frame-width))
11769 (and file bfn (concat (file-name-nondirectory bfn) separator))
11770 separator))
11771 (if just-return-string
11772 (org-no-properties res)
11773 (org-unlogged-message "%s" res))))
11775 (defvar org-refile-history nil
11776 "History for refiling operations.")
11778 (defvar org-after-refile-insert-hook nil
11779 "Hook run after `org-refile' has inserted its stuff at the new location.
11780 Note that this is still *before* the stuff will be removed from
11781 the *old* location.")
11783 (defvar org-capture-last-stored-marker)
11784 (defvar org-refile-keep nil
11785 "Non-nil means `org-refile' will copy instead of refile.")
11787 (defun org-copy ()
11788 "Like `org-refile', but copy."
11789 (interactive)
11790 (let ((org-refile-keep t))
11791 (funcall 'org-refile nil nil nil "Copy")))
11793 (defun org-refile (&optional arg default-buffer rfloc msg)
11794 "Move the entry or entries at point to another heading.
11795 The list of target headings is compiled using the information in
11796 `org-refile-targets', which see.
11798 At the target location, the entry is filed as a subitem of the
11799 target heading. Depending on `org-reverse-note-order', the new
11800 subitem will either be the first or the last subitem.
11802 If there is an active region, all entries in that region will be
11803 refiled. However, the region must fulfill the requirement that
11804 the first heading sets the top-level of the moved text.
11806 With prefix arg ARG, the command will only visit the target
11807 location and not actually move anything.
11809 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11810 refiling operation has put the subtree.
11812 With a numeric prefix argument of `2', refile to the running clock.
11814 With a numeric prefix argument of `3', emulate `org-refile-keep'
11815 being set to t and copy to the target location, don't move it.
11816 Beware that keeping refiled entries may result in duplicated ID
11817 properties.
11819 RFLOC can be a refile location obtained in a different way.
11821 MSG is a string to replace \"Refile\" in the default prompt with
11822 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11824 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11826 If you are using target caching (see `org-refile-use-cache'), you
11827 have to clear the target cache in order to find new targets.
11828 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11829 prefix argument (`C-u C-u C-u C-c C-w')."
11830 (interactive "P")
11831 (if (member arg '(0 (64)))
11832 (org-refile-cache-clear)
11833 (let* ((actionmsg (cond (msg msg)
11834 ((equal arg 3) "Refile (and keep)")
11835 (t "Refile")))
11836 (cbuf (current-buffer))
11837 (regionp (org-region-active-p))
11838 (region-start (and regionp (region-beginning)))
11839 (region-end (and regionp (region-end)))
11840 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11841 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11842 pos it nbuf file re level reversed)
11843 (setq last-command nil)
11844 (when regionp
11845 (goto-char region-start)
11846 (or (bolp) (goto-char (point-at-bol)))
11847 (setq region-start (point))
11848 (unless (or (org-kill-is-subtree-p
11849 (buffer-substring region-start region-end))
11850 (prog1 org-refile-active-region-within-subtree
11851 (let ((s (point-at-eol)))
11852 (org-toggle-heading)
11853 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11854 (user-error "The region is not a (sequence of) subtree(s)")))
11855 (if (equal arg '(16))
11856 (org-refile-goto-last-stored)
11857 (when (or
11858 (and (equal arg 2)
11859 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11860 (prog1
11861 (setq it (list (or org-clock-heading "running clock")
11862 (buffer-file-name
11863 (marker-buffer org-clock-hd-marker))
11865 (marker-position org-clock-hd-marker)))
11866 (setq arg nil)))
11867 (setq it (or rfloc
11868 (let (heading-text)
11869 (save-excursion
11870 (unless (and arg (listp arg))
11871 (org-back-to-heading t)
11872 (setq heading-text
11873 (replace-regexp-in-string
11874 org-bracket-link-regexp
11875 "\\3"
11876 (nth 4 (org-heading-components)))))
11877 (org-refile-get-location
11878 (cond ((and arg (listp arg)) "Goto")
11879 (regionp (concat actionmsg " region to"))
11880 (t (concat actionmsg " subtree \""
11881 heading-text "\" to")))
11882 default-buffer
11883 (and (not (equal '(4) arg))
11884 org-refile-allow-creating-parent-nodes)
11885 arg))))))
11886 (setq file (nth 1 it)
11887 re (nth 2 it)
11888 pos (nth 3 it))
11889 (if (and (not arg)
11891 (equal (buffer-file-name) file)
11892 (if regionp
11893 (and (>= pos region-start)
11894 (<= pos region-end))
11895 (and (>= pos (point))
11896 (< pos (save-excursion
11897 (org-end-of-subtree t t))))))
11898 (error "Cannot refile to position inside the tree or region"))
11899 (setq nbuf (or (find-buffer-visiting file)
11900 (find-file-noselect file)))
11901 (if (and arg (not (equal arg 3)))
11902 (progn
11903 (org-pop-to-buffer-same-window nbuf)
11904 (goto-char pos)
11905 (org-show-context 'org-goto))
11906 (if regionp
11907 (progn
11908 (org-kill-new (buffer-substring region-start region-end))
11909 (org-save-markers-in-region region-start region-end))
11910 (org-copy-subtree 1 nil t))
11911 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11912 (find-file-noselect file)))
11913 (setq reversed (org-notes-order-reversed-p))
11914 (save-excursion
11915 (save-restriction
11916 (widen)
11917 (if pos
11918 (progn
11919 (goto-char pos)
11920 (looking-at org-outline-regexp)
11921 (setq level (org-get-valid-level (funcall outline-level) 1))
11922 (goto-char
11923 (if reversed
11924 (or (outline-next-heading) (point-max))
11925 (or (save-excursion (org-get-next-sibling))
11926 (org-end-of-subtree t t)
11927 (point-max)))))
11928 (setq level 1)
11929 (if (not reversed)
11930 (goto-char (point-max))
11931 (goto-char (point-min))
11932 (or (outline-next-heading) (goto-char (point-max)))))
11933 (if (not (bolp)) (newline))
11934 (org-paste-subtree level nil nil t)
11935 (when org-log-refile
11936 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11937 (unless (eq org-log-refile 'note)
11938 (save-excursion (org-add-log-note))))
11939 (and org-auto-align-tags
11940 (let ((org-loop-over-headlines-in-active-region nil))
11941 (org-set-tags nil t)))
11942 (let ((bookmark-name (plist-get org-bookmark-names-plist
11943 :last-refile)))
11944 (when bookmark-name
11945 (with-demoted-errors
11946 (bookmark-set bookmark-name))))
11947 ;; If we are refiling for capture, make sure that the
11948 ;; last-capture pointers point here
11949 (when (org-bound-and-true-p org-refile-for-capture)
11950 (let ((bookmark-name (plist-get org-bookmark-names-plist
11951 :last-capture-marker)))
11952 (when bookmark-name
11953 (with-demoted-errors
11954 (bookmark-set bookmark-name))))
11955 (move-marker org-capture-last-stored-marker (point)))
11956 (if (fboundp 'deactivate-mark) (deactivate-mark))
11957 (run-hooks 'org-after-refile-insert-hook))))
11958 (unless org-refile-keep
11959 (if regionp
11960 (delete-region (point) (+ (point) (- region-end region-start)))
11961 (delete-region
11962 (and (org-back-to-heading t) (point))
11963 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11964 (when (featurep 'org-inlinetask)
11965 (org-inlinetask-remove-END-maybe))
11966 (setq org-markers-to-move nil)
11967 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11969 (defun org-refile-goto-last-stored ()
11970 "Go to the location where the last refile was stored."
11971 (interactive)
11972 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11973 (message "This is the location of the last refile"))
11975 (defun org-refile--get-location (refloc tbl)
11976 "When user refile to REFLOC, find the associated target in TBL.
11977 Also check `org-refile-target-table'."
11978 (car (delq
11980 (mapcar
11981 (lambda (r) (or (assoc r tbl)
11982 (assoc r org-refile-target-table)))
11983 (list (replace-regexp-in-string "/$" "" refloc)
11984 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11986 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11987 no-exclude)
11988 "Prompt the user for a refile location, using PROMPT.
11989 PROMPT should not be suffixed with a colon and a space, because
11990 this function appends the default value from
11991 `org-refile-history' automatically, if that is not empty.
11992 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11993 this is used for the GOTO interface."
11994 (let ((org-refile-targets org-refile-targets)
11995 (org-refile-use-outline-path org-refile-use-outline-path)
11996 excluded-entries)
11997 (when (and (derived-mode-p 'org-mode)
11998 (not org-refile-use-cache)
11999 (not no-exclude))
12000 (org-map-tree
12001 (lambda()
12002 (setq excluded-entries
12003 (append excluded-entries (list (org-get-heading t t)))))))
12004 (setq org-refile-target-table
12005 (org-refile-get-targets default-buffer excluded-entries)))
12006 (unless org-refile-target-table
12007 (user-error "No refile targets"))
12008 (let* ((cbuf (current-buffer))
12009 (partial-completion-mode nil)
12010 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12011 (cfunc (if (and org-refile-use-outline-path
12012 org-outline-path-complete-in-steps)
12013 'org-olpath-completing-read
12014 'org-icompleting-read))
12015 (extra (if org-refile-use-outline-path "/" ""))
12016 (cbnex (concat (buffer-name) extra))
12017 (filename (and cfn (expand-file-name cfn)))
12018 (tbl (mapcar
12019 (lambda (x)
12020 (if (and (not (member org-refile-use-outline-path
12021 '(file full-file-path)))
12022 (not (equal filename (nth 1 x))))
12023 (cons (concat (car x) extra " ("
12024 (file-name-nondirectory (nth 1 x)) ")")
12025 (cdr x))
12026 (cons (concat (car x) extra) (cdr x))))
12027 org-refile-target-table))
12028 (completion-ignore-case t)
12029 cdef
12030 (prompt (concat prompt
12031 (or (and (car org-refile-history)
12032 (concat " (default " (car org-refile-history) ")"))
12033 (and (assoc cbnex tbl) (setq cdef cbnex)
12034 (concat " (default " cbnex ")"))) ": "))
12035 pa answ parent-target child parent old-hist)
12036 (setq old-hist org-refile-history)
12037 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12038 nil 'org-refile-history (or cdef (car org-refile-history))))
12039 (if (setq pa (org-refile--get-location answ tbl))
12040 (progn
12041 (org-refile-check-position pa)
12042 (when (or (not org-refile-history)
12043 (not (eq old-hist org-refile-history))
12044 (not (equal (car pa) (car org-refile-history))))
12045 (setq org-refile-history
12046 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12047 org-refile-history
12048 (cdr org-refile-history))))
12049 (if (equal (car org-refile-history) (nth 1 org-refile-history))
12050 (pop org-refile-history)))
12052 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12053 (progn
12054 (setq parent (match-string 1 answ)
12055 child (match-string 2 answ))
12056 (setq parent-target (org-refile--get-location parent tbl))
12057 (when (and parent-target
12058 (or (eq new-nodes t)
12059 (and (eq new-nodes 'confirm)
12060 (y-or-n-p (format "Create new node \"%s\"? "
12061 child)))))
12062 (org-refile-new-child parent-target child)))
12063 (user-error "Invalid target location")))))
12065 (declare-function org-string-nw-p "org-macs" (s))
12066 (defun org-refile-check-position (refile-pointer)
12067 "Check if the refile pointer matches the headline to which it points."
12068 (let* ((file (nth 1 refile-pointer))
12069 (re (nth 2 refile-pointer))
12070 (pos (nth 3 refile-pointer))
12071 buffer)
12072 (if (and (not (markerp pos)) (not file))
12073 (user-error "Please indicate a target file in the refile path")
12074 (when (org-string-nw-p re)
12075 (setq buffer (if (markerp pos)
12076 (marker-buffer pos)
12077 (or (find-buffer-visiting file)
12078 (find-file-noselect file))))
12079 (with-current-buffer buffer
12080 (save-excursion
12081 (save-restriction
12082 (widen)
12083 (goto-char pos)
12084 (beginning-of-line 1)
12085 (unless (org-looking-at-p re)
12086 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12088 (defun org-refile-new-child (parent-target child)
12089 "Use refile target PARENT-TARGET to add new CHILD below it."
12090 (unless parent-target
12091 (error "Cannot find parent for new node"))
12092 (let ((file (nth 1 parent-target))
12093 (pos (nth 3 parent-target))
12094 level)
12095 (with-current-buffer (or (find-buffer-visiting file)
12096 (find-file-noselect file))
12097 (save-excursion
12098 (save-restriction
12099 (widen)
12100 (if pos
12101 (goto-char pos)
12102 (goto-char (point-max))
12103 (if (not (bolp)) (newline)))
12104 (when (looking-at org-outline-regexp)
12105 (setq level (funcall outline-level))
12106 (org-end-of-subtree t t))
12107 (org-back-over-empty-lines)
12108 (insert "\n" (make-string
12109 (if pos (org-get-valid-level level 1) 1) ?*)
12110 " " child "\n")
12111 (beginning-of-line 0)
12112 (list (concat (car parent-target) "/" child) file "" (point)))))))
12114 (defun org-olpath-completing-read (prompt collection &rest args)
12115 "Read an outline path like a file name."
12116 (let ((thetable collection)
12117 (org-completion-use-ido nil) ; does not work with ido.
12118 (org-completion-use-iswitchb nil)) ; or iswitchb
12119 (apply #'org-icompleting-read
12120 prompt
12121 (lambda (string predicate &optional flag)
12122 (cond
12123 ((eq flag nil) (try-completion string thetable))
12124 ((eq flag t)
12125 (let ((l (length string)))
12126 (mapcar (lambda (x)
12127 (let ((r (substring x l))
12128 (f (if (string-match " ([^)]*)$" x)
12129 (match-string 0 x)
12130 "")))
12131 (if (string-match "/" r)
12132 (concat string (substring r 0 (match-end 0)) f)
12133 x)))
12134 (all-completions string thetable predicate))))
12135 ;; Exact match?
12136 ((eq flag 'lambda) (assoc string thetable))))
12137 args)))
12139 ;;;; Dynamic blocks
12141 (defun org-find-dblock (name)
12142 "Find the first dynamic block with name NAME in the buffer.
12143 If not found, stay at current position and return nil."
12144 (let ((case-fold-search t) pos)
12145 (save-excursion
12146 (goto-char (point-min))
12147 (setq pos (and (re-search-forward
12148 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12149 (match-beginning 0))))
12150 (if pos (goto-char pos))
12151 pos))
12153 (defun org-create-dblock (plist)
12154 "Create a dynamic block section, with parameters taken from PLIST.
12155 PLIST must contain a :name entry which is used as the name of the block."
12156 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12157 (end-of-line 1)
12158 (newline))
12159 (let ((col (current-column))
12160 (name (plist-get plist :name)))
12161 (insert "#+BEGIN: " name)
12162 (while plist
12163 (if (eq (car plist) :name)
12164 (setq plist (cddr plist))
12165 (insert " " (prin1-to-string (pop plist)))))
12166 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12167 (beginning-of-line -2)))
12169 (defun org-prepare-dblock ()
12170 "Prepare dynamic block for refresh.
12171 This empties the block, puts the cursor at the insert position and returns
12172 the property list including an extra property :name with the block name."
12173 (unless (looking-at org-dblock-start-re)
12174 (user-error "Not at a dynamic block"))
12175 (let* ((begdel (1+ (match-end 0)))
12176 (name (org-no-properties (match-string 1)))
12177 (params (append (list :name name)
12178 (read (concat "(" (match-string 3) ")")))))
12179 (save-excursion
12180 (beginning-of-line 1)
12181 (skip-chars-forward " \t")
12182 (setq params (plist-put params :indentation-column (current-column))))
12183 (unless (re-search-forward org-dblock-end-re nil t)
12184 (error "Dynamic block not terminated"))
12185 (setq params
12186 (append params
12187 (list :content (buffer-substring
12188 begdel (match-beginning 0)))))
12189 (delete-region begdel (match-beginning 0))
12190 (goto-char begdel)
12191 (open-line 1)
12192 params))
12194 (defun org-map-dblocks (&optional command)
12195 "Apply COMMAND to all dynamic blocks in the current buffer.
12196 If COMMAND is not given, use `org-update-dblock'."
12197 (let ((cmd (or command 'org-update-dblock)))
12198 (save-excursion
12199 (goto-char (point-min))
12200 (while (re-search-forward org-dblock-start-re nil t)
12201 (goto-char (match-beginning 0))
12202 (save-excursion
12203 (condition-case nil
12204 (funcall cmd)
12205 (error (message "Error during update of dynamic block"))))
12206 (unless (re-search-forward org-dblock-end-re nil t)
12207 (error "Dynamic block not terminated"))))))
12209 (defun org-dblock-update (&optional arg)
12210 "User command for updating dynamic blocks.
12211 Update the dynamic block at point. With prefix ARG, update all dynamic
12212 blocks in the buffer."
12213 (interactive "P")
12214 (if arg
12215 (org-update-all-dblocks)
12216 (or (looking-at org-dblock-start-re)
12217 (org-beginning-of-dblock))
12218 (org-update-dblock)))
12220 (defun org-update-dblock ()
12221 "Update the dynamic block at point.
12222 This means to empty the block, parse for parameters and then call
12223 the correct writing function."
12224 (interactive)
12225 (save-excursion
12226 (let* ((win (selected-window))
12227 (pos (point))
12228 (line (org-current-line))
12229 (params (org-prepare-dblock))
12230 (name (plist-get params :name))
12231 (indent (plist-get params :indentation-column))
12232 (cmd (intern (concat "org-dblock-write:" name))))
12233 (message "Updating dynamic block `%s' at line %d..." name line)
12234 (funcall cmd params)
12235 (message "Updating dynamic block `%s' at line %d...done" name line)
12236 (goto-char pos)
12237 (when (and indent (> indent 0))
12238 (setq indent (make-string indent ?\ ))
12239 (save-excursion
12240 (select-window win)
12241 (org-beginning-of-dblock)
12242 (forward-line 1)
12243 (while (not (looking-at org-dblock-end-re))
12244 (insert indent)
12245 (beginning-of-line 2))
12246 (when (looking-at org-dblock-end-re)
12247 (and (looking-at "[ \t]+")
12248 (replace-match ""))
12249 (insert indent)))))))
12251 (defun org-beginning-of-dblock ()
12252 "Find the beginning of the dynamic block at point.
12253 Error if there is no such block at point."
12254 (let ((pos (point))
12255 beg)
12256 (end-of-line 1)
12257 (if (and (re-search-backward org-dblock-start-re nil t)
12258 (setq beg (match-beginning 0))
12259 (re-search-forward org-dblock-end-re nil t)
12260 (> (match-end 0) pos))
12261 (goto-char beg)
12262 (goto-char pos)
12263 (error "Not in a dynamic block"))))
12265 (defun org-update-all-dblocks ()
12266 "Update all dynamic blocks in the buffer.
12267 This function can be used in a hook."
12268 (interactive)
12269 (when (derived-mode-p 'org-mode)
12270 (org-map-dblocks 'org-update-dblock)))
12273 ;;;; Completion
12275 (declare-function org-export-backend-name "org-export" (cl-x))
12276 (declare-function org-export-backend-options "org-export" (cl-x))
12277 (defun org-get-export-keywords ()
12278 "Return a list of all currently understood export keywords.
12279 Export keywords include options, block names, attributes and
12280 keywords relative to each registered export back-end."
12281 (let (keywords)
12282 (dolist (backend
12283 (org-bound-and-true-p org-export-registered-backends)
12284 (delq nil keywords))
12285 ;; Back-end name (for keywords, like #+LATEX:)
12286 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12287 (dolist (option-entry (org-export-backend-options backend))
12288 ;; Back-end options.
12289 (push (nth 1 option-entry) keywords)))))
12291 (defconst org-options-keywords
12292 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12293 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12294 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12295 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12296 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12298 (defcustom org-structure-template-alist
12299 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12300 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12301 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12302 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12303 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12304 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12305 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12306 ("L" "#+LaTeX: ")
12307 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12308 ("H" "#+HTML: ")
12309 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12310 ("A" "#+ASCII: ")
12311 ("i" "#+INDEX: ?")
12312 ("I" "#+INCLUDE: %file ?"))
12313 "Structure completion elements.
12314 This is a list of abbreviation keys and values. The value gets inserted
12315 if you type `<' followed by the key and then press the completion key,
12316 usually `TAB'. %file will be replaced by a file name after prompting
12317 for the file using completion. The cursor will be placed at the position
12318 of the `?' in the template.
12319 There are two templates for each key, the first uses the original Org syntax,
12320 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12321 the default when the /org-mtags.el/ module has been loaded. See also the
12322 variable `org-mtags-prefer-muse-templates'."
12323 :group 'org-completion
12324 :type '(repeat
12325 (list
12326 (string :tag "Key")
12327 (string :tag "Template")))
12328 :version "25.1"
12329 :package-version '(Org . "8.3"))
12331 (defun org-try-structure-completion ()
12332 "Try to complete a structure template before point.
12333 This looks for strings like \"<e\" on an otherwise empty line and
12334 expands them."
12335 (let ((l (buffer-substring (point-at-bol) (point)))
12337 (when (and (looking-at "[ \t]*$")
12338 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12339 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12340 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12341 (match-beginning 1)) a)
12342 t)))
12344 (defun org-complete-expand-structure-template (start cell)
12345 "Expand a structure template."
12346 (let ((rpl (nth 1 cell))
12347 (ind ""))
12348 (delete-region start (point))
12349 (when (string-match "\\`[ \t]*#\\+" rpl)
12350 (cond
12351 ((bolp))
12352 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12353 (setq ind (buffer-substring (point-at-bol) (point))))
12354 (t (newline))))
12355 (setq start (point))
12356 (if (string-match "%file" rpl)
12357 (setq rpl (replace-match
12358 (concat
12359 "\""
12360 (save-match-data
12361 (abbreviate-file-name (read-file-name "Include file: ")))
12362 "\"")
12363 t t rpl)))
12364 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12365 (concat "\n" ind)))
12366 (insert rpl)
12367 (if (re-search-backward "\\?" start t) (delete-char 1))))
12369 ;;;; TODO, DEADLINE, Comments
12371 (defun org-toggle-comment ()
12372 "Change the COMMENT state of an entry."
12373 (interactive)
12374 (save-excursion
12375 (org-back-to-heading)
12376 (looking-at org-complex-heading-regexp)
12377 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12378 (skip-chars-forward " \t")
12379 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12380 (if (org-in-commented-heading-p t)
12381 (delete-region (point)
12382 (progn (search-forward " " (line-end-position) 'move)
12383 (skip-chars-forward " \t")
12384 (point)))
12385 (insert org-comment-string)
12386 (unless (eolp) (insert " ")))))
12388 (defvar org-last-todo-state-is-todo nil
12389 "This is non-nil when the last TODO state change led to a TODO state.
12390 If the last change removed the TODO tag or switched to DONE, then
12391 this is nil.")
12393 (defvar org-setting-tags nil) ; dynamically skipped
12395 (defvar org-todo-setup-filter-hook nil
12396 "Hook for functions that pre-filter todo specs.
12397 Each function takes a todo spec and returns either nil or the spec
12398 transformed into canonical form." )
12400 (defvar org-todo-get-default-hook nil
12401 "Hook for functions that get a default item for todo.
12402 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12403 nil or a string to be used for the todo mark." )
12405 (defvar org-agenda-headline-snapshot-before-repeat)
12407 (defun org-current-effective-time ()
12408 "Return current time adjusted for `org-extend-today-until' variable."
12409 (let* ((ct (org-current-time))
12410 (dct (decode-time ct))
12411 (ct1
12412 (cond
12413 (org-use-last-clock-out-time-as-effective-time
12414 (or (org-clock-get-last-clock-out-time) ct))
12415 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12416 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12417 (t ct))))
12418 ct1))
12420 (defun org-todo-yesterday (&optional arg)
12421 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12422 (interactive "P")
12423 (if (eq major-mode 'org-agenda-mode)
12424 (apply 'org-agenda-todo-yesterday arg)
12425 (let* ((org-use-effective-time t)
12426 (hour (third (decode-time
12427 (org-current-time))))
12428 (org-extend-today-until (1+ hour)))
12429 (org-todo arg))))
12431 (defvar org-block-entry-blocking ""
12432 "First entry preventing the TODO state change.")
12434 (defun org-cancel-repeater ()
12435 "Cancel a repeater by setting its numeric value to zero."
12436 (interactive)
12437 (save-excursion
12438 (org-back-to-heading t)
12439 (let ((bound1 (point))
12440 (bound0 (save-excursion (outline-next-heading) (point))))
12441 (when (re-search-forward
12442 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12443 org-deadline-time-regexp "\\)\\|\\("
12444 org-ts-regexp "\\)")
12445 bound0 t)
12446 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12447 (replace-match "0" t nil nil 1))))))
12449 (defun org-todo (&optional arg)
12450 "Change the TODO state of an item.
12451 The state of an item is given by a keyword at the start of the heading,
12452 like
12453 *** TODO Write paper
12454 *** DONE Call mom
12456 The different keywords are specified in the variable `org-todo-keywords'.
12457 By default the available states are \"TODO\" and \"DONE\".
12458 So for this example: when the item starts with TODO, it is changed to DONE.
12459 When it starts with DONE, the DONE is removed. And when neither TODO nor
12460 DONE are present, add TODO at the beginning of the heading.
12462 With \\[universal-argument] prefix arg, use completion to determine the new \
12463 state.
12464 With numeric prefix arg, switch to that state.
12465 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12466 keywords (nextset).
12467 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12468 With a numeric prefix arg of 0, inhibit note taking for the change.
12469 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12471 When called through ELisp, arg is also interpreted in the following way:
12472 `none' -> empty state
12473 \"\"(empty string) -> switch to empty state
12474 `done' -> switch to DONE
12475 `nextset' -> switch to the next set of keywords
12476 `previousset' -> switch to the previous set of keywords
12477 \"WAITING\" -> switch to the specified keyword, but only if it
12478 really is a member of `org-todo-keywords'."
12479 (interactive "P")
12480 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12481 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12482 'region-start-level 'region))
12483 org-loop-over-headlines-in-active-region)
12484 (org-map-entries
12485 `(org-todo ,arg)
12486 org-loop-over-headlines-in-active-region
12487 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12488 (if (equal arg '(16)) (setq arg 'nextset))
12489 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12490 (let ((org-blocker-hook org-blocker-hook)
12491 commentp
12492 case-fold-search)
12493 (when (equal arg '(64))
12494 (setq arg nil org-blocker-hook nil))
12495 (when (and org-blocker-hook
12496 (or org-inhibit-blocking
12497 (org-entry-get nil "NOBLOCKING")))
12498 (setq org-blocker-hook nil))
12499 (save-excursion
12500 (catch 'exit
12501 (org-back-to-heading t)
12502 (when (org-in-commented-heading-p t)
12503 (org-toggle-comment)
12504 (setq commentp t))
12505 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12506 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12507 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12508 (let* ((match-data (match-data))
12509 (startpos (point-at-bol))
12510 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12511 (org-log-done org-log-done)
12512 (org-log-repeat org-log-repeat)
12513 (org-todo-log-states org-todo-log-states)
12514 (org-inhibit-logging
12515 (if (equal arg 0)
12516 (progn (setq arg nil) 'note) org-inhibit-logging))
12517 (this (match-string 1))
12518 (hl-pos (match-beginning 0))
12519 (head (org-get-todo-sequence-head this))
12520 (ass (assoc head org-todo-kwd-alist))
12521 (interpret (nth 1 ass))
12522 (done-word (nth 3 ass))
12523 (final-done-word (nth 4 ass))
12524 (org-last-state (or this ""))
12525 (completion-ignore-case t)
12526 (member (member this org-todo-keywords-1))
12527 (tail (cdr member))
12528 (org-state (cond
12529 ((and org-todo-key-trigger
12530 (or (and (equal arg '(4))
12531 (eq org-use-fast-todo-selection 'prefix))
12532 (and (not arg) org-use-fast-todo-selection
12533 (not (eq org-use-fast-todo-selection
12534 'prefix)))))
12535 ;; Use fast selection
12536 (org-fast-todo-selection))
12537 ((and (equal arg '(4))
12538 (or (not org-use-fast-todo-selection)
12539 (not org-todo-key-trigger)))
12540 ;; Read a state with completion
12541 (org-icompleting-read
12542 "State: " (mapcar 'list org-todo-keywords-1)
12543 nil t))
12544 ((eq arg 'right)
12545 (if this
12546 (if tail (car tail) nil)
12547 (car org-todo-keywords-1)))
12548 ((eq arg 'left)
12549 (if (equal member org-todo-keywords-1)
12551 (if this
12552 (nth (- (length org-todo-keywords-1)
12553 (length tail) 2)
12554 org-todo-keywords-1)
12555 (org-last org-todo-keywords-1))))
12556 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12557 (setq arg nil))) ; hack to fall back to cycling
12558 (arg
12559 ;; user or caller requests a specific state
12560 (cond
12561 ((equal arg "") nil)
12562 ((eq arg 'none) nil)
12563 ((eq arg 'done) (or done-word (car org-done-keywords)))
12564 ((eq arg 'nextset)
12565 (or (car (cdr (member head org-todo-heads)))
12566 (car org-todo-heads)))
12567 ((eq arg 'previousset)
12568 (let ((org-todo-heads (reverse org-todo-heads)))
12569 (or (car (cdr (member head org-todo-heads)))
12570 (car org-todo-heads))))
12571 ((car (member arg org-todo-keywords-1)))
12572 ((stringp arg)
12573 (user-error "State `%s' not valid in this file" arg))
12574 ((nth (1- (prefix-numeric-value arg))
12575 org-todo-keywords-1))))
12576 ((null member) (or head (car org-todo-keywords-1)))
12577 ((equal this final-done-word) nil) ;; -> make empty
12578 ((null tail) nil) ;; -> first entry
12579 ((memq interpret '(type priority))
12580 (if (eq this-command last-command)
12581 (car tail)
12582 (if (> (length tail) 0)
12583 (or done-word (car org-done-keywords))
12584 nil)))
12586 (car tail))))
12587 (org-state (or
12588 (run-hook-with-args-until-success
12589 'org-todo-get-default-hook org-state org-last-state)
12590 org-state))
12591 (next (if org-state (concat " " org-state " ") " "))
12592 (change-plist (list :type 'todo-state-change :from this :to org-state
12593 :position startpos))
12594 dolog now-done-p)
12595 (when org-blocker-hook
12596 (setq org-last-todo-state-is-todo
12597 (not (member this org-done-keywords)))
12598 (unless (save-excursion
12599 (save-match-data
12600 (org-with-wide-buffer
12601 (run-hook-with-args-until-failure
12602 'org-blocker-hook change-plist))))
12603 (if (org-called-interactively-p 'interactive)
12604 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12605 this org-state org-block-entry-blocking)
12606 ;; fail silently
12607 (message "TODO state change from %s to %s blocked (by \"%s\")"
12608 this org-state org-block-entry-blocking)
12609 (throw 'exit nil))))
12610 (store-match-data match-data)
12611 (replace-match next t t)
12612 (cond ((equal this org-state)
12613 (message "TODO state was already %s" (org-trim next)))
12614 ((pos-visible-in-window-p hl-pos)
12615 (message "TODO state changed to %s" (org-trim next))))
12616 (unless head
12617 (setq head (org-get-todo-sequence-head org-state)
12618 ass (assoc head org-todo-kwd-alist)
12619 interpret (nth 1 ass)
12620 done-word (nth 3 ass)
12621 final-done-word (nth 4 ass)))
12622 (when (memq arg '(nextset previousset))
12623 (message "Keyword-Set %d/%d: %s"
12624 (- (length org-todo-sets) -1
12625 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12626 (length org-todo-sets)
12627 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12628 (setq org-last-todo-state-is-todo
12629 (not (member org-state org-done-keywords)))
12630 (setq now-done-p (and (member org-state org-done-keywords)
12631 (not (member this org-done-keywords))))
12632 (and logging (org-local-logging logging))
12633 (when (and (or org-todo-log-states org-log-done)
12634 (not (eq org-inhibit-logging t))
12635 (not (memq arg '(nextset previousset))))
12636 ;; we need to look at recording a time and note
12637 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12638 (nth 2 (assoc this org-todo-log-states))))
12639 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12640 (setq dolog 'time))
12641 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12642 (and org-state
12643 (member org-state org-not-done-keywords)
12644 (not (member this org-not-done-keywords))))
12645 ;; This is now a todo state and was not one before
12646 ;; If there was a CLOSED time stamp, get rid of it.
12647 (org-add-planning-info nil nil 'closed))
12648 (when (and now-done-p org-log-done)
12649 ;; It is now done, and it was not done before
12650 (org-add-planning-info 'closed (org-current-effective-time))
12651 (if (and (not dolog) (eq 'note org-log-done))
12652 (org-add-log-setup 'done org-state this 'findpos 'note)))
12653 (when (and org-state dolog)
12654 ;; This is a non-nil state, and we need to log it
12655 (org-add-log-setup 'state org-state this 'findpos dolog)))
12656 ;; Fixup tag positioning
12657 (org-todo-trigger-tag-changes org-state)
12658 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12659 (when org-provide-todo-statistics
12660 (org-update-parent-todo-statistics))
12661 (run-hooks 'org-after-todo-state-change-hook)
12662 (if (and arg (not (member org-state org-done-keywords)))
12663 (setq head (org-get-todo-sequence-head org-state)))
12664 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12665 ;; Do we need to trigger a repeat?
12666 (when now-done-p
12667 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12668 ;; This is for the agenda, take a snapshot of the headline.
12669 (save-match-data
12670 (setq org-agenda-headline-snapshot-before-repeat
12671 (org-get-heading))))
12672 (org-auto-repeat-maybe org-state))
12673 ;; Fixup cursor location if close to the keyword
12674 (if (and (outline-on-heading-p)
12675 (not (bolp))
12676 (save-excursion (beginning-of-line 1)
12677 (looking-at org-todo-line-regexp))
12678 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12679 (progn
12680 (goto-char (or (match-end 2) (match-end 1)))
12681 (and (looking-at " ") (just-one-space))))
12682 (when org-trigger-hook
12683 (save-excursion
12684 (run-hook-with-args 'org-trigger-hook change-plist)))
12685 (when commentp (org-toggle-comment))))))))
12687 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12688 "Block turning an entry into a TODO, using the hierarchy.
12689 This checks whether the current task should be blocked from state
12690 changes. Such blocking occurs when:
12692 1. The task has children which are not all in a completed state.
12694 2. A task has a parent with the property :ORDERED:, and there
12695 are siblings prior to the current task with incomplete
12696 status.
12698 3. The parent of the task is blocked because it has siblings that should
12699 be done first, or is child of a block grandparent TODO entry."
12701 (if (not org-enforce-todo-dependencies)
12702 t ; if locally turned off don't block
12703 (catch 'dont-block
12704 ;; If this is not a todo state change, or if this entry is already DONE,
12705 ;; do not block
12706 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12707 (member (plist-get change-plist :from)
12708 (cons 'done org-done-keywords))
12709 (member (plist-get change-plist :to)
12710 (cons 'todo org-not-done-keywords))
12711 (not (plist-get change-plist :to)))
12712 (throw 'dont-block t))
12713 ;; If this task has children, and any are undone, it's blocked
12714 (save-excursion
12715 (org-back-to-heading t)
12716 (let ((this-level (funcall outline-level)))
12717 (outline-next-heading)
12718 (let ((child-level (funcall outline-level)))
12719 (while (and (not (eobp))
12720 (> child-level this-level))
12721 ;; this todo has children, check whether they are all
12722 ;; completed
12723 (if (and (not (org-entry-is-done-p))
12724 (org-entry-is-todo-p))
12725 (progn (setq org-block-entry-blocking (org-get-heading))
12726 (throw 'dont-block nil)))
12727 (outline-next-heading)
12728 (setq child-level (funcall outline-level))))))
12729 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12730 ;; any previous siblings are undone, it's blocked
12731 (save-excursion
12732 (org-back-to-heading t)
12733 (let* ((pos (point))
12734 (parent-pos (and (org-up-heading-safe) (point))))
12735 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12736 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12737 (forward-line 1)
12738 (re-search-forward org-not-done-heading-regexp pos t))
12739 (setq org-block-entry-blocking (match-string 0))
12740 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12741 ;; Search further up the hierarchy, to see if an ancestor is blocked
12742 (while t
12743 (goto-char parent-pos)
12744 (if (not (looking-at org-not-done-heading-regexp))
12745 (throw 'dont-block t)) ; do not block, parent is not a TODO
12746 (setq pos (point))
12747 (setq parent-pos (and (org-up-heading-safe) (point)))
12748 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12749 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12750 (forward-line 1)
12751 (re-search-forward org-not-done-heading-regexp pos t)
12752 (setq org-block-entry-blocking (org-get-heading)))
12753 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12755 (defcustom org-track-ordered-property-with-tag nil
12756 "Should the ORDERED property also be shown as a tag?
12757 The ORDERED property decides if an entry should require subtasks to be
12758 completed in sequence. Since a property is not very visible, setting
12759 this option means that toggling the ORDERED property with the command
12760 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12761 not relevant for the behavior, but it makes things more visible.
12763 Note that toggling the tag with tags commands will not change the property
12764 and therefore not influence behavior!
12766 This can be t, meaning the tag ORDERED should be used, It can also be a
12767 string to select a different tag for this task."
12768 :group 'org-todo
12769 :type '(choice
12770 (const :tag "No tracking" nil)
12771 (const :tag "Track with ORDERED tag" t)
12772 (string :tag "Use other tag")))
12774 (defun org-toggle-ordered-property ()
12775 "Toggle the ORDERED property of the current entry.
12776 For better visibility, you can track the value of this property with a tag.
12777 See variable `org-track-ordered-property-with-tag'."
12778 (interactive)
12779 (let* ((t1 org-track-ordered-property-with-tag)
12780 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12781 (save-excursion
12782 (org-back-to-heading)
12783 (if (org-entry-get nil "ORDERED")
12784 (progn
12785 (org-delete-property "ORDERED")
12786 (and tag (org-toggle-tag tag 'off))
12787 (message "Subtasks can be completed in arbitrary order"))
12788 (org-entry-put nil "ORDERED" "t")
12789 (and tag (org-toggle-tag tag 'on))
12790 (message "Subtasks must be completed in sequence")))))
12792 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12793 (defun org-block-todo-from-checkboxes (change-plist)
12794 "Block turning an entry into a TODO, using checkboxes.
12795 This checks whether the current task should be blocked from state
12796 changes because there are unchecked boxes in this entry."
12797 (if (not org-enforce-todo-checkbox-dependencies)
12798 t ; if locally turned off don't block
12799 (catch 'dont-block
12800 ;; If this is not a todo state change, or if this entry is already DONE,
12801 ;; do not block
12802 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12803 (member (plist-get change-plist :from)
12804 (cons 'done org-done-keywords))
12805 (member (plist-get change-plist :to)
12806 (cons 'todo org-not-done-keywords))
12807 (not (plist-get change-plist :to)))
12808 (throw 'dont-block t))
12809 ;; If this task has checkboxes that are not checked, it's blocked
12810 (save-excursion
12811 (org-back-to-heading t)
12812 (let ((beg (point)) end)
12813 (outline-next-heading)
12814 (setq end (point))
12815 (goto-char beg)
12816 (if (org-list-search-forward
12817 (concat (org-item-beginning-re)
12818 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12819 "\\[[- ]\\]")
12820 end t)
12821 (progn
12822 (if (boundp 'org-blocked-by-checkboxes)
12823 (setq org-blocked-by-checkboxes t))
12824 (throw 'dont-block nil)))))
12825 t))) ; do not block
12827 (defun org-entry-blocked-p ()
12828 "Non-nil if entry at point is blocked."
12829 (and (not (org-entry-get nil "NOBLOCKING"))
12830 (member (org-entry-get nil "TODO") org-not-done-keywords)
12831 (not (run-hook-with-args-until-failure
12832 'org-blocker-hook
12833 (list :type 'todo-state-change
12834 :position (point)
12835 :from 'todo
12836 :to 'done)))))
12838 (defun org-update-statistics-cookies (all)
12839 "Update the statistics cookie, either from TODO or from checkboxes.
12840 This should be called with the cursor in a line with a statistics cookie."
12841 (interactive "P")
12842 (if all
12843 (progn
12844 (org-update-checkbox-count 'all)
12845 (org-map-entries 'org-update-parent-todo-statistics))
12846 (if (not (org-at-heading-p))
12847 (org-update-checkbox-count)
12848 (let ((pos (point-marker))
12849 end l1 l2)
12850 (ignore-errors (org-back-to-heading t))
12851 (if (not (org-at-heading-p))
12852 (org-update-checkbox-count)
12853 (setq l1 (org-outline-level))
12854 (setq end (save-excursion
12855 (outline-next-heading)
12856 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12857 (point)))
12858 (if (and (save-excursion
12859 (re-search-forward
12860 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12861 (not (save-excursion (re-search-forward
12862 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12863 (org-update-checkbox-count)
12864 (if (and l2 (> l2 l1))
12865 (progn
12866 (goto-char end)
12867 (org-update-parent-todo-statistics))
12868 (goto-char pos)
12869 (beginning-of-line 1)
12870 (while (re-search-forward
12871 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12872 (point-at-eol) t)
12873 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12874 (goto-char pos)
12875 (move-marker pos nil)))))
12877 (defvar org-entry-property-inherited-from) ;; defined below
12878 (defun org-update-parent-todo-statistics ()
12879 "Update any statistics cookie in the parent of the current headline.
12880 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12881 the entire subtree and this will travel up the hierarchy and update
12882 statistics everywhere."
12883 (let* ((prop (save-excursion (org-up-heading-safe)
12884 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12885 (recursive (or (not org-hierarchical-todo-statistics)
12886 (and prop (string-match "\\<recursive\\>" prop))))
12887 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12889 (first t)
12890 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12891 level ltoggle l1 new ndel
12892 (cnt-all 0) (cnt-done 0) is-percent kwd
12893 checkbox-beg ov ovs ove cookie-present)
12894 (catch 'exit
12895 (save-excursion
12896 (beginning-of-line 1)
12897 (setq ltoggle (funcall outline-level))
12898 ;; Three situations are to consider:
12900 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12901 ;; to the top-level ancestor on the headline;
12903 ;; 2. If parent has "recursive" property, repeat up to the
12904 ;; headline setting that property, taking inheritance into
12905 ;; account;
12907 ;; 3. Else, move up to direct parent and proceed only once.
12908 (while (and (setq level (org-up-heading-safe))
12909 (or recursive first)
12910 (>= (point) lim))
12911 (setq first nil cookie-present nil)
12912 (unless (and level
12913 (not (string-match
12914 "\\<checkbox\\>"
12915 (downcase (or (org-entry-get nil "COOKIE_DATA")
12916 "")))))
12917 (throw 'exit nil))
12918 (while (re-search-forward box-re (point-at-eol) t)
12919 (setq cnt-all 0 cnt-done 0 cookie-present t)
12920 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12921 (save-match-data
12922 (unless (outline-next-heading) (throw 'exit nil))
12923 (while (and (looking-at org-complex-heading-regexp)
12924 (> (setq l1 (length (match-string 1))) level))
12925 (setq kwd (and (or recursive (= l1 ltoggle))
12926 (match-string 2)))
12927 (if (or (eq org-provide-todo-statistics 'all-headlines)
12928 (and (eq org-provide-todo-statistics t)
12929 (or (member kwd org-done-keywords)))
12930 (and (listp org-provide-todo-statistics)
12931 (stringp (car org-provide-todo-statistics))
12932 (or (member kwd org-provide-todo-statistics)
12933 (member kwd org-done-keywords)))
12934 (and (listp org-provide-todo-statistics)
12935 (listp (car org-provide-todo-statistics))
12936 (or (member kwd (car org-provide-todo-statistics))
12937 (and (member kwd org-done-keywords)
12938 (member kwd (cadr org-provide-todo-statistics))))))
12939 (setq cnt-all (1+ cnt-all))
12940 (if (eq org-provide-todo-statistics t)
12941 (and kwd (setq cnt-all (1+ cnt-all)))))
12942 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12943 (member kwd org-done-keywords))
12944 (and (listp org-provide-todo-statistics)
12945 (listp (car org-provide-todo-statistics))
12946 (member kwd org-done-keywords)
12947 (member kwd (cadr org-provide-todo-statistics)))
12948 (and (listp org-provide-todo-statistics)
12949 (stringp (car org-provide-todo-statistics))
12950 (member kwd org-done-keywords)))
12951 (setq cnt-done (1+ cnt-done)))
12952 (outline-next-heading)))
12953 (setq new
12954 (if is-percent
12955 (format "[%d%%]" (floor (* 100.0 cnt-done)
12956 (max 1 cnt-all)))
12957 (format "[%d/%d]" cnt-done cnt-all))
12958 ndel (- (match-end 0) checkbox-beg))
12959 ;; handle overlays when updating cookie from column view
12960 (when (setq ov (car (overlays-at checkbox-beg)))
12961 (setq ovs (overlay-start ov) ove (overlay-end ov))
12962 (delete-overlay ov))
12963 (goto-char checkbox-beg)
12964 (insert new)
12965 (delete-region (point) (+ (point) ndel))
12966 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12967 (when ov (move-overlay ov ovs ove)))
12968 (when cookie-present
12969 (run-hook-with-args 'org-after-todo-statistics-hook
12970 cnt-done (- cnt-all cnt-done))))))
12971 (run-hooks 'org-todo-statistics-hook)))
12973 (defvar org-after-todo-statistics-hook nil
12974 "Hook that is called after a TODO statistics cookie has been updated.
12975 Each function is called with two arguments: the number of not-done entries
12976 and the number of done entries.
12978 For example, the following function, when added to this hook, will switch
12979 an entry to DONE when all children are done, and back to TODO when new
12980 entries are set to a TODO status. Note that this hook is only called
12981 when there is a statistics cookie in the headline!
12983 (defun org-summary-todo (n-done n-not-done)
12984 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12985 (let (org-log-done org-log-states) ; turn off logging
12986 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12989 (defvar org-todo-statistics-hook nil
12990 "Hook that is run whenever Org thinks TODO statistics should be updated.
12991 This hook runs even if there is no statistics cookie present, in which case
12992 `org-after-todo-statistics-hook' would not run.")
12994 (defun org-todo-trigger-tag-changes (state)
12995 "Apply the changes defined in `org-todo-state-tags-triggers'."
12996 (let ((l org-todo-state-tags-triggers)
12997 changes)
12998 (when (or (not state) (equal state ""))
12999 (setq changes (append changes (cdr (assoc "" l)))))
13000 (when (and (stringp state) (> (length state) 0))
13001 (setq changes (append changes (cdr (assoc state l)))))
13002 (when (member state org-not-done-keywords)
13003 (setq changes (append changes (cdr (assoc 'todo l)))))
13004 (when (member state org-done-keywords)
13005 (setq changes (append changes (cdr (assoc 'done l)))))
13006 (dolist (c changes)
13007 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13009 (defun org-local-logging (value)
13010 "Get logging settings from a property VALUE."
13011 ;; Directly set the variables, they are already local.
13012 (setq org-log-done nil
13013 org-log-repeat nil
13014 org-todo-log-states nil)
13015 (dolist (w (org-split-string value))
13016 (let (a)
13017 (cond
13018 ((setq a (assoc w org-startup-options))
13019 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13020 (set (nth 1 a) (nth 2 a))))
13021 ((setq a (org-extract-log-state-settings w))
13022 (and (member (car a) org-todo-keywords-1)
13023 (push a org-todo-log-states)))))))
13025 (defun org-get-todo-sequence-head (kwd)
13026 "Return the head of the TODO sequence to which KWD belongs.
13027 If KWD is not set, check if there is a text property remembering the
13028 right sequence."
13029 (let (p)
13030 (cond
13031 ((not kwd)
13032 (or (get-text-property (point-at-bol) 'org-todo-head)
13033 (progn
13034 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13035 nil (point-at-eol)))
13036 (get-text-property p 'org-todo-head))))
13037 ((not (member kwd org-todo-keywords-1))
13038 (car org-todo-keywords-1))
13039 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13041 (defun org-fast-todo-selection ()
13042 "Fast TODO keyword selection with single keys.
13043 Returns the new TODO keyword, or nil if no state change should occur."
13044 (let* ((fulltable org-todo-key-alist)
13045 (done-keywords org-done-keywords) ;; needed for the faces.
13046 (maxlen (apply 'max (mapcar
13047 (lambda (x)
13048 (if (stringp (car x)) (string-width (car x)) 0))
13049 fulltable)))
13050 (expert nil)
13051 (fwidth (+ maxlen 3 1 3))
13052 (ncol (/ (- (window-width) 4) fwidth))
13053 tg cnt e c tbl
13054 groups ingroup)
13055 (save-excursion
13056 (save-window-excursion
13057 (if expert
13058 (set-buffer (get-buffer-create " *Org todo*"))
13059 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13060 (erase-buffer)
13061 (setq-local org-done-keywords done-keywords)
13062 (setq tbl fulltable cnt 0)
13063 (while (setq e (pop tbl))
13064 (cond
13065 ((equal e '(:startgroup))
13066 (push '() groups) (setq ingroup t)
13067 (when (not (= cnt 0))
13068 (setq cnt 0)
13069 (insert "\n"))
13070 (insert "{ "))
13071 ((equal e '(:endgroup))
13072 (setq ingroup nil cnt 0)
13073 (insert "}\n"))
13074 ((equal e '(:newline))
13075 (when (not (= cnt 0))
13076 (setq cnt 0)
13077 (insert "\n")
13078 (setq e (car tbl))
13079 (while (equal (car tbl) '(:newline))
13080 (insert "\n")
13081 (setq tbl (cdr tbl)))))
13083 (setq tg (car e) c (cdr e))
13084 (if ingroup (push tg (car groups)))
13085 (setq tg (org-add-props tg nil 'face
13086 (org-get-todo-face tg)))
13087 (if (and (= cnt 0) (not ingroup)) (insert " "))
13088 (insert "[" c "] " tg (make-string
13089 (- fwidth 4 (length tg)) ?\ ))
13090 (when (= (setq cnt (1+ cnt)) ncol)
13091 (insert "\n")
13092 (if ingroup (insert " "))
13093 (setq cnt 0)))))
13094 (insert "\n")
13095 (goto-char (point-min))
13096 (if (not expert) (org-fit-window-to-buffer))
13097 (message "[a-z..]:Set [SPC]:clear")
13098 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13099 (cond
13100 ((or (= c ?\C-g)
13101 (and (= c ?q) (not (rassoc c fulltable))))
13102 (setq quit-flag t))
13103 ((= c ?\ ) nil)
13104 ((setq e (rassoc c fulltable) tg (car e))
13106 (t (setq quit-flag t)))))))
13108 (defun org-entry-is-todo-p ()
13109 (member (org-get-todo-state) org-not-done-keywords))
13111 (defun org-entry-is-done-p ()
13112 (member (org-get-todo-state) org-done-keywords))
13114 (defun org-get-todo-state ()
13115 "Return the TODO keyword of the current subtree."
13116 (save-excursion
13117 (org-back-to-heading t)
13118 (and (looking-at org-todo-line-regexp)
13119 (match-end 2)
13120 (match-string 2))))
13122 (defun org-at-date-range-p (&optional inactive-ok)
13123 "Non-nil if point is inside a date range.
13125 When optional argument INACTIVE-OK is non-nil, also consider
13126 inactive time ranges.
13128 When this function returns a non-nil value, match data is set
13129 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13130 on INACTIVE-OK."
13131 (interactive)
13132 (save-excursion
13133 (catch 'exit
13134 (let ((pos (point)))
13135 (skip-chars-backward "^[<\r\n")
13136 (skip-chars-backward "<[")
13137 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13138 (>= (match-end 0) pos)
13139 (throw 'exit t))
13140 (skip-chars-backward "^<[\r\n")
13141 (skip-chars-backward "<[")
13142 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13143 (>= (match-end 0) pos)
13144 (throw 'exit t)))
13145 nil)))
13147 (defun org-get-repeat (&optional tagline)
13148 "Check if there is a deadline/schedule with repeater in this entry."
13149 (save-match-data
13150 (save-excursion
13151 (org-back-to-heading t)
13152 (and (re-search-forward (if tagline
13153 (concat tagline "\\s-*" org-repeat-re)
13154 org-repeat-re)
13155 (org-entry-end-position) t)
13156 (match-string-no-properties 1)))))
13158 (defvar org-last-changed-timestamp)
13159 (defvar org-last-inserted-timestamp)
13160 (defvar org-log-post-message)
13161 (defvar org-log-note-purpose)
13162 (defvar org-log-note-how nil)
13163 (defvar org-log-note-extra)
13164 (defun org-auto-repeat-maybe (done-word)
13165 "Check if the current headline contains a repeated deadline/schedule.
13166 If yes, set TODO state back to what it was and change the base date
13167 of repeating deadline/scheduled time stamps to new date.
13168 This function is run automatically after each state change to a DONE state."
13169 ;; last-state is dynamically scoped into this function
13170 (let* ((repeat (org-get-repeat))
13171 (aa (assoc org-last-state org-todo-kwd-alist))
13172 (interpret (nth 1 aa))
13173 (head (nth 2 aa))
13174 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13175 (msg "Entry repeats: ")
13176 (org-log-done nil)
13177 (org-todo-log-states nil)
13178 re type n what ts time to-state)
13179 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13180 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13181 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13182 org-todo-repeat-to-state))
13183 (unless (and to-state (member to-state org-todo-keywords-1))
13184 (setq to-state (if (eq interpret 'type) org-last-state head)))
13185 (org-todo to-state)
13186 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13187 (org-entry-put nil "LAST_REPEAT" (format-time-string
13188 (org-time-stamp-format t t))))
13189 (when org-log-repeat
13190 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13191 (memq 'org-add-log-note post-command-hook))
13192 ;; OK, we are already setup for some record
13193 (if (eq org-log-repeat 'note)
13194 ;; make sure we take a note, not only a time stamp
13195 (setq org-log-note-how 'note))
13196 ;; Set up for taking a record
13197 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13198 org-last-state
13199 'findpos org-log-repeat)))
13200 (org-back-to-heading t)
13201 (org-add-planning-info nil nil 'closed)
13202 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13203 org-deadline-time-regexp "\\)\\|\\("
13204 org-ts-regexp "\\)"))
13205 (while (re-search-forward
13206 re (save-excursion (outline-next-heading) (point)) t)
13207 (setq type (if (match-end 1) org-scheduled-string
13208 (if (match-end 3) org-deadline-string "Plain:"))
13209 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13210 (if (not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13211 (org-remove-timestamp-with-keyword org-scheduled-string)
13212 (setq n (string-to-number (match-string 2 ts))
13213 what (match-string 3 ts))
13214 (if (equal what "w") (setq n (* n 7) what "d"))
13215 (if (and (equal what "h")
13216 (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13217 (user-error
13218 "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13219 ;; Preparation, see if we need to modify the start date for the change
13220 (when (match-end 1)
13221 (setq time (save-match-data (org-time-string-to-time ts)))
13222 (cond
13223 ((equal (match-string 1 ts) ".")
13224 ;; Shift starting date to today
13225 (org-timestamp-change
13226 (- (org-today) (time-to-days time))
13227 'day))
13228 ((equal (match-string 1 ts) "+")
13229 (let ((nshiftmax 10) (nshift 0))
13230 (while (or (= nshift 0)
13231 (<= (time-to-days time)
13232 (time-to-days (current-time))))
13233 (when (= (incf nshift) nshiftmax)
13234 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13235 (user-error "Abort")))
13236 (org-timestamp-change n (cdr (assoc what whata)))
13237 (org-at-timestamp-p t)
13238 (setq ts (match-string 1))
13239 (setq time (save-match-data (org-time-string-to-time ts)))))
13240 (org-timestamp-change (- n) (cdr (assoc what whata)))
13241 ;; rematch, so that we have everything in place for the real shift
13242 (org-at-timestamp-p t)
13243 (setq ts (match-string 1))
13244 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13245 (save-excursion
13246 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13247 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13248 (setq org-log-post-message msg)
13249 (message "%s" msg))))
13251 (defun org-show-todo-tree (arg)
13252 "Make a compact tree which shows all headlines marked with TODO.
13253 The tree will show the lines where the regexp matches, and all higher
13254 headlines above the match.
13255 With a \\[universal-argument] prefix, prompt for a regexp to match.
13256 With a numeric prefix N, construct a sparse tree for the Nth element
13257 of `org-todo-keywords-1'."
13258 (interactive "P")
13259 (let ((case-fold-search nil)
13260 (kwd-re
13261 (cond ((null arg) org-not-done-regexp)
13262 ((equal arg '(4))
13263 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13264 (mapcar 'list org-todo-keywords-1))))
13265 (concat "\\("
13266 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13267 "\\)\\>")))
13268 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13269 (regexp-quote (nth (1- (prefix-numeric-value arg))
13270 org-todo-keywords-1)))
13271 (t (user-error "Invalid prefix argument: %s" arg)))))
13272 (message "%d TODO entries found"
13273 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13275 (defun org-deadline (arg &optional time)
13276 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13277 With one universal prefix argument, remove any deadline from the item.
13278 With two universal prefix arguments, prompt for a warning delay.
13279 With argument TIME, set the deadline at the corresponding date. TIME
13280 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13281 (interactive "P")
13282 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13283 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13284 'region-start-level 'region))
13285 org-loop-over-headlines-in-active-region)
13286 (org-map-entries
13287 `(org-deadline ',arg ,time)
13288 org-loop-over-headlines-in-active-region
13289 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13290 (let* ((old-date (org-entry-get nil "DEADLINE"))
13291 (old-date-time (if old-date (org-time-string-to-time old-date)))
13292 (repeater (and old-date
13293 (string-match
13294 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13295 old-date)
13296 (match-string 1 old-date))))
13297 (cond
13298 ((equal arg '(4))
13299 (when (and old-date org-log-redeadline)
13300 (org-add-log-setup 'deldeadline nil old-date 'findpos
13301 org-log-redeadline))
13302 (org-remove-timestamp-with-keyword org-deadline-string)
13303 (message "Item no longer has a deadline."))
13304 ((equal arg '(16))
13305 (save-excursion
13306 (org-back-to-heading t)
13307 (if (re-search-forward
13308 org-deadline-time-regexp
13309 (save-excursion (outline-next-heading) (point)) t)
13310 (let* ((rpl0 (match-string 1))
13311 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13312 (replace-match
13313 (concat org-deadline-string
13314 " <" rpl
13315 (format " -%dd"
13316 (abs
13317 (- (time-to-days
13318 (save-match-data
13319 (org-read-date nil t nil "Warn starting from" old-date-time)))
13320 (time-to-days old-date-time))))
13321 ">") t t))
13322 (user-error "No deadline information to update"))))
13324 (org-add-planning-info 'deadline time 'closed)
13325 (when (and old-date
13326 org-log-redeadline
13327 (not (equal old-date org-last-inserted-timestamp)))
13328 (org-add-log-setup
13329 'redeadline org-last-inserted-timestamp old-date 'findpos
13330 org-log-redeadline))
13331 (when repeater
13332 (save-excursion
13333 (org-back-to-heading t)
13334 (when (re-search-forward (concat org-deadline-string " "
13335 org-last-inserted-timestamp)
13336 (save-excursion
13337 (outline-next-heading) (point)) t)
13338 (goto-char (1- (match-end 0)))
13339 (insert " " repeater)
13340 (setq org-last-inserted-timestamp
13341 (concat (substring org-last-inserted-timestamp 0 -1)
13342 " " repeater
13343 (substring org-last-inserted-timestamp -1))))))
13344 (message "Deadline on %s" org-last-inserted-timestamp))))))
13346 (defun org-schedule (arg &optional time)
13347 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13348 With one universal prefix argument, remove any scheduling date from the item.
13349 With two universal prefix arguments, prompt for a delay cookie.
13350 With argument TIME, scheduled at the corresponding date. TIME can
13351 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13352 (interactive "P")
13353 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13354 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13355 'region-start-level 'region))
13356 org-loop-over-headlines-in-active-region)
13357 (org-map-entries
13358 `(org-schedule ',arg ,time)
13359 org-loop-over-headlines-in-active-region
13360 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13361 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13362 (old-date-time (if old-date (org-time-string-to-time old-date)))
13363 (repeater (and old-date
13364 (string-match
13365 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13366 old-date)
13367 (match-string 1 old-date))))
13368 (cond
13369 ((equal arg '(4))
13370 (progn
13371 (when (and old-date org-log-reschedule)
13372 (org-add-log-setup 'delschedule nil old-date 'findpos
13373 org-log-reschedule))
13374 (org-remove-timestamp-with-keyword org-scheduled-string)
13375 (message "Item is no longer scheduled.")))
13376 ((equal arg '(16))
13377 (save-excursion
13378 (org-back-to-heading t)
13379 (if (re-search-forward
13380 org-scheduled-time-regexp
13381 (save-excursion (outline-next-heading) (point)) t)
13382 (let* ((rpl0 (match-string 1))
13383 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13384 (replace-match
13385 (concat org-scheduled-string
13386 " <" rpl
13387 (format " -%dd"
13388 (abs
13389 (- (time-to-days
13390 (save-match-data
13391 (org-read-date nil t nil "Delay until" old-date-time)))
13392 (time-to-days old-date-time))))
13393 ">") t t))
13394 (user-error "No scheduled information to update"))))
13396 (org-add-planning-info 'scheduled time 'closed)
13397 (when (and old-date
13398 org-log-reschedule
13399 (not (equal old-date org-last-inserted-timestamp)))
13400 (org-add-log-setup
13401 'reschedule org-last-inserted-timestamp old-date 'findpos
13402 org-log-reschedule))
13403 (when repeater
13404 (save-excursion
13405 (org-back-to-heading t)
13406 (when (re-search-forward (concat org-scheduled-string " "
13407 org-last-inserted-timestamp)
13408 (save-excursion
13409 (outline-next-heading) (point)) t)
13410 (goto-char (1- (match-end 0)))
13411 (insert " " repeater)
13412 (setq org-last-inserted-timestamp
13413 (concat (substring org-last-inserted-timestamp 0 -1)
13414 " " repeater
13415 (substring org-last-inserted-timestamp -1))))))
13416 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13418 (defun org-get-scheduled-time (pom &optional inherit)
13419 "Get the scheduled time as a time tuple, of a format suitable
13420 for calling org-schedule with, or if there is no scheduling,
13421 returns nil."
13422 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13423 (when time
13424 (apply 'encode-time (org-parse-time-string time)))))
13426 (defun org-get-deadline-time (pom &optional inherit)
13427 "Get the deadline as a time tuple, of a format suitable for
13428 calling org-deadline with, or if there is no scheduling, returns
13429 nil."
13430 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13431 (when time
13432 (apply 'encode-time (org-parse-time-string time)))))
13434 (defun org-remove-timestamp-with-keyword (keyword)
13435 "Remove all time stamps with KEYWORD in the current entry."
13436 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13437 beg)
13438 (save-excursion
13439 (org-back-to-heading t)
13440 (setq beg (point))
13441 (outline-next-heading)
13442 (while (re-search-backward re beg t)
13443 (replace-match "")
13444 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13445 (equal (char-before) ?\ ))
13446 (backward-delete-char 1)
13447 (if (string-match "^[ \t]*$" (buffer-substring
13448 (point-at-bol) (point-at-eol)))
13449 (delete-region (point-at-bol)
13450 (min (point-max) (1+ (point-at-eol))))))))))
13452 (defvar org-time-was-given) ; dynamically scoped parameter
13453 (defvar org-end-time-was-given) ; dynamically scoped parameter
13455 (defun org-at-planning-p ()
13456 "Non-nil when point is on a planning info line."
13457 ;; This is as accurate and faster than `org-element-at-point' since
13458 ;; planning info location is fixed in the section.
13459 (org-with-wide-buffer
13460 (beginning-of-line)
13461 (and (org-looking-at-p org-planning-line-re)
13462 (eq (point)
13463 (ignore-errors
13464 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13465 (org-back-to-heading t)
13466 (org-with-limited-levels (org-back-to-heading t)))
13467 (line-beginning-position 2))))))
13469 (defun org-add-planning-info (what &optional time &rest remove)
13470 "Insert new timestamp with keyword in the planning line.
13471 WHAT indicates what kind of time stamp to add. It is a symbol
13472 among `closed', `deadline', `scheduled' and nil. TIME indicates
13473 the time to use. If none is given, the user is prompted for
13474 a date. REMOVE indicates what kind of entries to remove. An old
13475 WHAT entry will also be removed."
13476 (let (org-time-was-given org-end-time-was-given default-time default-input)
13477 (catch 'exit
13478 (when (and (memq what '(scheduled deadline))
13479 (or (not time)
13480 (and (stringp time)
13481 (string-match "^[-+]+[0-9]" time))))
13482 ;; Try to get a default date/time from existing timestamp
13483 (save-excursion
13484 (org-back-to-heading t)
13485 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13486 (when (re-search-forward (if (eq what 'scheduled)
13487 org-scheduled-time-regexp
13488 org-deadline-time-regexp)
13489 end t)
13490 (setq ts (match-string 1)
13491 default-time (apply 'encode-time (org-parse-time-string ts))
13492 default-input (and ts (org-get-compact-tod ts)))))))
13493 (when what
13494 (setq time
13495 (if (stringp time)
13496 ;; This is a string (relative or absolute), set
13497 ;; proper date.
13498 (apply #'encode-time
13499 (org-read-date-analyze
13500 time default-time (decode-time default-time)))
13501 ;; If necessary, get the time from the user
13502 (or time (org-read-date nil 'to-time nil nil
13503 default-time default-input)))))
13505 (org-with-wide-buffer
13506 (org-back-to-heading t)
13507 (forward-line)
13508 (unless (bolp) (insert "\n"))
13509 (cond ((org-looking-at-p org-planning-line-re)
13510 ;; Move to current indentation.
13511 (skip-chars-forward " \t")
13512 ;; Check if we have to remove something.
13513 (dolist (type (if what (cons what remove) remove))
13514 (save-excursion
13515 (when (re-search-forward
13516 (case type
13517 (closed org-closed-time-regexp)
13518 (deadline org-deadline-time-regexp)
13519 (scheduled org-scheduled-time-regexp)
13520 (otherwise
13521 (error "Invalid planning type: %s" type)))
13522 (line-end-position) t)
13523 ;; Delete until next keyword or end of line.
13524 (delete-region
13525 (match-beginning 0)
13526 (if (re-search-forward org-keyword-time-not-clock-regexp
13527 (line-end-position)
13529 (match-beginning 0)
13530 (line-end-position))))))
13531 ;; If there is nothing more to add and no more keyword
13532 ;; is left, remove the line completely.
13533 (if (and (org-looking-at-p "[ \t]*$") (not what))
13534 (delete-region (line-beginning-position)
13535 (line-beginning-position 2))
13536 ;; If we removed last keyword, do not leave trailing
13537 ;; white space at the end of line.
13538 (let ((p (point)))
13539 (save-excursion
13540 (end-of-line)
13541 (unless (= (skip-chars-backward " \t" p) 0)
13542 (delete-region (point) (line-end-position)))))))
13543 ((not what) (throw 'exit nil)) ; Nothing to do.
13544 (t (insert-before-markers "\n")
13545 (backward-char 1)
13546 (when org-adapt-indentation
13547 (org-indent-to-column (1+ (org-outline-level))))))
13548 (when what
13549 ;; Insert planning keyword.
13550 (insert (case what
13551 (closed org-closed-string)
13552 (deadline org-deadline-string)
13553 (scheduled org-scheduled-string)
13554 (otherwise (error "Invalid planning type: %s" what)))
13555 " ")
13556 ;; Insert associated timestamp.
13557 (let ((ts (org-insert-time-stamp
13558 time
13559 (or org-time-was-given
13560 (and (eq what 'closed) org-log-done-with-time))
13561 (eq what 'closed)
13562 nil nil (list org-end-time-was-given))))
13563 (unless (eolp) (insert " "))
13564 ts))))))
13566 (defvar org-log-note-marker (make-marker))
13567 (defvar org-log-note-purpose nil)
13568 (defvar org-log-note-state nil)
13569 (defvar org-log-note-previous-state nil)
13570 (defvar org-log-note-extra nil)
13571 (defvar org-log-note-window-configuration nil)
13572 (defvar org-log-note-return-to (make-marker))
13573 (defvar org-log-note-effective-time nil
13574 "Remembered current time so that dynamically scoped
13575 `org-extend-today-until' affects tha timestamps in state change
13576 log")
13578 (defvar org-log-post-message nil
13579 "Message to be displayed after a log note has been stored.
13580 The auto-repeater uses this.")
13582 (defun org-add-note ()
13583 "Add a note to the current entry.
13584 This is done in the same way as adding a state change note."
13585 (interactive)
13586 (org-add-log-setup 'note nil nil 'findpos nil))
13588 (defun org-log-beginning (&optional create)
13589 "Return expected start of log notes in current entry.
13590 When optional argument CREATE is non-nil, the function creates
13591 a drawer to store notes, if necessary. Returned position ignores
13592 narrowing."
13593 (org-with-wide-buffer
13594 (org-end-of-meta-data)
13595 (let ((end (if (org-at-heading-p) (point)
13596 (save-excursion (outline-next-heading) (point))))
13597 (drawer (org-log-into-drawer)))
13598 (cond
13599 (drawer
13600 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13601 (case-fold-search t))
13602 (catch 'exit
13603 ;; Try to find existing drawer.
13604 (while (re-search-forward regexp end t)
13605 (let ((element (org-element-at-point)))
13606 (when (eq (org-element-type element) 'drawer)
13607 (let ((cend (org-element-property :contents-end element)))
13608 (when (and (not org-log-states-order-reversed) cend)
13609 (goto-char cend)))
13610 (throw 'exit nil))))
13611 ;; No drawer found. Create one, if permitted.
13612 (when create
13613 (unless (bolp) (insert "\n"))
13614 (let ((beg (point)))
13615 (insert ":" drawer ":\n:END:\n")
13616 (org-indent-region beg (point)))
13617 (end-of-line -1)))))
13618 (org-log-state-notes-insert-after-drawers
13619 (while (and (looking-at org-drawer-regexp)
13620 (progn (goto-char (match-end 0))
13621 (re-search-forward org-property-end-re end t)))
13622 (forward-line)))))
13623 (if (bolp) (point) (line-beginning-position 2))))
13625 (defun org-add-log-setup (&optional purpose state prev-state findpos how extra)
13626 "Set up the post command hook to take a note.
13627 If this is about to TODO state change, the new state is expected in STATE.
13628 When FINDPOS is non-nil, find the correct position for the note in
13629 the current entry. If not, assume that it can be inserted at point.
13630 HOW is an indicator what kind of note should be created.
13631 EXTRA is additional text that will be inserted into the notes buffer."
13632 (org-with-wide-buffer
13633 (when findpos
13634 (goto-char (org-log-beginning t))
13635 (unless org-log-states-order-reversed
13636 (org-skip-over-state-notes)
13637 (skip-chars-backward " \t\n\r")
13638 (forward-line)))
13639 (move-marker org-log-note-marker (point))
13640 ;; Preserve position even if a property drawer is inserted in the
13641 ;; process.
13642 (set-marker-insertion-type org-log-note-marker t)
13643 (setq org-log-note-purpose purpose
13644 org-log-note-state state
13645 org-log-note-previous-state prev-state
13646 org-log-note-how how
13647 org-log-note-extra extra
13648 org-log-note-effective-time (org-current-effective-time))
13649 (add-hook 'post-command-hook 'org-add-log-note 'append)))
13651 (defun org-skip-over-state-notes ()
13652 "Skip past the list of State notes in an entry."
13653 (when (ignore-errors (goto-char (org-in-item-p)))
13654 (let* ((struct (org-list-struct))
13655 (prevs (org-list-prevs-alist struct))
13656 (regexp
13657 (concat "[ \t]*- +"
13658 (replace-regexp-in-string
13659 " +" " +"
13660 (org-replace-escapes
13661 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13662 `(("%d" . ,org-ts-regexp-inactive)
13663 ("%D" . ,org-ts-regexp)
13664 ("%s" . "\"\\S-+\"")
13665 ("%S" . "\"\\S-+\"")
13666 ("%t" . ,org-ts-regexp-inactive)
13667 ("%T" . ,org-ts-regexp)
13668 ("%u" . ".*?")
13669 ("%U" . ".*?")))))))
13670 (while (org-looking-at-p regexp)
13671 (goto-char (or (org-list-get-next-item (point) struct prevs)
13672 (org-list-get-item-end (point) struct)))))))
13674 (defun org-add-log-note (&optional purpose)
13675 "Pop up a window for taking a note, and add this note later at point."
13676 (remove-hook 'post-command-hook 'org-add-log-note)
13677 (setq org-log-note-window-configuration (current-window-configuration))
13678 (delete-other-windows)
13679 (move-marker org-log-note-return-to (point))
13680 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13681 (goto-char org-log-note-marker)
13682 (org-switch-to-buffer-other-window "*Org Note*")
13683 (erase-buffer)
13684 (if (memq org-log-note-how '(time state))
13685 (let (current-prefix-arg) (org-store-log-note))
13686 (let ((org-inhibit-startup t)) (org-mode))
13687 (insert (format "# Insert note for %s.
13688 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13689 (cond
13690 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13691 ((eq org-log-note-purpose 'done) "closed todo item")
13692 ((eq org-log-note-purpose 'state)
13693 (format "state change from \"%s\" to \"%s\""
13694 (or org-log-note-previous-state "")
13695 (or org-log-note-state "")))
13696 ((eq org-log-note-purpose 'reschedule)
13697 "rescheduling")
13698 ((eq org-log-note-purpose 'delschedule)
13699 "no longer scheduled")
13700 ((eq org-log-note-purpose 'redeadline)
13701 "changing deadline")
13702 ((eq org-log-note-purpose 'deldeadline)
13703 "removing deadline")
13704 ((eq org-log-note-purpose 'refile)
13705 "refiling")
13706 ((eq org-log-note-purpose 'note)
13707 "this entry")
13708 (t (error "This should not happen")))))
13709 (if org-log-note-extra (insert org-log-note-extra))
13710 (setq-local org-finish-function 'org-store-log-note)
13711 (run-hooks 'org-log-buffer-setup-hook)))
13713 (defvar org-note-abort nil) ; dynamically scoped
13714 (defun org-store-log-note ()
13715 "Finish taking a log note, and insert it to where it belongs."
13716 (let ((txt (buffer-string)))
13717 (kill-buffer (current-buffer))
13718 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings))) lines)
13719 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13720 (setq txt (replace-match "" t t txt)))
13721 (if (string-match "\\s-+\\'" txt)
13722 (setq txt (replace-match "" t t txt)))
13723 (setq lines (org-split-string txt "\n"))
13724 (when (and note (string-match "\\S-" note))
13725 (setq note
13726 (org-replace-escapes
13727 note
13728 (list (cons "%u" (user-login-name))
13729 (cons "%U" user-full-name)
13730 (cons "%t" (format-time-string
13731 (org-time-stamp-format 'long 'inactive)
13732 org-log-note-effective-time))
13733 (cons "%T" (format-time-string
13734 (org-time-stamp-format 'long nil)
13735 org-log-note-effective-time))
13736 (cons "%d" (format-time-string
13737 (org-time-stamp-format nil 'inactive)
13738 org-log-note-effective-time))
13739 (cons "%D" (format-time-string
13740 (org-time-stamp-format nil nil)
13741 org-log-note-effective-time))
13742 (cons "%s" (cond
13743 ((not org-log-note-state) "")
13744 ((org-string-match-p org-ts-regexp
13745 org-log-note-state)
13746 (format "\"[%s]\""
13747 (substring org-log-note-state 1 -1)))
13748 (t (format "\"%s\"" org-log-note-state))))
13749 (cons "%S"
13750 (cond
13751 ((not org-log-note-previous-state) "")
13752 ((org-string-match-p org-ts-regexp
13753 org-log-note-previous-state)
13754 (format "\"[%s]\""
13755 (substring
13756 org-log-note-previous-state 1 -1)))
13757 (t (format "\"%s\""
13758 org-log-note-previous-state)))))))
13759 (when lines (setq note (concat note " \\\\")))
13760 (push note lines))
13761 (when (or current-prefix-arg org-note-abort)
13762 (when (org-log-into-drawer)
13763 (org-remove-empty-drawer-at org-log-note-marker))
13764 (setq lines nil))
13765 (when lines
13766 (with-current-buffer (marker-buffer org-log-note-marker)
13767 (org-with-wide-buffer
13768 (goto-char org-log-note-marker)
13769 (move-marker org-log-note-marker nil)
13770 ;; Make sure point is at the beginning of an empty line.
13771 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13772 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13773 ;; In an existing list, add a new item at the top level.
13774 ;; Otherwise, indent line like a regular one.
13775 (let ((itemp (org-in-item-p)))
13776 (if itemp
13777 (org-indent-line-to
13778 (let ((struct (save-excursion
13779 (goto-char itemp) (org-list-struct))))
13780 (org-list-get-ind (org-list-get-top-point struct) struct)))
13781 (org-indent-line)))
13782 (insert (org-list-bullet-string "-") (pop lines))
13783 (let ((ind (org-list-item-body-column (line-beginning-position))))
13784 (dolist (line lines)
13785 (insert "\n")
13786 (org-indent-line-to ind)
13787 (insert line)))
13788 (message "Note stored")
13789 (org-back-to-heading t)
13790 (org-cycle-hide-drawers 'children))
13791 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13792 ;; from within `org-add-log-note' because `buffer-undo-list'
13793 ;; is then modified outside of `org-with-remote-undo'.
13794 (when (eq this-command 'org-agenda-todo)
13795 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13796 ;; Don't add undo information when called from `org-agenda-todo'
13797 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13798 (set-window-configuration org-log-note-window-configuration)
13799 (with-current-buffer (marker-buffer org-log-note-return-to)
13800 (goto-char org-log-note-return-to))
13801 (move-marker org-log-note-return-to nil)
13802 (and org-log-post-message (message "%s" org-log-post-message))))
13804 (defun org-remove-empty-drawer-at (pos)
13805 "Remove an empty drawer at position POS.
13806 POS may also be a marker."
13807 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13808 (org-with-wide-buffer
13809 (goto-char pos)
13810 (let ((drawer (org-element-at-point)))
13811 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13812 (not (org-element-property :contents-begin drawer)))
13813 (delete-region (org-element-property :begin drawer)
13814 (progn (goto-char (org-element-property :end drawer))
13815 (skip-chars-backward " \r\t\n")
13816 (forward-line)
13817 (point))))))))
13819 (defvar org-ts-type nil)
13820 (defun org-sparse-tree (&optional arg type)
13821 "Create a sparse tree, prompt for the details.
13822 This command can create sparse trees. You first need to select the type
13823 of match used to create the tree:
13825 t Show all TODO entries.
13826 T Show entries with a specific TODO keyword.
13827 m Show entries selected by a tags/property match.
13828 p Enter a property name and its value (both with completion on existing
13829 names/values) and show entries with that property.
13830 r Show entries matching a regular expression (`/' can be used as well).
13831 b Show deadlines and scheduled items before a date.
13832 a Show deadlines and scheduled items after a date.
13833 d Show deadlines due within `org-deadline-warning-days'.
13834 D Show deadlines and scheduled items between a date range."
13835 (interactive "P")
13836 (setq type (or type org-sparse-tree-default-date-type))
13837 (setq org-ts-type type)
13838 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13839 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13840 [c]ycle through date types: %s"
13841 (case type
13842 (all "all timestamps")
13843 (scheduled "only scheduled")
13844 (deadline "only deadline")
13845 (active "only active timestamps")
13846 (inactive "only inactive timestamps")
13847 (closed "with a closed time-stamp")
13848 (otherwise "scheduled/deadline")))
13849 (let ((answer (read-char-exclusive)))
13850 (case answer
13852 (org-sparse-tree
13854 (cadr
13855 (memq type '(nil all scheduled deadline active inactive closed)))))
13856 (?d (call-interactively 'org-check-deadlines))
13857 (?b (call-interactively 'org-check-before-date))
13858 (?a (call-interactively 'org-check-after-date))
13859 (?D (call-interactively 'org-check-dates-range))
13860 (?t (call-interactively 'org-show-todo-tree))
13861 (?T (org-show-todo-tree '(4)))
13862 (?m (call-interactively 'org-match-sparse-tree))
13863 ((?p ?P)
13864 (let* ((kwd (org-icompleting-read
13865 "Property: " (mapcar 'list (org-buffer-property-keys))))
13866 (value (org-icompleting-read
13867 "Value: " (mapcar 'list (org-property-values kwd)))))
13868 (unless (string-match "\\`{.*}\\'" value)
13869 (setq value (concat "\"" value "\"")))
13870 (org-match-sparse-tree arg (concat kwd "=" value))))
13871 ((?r ?R ?/) (call-interactively 'org-occur))
13872 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13874 (defvar-local org-occur-highlights nil
13875 "List of overlays used for occur matches.")
13876 (defvar-local org-occur-parameters nil
13877 "Parameters of the active org-occur calls.
13878 This is a list, each call to org-occur pushes as cons cell,
13879 containing the regular expression and the callback, onto the list.
13880 The list can contain several entries if `org-occur' has been called
13881 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13882 will only contain one set of parameters. When the highlights are
13883 removed (for example with `C-c C-c', or with the next edit (depending
13884 on `org-remove-highlights-with-change'), this variable is emptied
13885 as well.")
13887 (defun org-occur (regexp &optional keep-previous callback)
13888 "Make a compact tree which shows all matches of REGEXP.
13889 The tree will show the lines where the regexp matches, and all higher
13890 headlines above the match. It will also show the heading after the match,
13891 to make sure editing the matching entry is easy.
13892 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13893 call to `org-occur' will be kept, to allow stacking of calls to this
13894 command.
13895 If CALLBACK is non-nil, it is a function which is called to confirm
13896 that the match should indeed be shown."
13897 (interactive "sRegexp: \nP")
13898 (when (equal regexp "")
13899 (user-error "Regexp cannot be empty"))
13900 (unless keep-previous
13901 (org-remove-occur-highlights nil nil t))
13902 (push (cons regexp callback) org-occur-parameters)
13903 (let ((cnt 0))
13904 (save-excursion
13905 (goto-char (point-min))
13906 (if (or (not keep-previous) ; do not want to keep
13907 (not org-occur-highlights)) ; no previous matches
13908 ;; hide everything
13909 (org-overview))
13910 (while (re-search-forward regexp nil t)
13911 (backward-char) ;; FIXME: Match timestamps at the end of a headline
13912 (when (or (not callback)
13913 (save-match-data (funcall callback)))
13914 (setq cnt (1+ cnt))
13915 (when org-highlight-sparse-tree-matches
13916 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13917 (org-show-context 'occur-tree))))
13918 (when org-remove-highlights-with-change
13919 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13920 nil 'local))
13921 (unless org-sparse-tree-open-archived-trees
13922 (org-hide-archived-subtrees (point-min) (point-max)))
13923 (run-hooks 'org-occur-hook)
13924 (if (org-called-interactively-p 'interactive)
13925 (message "%d match(es) for regexp %s" cnt regexp))
13926 cnt))
13928 (defun org-occur-next-match (&optional n reset)
13929 "Function for `next-error-function' to find sparse tree matches.
13930 N is the number of matches to move, when negative move backwards.
13931 RESET is entirely ignored - this function always goes back to the
13932 starting point when no match is found."
13933 (let* ((limit (if (< n 0) (point-min) (point-max)))
13934 (search-func (if (< n 0)
13935 'previous-single-char-property-change
13936 'next-single-char-property-change))
13937 (n (abs n))
13938 (pos (point))
13940 (catch 'exit
13941 (while (setq p1 (funcall search-func (point) 'org-type))
13942 (when (equal p1 limit)
13943 (goto-char pos)
13944 (user-error "No more matches"))
13945 (when (equal (get-char-property p1 'org-type) 'org-occur)
13946 (setq n (1- n))
13947 (when (= n 0)
13948 (goto-char p1)
13949 (throw 'exit (point))))
13950 (goto-char p1))
13951 (goto-char p1)
13952 (user-error "No more matches"))))
13954 (defun org-show-context (&optional key)
13955 "Make sure point and context are visible.
13956 Optional argument KEY, when non-nil, is a symbol. See
13957 `org-show-context-detail' for allowed values and how much is to
13958 be shown."
13959 (org-show-set-visibility
13960 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13961 ((cdr (assq key org-show-context-detail)))
13962 (t (cdr (assq 'default org-show-context-detail))))))
13964 (defun org-show-set-visibility (detail)
13965 "Set visibility around point according to DETAIL.
13966 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13967 `tree', `canonical' or t. See `org-show-context-detail' for more
13968 information."
13969 (unless (org-before-first-heading-p)
13970 ;; Show current heading and possibly its entry, following headline
13971 ;; or all children.
13972 (if (and (org-at-heading-p) (not (eq detail 'local)))
13973 (org-flag-heading nil)
13974 (org-show-entry)
13975 (org-with-limited-levels
13976 (case detail
13977 ((tree canonical t) (org-show-children))
13978 ((nil minimal ancestors))
13979 (t (save-excursion
13980 (outline-next-heading)
13981 (org-flag-heading nil))))))
13982 ;; Show all siblings.
13983 (when (eq detail 'lineage) (org-show-siblings))
13984 ;; Show ancestors, possibly with their children.
13985 (when (memq detail '(ancestors lineage tree canonical t))
13986 (save-excursion
13987 (while (org-up-heading-safe)
13988 (org-flag-heading nil)
13989 (when (memq detail '(canonical t)) (org-show-entry))
13990 (when (memq detail '(tree canonical t)) (org-show-children)))))))
13992 (defvar org-reveal-start-hook nil
13993 "Hook run before revealing a location.")
13995 (defun org-reveal (&optional siblings)
13996 "Show current entry, hierarchy above it, and the following headline.
13998 This can be used to show a consistent set of context around
13999 locations exposed with `org-show-context'.
14001 With optional argument SIBLINGS, on each level of the hierarchy all
14002 siblings are shown. This repairs the tree structure to what it would
14003 look like when opened with hierarchical calls to `org-cycle'.
14005 With double optional argument \\[universal-argument] \\[universal-argument], \
14006 go to the parent and show the
14007 entire tree."
14008 (interactive "P")
14009 (run-hooks 'org-reveal-start-hook)
14010 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14011 ((equal siblings '(16))
14012 (save-excursion
14013 (when (org-up-heading-safe)
14014 (org-show-subtree)
14015 (run-hook-with-args 'org-cycle-hook 'subtree))))
14016 (t (org-show-set-visibility 'lineage))))
14018 (defun org-highlight-new-match (beg end)
14019 "Highlight from BEG to END and mark the highlight is an occur headline."
14020 (let ((ov (make-overlay beg end)))
14021 (overlay-put ov 'face 'secondary-selection)
14022 (overlay-put ov 'org-type 'org-occur)
14023 (push ov org-occur-highlights)))
14025 (defun org-remove-occur-highlights (&optional beg end noremove)
14026 "Remove the occur highlights from the buffer.
14027 BEG and END are ignored. If NOREMOVE is nil, remove this function
14028 from the `before-change-functions' in the current buffer."
14029 (interactive)
14030 (unless org-inhibit-highlight-removal
14031 (mapc 'delete-overlay org-occur-highlights)
14032 (setq org-occur-highlights nil)
14033 (setq org-occur-parameters nil)
14034 (unless noremove
14035 (remove-hook 'before-change-functions
14036 'org-remove-occur-highlights 'local))))
14038 ;;;; Priorities
14040 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14041 "Regular expression matching the priority indicator.")
14043 (defvar org-remove-priority-next-time nil)
14045 (defun org-priority-up ()
14046 "Increase the priority of the current item."
14047 (interactive)
14048 (org-priority 'up))
14050 (defun org-priority-down ()
14051 "Decrease the priority of the current item."
14052 (interactive)
14053 (org-priority 'down))
14055 (defun org-priority (&optional action show)
14056 "Change the priority of an item.
14057 ACTION can be `set', `up', `down', or a character."
14058 (interactive "P")
14059 (if (equal action '(4))
14060 (org-show-priority)
14061 (unless org-enable-priority-commands
14062 (user-error "Priority commands are disabled"))
14063 (setq action (or action 'set))
14064 (let (current new news have remove)
14065 (save-excursion
14066 (org-back-to-heading t)
14067 (if (looking-at org-priority-regexp)
14068 (setq current (string-to-char (match-string 2))
14069 have t))
14070 (cond
14071 ((eq action 'remove)
14072 (setq remove t new ?\ ))
14073 ((or (eq action 'set)
14074 (if (featurep 'xemacs) (characterp action) (integerp action)))
14075 (if (not (eq action 'set))
14076 (setq new action)
14077 (message "Priority %c-%c, SPC to remove: "
14078 org-highest-priority org-lowest-priority)
14079 (save-match-data
14080 (setq new (read-char-exclusive))))
14081 (if (and (= (upcase org-highest-priority) org-highest-priority)
14082 (= (upcase org-lowest-priority) org-lowest-priority))
14083 (setq new (upcase new)))
14084 (cond ((equal new ?\ ) (setq remove t))
14085 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14086 (user-error "Priority must be between `%c' and `%c'"
14087 org-highest-priority org-lowest-priority))))
14088 ((eq action 'up)
14089 (setq new (if have
14090 (1- current) ; normal cycling
14091 ;; last priority was empty
14092 (if (eq last-command this-command)
14093 org-lowest-priority ; wrap around empty to lowest
14094 ;; default
14095 (if org-priority-start-cycle-with-default
14096 org-default-priority
14097 (1- org-default-priority))))))
14098 ((eq action 'down)
14099 (setq new (if have
14100 (1+ current) ; normal cycling
14101 ;; last priority was empty
14102 (if (eq last-command this-command)
14103 org-highest-priority ; wrap around empty to highest
14104 ;; default
14105 (if org-priority-start-cycle-with-default
14106 org-default-priority
14107 (1+ org-default-priority))))))
14108 (t (user-error "Invalid action")))
14109 (if (or (< (upcase new) org-highest-priority)
14110 (> (upcase new) org-lowest-priority))
14111 (if (and (memq action '(up down))
14112 (not have) (not (eq last-command this-command)))
14113 ;; `new' is from default priority
14114 (error
14115 "The default can not be set, see `org-default-priority' why")
14116 ;; normal cycling: `new' is beyond highest/lowest priority
14117 ;; and is wrapped around to the empty priority
14118 (setq remove t)))
14119 (setq news (format "%c" new))
14120 (if have
14121 (if remove
14122 (replace-match "" t t nil 1)
14123 (replace-match news t t nil 2))
14124 (if remove
14125 (user-error "No priority cookie found in line")
14126 (let ((case-fold-search nil))
14127 (looking-at org-todo-line-regexp))
14128 (if (match-end 2)
14129 (progn
14130 (goto-char (match-end 2))
14131 (insert " [#" news "]"))
14132 (goto-char (match-beginning 3))
14133 (insert "[#" news "] "))))
14134 (org-set-tags nil 'align))
14135 (if remove
14136 (message "Priority removed")
14137 (message "Priority of current item set to %s" news)))))
14139 (defun org-show-priority ()
14140 "Show the priority of the current item.
14141 This priority is composed of the main priority given with the [#A] cookies,
14142 and by additional input from the age of a schedules or deadline entry."
14143 (interactive)
14144 (let ((pri (if (eq major-mode 'org-agenda-mode)
14145 (org-get-at-bol 'priority)
14146 (save-excursion
14147 (save-match-data
14148 (beginning-of-line)
14149 (and (looking-at org-heading-regexp)
14150 (org-get-priority (match-string 0))))))))
14151 (message "Priority is %d" (if pri pri -1000))))
14153 (defun org-get-priority (s)
14154 "Find priority cookie and return priority."
14155 (save-match-data
14156 (if (functionp org-get-priority-function)
14157 (funcall org-get-priority-function)
14158 (if (not (string-match org-priority-regexp s))
14159 (* 1000 (- org-lowest-priority org-default-priority))
14160 (* 1000 (- org-lowest-priority
14161 (string-to-char (match-string 2 s))))))))
14163 ;;;; Tags
14165 (defvar org-agenda-archives-mode)
14166 (defvar org-map-continue-from nil
14167 "Position from where mapping should continue.
14168 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14170 (defvar org-scanner-tags nil
14171 "The current tag list while the tags scanner is running.")
14172 (defvar org-trust-scanner-tags nil
14173 "Should `org-get-tags-at' use the tags for the scanner.
14174 This is for internal dynamical scoping only.
14175 When this is non-nil, the function `org-get-tags-at' will return the value
14176 of `org-scanner-tags' instead of building the list by itself. This
14177 can lead to large speed-ups when the tags scanner is used in a file with
14178 many entries, and when the list of tags is retrieved, for example to
14179 obtain a list of properties. Building the tags list for each entry in such
14180 a file becomes an N^2 operation - but with this variable set, it scales
14181 as N.")
14183 (defun org-scan-tags (action matcher todo-only &optional start-level)
14184 "Scan headline tags with inheritance and produce output ACTION.
14186 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14187 or `agenda' to produce an entry list for an agenda view. It can also be
14188 a Lisp form or a function that should be called at each matched headline, in
14189 this case the return value is a list of all return values from these calls.
14191 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14192 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14193 only lines with a not-done TODO keyword are included in the output.
14194 This should be the same variable that was scoped into
14195 and set by `org-make-tags-matcher' when it constructed MATCHER.
14197 START-LEVEL can be a string with asterisks, reducing the scope to
14198 headlines matching this string."
14199 (require 'org-agenda)
14200 (let* ((re (concat "^"
14201 (if start-level
14202 ;; Get the correct level to match
14203 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14204 org-outline-regexp)
14205 " *\\(\\<\\("
14206 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14207 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14208 (props (list 'face 'default
14209 'done-face 'org-agenda-done
14210 'undone-face 'default
14211 'mouse-face 'highlight
14212 'org-not-done-regexp org-not-done-regexp
14213 'org-todo-regexp org-todo-regexp
14214 'org-complex-heading-regexp org-complex-heading-regexp
14215 'help-echo
14216 (format "mouse-2 or RET jump to org file %s"
14217 (abbreviate-file-name
14218 (or (buffer-file-name (buffer-base-buffer))
14219 (buffer-name (buffer-base-buffer)))))))
14220 (org-map-continue-from nil)
14221 lspos tags tags-list
14222 (tags-alist (list (cons 0 org-file-tags)))
14223 (llast 0) rtn rtn1 level category i txt
14224 todo marker entry priority
14225 ts-date ts-date-type ts-date-pair)
14226 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14227 (setq action (list 'lambda nil action)))
14228 (save-excursion
14229 (goto-char (point-min))
14230 (when (eq action 'sparse-tree)
14231 (org-overview)
14232 (org-remove-occur-highlights))
14233 (while (let (case-fold-search)
14234 (re-search-forward re nil t))
14235 (setq org-map-continue-from nil)
14236 (catch :skip
14237 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14238 tags (if (match-end 4) (org-match-string-no-properties 4)))
14239 (goto-char (setq lspos (match-beginning 0)))
14240 (setq level (org-reduced-level (org-outline-level))
14241 category (org-get-category))
14242 (when (eq action 'agenda)
14243 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14244 ts-date (car ts-date-pair)
14245 ts-date-type (cdr ts-date-pair)))
14246 (setq i llast llast level)
14247 ;; remove tag lists from same and sublevels
14248 (while (>= i level)
14249 (when (setq entry (assoc i tags-alist))
14250 (setq tags-alist (delete entry tags-alist)))
14251 (setq i (1- i)))
14252 ;; add the next tags
14253 (when tags
14254 (setq tags (org-split-string tags ":")
14255 tags-alist
14256 (cons (cons level tags) tags-alist)))
14257 ;; compile tags for current headline
14258 (setq tags-list
14259 (if org-use-tag-inheritance
14260 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14261 tags)
14262 org-scanner-tags tags-list)
14263 (when org-use-tag-inheritance
14264 (setcdr (car tags-alist)
14265 (mapcar (lambda (x)
14266 (setq x (copy-sequence x))
14267 (org-add-prop-inherited x))
14268 (cdar tags-alist))))
14269 (when (and tags org-use-tag-inheritance
14270 (or (not (eq t org-use-tag-inheritance))
14271 org-tags-exclude-from-inheritance))
14272 ;; selective inheritance, remove uninherited ones
14273 (setcdr (car tags-alist)
14274 (org-remove-uninherited-tags (cdar tags-alist))))
14275 (when (and
14277 ;; eval matcher only when the todo condition is OK
14278 (and (or (not todo-only) (member todo org-not-done-keywords))
14279 (let ((case-fold-search t) (org-trust-scanner-tags t))
14280 (eval matcher)))
14282 ;; Call the skipper, but return t if it does not skip,
14283 ;; so that the `and' form continues evaluating
14284 (progn
14285 (unless (eq action 'sparse-tree) (org-agenda-skip))
14288 ;; Check if timestamps are deselecting this entry
14289 (or (not todo-only)
14290 (and (member todo org-not-done-keywords)
14291 (or (not org-agenda-tags-todo-honor-ignore-options)
14292 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14294 ;; select this headline
14295 (cond
14296 ((eq action 'sparse-tree)
14297 (and org-highlight-sparse-tree-matches
14298 (org-get-heading) (match-end 0)
14299 (org-highlight-new-match
14300 (match-beginning 1) (match-end 1)))
14301 (org-show-context 'tags-tree))
14302 ((eq action 'agenda)
14303 (setq txt (org-agenda-format-item
14305 (concat
14306 (if (eq org-tags-match-list-sublevels 'indented)
14307 (make-string (1- level) ?.) "")
14308 (org-get-heading))
14309 (make-string level ?\s)
14310 category
14311 tags-list)
14312 priority (org-get-priority txt))
14313 (goto-char lspos)
14314 (setq marker (org-agenda-new-marker))
14315 (org-add-props txt props
14316 'org-marker marker 'org-hd-marker marker 'org-category category
14317 'todo-state todo
14318 'ts-date ts-date
14319 'priority priority
14320 'type (concat "tagsmatch" ts-date-type))
14321 (push txt rtn))
14322 ((functionp action)
14323 (setq org-map-continue-from nil)
14324 (save-excursion
14325 (setq rtn1 (funcall action))
14326 (push rtn1 rtn)))
14327 (t (user-error "Invalid action")))
14329 ;; if we are to skip sublevels, jump to end of subtree
14330 (unless org-tags-match-list-sublevels
14331 (org-end-of-subtree t)
14332 (backward-char 1))))
14333 ;; Get the correct position from where to continue
14334 (if org-map-continue-from
14335 (goto-char org-map-continue-from)
14336 (and (= (point) lspos) (end-of-line 1)))))
14337 (when (and (eq action 'sparse-tree)
14338 (not org-sparse-tree-open-archived-trees))
14339 (org-hide-archived-subtrees (point-min) (point-max)))
14340 (nreverse rtn)))
14342 (defun org-remove-uninherited-tags (tags)
14343 "Remove all tags that are not inherited from the list TAGS."
14344 (cond
14345 ((eq org-use-tag-inheritance t)
14346 (if org-tags-exclude-from-inheritance
14347 (org-delete-all org-tags-exclude-from-inheritance tags)
14348 tags))
14349 ((not org-use-tag-inheritance) nil)
14350 ((stringp org-use-tag-inheritance)
14351 (delq nil (mapcar
14352 (lambda (x)
14353 (if (and (string-match org-use-tag-inheritance x)
14354 (not (member x org-tags-exclude-from-inheritance)))
14355 x nil))
14356 tags)))
14357 ((listp org-use-tag-inheritance)
14358 (delq nil (mapcar
14359 (lambda (x)
14360 (if (member x org-use-tag-inheritance) x nil))
14361 tags)))))
14363 (defun org-match-sparse-tree (&optional todo-only match)
14364 "Create a sparse tree according to tags string MATCH.
14365 MATCH can contain positive and negative selection of tags, like
14366 \"+WORK+URGENT-WITHBOSS\".
14367 If optional argument TODO-ONLY is non-nil, only select lines that are
14368 also TODO lines."
14369 (interactive "P")
14370 (org-agenda-prepare-buffers (list (current-buffer)))
14371 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14373 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14375 (defvar org-cached-props nil)
14376 (defun org-cached-entry-get (pom property)
14377 (if (or (eq t org-use-property-inheritance)
14378 (and (stringp org-use-property-inheritance)
14379 (let ((case-fold-search t))
14380 (org-string-match-p org-use-property-inheritance property)))
14381 (and (listp org-use-property-inheritance)
14382 (member-ignore-case property org-use-property-inheritance)))
14383 ;; Caching is not possible, check it directly.
14384 (org-entry-get pom property 'inherit)
14385 ;; Get all properties, so we can do complicated checks easily.
14386 (cdr (assoc-string property
14387 (or org-cached-props
14388 (setq org-cached-props (org-entry-properties pom)))
14389 t))))
14391 (defun org-global-tags-completion-table (&optional files)
14392 "Return the list of all tags in all agenda buffer/files.
14393 Optional FILES argument is a list of files which can be used
14394 instead of the agenda files."
14395 (save-excursion
14396 (org-uniquify
14397 (delq nil
14398 (apply 'append
14399 (mapcar
14400 (lambda (file)
14401 (set-buffer (find-file-noselect file))
14402 (append (org-get-buffer-tags)
14403 (mapcar (lambda (x) (if (stringp (car-safe x))
14404 (list (car-safe x)) nil))
14405 org-tag-alist)))
14406 (if (and files (car files))
14407 files
14408 (org-agenda-files))))))))
14410 (defun org-make-tags-matcher (match)
14411 "Create the TAGS/TODO matcher form for the selection string MATCH.
14413 The variable `todo-only' is scoped dynamically into this function.
14414 It will be set to t if the matcher restricts matching to TODO entries,
14415 otherwise will not be touched.
14417 Returns a cons of the selection string MATCH and the constructed
14418 lisp form implementing the matcher. The matcher is to be evaluated
14419 at an Org entry, with point on the headline, and returns t if the
14420 entry matches the selection string MATCH. The returned lisp form
14421 references two variables with information about the entry, which
14422 must be bound around the form's evaluation: todo, the TODO keyword
14423 at the entry (or nil of none); and tags-list, the list of all tags
14424 at the entry including inherited ones. Additionally, the category
14425 of the entry (if any) must be specified as the text property
14426 `org-category' on the headline.
14428 See also `org-scan-tags'.
14430 (declare (special todo-only))
14431 (unless (boundp 'todo-only)
14432 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14433 (unless match
14434 ;; Get a new match request, with completion against the global
14435 ;; tags table and the local tags in current buffer
14436 (let ((org-last-tags-completion-table
14437 (org-uniquify
14438 (delq nil (append (org-get-buffer-tags)
14439 (org-global-tags-completion-table))))))
14440 (setq match (org-completing-read-no-i
14441 "Match: " 'org-tags-completion-function nil nil nil
14442 'org-tags-history))))
14444 ;; Parse the string and create a lisp form
14445 (let ((match0 match)
14446 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14447 minus tag mm
14448 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14449 orterms term orlist re-p str-p level-p level-op time-p
14450 prop-p pn pv po gv rest (start 0) (ss 0))
14451 ;; Expand group tags
14452 (setq match (org-tags-expand match))
14454 ;; Check if there is a TODO part of this match, which would be the
14455 ;; part after a "/". TO make sure that this slash is not part of
14456 ;; a property value to be matched against, we also check that there
14457 ;; is no " after that slash.
14458 ;; First, find the last slash
14459 (while (string-match "/+" match ss)
14460 (setq start (match-beginning 0) ss (match-end 0)))
14461 (if (and (string-match "/+" match start)
14462 (not (save-match-data (string-match "\"" match start))))
14463 ;; match contains also a todo-matching request
14464 (progn
14465 (setq tagsmatch (substring match 0 (match-beginning 0))
14466 todomatch (substring match (match-end 0)))
14467 (if (string-match "^!" todomatch)
14468 (setq todo-only t todomatch (substring todomatch 1)))
14469 (if (string-match "^\\s-*$" todomatch)
14470 (setq todomatch nil)))
14471 ;; only matching tags
14472 (setq tagsmatch match todomatch nil))
14474 ;; Make the tags matcher
14475 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14476 (setq tagsmatcher t)
14477 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14478 (while (setq term (pop orterms))
14479 (while (and (equal (substring term -1) "\\") orterms)
14480 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14481 (while (string-match re term)
14482 (setq rest (substring term (match-end 0))
14483 minus (and (match-end 1)
14484 (equal (match-string 1 term) "-"))
14485 tag (save-match-data (replace-regexp-in-string
14486 "\\\\-" "-"
14487 (match-string 2 term)))
14488 re-p (equal (string-to-char tag) ?{)
14489 level-p (match-end 4)
14490 prop-p (match-end 5)
14491 mm (cond
14492 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14493 (level-p
14494 (setq level-op (org-op-to-function (match-string 3 term)))
14495 `(,level-op level ,(string-to-number
14496 (match-string 4 term))))
14497 (prop-p
14498 (setq pn (match-string 5 term)
14499 po (match-string 6 term)
14500 pv (match-string 7 term)
14501 re-p (equal (string-to-char pv) ?{)
14502 str-p (equal (string-to-char pv) ?\")
14503 time-p (save-match-data
14504 (string-match "^\"[[<].*[]>]\"$" pv))
14505 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14506 (if time-p (setq pv (org-matcher-time pv)))
14507 (setq po (org-op-to-function po (if time-p 'time str-p)))
14508 (cond
14509 ((equal pn "CATEGORY")
14510 (setq gv '(get-text-property (point) 'org-category)))
14511 ((equal pn "TODO")
14512 (setq gv 'todo))
14514 (setq gv `(org-cached-entry-get nil ,pn))))
14515 (if re-p
14516 (if (eq po 'org<>)
14517 `(not (string-match ,pv (or ,gv "")))
14518 `(string-match ,pv (or ,gv "")))
14519 (if str-p
14520 `(,po (or ,gv "") ,pv)
14521 `(,po (string-to-number (or ,gv ""))
14522 ,(string-to-number pv) ))))
14523 (t `(member ,tag tags-list)))
14524 mm (if minus (list 'not mm) mm)
14525 term rest)
14526 (push mm tagsmatcher))
14527 (push (if (> (length tagsmatcher) 1)
14528 (cons 'and tagsmatcher)
14529 (car tagsmatcher))
14530 orlist)
14531 (setq tagsmatcher nil))
14532 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14533 (setq tagsmatcher
14534 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14535 ;; Make the todo matcher
14536 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14537 (setq todomatcher t)
14538 (setq orterms (org-split-string todomatch "|") orlist nil)
14539 (dolist (term orterms)
14540 (while (string-match re term)
14541 (setq minus (and (match-end 1)
14542 (equal (match-string 1 term) "-"))
14543 kwd (match-string 2 term)
14544 re-p (equal (string-to-char kwd) ?{)
14545 term (substring term (match-end 0))
14546 mm (if re-p
14547 `(string-match ,(substring kwd 1 -1) todo)
14548 (list 'equal 'todo kwd))
14549 mm (if minus (list 'not mm) mm))
14550 (push mm todomatcher))
14551 (push (if (> (length todomatcher) 1)
14552 (cons 'and todomatcher)
14553 (car todomatcher))
14554 orlist)
14555 (setq todomatcher nil))
14556 (setq todomatcher (if (> (length orlist) 1)
14557 (cons 'or orlist) (car orlist))))
14559 ;; Return the string and lisp forms of the matcher
14560 (setq matcher (if todomatcher
14561 (list 'and tagsmatcher todomatcher)
14562 tagsmatcher))
14563 (when todo-only
14564 (setq matcher (list 'and '(member todo org-not-done-keywords)
14565 matcher)))
14566 (cons match0 matcher)))
14568 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14569 "Expand group tags in MATCH.
14571 This replaces every group tag in MATCH with a regexp tag search.
14572 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14573 will be replaced like this:
14575 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14576 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14577 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14579 Replacing by a regexp preserves the structure of the match.
14580 E.g., this expansion
14582 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14584 will match anything tagged with \"Lab\" and \"Home\", or tagged
14585 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14587 A group tag in MATCH can contain regular expressions of its own.
14588 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14589 will be replaced like this:
14591 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14593 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14594 assumed to be a single group tag, and the function will return
14595 the list of tags in this group.
14597 When DOWNCASE is non-nil, expand downcased TAGS."
14598 (if org-group-tags
14599 (let* ((case-fold-search t)
14600 (stable org-mode-syntax-table)
14601 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14602 (taggroups (if downcased
14603 (mapcar (lambda (tg) (mapcar #'downcase tg))
14604 taggroups)
14605 taggroups))
14606 (taggroups-keys (mapcar #'car taggroups))
14607 (return-match (if downcased (downcase match) match))
14608 (count 0)
14609 (work-already-expanded tags-already-expanded)
14610 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14611 ;; @ and _ are allowed as word-components in tags.
14612 (modify-syntax-entry ?@ "w" stable)
14613 (modify-syntax-entry ?_ "w" stable)
14614 ;; Temporarily replace regexp-expressions in the match-expression.
14615 (while (string-match "{.+?}" return-match)
14616 (incf count)
14617 (push (match-string 0 return-match) regexps-in-match)
14618 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14619 (while (and taggroups-keys
14620 (with-syntax-table stable
14621 (string-match
14622 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14623 (regexp-opt taggroups-keys) "\\>\\)")
14624 return-match)))
14625 (let* ((dir (match-string 1 return-match))
14626 (tag (match-string 2 return-match))
14627 (tag (if downcased (downcase tag) tag)))
14628 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14629 (member tag work-already-expanded))
14630 (setq tags-in-group (assoc tag taggroups))
14631 (push tag work-already-expanded)
14632 ;; Recursively expand each tag in the group, if the tag hasn't
14633 ;; already been expanded. Restore the match-data after all recursive calls.
14634 (save-match-data
14635 (let (tags-expanded)
14636 (dolist (x (cdr tags-in-group))
14637 (if (and (member x taggroups-keys)
14638 (not (member x work-already-expanded)))
14639 (setq tags-expanded
14640 (delete-dups
14641 (append
14642 (org-tags-expand x t downcased
14643 work-already-expanded)
14644 tags-expanded)))
14645 (setq tags-expanded
14646 (append (list x) tags-expanded)))
14647 (setq work-already-expanded
14648 (delete-dups
14649 (append tags-expanded
14650 work-already-expanded))))
14651 (setq tags-in-group
14652 (delete-dups (cons (car tags-in-group)
14653 tags-expanded)))))
14654 ;; Filter tag-regexps from tags.
14655 (setq regexp-in-group-escaped
14656 (delq nil (mapcar (lambda (x)
14657 (if (stringp x)
14658 (and (equal "{" (substring x 0 1))
14659 (equal "}" (substring x -1))
14662 tags-in-group))
14663 regexp-in-group
14664 (mapcar (lambda (x)
14665 (substring x 1 -1))
14666 regexp-in-group-escaped)
14667 tags-in-group
14668 (delq nil (mapcar (lambda (x)
14669 (if (stringp x)
14670 (and (not (equal "{" (substring x 0 1)))
14671 (not (equal "}" (substring x -1)))
14674 tags-in-group)))
14675 ;; If single-as-list, do no more in the while-loop.
14676 (if (not single-as-list)
14677 (progn
14678 (when regexp-in-group
14679 (setq regexp-in-group
14680 (concat "\\|"
14681 (mapconcat 'identity regexp-in-group
14682 "\\|"))))
14683 (setq tags-in-group
14684 (concat dir
14685 "{\\<"
14686 (regexp-opt tags-in-group)
14687 "\\>"
14688 regexp-in-group
14689 "}"))
14690 (when (stringp tags-in-group)
14691 (org-add-props tags-in-group '(grouptag t)))
14692 (setq return-match
14693 (replace-match tags-in-group t t return-match)))
14694 (setq tags-in-group
14695 (append regexp-in-group-escaped tags-in-group))))
14696 (setq taggroups-keys (delete tag taggroups-keys))))
14697 ;; Add the regular expressions back into the match-expression again.
14698 (while regexps-in-match
14699 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14700 (pop regexps-in-match)
14701 return-match t t))
14702 (decf count))
14703 (if single-as-list
14704 (if tags-in-group tags-in-group (list return-match))
14705 return-match))
14706 (if single-as-list
14707 (list (if downcased (downcase match) match))
14708 match)))
14710 (defun org-op-to-function (op &optional stringp)
14711 "Turn an operator into the appropriate function."
14712 (setq op
14713 (cond
14714 ((equal op "<" ) '(< string< org-time<))
14715 ((equal op ">" ) '(> org-string> org-time>))
14716 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14717 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14718 ((member op '("=" "==")) '(= string= org-time=))
14719 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14720 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14722 (defun org<> (a b) (not (= a b)))
14723 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14724 (defun org-string>= (a b) (not (string< a b)))
14725 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14726 (defun org-string<> (a b) (not (string= a b)))
14727 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14728 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14729 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14730 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14731 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14732 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14733 (defun org-2ft (s)
14734 "Convert S to a floating point time.
14735 If S is already a number, just return it. If it is a string, parse
14736 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14737 (cond
14738 ((numberp s) s)
14739 ((stringp s)
14740 (condition-case nil
14741 (float-time (apply 'encode-time (org-parse-time-string s)))
14742 (error 0.)))
14743 (t 0.)))
14745 (defun org-time-today ()
14746 "Time in seconds today at 0:00.
14747 Returns the float number of seconds since the beginning of the
14748 epoch to the beginning of today (00:00)."
14749 (float-time (apply 'encode-time
14750 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14752 (defun org-matcher-time (s)
14753 "Interpret a time comparison value."
14754 (save-match-data
14755 (cond
14756 ((string= s "<now>") (float-time))
14757 ((string= s "<today>") (org-time-today))
14758 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14759 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14760 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14761 (+ (org-time-today)
14762 (* (string-to-number (match-string 1 s))
14763 (cdr (assoc (match-string 2 s)
14764 '(("d" . 86400.0) ("w" . 604800.0)
14765 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14766 (t (org-2ft s)))))
14768 (defun org-match-any-p (re list)
14769 "Does re match any element of list?"
14770 (setq list (mapcar (lambda (x) (string-match re x)) list))
14771 (delq nil list))
14773 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14774 (defvar org-tags-overlay (make-overlay 1 1))
14775 (org-detach-overlay org-tags-overlay)
14777 (defun org-get-local-tags-at (&optional pos)
14778 "Get a list of tags defined in the current headline."
14779 (org-get-tags-at pos 'local))
14781 (defun org-get-local-tags ()
14782 "Get a list of tags defined in the current headline."
14783 (org-get-tags-at nil 'local))
14785 (defun org-get-tags-at (&optional pos local)
14786 "Get a list of all headline tags applicable at POS.
14787 POS defaults to point. If tags are inherited, the list contains
14788 the targets in the same sequence as the headlines appear, i.e.
14789 the tags of the current headline come last.
14790 When LOCAL is non-nil, only return tags from the current headline,
14791 ignore inherited ones."
14792 (interactive)
14793 (if (and org-trust-scanner-tags
14794 (or (not pos) (equal pos (point)))
14795 (not local))
14796 org-scanner-tags
14797 (let (tags ltags lastpos parent)
14798 (save-excursion
14799 (save-restriction
14800 (widen)
14801 (goto-char (or pos (point)))
14802 (save-match-data
14803 (catch 'done
14804 (condition-case nil
14805 (progn
14806 (org-back-to-heading t)
14807 (while (not (equal lastpos (point)))
14808 (setq lastpos (point))
14809 (when (looking-at
14810 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14811 (setq ltags (org-split-string
14812 (org-match-string-no-properties 1) ":"))
14813 (when parent
14814 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14815 (setq tags (append
14816 (if parent
14817 (org-remove-uninherited-tags ltags)
14818 ltags)
14819 tags)))
14820 (or org-use-tag-inheritance (throw 'done t))
14821 (if local (throw 'done t))
14822 (or (org-up-heading-safe) (error nil))
14823 (setq parent t)))
14824 (error nil)))))
14825 (if local
14826 tags
14827 (reverse (delete-dups
14828 (reverse (append
14829 (org-remove-uninherited-tags
14830 org-file-tags)
14831 tags)))))))))
14833 (defun org-add-prop-inherited (s)
14834 (add-text-properties 0 (length s) '(inherited t) s)
14837 (defun org-toggle-tag (tag &optional onoff)
14838 "Toggle the tag TAG for the current line.
14839 If ONOFF is `on' or `off', don't toggle but set to this state."
14840 (let (res current)
14841 (save-excursion
14842 (org-back-to-heading t)
14843 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14844 (point-at-eol) t)
14845 (progn
14846 (setq current (match-string 1))
14847 (replace-match ""))
14848 (setq current ""))
14849 (setq current (nreverse (org-split-string current ":")))
14850 (cond
14851 ((eq onoff 'on)
14852 (setq res t)
14853 (or (member tag current) (push tag current)))
14854 ((eq onoff 'off)
14855 (or (not (member tag current)) (setq current (delete tag current))))
14856 (t (if (member tag current)
14857 (setq current (delete tag current))
14858 (setq res t)
14859 (push tag current))))
14860 (end-of-line 1)
14861 (if current
14862 (progn
14863 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14864 (org-set-tags nil t))
14865 (delete-horizontal-space))
14866 (run-hooks 'org-after-tags-change-hook))
14867 res))
14869 (defun org-align-tags-here (to-col)
14870 ;; Assumes that this is a headline
14871 "Align tags on the current headline to TO-COL."
14872 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14873 (beginning-of-line 1)
14874 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14875 (< pos (match-beginning 2)))
14876 (progn
14877 (setq tags-l (- (match-end 2) (match-beginning 2)))
14878 (goto-char (match-beginning 1))
14879 (insert " ")
14880 (delete-region (point) (1+ (match-beginning 2)))
14881 (setq ncol (max (current-column)
14882 (1+ col)
14883 (if (> to-col 0)
14884 to-col
14885 (- (abs to-col) tags-l))))
14886 (setq p (point))
14887 (insert (make-string (- ncol (current-column)) ?\ ))
14888 (setq ncol (current-column))
14889 (when indent-tabs-mode (tabify p (point-at-eol)))
14890 (org-move-to-column (min ncol col)))
14891 (goto-char pos))))
14893 (defun org-set-tags-command (&optional arg just-align)
14894 "Call the set-tags command for the current entry."
14895 (interactive "P")
14896 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14897 (org-set-tags arg just-align)
14898 (save-excursion
14899 (unless (and (org-region-active-p)
14900 org-loop-over-headlines-in-active-region)
14901 (org-back-to-heading t))
14902 (org-set-tags arg just-align))))
14904 (defun org-set-tags-to (data)
14905 "Set the tags of the current entry to DATA, replacing the current tags.
14906 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14907 If DATA is nil or the empty string, any tags will be removed."
14908 (interactive "sTags: ")
14909 (setq data
14910 (cond
14911 ((eq data nil) "")
14912 ((equal data "") "")
14913 ((stringp data)
14914 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14915 ":"))
14916 ((listp data)
14917 (concat ":" (mapconcat 'identity data ":") ":"))))
14918 (when data
14919 (save-excursion
14920 (org-back-to-heading t)
14921 (when (looking-at org-complex-heading-regexp)
14922 (if (match-end 5)
14923 (progn
14924 (goto-char (match-beginning 5))
14925 (insert data)
14926 (delete-region (point) (point-at-eol))
14927 (org-set-tags nil 'align))
14928 (goto-char (point-at-eol))
14929 (insert " " data)
14930 (org-set-tags nil 'align)))
14931 (beginning-of-line 1)
14932 (if (looking-at ".*?\\([ \t]+\\)$")
14933 (delete-region (match-beginning 1) (match-end 1))))))
14935 (defun org-align-all-tags ()
14936 "Align the tags i all headings."
14937 (interactive)
14938 (save-excursion
14939 (or (ignore-errors (org-back-to-heading t))
14940 (outline-next-heading))
14941 (if (org-at-heading-p)
14942 (org-set-tags t)
14943 (message "No headings"))))
14945 (defvar org-indent-indentation-per-level)
14946 (defun org-set-tags (&optional arg just-align)
14947 "Set the tags for the current headline.
14948 With prefix ARG, realign all tags in headings in the current buffer.
14949 When JUST-ALIGN is non-nil, only align tags."
14950 (interactive "P")
14951 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14952 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14953 'region-start-level
14954 'region))
14955 org-loop-over-headlines-in-active-region)
14956 (org-map-entries
14957 ;; We don't use ARG and JUST-ALIGN here because these args
14958 ;; are not useful when looping over headlines.
14959 #'org-set-tags
14960 org-loop-over-headlines-in-active-region
14962 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14963 (let ((org-setting-tags t))
14964 (if arg
14965 (save-excursion
14966 (goto-char (point-min))
14967 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14968 (while (re-search-forward org-outline-regexp-bol nil t)
14969 (org-set-tags nil t)
14970 (end-of-line)))
14971 (message "All tags realigned to column %d" org-tags-column))
14972 (let* ((current (org-get-tags-string))
14973 (col (current-column))
14974 (tags
14975 (if just-align current
14976 ;; Get a new set of tags from the user.
14977 (save-excursion
14978 (let* ((table
14979 (setq
14980 org-last-tags-completion-table
14981 (append
14982 org-tag-persistent-alist
14983 (or org-tag-alist (org-get-buffer-tags))
14984 (and
14985 org-complete-tags-always-offer-all-agenda-tags
14986 (org-global-tags-completion-table
14987 (org-agenda-files))))))
14988 (current-tags (org-split-string current ":"))
14989 (inherited-tags
14990 (nreverse (nthcdr (length current-tags)
14991 (nreverse (org-get-tags-at))))))
14992 (replace-regexp-in-string
14993 "\\([-+&]+\\|,\\)"
14995 (if (or (eq t org-use-fast-tag-selection)
14996 (and org-use-fast-tag-selection
14997 (delq nil (mapcar #'cdr table))))
14998 (org-fast-tag-selection
14999 current-tags inherited-tags table
15000 (and org-fast-tag-selection-include-todo
15001 org-todo-key-alist))
15002 (let ((org-add-colon-after-tag-completion
15003 (< 1 (length table))))
15004 (org-trim
15005 (completing-read
15006 "Tags: "
15007 #'org-tags-completion-function
15008 nil nil current 'org-tags-history))))))))))
15010 (when org-tags-sort-function
15011 (setq tags
15012 (mapconcat
15013 #'identity
15014 (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
15015 org-tags-sort-function)
15016 ":")))
15018 (if (not (org-string-nw-p tags)) (setq tags "")
15019 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15020 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15022 ;; Insert new tags at the correct column
15023 (beginning-of-line)
15024 (let ((level (if (looking-at org-outline-regexp)
15025 (- (match-end 0) (point) 1)
15026 1)))
15027 (cond
15028 ((and (equal current "") (equal tags "")))
15029 ((re-search-forward
15030 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15031 (line-end-position)
15033 (if (equal tags "") (replace-match "" t t)
15034 (goto-char (match-beginning 0))
15035 (let* ((c0 (current-column))
15036 ;; Compute offset for the case of org-indent-mode
15037 ;; active.
15038 (di (if (org-bound-and-true-p org-indent-mode)
15039 (* (1- org-indent-indentation-per-level)
15040 (1- level))
15042 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15043 (tc (+ org-tags-column
15044 (if (> org-tags-column 0) (- di) di)))
15045 (c1 (max (1+ c0)
15046 (if (> tc 0) tc
15047 (- (- tc) (string-width tags)))))
15048 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15049 (replace-match rpl t t)
15050 (when (and (not (featurep 'xemacs)) indent-tabs-mode)
15051 (tabify p0 (point))))))
15052 (t (error "Tags alignment failed"))))
15053 (org-move-to-column col))
15054 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15056 (defun org-change-tag-in-region (beg end tag off)
15057 "Add or remove TAG for each entry in the region.
15058 This works in the agenda, and also in an org-mode buffer."
15059 (interactive
15060 (list (region-beginning) (region-end)
15061 (let ((org-last-tags-completion-table
15062 (if (derived-mode-p 'org-mode)
15063 (org-uniquify
15064 (delq nil (append (org-get-buffer-tags)
15065 (org-global-tags-completion-table))))
15066 (org-global-tags-completion-table))))
15067 (org-icompleting-read
15068 "Tag: " 'org-tags-completion-function nil nil nil
15069 'org-tags-history))
15070 (progn
15071 (message "[s]et or [r]emove? ")
15072 (equal (read-char-exclusive) ?r))))
15073 (if (fboundp 'deactivate-mark) (deactivate-mark))
15074 (let ((agendap (equal major-mode 'org-agenda-mode))
15075 l1 l2 m buf pos newhead (cnt 0))
15076 (goto-char end)
15077 (setq l2 (1- (org-current-line)))
15078 (goto-char beg)
15079 (setq l1 (org-current-line))
15080 (loop for l from l1 to l2 do
15081 (org-goto-line l)
15082 (setq m (get-text-property (point) 'org-hd-marker))
15083 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15084 (and agendap m))
15085 (setq buf (if agendap (marker-buffer m) (current-buffer))
15086 pos (if agendap m (point)))
15087 (with-current-buffer buf
15088 (save-excursion
15089 (save-restriction
15090 (goto-char pos)
15091 (setq cnt (1+ cnt))
15092 (org-toggle-tag tag (if off 'off 'on))
15093 (setq newhead (org-get-heading)))))
15094 (and agendap (org-agenda-change-all-lines newhead m))))
15095 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15097 (defun org-tags-completion-function (string predicate &optional flag)
15098 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15099 (confirm (lambda (x) (stringp (car x)))))
15100 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15101 (setq s1 (match-string 1 string)
15102 s2 (match-string 2 string))
15103 (setq s1 "" s2 string))
15104 (cond
15105 ((eq flag nil)
15106 ;; try completion
15107 (setq rtn (try-completion s2 ctable confirm))
15108 (if (stringp rtn)
15109 (setq rtn
15110 (concat s1 s2 (substring rtn (length s2))
15111 (if (and org-add-colon-after-tag-completion
15112 (assoc rtn ctable))
15113 ":" ""))))
15114 rtn)
15115 ((eq flag t)
15116 ;; all-completions
15117 (all-completions s2 ctable confirm))
15118 ((eq flag 'lambda)
15119 ;; exact match?
15120 (assoc s2 ctable)))))
15122 (defun org-fast-tag-insert (kwd tags face &optional end)
15123 "Insert KDW, and the TAGS, the latter with face FACE.
15124 Also insert END."
15125 (insert (format "%-12s" (concat kwd ":"))
15126 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15127 (or end "")))
15129 (defun org-fast-tag-show-exit (flag)
15130 (save-excursion
15131 (org-goto-line 3)
15132 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15133 (replace-match ""))
15134 (when flag
15135 (end-of-line 1)
15136 (org-move-to-column (- (window-width) 19) t)
15137 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15139 (defun org-set-current-tags-overlay (current prefix)
15140 "Add an overlay to CURRENT tag with PREFIX."
15141 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15142 (if (featurep 'xemacs)
15143 (org-overlay-display org-tags-overlay (concat prefix s)
15144 'secondary-selection)
15145 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15146 (org-overlay-display org-tags-overlay (concat prefix s)))))
15148 (defvar org-last-tag-selection-key nil)
15149 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15150 "Fast tag selection with single keys.
15151 CURRENT is the current list of tags in the headline, INHERITED is the
15152 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15153 possibly with grouping information. TODO-TABLE is a similar table with
15154 TODO keywords, should these have keys assigned to them.
15155 If the keys are nil, a-z are automatically assigned.
15156 Returns the new tags string, or nil to not change the current settings."
15157 (let* ((fulltable (append table todo-table))
15158 (maxlen (apply 'max (mapcar
15159 (lambda (x)
15160 (if (stringp (car x)) (string-width (car x)) 0))
15161 fulltable)))
15162 (buf (current-buffer))
15163 (expert (eq org-fast-tag-selection-single-key 'expert))
15164 (buffer-tags nil)
15165 (fwidth (+ maxlen 3 1 3))
15166 (ncol (/ (- (window-width) 4) fwidth))
15167 (i-face 'org-done)
15168 (c-face 'org-todo)
15169 tg cnt e c char c1 c2 ntable tbl rtn
15170 ov-start ov-end ov-prefix
15171 (exit-after-next org-fast-tag-selection-single-key)
15172 (done-keywords org-done-keywords)
15173 groups ingroup intaggroup)
15174 (save-excursion
15175 (beginning-of-line 1)
15176 (if (looking-at
15177 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15178 (setq ov-start (match-beginning 1)
15179 ov-end (match-end 1)
15180 ov-prefix "")
15181 (setq ov-start (1- (point-at-eol))
15182 ov-end (1+ ov-start))
15183 (skip-chars-forward "^\n\r")
15184 (setq ov-prefix
15185 (concat
15186 (buffer-substring (1- (point)) (point))
15187 (if (> (current-column) org-tags-column)
15189 (make-string (- org-tags-column (current-column)) ?\ ))))))
15190 (move-overlay org-tags-overlay ov-start ov-end)
15191 (save-window-excursion
15192 (if expert
15193 (set-buffer (get-buffer-create " *Org tags*"))
15194 (delete-other-windows)
15195 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15196 (org-switch-to-buffer-other-window " *Org tags*"))
15197 (erase-buffer)
15198 (setq-local org-done-keywords done-keywords)
15199 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15200 (org-fast-tag-insert "Current" current c-face "\n\n")
15201 (org-fast-tag-show-exit exit-after-next)
15202 (org-set-current-tags-overlay current ov-prefix)
15203 (setq tbl fulltable char ?a cnt 0)
15204 (while (setq e (pop tbl))
15205 (cond
15206 ((eq (car e) :startgroup)
15207 (push '() groups) (setq ingroup t)
15208 (unless (zerop cnt)
15209 (setq cnt 0)
15210 (insert "\n"))
15211 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15212 ((eq (car e) :endgroup)
15213 (setq ingroup nil cnt 0)
15214 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15215 ((eq (car e) :startgrouptag)
15216 (setq intaggroup t)
15217 (unless (zerop cnt)
15218 (setq cnt 0)
15219 (insert "\n"))
15220 (insert "[ "))
15221 ((eq (car e) :endgrouptag)
15222 (setq intaggroup nil cnt 0)
15223 (insert "]\n"))
15224 ((equal e '(:newline))
15225 (unless (zerop cnt)
15226 (setq cnt 0)
15227 (insert "\n")
15228 (setq e (car tbl))
15229 (while (equal (car tbl) '(:newline))
15230 (insert "\n")
15231 (setq tbl (cdr tbl)))))
15232 ((equal e '(:grouptags)) (insert " : "))
15234 (setq tg (copy-sequence (car e)) c2 nil)
15235 (if (cdr e)
15236 (setq c (cdr e))
15237 ;; automatically assign a character.
15238 (setq c1 (string-to-char
15239 (downcase (substring
15240 tg (if (= (string-to-char tg) ?@) 1 0)))))
15241 (if (or (rassoc c1 ntable) (rassoc c1 table))
15242 (while (or (rassoc char ntable) (rassoc char table))
15243 (setq char (1+ char)))
15244 (setq c2 c1))
15245 (setq c (or c2 char)))
15246 (when ingroup (push tg (car groups)))
15247 (setq tg (org-add-props tg nil 'face
15248 (cond
15249 ((not (assoc tg table))
15250 (org-get-todo-face tg))
15251 ((member tg current) c-face)
15252 ((member tg inherited) i-face))))
15253 (when (equal (caar tbl) :grouptags)
15254 (org-add-props tg nil 'face 'org-tag-group))
15255 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15256 (insert "[" c "] " tg (make-string
15257 (- fwidth 4 (length tg)) ?\ ))
15258 (push (cons tg c) ntable)
15259 (when (= (incf cnt) ncol)
15260 (insert "\n")
15261 (when (or ingroup intaggroup) (insert " "))
15262 (setq cnt 0)))))
15263 (setq ntable (nreverse ntable))
15264 (insert "\n")
15265 (goto-char (point-min))
15266 (unless expert (org-fit-window-to-buffer))
15267 (setq rtn
15268 (catch 'exit
15269 (while t
15270 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15271 (if (not groups) "no " "")
15272 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15273 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15274 (setq org-last-tag-selection-key c)
15275 (cond
15276 ((= c ?\r) (throw 'exit t))
15277 ((= c ?!)
15278 (setq groups (not groups))
15279 (goto-char (point-min))
15280 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15281 ((= c ?\C-c)
15282 (if (not expert)
15283 (org-fast-tag-show-exit
15284 (setq exit-after-next (not exit-after-next)))
15285 (setq expert nil)
15286 (delete-other-windows)
15287 (set-window-buffer (split-window-vertically) " *Org tags*")
15288 (org-switch-to-buffer-other-window " *Org tags*")
15289 (org-fit-window-to-buffer)))
15290 ((or (= c ?\C-g)
15291 (and (= c ?q) (not (rassoc c ntable))))
15292 (org-detach-overlay org-tags-overlay)
15293 (setq quit-flag t))
15294 ((= c ?\ )
15295 (setq current nil)
15296 (when exit-after-next (setq exit-after-next 'now)))
15297 ((= c ?\t)
15298 (condition-case nil
15299 (setq tg (org-icompleting-read
15300 "Tag: "
15301 (or buffer-tags
15302 (with-current-buffer buf
15303 (setq buffer-tags
15304 (org-get-buffer-tags))))))
15305 (quit (setq tg "")))
15306 (when (string-match "\\S-" tg)
15307 (add-to-list 'buffer-tags (list tg))
15308 (if (member tg current)
15309 (setq current (delete tg current))
15310 (push tg current)))
15311 (when exit-after-next (setq exit-after-next 'now)))
15312 ((setq e (rassoc c todo-table) tg (car e))
15313 (with-current-buffer buf
15314 (save-excursion (org-todo tg)))
15315 (when exit-after-next (setq exit-after-next 'now)))
15316 ((setq e (rassoc c ntable) tg (car e))
15317 (if (member tg current)
15318 (setq current (delete tg current))
15319 (loop for g in groups do
15320 (when (member tg g)
15321 (dolist (x g) (setq current (delete x current)))))
15322 (push tg current))
15323 (when exit-after-next (setq exit-after-next 'now))))
15325 ;; Create a sorted list
15326 (setq current
15327 (sort current
15328 (lambda (a b)
15329 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15330 (when (eq exit-after-next 'now) (throw 'exit t))
15331 (goto-char (point-min))
15332 (beginning-of-line 2)
15333 (delete-region (point) (point-at-eol))
15334 (org-fast-tag-insert "Current" current c-face)
15335 (org-set-current-tags-overlay current ov-prefix)
15336 (while (re-search-forward
15337 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15338 (setq tg (match-string 1))
15339 (add-text-properties
15340 (match-beginning 1) (match-end 1)
15341 (list 'face
15342 (cond
15343 ((member tg current) c-face)
15344 ((member tg inherited) i-face)
15345 (t (get-text-property (match-beginning 1) 'face))))))
15346 (goto-char (point-min)))))
15347 (org-detach-overlay org-tags-overlay)
15348 (if rtn
15349 (mapconcat 'identity current ":")
15350 nil))))
15352 (defun org-get-tags-string ()
15353 "Get the TAGS string in the current headline."
15354 (unless (org-at-heading-p t)
15355 (user-error "Not on a heading"))
15356 (save-excursion
15357 (beginning-of-line 1)
15358 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15359 (org-match-string-no-properties 1)
15360 "")))
15362 (defun org-get-tags ()
15363 "Get the list of tags specified in the current headline."
15364 (org-split-string (org-get-tags-string) ":"))
15366 (defun org-get-buffer-tags ()
15367 "Get a table of all tags used in the buffer, for completion."
15368 (org-with-wide-buffer
15369 (goto-char (point-min))
15370 (let ((tag-re (concat org-outline-regexp-bol
15371 "\\(?:.*?[ \t]\\)?"
15372 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15373 tags)
15374 (while (re-search-forward tag-re nil t)
15375 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15376 (push tag tags)))
15377 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15379 ;;;; The mapping API
15381 (defun org-map-entries (func &optional match scope &rest skip)
15382 "Call FUNC at each headline selected by MATCH in SCOPE.
15384 FUNC is a function or a lisp form. The function will be called without
15385 arguments, with the cursor positioned at the beginning of the headline.
15386 The return values of all calls to the function will be collected and
15387 returned as a list.
15389 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15390 does not need to preserve point. After evaluation, the cursor will be
15391 moved to the end of the line (presumably of the headline of the
15392 processed entry) and search continues from there. Under some
15393 circumstances, this may not produce the wanted results. For example,
15394 if you have removed (e.g. archived) the current (sub)tree it could
15395 mean that the next entry will be skipped entirely. In such cases, you
15396 can specify the position from where search should continue by making
15397 FUNC set the variable `org-map-continue-from' to the desired buffer
15398 position.
15400 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15401 Only headlines that are matched by this query will be considered during
15402 the iteration. When MATCH is nil or t, all headlines will be
15403 visited by the iteration.
15405 SCOPE determines the scope of this command. It can be any of:
15407 nil The current buffer, respecting the restriction if any
15408 tree The subtree started with the entry at point
15409 region The entries within the active region, if any
15410 region-start-level
15411 The entries within the active region, but only those at
15412 the same level than the first one.
15413 file The current buffer, without restriction
15414 file-with-archives
15415 The current buffer, and any archives associated with it
15416 agenda All agenda files
15417 agenda-with-archives
15418 All agenda files with any archive files associated with them
15419 \(file1 file2 ...)
15420 If this is a list, all files in the list will be scanned
15422 The remaining args are treated as settings for the skipping facilities of
15423 the scanner. The following items can be given here:
15425 archive skip trees with the archive tag
15426 comment skip trees with the COMMENT keyword
15427 function or Emacs Lisp form:
15428 will be used as value for `org-agenda-skip-function', so
15429 whenever the function returns a position, FUNC will not be
15430 called for that entry and search will continue from the
15431 position returned
15433 If your function needs to retrieve the tags including inherited tags
15434 at the *current* entry, you can use the value of the variable
15435 `org-scanner-tags' which will be much faster than getting the value
15436 with `org-get-tags-at'. If your function gets properties with
15437 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15438 to t around the call to `org-entry-properties' to get the same speedup.
15439 Note that if your function moves around to retrieve tags and properties at
15440 a *different* entry, you cannot use these techniques."
15441 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15442 (not (org-region-active-p)))
15443 (let* ((org-agenda-archives-mode nil) ; just to make sure
15444 (org-agenda-skip-archived-trees (memq 'archive skip))
15445 (org-agenda-skip-comment-trees (memq 'comment skip))
15446 (org-agenda-skip-function
15447 (car (org-delete-all '(comment archive) skip)))
15448 (org-tags-match-list-sublevels t)
15449 (start-level (eq scope 'region-start-level))
15450 matcher file res
15451 org-todo-keywords-for-agenda
15452 org-done-keywords-for-agenda
15453 org-todo-keyword-alist-for-agenda
15454 org-tag-alist-for-agenda
15455 todo-only)
15457 (cond
15458 ((eq match t) (setq matcher t))
15459 ((eq match nil) (setq matcher t))
15460 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15462 (save-excursion
15463 (save-restriction
15464 (cond ((eq scope 'tree)
15465 (org-back-to-heading t)
15466 (org-narrow-to-subtree)
15467 (setq scope nil))
15468 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15469 (org-region-active-p))
15470 ;; If needed, set start-level to a string like "2"
15471 (when start-level
15472 (save-excursion
15473 (goto-char (region-beginning))
15474 (unless (org-at-heading-p) (outline-next-heading))
15475 (setq start-level (org-current-level))))
15476 (narrow-to-region (region-beginning)
15477 (save-excursion
15478 (goto-char (region-end))
15479 (unless (and (bolp) (org-at-heading-p))
15480 (outline-next-heading))
15481 (point)))
15482 (setq scope nil)))
15484 (if (not scope)
15485 (progn
15486 (org-agenda-prepare-buffers
15487 (and buffer-file-name (list buffer-file-name)))
15488 (setq res (org-scan-tags func matcher todo-only start-level)))
15489 ;; Get the right scope
15490 (cond
15491 ((and scope (listp scope) (symbolp (car scope)))
15492 (setq scope (eval scope)))
15493 ((eq scope 'agenda)
15494 (setq scope (org-agenda-files t)))
15495 ((eq scope 'agenda-with-archives)
15496 (setq scope (org-agenda-files t))
15497 (setq scope (org-add-archive-files scope)))
15498 ((eq scope 'file)
15499 (setq scope (and buffer-file-name (list buffer-file-name))))
15500 ((eq scope 'file-with-archives)
15501 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15502 (org-agenda-prepare-buffers scope)
15503 (dolist (file scope)
15504 (with-current-buffer (org-find-base-buffer-visiting file)
15505 (save-excursion
15506 (save-restriction
15507 (widen)
15508 (goto-char (point-min))
15509 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15510 res)))
15512 ;;; Properties API
15514 (defconst org-special-properties
15515 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15516 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15517 "The special properties valid in Org mode.
15518 These are properties that are not defined in the property drawer,
15519 but in some other way.")
15521 (defconst org-default-properties
15522 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15523 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15524 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15525 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15526 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15527 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15528 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15529 "Some properties that are used by Org mode for various purposes.
15530 Being in this list makes sure that they are offered for completion.")
15532 (defun org--update-property-plist (key val props)
15533 "Associate KEY to VAL in alist PROPS.
15534 Modifications are made by side-effect. Return new alist."
15535 (let* ((appending (string= (substring key -1) "+"))
15536 (key (if appending (substring key 0 -1) key))
15537 (old (assoc-string key props t)))
15538 (if (not old) (cons (cons key val) props)
15539 (setcdr old (if appending (concat (cdr old) " " val) val))
15540 props)))
15542 (defun org-get-property-block (&optional beg force)
15543 "Return the (beg . end) range of the body of the property drawer.
15544 BEG is the beginning of the current subtree, or of the part
15545 before the first headline. If it is not given, it will be found.
15546 If the drawer does not exist, create it if FORCE is non-nil, or
15547 return nil."
15548 (org-with-wide-buffer
15549 (when beg (goto-char beg))
15550 (unless (org-before-first-heading-p)
15551 (let ((beg (cond (beg)
15552 ((or (not (featurep 'org-inlinetask))
15553 (org-inlinetask-in-task-p))
15554 (org-back-to-heading t))
15555 (t (org-with-limited-levels (org-back-to-heading t))))))
15556 (forward-line)
15557 (when (org-looking-at-p org-planning-line-re) (forward-line))
15558 (cond ((looking-at org-property-drawer-re)
15559 (forward-line)
15560 (cons (point) (progn (goto-char (match-end 0))
15561 (line-beginning-position))))
15562 (force
15563 (goto-char beg)
15564 (org-insert-property-drawer)
15565 (let ((pos (save-excursion (search-forward ":END:")
15566 (line-beginning-position))))
15567 (cons pos pos))))))))
15569 (defun org-at-property-p ()
15570 "Non-nil when point is inside a property drawer.
15571 See `org-property-re' for match data, if applicable."
15572 (save-excursion
15573 (beginning-of-line)
15574 (and (looking-at org-property-re)
15575 (let ((property-drawer (save-match-data (org-get-property-block))))
15576 (and property-drawer
15577 (>= (point) (car property-drawer))
15578 (< (point) (cdr property-drawer)))))))
15580 (defun org-property-action ()
15581 "Do an action on properties."
15582 (interactive)
15583 (unless (org-at-property-p) (user-error "Not at a property"))
15584 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15585 (let ((c (read-char-exclusive)))
15586 (case c
15587 (?s (call-interactively #'org-set-property))
15588 (?d (call-interactively #'org-delete-property))
15589 (?D (call-interactively #'org-delete-property-globally))
15590 (?c (call-interactively #'org-compute-property-at-point))
15591 (otherwise (user-error "No such property action %c" c)))))
15593 (defun org-inc-effort ()
15594 "Increment the value of the effort property in the current entry."
15595 (interactive)
15596 (org-set-effort nil t))
15598 (defvar org-clock-effort) ; Defined in org-clock.el.
15599 (defvar org-clock-current-task) ; Defined in org-clock.el.
15600 (defun org-set-effort (&optional value increment)
15601 "Set the effort property of the current entry.
15602 With numerical prefix arg, use the nth allowed value, 0 stands for the
15603 10th allowed value.
15605 When INCREMENT is non-nil, set the property to the next allowed value."
15606 (interactive "P")
15607 (if (equal value 0) (setq value 10))
15608 (let* ((completion-ignore-case t)
15609 (prop org-effort-property)
15610 (cur (org-entry-get nil prop))
15611 (allowed (org-property-get-allowed-values nil prop 'table))
15612 (existing (mapcar 'list (org-property-values prop)))
15613 (heading (nth 4 (org-heading-components)))
15615 (val (cond
15616 ((stringp value) value)
15617 ((and allowed (integerp value))
15618 (or (car (nth (1- value) allowed))
15619 (car (org-last allowed))))
15620 ((and allowed increment)
15621 (or (caadr (member (list cur) allowed))
15622 (user-error "Allowed effort values are not set")))
15623 (allowed
15624 (message "Select 1-9,0, [RET%s]: %s"
15625 (if cur (concat "=" cur) "")
15626 (mapconcat 'car allowed " "))
15627 (setq rpl (read-char-exclusive))
15628 (if (equal rpl ?\r)
15630 (setq rpl (- rpl ?0))
15631 (if (equal rpl 0) (setq rpl 10))
15632 (if (and (> rpl 0) (<= rpl (length allowed)))
15633 (car (nth (1- rpl) allowed))
15634 (org-completing-read "Effort: " allowed nil))))
15636 (let (org-completion-use-ido org-completion-use-iswitchb)
15637 (org-completing-read
15638 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15639 (concat "[" cur "]") "")
15640 ": ")
15641 existing nil nil "" nil cur))))))
15642 (unless (equal (org-entry-get nil prop) val)
15643 (org-entry-put nil prop val))
15644 (org-refresh-property
15645 '((effort . identity)
15646 (effort-minutes . org-duration-string-to-minutes))
15647 val)
15648 (when (string= heading org-clock-current-task)
15649 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15650 (org-clock-update-mode-line))
15651 (message "%s is now %s" prop val)))
15653 (defun org-entry-properties (&optional pom which)
15654 "Get all properties of the current entry.
15656 When POM is a buffer position, get all properties from the entry
15657 there instead.
15659 This includes the TODO keyword, the tags, time strings for
15660 deadline, scheduled, and clocking, and any additional properties
15661 defined in the entry.
15663 If WHICH is nil or `all', get all properties. If WHICH is
15664 `special' or `standard', only get that subclass. If WHICH is
15665 a string, only get that property.
15667 Return value is an alist. Keys are properties, as upcased
15668 strings."
15669 (org-with-point-at pom
15670 (when (and (derived-mode-p 'org-mode)
15671 (ignore-errors (org-back-to-heading t)))
15672 (catch 'exit
15673 (let* ((beg (point))
15674 (specific (and (stringp which) (upcase which)))
15675 (which (cond ((not specific) which)
15676 ((member specific org-special-properties) 'special)
15677 (t 'standard)))
15678 props)
15679 ;; Get the special properties, like TODO and TAGS.
15680 (when (memq which '(nil all special))
15681 (when (or (not specific) (string= specific "CLOCKSUM"))
15682 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15683 (when clocksum
15684 (push (cons "CLOCKSUM"
15685 (org-columns-number-to-string
15686 (/ (float clocksum) 60.) 'add_times))
15687 props)))
15688 (when specific (throw 'exit props)))
15689 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15690 (let ((clocksumt (get-text-property (point)
15691 :org-clock-minutes-today)))
15692 (when clocksumt
15693 (push (cons "CLOCKSUM_T"
15694 (org-columns-number-to-string
15695 (/ (float clocksumt) 60.) 'add_times))
15696 props)))
15697 (when specific (throw 'exit props)))
15698 (when (or (not specific) (string= specific "ITEM"))
15699 (when (looking-at org-complex-heading-regexp)
15700 (push (cons "ITEM"
15701 (concat
15702 (org-match-string-no-properties 1)
15703 (let ((title (org-match-string-no-properties 4)))
15704 (when (org-string-nw-p title)
15705 (concat " " (org-remove-tabs title))))))
15706 props))
15707 (when specific (throw 'exit props)))
15708 (when (or (not specific) (string= specific "TODO"))
15709 (let ((case-fold-search nil))
15710 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15711 (push (cons "TODO" (org-match-string-no-properties 2)) props)))
15712 (when specific (throw 'exit props)))
15713 (when (or (not specific) (string= specific "PRIORITY"))
15714 (push (cons "PRIORITY"
15715 (if (looking-at org-priority-regexp)
15716 (org-match-string-no-properties 2)
15717 (char-to-string org-default-priority)))
15718 props)
15719 (when specific (throw 'exit props)))
15720 (when (or (not specific) (string= specific "FILE"))
15721 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15722 props)
15723 (when specific (throw 'exit props)))
15724 (when (or (not specific) (string= specific "TAGS"))
15725 (let ((value (org-string-nw-p (org-get-tags-string))))
15726 (when value (push (cons "TAGS" value) props)))
15727 (when specific (throw 'exit props)))
15728 (when (or (not specific) (string= specific "ALLTAGS"))
15729 (let ((value (org-get-tags-at)))
15730 (when value
15731 (push (cons "ALLTAGS"
15732 (format ":%s:" (mapconcat #'identity value ":")))
15733 props)))
15734 (when specific (throw 'exit props)))
15735 (when (or (not specific) (string= specific "BLOCKED"))
15736 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15737 (when specific (throw 'exit props)))
15738 (when (or (not specific)
15739 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15740 (forward-line)
15741 (when (org-looking-at-p org-planning-line-re)
15742 (end-of-line)
15743 (let ((bol (line-beginning-position))
15744 ;; Backward compatibility: time keywords used to
15745 ;; be configurable (before 8.3). Make sure we
15746 ;; get the correct keyword.
15747 (key-assoc `(("CLOSED" . ,org-closed-string)
15748 ("DEADLINE" . ,org-deadline-string)
15749 ("SCHEDULED" . ,org-scheduled-string))))
15750 (dolist (pair (if specific (list (assoc specific key-assoc))
15751 key-assoc))
15752 (save-excursion
15753 (when (search-backward (cdr pair) bol t)
15754 (goto-char (match-end 0))
15755 (skip-chars-forward " \t")
15756 (and (looking-at org-ts-regexp-both)
15757 (push (cons (car pair)
15758 (org-match-string-no-properties 0))
15759 props)))))))
15760 (when specific (throw 'exit props)))
15761 (when (or (not specific)
15762 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15763 (let ((find-ts
15764 (lambda (end ts)
15765 (let ((regexp (cond
15766 ((string= specific "TIMESTAMP")
15767 org-ts-regexp)
15768 ((string= specific "TIMESTAMP_IA")
15769 org-ts-regexp-inactive)
15770 ((assoc "TIMESTAMP_IA" ts)
15771 org-ts-regexp)
15772 ((assoc "TIMESTAMP" ts)
15773 org-ts-regexp-inactive)
15774 (t org-ts-regexp-both))))
15775 (catch 'next
15776 (while (re-search-forward regexp end t)
15777 (backward-char)
15778 (let ((object (org-element-context)))
15779 ;; Accept to match timestamps in node
15780 ;; properties, too.
15781 (when (memq (org-element-type object)
15782 '(node-property timestamp))
15783 (let ((type
15784 (org-element-property :type object)))
15785 (cond
15786 ((and (memq type '(active active-range))
15787 (not (equal specific "TIMESTAMP_IA")))
15788 (unless (assoc "TIMESTAMP" ts)
15789 (push (cons "TIMESTAMP"
15790 (org-element-property
15791 :raw-value object))
15793 (when specific (throw 'exit ts))))
15794 ((and (memq type '(inactive inactive-range))
15795 (not (string= specific "TIMESTAMP")))
15796 (unless (assoc "TIMESTAMP_IA" ts)
15797 (push (cons "TIMESTAMP_IA"
15798 (org-element-property
15799 :raw-value object))
15801 (when specific (throw 'exit ts))))))
15802 ;; Both timestamp types are found,
15803 ;; move to next part.
15804 (when (= (length ts) 2) (throw 'next ts)))))
15805 ts)))))
15806 (goto-char beg)
15807 ;; First look for timestamps within headline.
15808 (let ((ts (funcall find-ts (line-end-position) nil)))
15809 (if (= (length ts) 2) (setq props (nconc ts props))
15810 (forward-line)
15811 ;; Then find timestamps in the section, skipping
15812 ;; planning line.
15813 (when (org-looking-at-p org-planning-line-re)
15814 (forward-line))
15815 (let ((end (save-excursion (outline-next-heading))))
15816 (setq props (nconc (funcall find-ts end ts) props))))))))
15817 ;; Get the standard properties, like :PROP:.
15818 (when (memq which '(nil all standard))
15819 ;; If we are looking after a specific property, delegate
15820 ;; to `org-entry-get', which is faster. However, make an
15821 ;; exception for "CATEGORY", since it can be also set
15822 ;; through keywords (i.e. #+CATEGORY).
15823 (if (and specific (not (equal specific "CATEGORY")))
15824 (let ((value (org-entry-get beg specific nil t)))
15825 (throw 'exit (and value (list (cons specific value)))))
15826 (let ((range (org-get-property-block beg)))
15827 (when range
15828 (let ((end (cdr range)) seen-base)
15829 (goto-char (car range))
15830 ;; Unlike to `org--update-property-plist', we
15831 ;; handle the case where base values is found
15832 ;; after its extension. We also forbid standard
15833 ;; properties to be named as special properties.
15834 (while (re-search-forward org-property-re end t)
15835 (let* ((key (upcase (org-match-string-no-properties 2)))
15836 (extendp (org-string-match-p "\\+\\'" key))
15837 (key-base (if extendp (substring key 0 -1) key))
15838 (value (org-match-string-no-properties 3)))
15839 (cond
15840 ((member-ignore-case key-base org-special-properties))
15841 (extendp
15842 (setq props
15843 (org--update-property-plist key value props)))
15844 ((member key seen-base))
15845 (t (push key seen-base)
15846 (let ((p (assoc-string key props t)))
15847 (if p (setcdr p (concat value " " (cdr p)))
15848 (push (cons key value) props))))))))))))
15849 (unless (assoc "CATEGORY" props)
15850 (push (cons "CATEGORY" (org-get-category beg)) props)
15851 (when (string= specific "CATEGORY") (throw 'exit props)))
15852 ;; Return value.
15853 props)))))
15855 (defun org-property--local-values (property literal-nil)
15856 "Return value for PROPERTY in current entry.
15857 Value is a list whose care is the base value for PROPERTY and cdr
15858 a list of accumulated values. Return nil if neither is found in
15859 the entry. Also return nil when PROPERTY is set to \"nil\",
15860 unless LITERAL-NIL is non-nil."
15861 (let ((range (org-get-property-block)))
15862 (when range
15863 (goto-char (car range))
15864 (let* ((case-fold-search t)
15865 (end (cdr range))
15866 (value
15867 ;; Base value.
15868 (save-excursion
15869 (let ((v (and (re-search-forward
15870 (org-re-property property nil t) end t)
15871 (org-match-string-no-properties 3))))
15872 (list (if literal-nil v (org-not-nil v)))))))
15873 ;; Find additional values.
15874 (let* ((property+ (org-re-property (concat property "+") nil t)))
15875 (while (re-search-forward property+ end t)
15876 (push (org-match-string-no-properties 3) value)))
15877 ;; Return final values.
15878 (and (not (equal value '(nil))) (nreverse value))))))
15880 (defun org-entry-get (pom property &optional inherit literal-nil)
15881 "Get value of PROPERTY for entry or content at point-or-marker POM.
15883 If INHERIT is non-nil and the entry does not have the property,
15884 then also check higher levels of the hierarchy. If INHERIT is
15885 the symbol `selective', use inheritance only if the setting in
15886 `org-use-property-inheritance' selects PROPERTY for inheritance.
15888 If the property is present but empty, the return value is the
15889 empty string. If the property is not present at all, nil is
15890 returned. In any other case, return the value as a string.
15891 Search is case-insensitive.
15893 If LITERAL-NIL is set, return the string value \"nil\" as
15894 a string, do not interpret it as the list atom nil. This is used
15895 for inheritance when a \"nil\" value can supersede a non-nil
15896 value higher up the hierarchy."
15897 (org-with-point-at pom
15898 (cond
15899 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15900 ;; We need a special property. Use `org-entry-properties' to
15901 ;; retrieve it, but specify the wanted property.
15902 (cdr (assoc-string property (org-entry-properties nil property))))
15903 ((and inherit
15904 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15905 (org-entry-get-with-inheritance property literal-nil))
15907 (let* ((local (org-property--local-values property literal-nil))
15908 (value (and local (mapconcat #'identity (delq nil local) " "))))
15909 (if literal-nil value (org-not-nil value)))))))
15911 (defun org-property-or-variable-value (var &optional inherit)
15912 "Check if there is a property fixing the value of VAR.
15913 If yes, return this value. If not, return the current value of the variable."
15914 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15915 (if (and prop (stringp prop) (string-match "\\S-" prop))
15916 (read prop)
15917 (symbol-value var))))
15919 (defun org-entry-delete (pom property)
15920 "Delete PROPERTY from entry at point-or-marker POM.
15921 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15922 non-nil when a property was removed."
15923 (unless (member property org-special-properties)
15924 (org-with-point-at pom
15925 (let ((range (org-get-property-block)))
15926 (when range
15927 (let* ((begin (car range))
15928 (origin (cdr range))
15929 (end (copy-marker origin))
15930 (re (org-re-property
15931 (concat (regexp-quote property) "\\+?") t t)))
15932 (goto-char begin)
15933 (while (re-search-forward re end t)
15934 (delete-region (match-beginning 0) (line-beginning-position 2)))
15935 ;; If drawer is empty, remove it altogether.
15936 (when (= begin end)
15937 (delete-region (line-beginning-position 0)
15938 (line-beginning-position 2)))
15939 ;; Return non-nil if some property was removed.
15940 (prog1 (/= end origin) (set-marker end nil))))))))
15942 ;; Multi-values properties are properties that contain multiple values
15943 ;; These values are assumed to be single words, separated by whitespace.
15944 (defun org-entry-add-to-multivalued-property (pom property value)
15945 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15946 (let* ((old (org-entry-get pom property))
15947 (values (and old (org-split-string old "[ \t]"))))
15948 (setq value (org-entry-protect-space value))
15949 (unless (member value values)
15950 (setq values (append values (list value)))
15951 (org-entry-put pom property
15952 (mapconcat 'identity values " ")))))
15954 (defun org-entry-remove-from-multivalued-property (pom property value)
15955 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15956 (let* ((old (org-entry-get pom property))
15957 (values (and old (org-split-string old "[ \t]"))))
15958 (setq value (org-entry-protect-space value))
15959 (when (member value values)
15960 (setq values (delete value values))
15961 (org-entry-put pom property
15962 (mapconcat 'identity values " ")))))
15964 (defun org-entry-member-in-multivalued-property (pom property value)
15965 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15966 (let* ((old (org-entry-get pom property))
15967 (values (and old (org-split-string old "[ \t]"))))
15968 (setq value (org-entry-protect-space value))
15969 (member value values)))
15971 (defun org-entry-get-multivalued-property (pom property)
15972 "Return a list of values in a multivalued property."
15973 (let* ((value (org-entry-get pom property))
15974 (values (and value (org-split-string value "[ \t]"))))
15975 (mapcar 'org-entry-restore-space values)))
15977 (defun org-entry-put-multivalued-property (pom property &rest values)
15978 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15979 VALUES should be a list of strings. Spaces will be protected."
15980 (org-entry-put pom property
15981 (mapconcat 'org-entry-protect-space values " "))
15982 (let* ((value (org-entry-get pom property))
15983 (values (and value (org-split-string value "[ \t]"))))
15984 (mapcar 'org-entry-restore-space values)))
15986 (defun org-entry-protect-space (s)
15987 "Protect spaces and newline in string S."
15988 (while (string-match " " s)
15989 (setq s (replace-match "%20" t t s)))
15990 (while (string-match "\n" s)
15991 (setq s (replace-match "%0A" t t s)))
15994 (defun org-entry-restore-space (s)
15995 "Restore spaces and newline in string S."
15996 (while (string-match "%20" s)
15997 (setq s (replace-match " " t t s)))
15998 (while (string-match "%0A" s)
15999 (setq s (replace-match "\n" t t s)))
16002 (defvar org-entry-property-inherited-from (make-marker)
16003 "Marker pointing to the entry from where a property was inherited.
16004 Each call to `org-entry-get-with-inheritance' will set this marker to the
16005 location of the entry where the inheritance search matched. If there was
16006 no match, the marker will point nowhere.
16007 Note that also `org-entry-get' calls this function, if the INHERIT flag
16008 is set.")
16010 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16011 "Get PROPERTY of entry or content at point, search higher levels if needed.
16012 The search will stop at the first ancestor which has the property defined.
16013 If the value found is \"nil\", return nil to show that the property
16014 should be considered as undefined (this is the meaning of nil here).
16015 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16016 (move-marker org-entry-property-inherited-from nil)
16017 (org-with-wide-buffer
16018 (let (value)
16019 (catch 'exit
16020 (while t
16021 (let ((v (org-property--local-values property literal-nil)))
16022 (when v
16023 (setq value
16024 (concat (mapconcat #'identity (delq nil v) " ")
16025 (and value " ")
16026 value)))
16027 (cond
16028 ((car v)
16029 (org-back-to-heading t)
16030 (move-marker org-entry-property-inherited-from (point))
16031 (throw 'exit nil))
16032 ((org-up-heading-safe))
16034 (let ((global
16035 (cdr (or (assoc-string property org-file-properties t)
16036 (assoc-string property org-global-properties t)
16037 (assoc-string property org-global-properties-fixed t)))))
16038 (cond ((not global))
16039 (value (setq value (concat global " " value)))
16040 (t (setq value global))))
16041 (throw 'exit nil))))))
16042 (if literal-nil value (org-not-nil value)))))
16044 (defvar org-property-changed-functions nil
16045 "Hook called when the value of a property has changed.
16046 Each hook function should accept two arguments, the name of the property
16047 and the new value.")
16049 (defun org-entry-put (pom property value)
16050 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16052 If the value is nil, it is converted to the empty string. If
16053 it is not a string, an error is raised.
16055 PROPERTY can be any regular property (see
16056 `org-special-properties'). It can also be \"TODO\",
16057 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16059 For the last two properties, VALUE may have any of the special
16060 values \"earlier\" and \"later\". The function then increases or
16061 decreases scheduled or deadline date by one day."
16062 (cond ((null value) (setq value ""))
16063 ((not (stringp value)) (error "Properties values should be strings")))
16064 (org-with-point-at pom
16065 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16066 (org-back-to-heading t)
16067 (org-with-limited-levels (org-back-to-heading t)))
16068 (let ((beg (point)))
16069 (cond
16070 ((equal property "TODO")
16071 (cond ((not (org-string-nw-p value)) (setq value 'none))
16072 ((not (member value org-todo-keywords-1))
16073 (user-error "\"%s\" is not a valid TODO state" value)))
16074 (org-todo value)
16075 (org-set-tags nil 'align))
16076 ((equal property "PRIORITY")
16077 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16078 (org-set-tags nil 'align))
16079 ((equal property "SCHEDULED")
16080 (forward-line)
16081 (if (and (org-looking-at-p org-planning-line-re)
16082 (re-search-forward
16083 org-scheduled-time-regexp (line-end-position) t))
16084 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16085 ((string= value "later") (org-timestamp-change 1 'day))
16086 ((string= value "") (org-schedule '(4)))
16087 (t (org-schedule nil value)))
16088 (if (member value '("earlier" "later" ""))
16089 (call-interactively #'org-schedule)
16090 (org-schedule nil value))))
16091 ((equal property "DEADLINE")
16092 (forward-line)
16093 (if (and (org-looking-at-p org-planning-line-re)
16094 (re-search-forward
16095 org-deadline-time-regexp (line-end-position) t))
16096 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16097 ((string= value "later") (org-timestamp-change 1 'day))
16098 ((string= value "") (org-deadline '(4)))
16099 (t (org-deadline nil value)))
16100 (if (member value '("earlier" "later" ""))
16101 (call-interactively #'org-deadline)
16102 (org-deadline nil value))))
16103 ((member property org-special-properties)
16104 (error "The %s property cannot be set with `org-entry-put'" property))
16106 (let* ((range (org-get-property-block beg 'force))
16107 (end (cdr range))
16108 (case-fold-search t))
16109 (goto-char (car range))
16110 (if (re-search-forward (org-re-property property nil t) end t)
16111 (progn (delete-region (match-beginning 0) (match-end 0))
16112 (goto-char (match-beginning 0)))
16113 (goto-char end)
16114 (insert "\n")
16115 (backward-char))
16116 (insert ":" property ":")
16117 (when value (insert " " value))
16118 (org-indent-line)))))
16119 (run-hook-with-args 'org-property-changed-functions property value)))
16121 (defun org-buffer-property-keys (&optional specials defaults columns)
16122 "Get all property keys in the current buffer.
16124 When SPECIALS is non-nil, also list the special properties that
16125 reflect things like tags and TODO state.
16127 When DEFAULTS is non-nil, also include properties that has
16128 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16129 DESCRIPTION, LOCATION, and LOGGING and others.
16131 When COLUMNS in non-nil, also include property names given in
16132 COLUMN formats in the current buffer."
16133 (let ((case-fold-search t)
16134 (props (append
16135 (and specials org-special-properties)
16136 (and defaults (cons org-effort-property org-default-properties))
16137 nil)))
16138 (org-with-wide-buffer
16139 (goto-char (point-min))
16140 (while (re-search-forward org-property-start-re nil t)
16141 (let ((range (org-get-property-block)))
16142 (catch 'skip
16143 (unless range
16144 (when (and (not (org-before-first-heading-p))
16145 (y-or-n-p (format "Malformed drawer at %d, repair?"
16146 (line-beginning-position))))
16147 (org-get-property-block nil t))
16148 (throw 'skip nil))
16149 (goto-char (car range))
16150 (let ((begin (car range))
16151 (end (cdr range)))
16152 ;; Make sure that found property block is not located
16153 ;; before current point, as it would generate an infloop.
16154 ;; It can happen, for example, in the following
16155 ;; situation:
16157 ;; * Headline
16158 ;; :PROPERTIES:
16159 ;; ...
16160 ;; :END:
16161 ;; *************** Inlinetask
16162 ;; #+BEGIN_EXAMPLE
16163 ;; :PROPERTIES:
16164 ;; #+END_EXAMPLE
16166 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16167 (while (< (point) end)
16168 (let ((p (progn (looking-at org-property-re)
16169 (org-match-string-no-properties 2))))
16170 ;; Only add true property name, not extension symbol.
16171 (add-to-list 'props
16172 (if (not (org-string-match-p "\\+\\'" p)) p
16173 (substring p 0 -1))))
16174 (forward-line))))
16175 (outline-next-heading)))
16176 (when columns
16177 (goto-char (point-min))
16178 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16179 (let ((element (org-element-at-point)))
16180 (when (memq (org-element-type element) '(keyword node-property))
16181 (let ((value (org-element-property :value element))
16182 (start 0))
16183 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16184 (setq start (match-end 0))
16185 (let ((p (org-match-string-no-properties 1 value)))
16186 (unless (member-ignore-case p org-special-properties)
16187 (add-to-list 'props p))))))))))
16188 (sort props (lambda (a b) (string< (upcase a) (upcase b))))))
16190 (defun org-property-values (key)
16191 "List all non-nil values of property KEY in current buffer."
16192 (org-with-wide-buffer
16193 (goto-char (point-min))
16194 (let ((case-fold-search t)
16195 (re (org-re-property key))
16196 values)
16197 (while (re-search-forward re nil t)
16198 (add-to-list 'values (org-entry-get (point) key)))
16199 values)))
16201 (defun org-insert-property-drawer ()
16202 "Insert a property drawer into the current entry."
16203 (org-with-wide-buffer
16204 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16205 (org-back-to-heading t)
16206 (org-with-limited-levels (org-back-to-heading t)))
16207 (forward-line)
16208 (when (org-looking-at-p org-planning-line-re) (forward-line))
16209 (unless (org-looking-at-p org-property-drawer-re)
16210 ;; Make sure we start editing a line from current entry, not from
16211 ;; next one. It prevents extending text properties or overlays
16212 ;; belonging to the latter.
16213 (when (bolp) (backward-char))
16214 (let ((begin (1+ (point)))
16215 (inhibit-read-only t))
16216 (insert "\n:PROPERTIES:\n:END:")
16217 (when (eobp) (insert "\n"))
16218 (org-indent-region begin (point))))))
16220 (defun org-insert-drawer (&optional arg drawer)
16221 "Insert a drawer at point.
16223 When optional argument ARG is non-nil, insert a property drawer.
16225 Optional argument DRAWER, when non-nil, is a string representing
16226 drawer's name. Otherwise, the user is prompted for a name.
16228 If a region is active, insert the drawer around that region
16229 instead.
16231 Point is left between drawer's boundaries."
16232 (interactive "P")
16233 (let* ((drawer (if arg "PROPERTIES"
16234 (or drawer (read-from-minibuffer "Drawer: ")))))
16235 (cond
16236 ;; With C-u, fall back on `org-insert-property-drawer'
16237 (arg (org-insert-property-drawer))
16238 ;; Check validity of suggested drawer's name.
16239 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16240 (user-error "Invalid drawer name"))
16241 ;; With an active region, insert a drawer at point.
16242 ((not (org-region-active-p))
16243 (progn
16244 (unless (bolp) (insert "\n"))
16245 (insert (format ":%s:\n\n:END:\n" drawer))
16246 (forward-line -2)))
16247 ;; Otherwise, insert the drawer at point
16249 (let ((rbeg (region-beginning))
16250 (rend (copy-marker (region-end))))
16251 (unwind-protect
16252 (progn
16253 (goto-char rbeg)
16254 (beginning-of-line)
16255 (when (save-excursion
16256 (re-search-forward org-outline-regexp-bol rend t))
16257 (user-error "Drawers cannot contain headlines"))
16258 ;; Position point at the beginning of the first
16259 ;; non-blank line in region. Insert drawer's opening
16260 ;; there, then indent it.
16261 (org-skip-whitespace)
16262 (beginning-of-line)
16263 (insert ":" drawer ":\n")
16264 (forward-line -1)
16265 (indent-for-tab-command)
16266 ;; Move point to the beginning of the first blank line
16267 ;; after the last non-blank line in region. Insert
16268 ;; drawer's closing, then indent it.
16269 (goto-char rend)
16270 (skip-chars-backward " \r\t\n")
16271 (insert "\n:END:")
16272 (deactivate-mark t)
16273 (indent-for-tab-command)
16274 (unless (eolp) (insert "\n")))
16275 ;; Clear marker, whatever the outcome of insertion is.
16276 (set-marker rend nil)))))))
16278 (defvar org-property-set-functions-alist nil
16279 "Property set function alist.
16280 Each entry should have the following format:
16282 (PROPERTY . READ-FUNCTION)
16284 The read function will be called with the same argument as
16285 `org-completing-read'.")
16287 (defun org-set-property-function (property)
16288 "Get the function that should be used to set PROPERTY.
16289 This is computed according to `org-property-set-functions-alist'."
16290 (or (cdr (assoc property org-property-set-functions-alist))
16291 'org-completing-read))
16293 (defun org-read-property-value (property)
16294 "Read PROPERTY value from user."
16295 (let* ((completion-ignore-case t)
16296 (allowed (org-property-get-allowed-values nil property 'table))
16297 (cur (org-entry-get nil property))
16298 (prompt (concat property " value"
16299 (if (and cur (string-match "\\S-" cur))
16300 (concat " [" cur "]") "") ": "))
16301 (set-function (org-set-property-function property))
16302 (val (if allowed
16303 (funcall set-function prompt allowed nil
16304 (not (get-text-property 0 'org-unrestricted
16305 (caar allowed))))
16306 (let (org-completion-use-ido org-completion-use-iswitchb)
16307 (funcall set-function prompt
16308 (mapcar 'list (org-property-values property))
16309 nil nil "" nil cur)))))
16310 (org-trim val)))
16312 (defvar org-last-set-property nil)
16313 (defvar org-last-set-property-value nil)
16314 (defun org-read-property-name ()
16315 "Read a property name."
16316 (let ((completion-ignore-case t)
16317 (default-prop (or (and (org-at-property-p)
16318 (org-match-string-no-properties 2))
16319 org-last-set-property)))
16320 (org-completing-read
16321 (concat "Property"
16322 (if default-prop (concat " [" default-prop "]") "")
16323 ": ")
16324 (mapcar #'list (org-buffer-property-keys nil t t))
16325 nil nil nil nil default-prop)))
16327 (defun org-set-property-and-value (use-last)
16328 "Allow to set [PROPERTY]: [value] direction from prompt.
16329 When use-default, don't even ask, just use the last
16330 \"[PROPERTY]: [value]\" string from the history."
16331 (interactive "P")
16332 (let* ((completion-ignore-case t)
16333 (pv (or (and use-last org-last-set-property-value)
16334 (org-completing-read
16335 "Enter a \"[Property]: [value]\" pair: "
16336 nil nil nil nil nil
16337 org-last-set-property-value)))
16338 prop val)
16339 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16340 (setq prop (match-string 1 pv)
16341 val (match-string 2 pv))
16342 (org-set-property prop val))))
16344 (defun org-set-property (property value)
16345 "In the current entry, set PROPERTY to VALUE.
16346 When called interactively, this will prompt for a property name, offering
16347 completion on existing and default properties. And then it will prompt
16348 for a value, offering completion either on allowed values (via an inherited
16349 xxx_ALL property) or on existing values in other instances of this property
16350 in the current file."
16351 (interactive (list nil nil))
16352 (let* ((property (or property (org-read-property-name)))
16353 (value (or value (org-read-property-value property)))
16354 (fn (cdr (assoc property org-properties-postprocess-alist))))
16355 (setq org-last-set-property property)
16356 (setq org-last-set-property-value (concat property ": " value))
16357 ;; Possibly postprocess the inserted value:
16358 (when fn (setq value (funcall fn value)))
16359 (unless (equal (org-entry-get nil property) value)
16360 (org-entry-put nil property value))))
16362 (defun org-find-property (property &optional value)
16363 "Find first entry in buffer that sets PROPERTY.
16365 When optional argument VALUE is non-nil, only consider an entry
16366 if it contains PROPERTY set to this value. If PROPERTY should be
16367 explicitly set to nil, use string \"nil\" for VALUE.
16369 Return position where the entry begins, or nil if there is no
16370 such entry. If narrowing is in effect, only search the visible
16371 part of the buffer."
16372 (save-excursion
16373 (goto-char (point-min))
16374 (let ((case-fold-search t)
16375 (re (org-re-property property nil (not value) value)))
16376 (catch 'exit
16377 (while (re-search-forward re nil t)
16378 (when (if value (org-at-property-p)
16379 (org-entry-get (point) property nil t))
16380 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16382 (defun org-delete-property (property)
16383 "In the current entry, delete PROPERTY."
16384 (interactive
16385 (let* ((completion-ignore-case t)
16386 (cat (org-entry-get (point) "CATEGORY"))
16387 (props0 (org-entry-properties nil 'standard))
16388 (props (if cat props0
16389 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16390 (prop (if (< 1 (length props))
16391 (org-icompleting-read "Property: " props nil t)
16392 (caar props))))
16393 (list prop)))
16394 (if (not property)
16395 (message "No property to delete in this entry")
16396 (org-entry-delete nil property)
16397 (message "Property \"%s\" deleted" property)))
16399 (defun org-delete-property-globally (property)
16400 "Remove PROPERTY globally, from all entries.
16401 This function ignores narrowing, if any."
16402 (interactive
16403 (let* ((completion-ignore-case t)
16404 (prop (org-icompleting-read
16405 "Globally remove property: "
16406 (mapcar #'list (org-buffer-property-keys)))))
16407 (list prop)))
16408 (org-with-wide-buffer
16409 (goto-char (point-min))
16410 (let ((count 0)
16411 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16412 (while (re-search-forward re nil t)
16413 (when (org-entry-delete (point) property) (incf count)))
16414 (message "Property \"%s\" removed from %d entries" property count))))
16416 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16418 (defun org-compute-property-at-point ()
16419 "Compute the property at point.
16420 This looks for an enclosing column format, extracts the operator and
16421 then applies it to the property in the column format's scope."
16422 (interactive)
16423 (unless (org-at-property-p)
16424 (user-error "Not at a property"))
16425 (let ((prop (org-match-string-no-properties 2)))
16426 (org-columns-get-format-and-top-level)
16427 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16428 (user-error "No operator defined for property %s" prop))
16429 (org-columns-compute prop)))
16431 (defvar org-property-allowed-value-functions nil
16432 "Hook for functions supplying allowed values for a specific property.
16433 The functions must take a single argument, the name of the property, and
16434 return a flat list of allowed values. If \":ETC\" is one of
16435 the values, this means that these values are intended as defaults for
16436 completion, but that other values should be allowed too.
16437 The functions must return nil if they are not responsible for this
16438 property.")
16440 (defun org-property-get-allowed-values (pom property &optional table)
16441 "Get allowed values for the property PROPERTY.
16442 When TABLE is non-nil, return an alist that can directly be used for
16443 completion."
16444 (let (vals)
16445 (cond
16446 ((equal property "TODO")
16447 (setq vals (org-with-point-at pom
16448 (append org-todo-keywords-1 '("")))))
16449 ((equal property "PRIORITY")
16450 (let ((n org-lowest-priority))
16451 (while (>= n org-highest-priority)
16452 (push (char-to-string n) vals)
16453 (setq n (1- n)))))
16454 ((equal property "CATEGORY"))
16455 ((member property org-special-properties))
16456 ((setq vals (run-hook-with-args-until-success
16457 'org-property-allowed-value-functions property)))
16459 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16460 (when (and vals (string-match "\\S-" vals))
16461 (setq vals (car (read-from-string (concat "(" vals ")"))))
16462 (setq vals (mapcar (lambda (x)
16463 (cond ((stringp x) x)
16464 ((numberp x) (number-to-string x))
16465 ((symbolp x) (symbol-name x))
16466 (t "???")))
16467 vals)))))
16468 (when (member ":ETC" vals)
16469 (setq vals (remove ":ETC" vals))
16470 (org-add-props (car vals) '(org-unrestricted t)))
16471 (if table (mapcar 'list vals) vals)))
16473 (defun org-property-previous-allowed-value (&optional previous)
16474 "Switch to the next allowed value for this property."
16475 (interactive)
16476 (org-property-next-allowed-value t))
16478 (defun org-property-next-allowed-value (&optional previous)
16479 "Switch to the next allowed value for this property."
16480 (interactive)
16481 (unless (org-at-property-p)
16482 (user-error "Not at a property"))
16483 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16484 (key (match-string 2))
16485 (value (match-string 3))
16486 (allowed (or (org-property-get-allowed-values (point) key)
16487 (and (member value '("[ ]" "[-]" "[X]"))
16488 '("[ ]" "[X]"))))
16489 (heading (save-match-data (nth 4 (org-heading-components))))
16490 nval)
16491 (unless allowed
16492 (user-error "Allowed values for this property have not been defined"))
16493 (if previous (setq allowed (reverse allowed)))
16494 (if (member value allowed)
16495 (setq nval (car (cdr (member value allowed)))))
16496 (setq nval (or nval (car allowed)))
16497 (if (equal nval value)
16498 (user-error "Only one allowed value for this property"))
16499 (org-at-property-p)
16500 (replace-match (concat " :" key ": " nval) t t)
16501 (org-indent-line)
16502 (beginning-of-line 1)
16503 (skip-chars-forward " \t")
16504 (when (equal prop org-effort-property)
16505 (org-refresh-property
16506 '((effort . identity)
16507 (effort-minutes . org-duration-string-to-minutes))
16508 nval)
16509 (when (string= org-clock-current-task heading)
16510 (setq org-clock-effort nval)
16511 (org-clock-update-mode-line)))
16512 (run-hook-with-args 'org-property-changed-functions key nval)))
16514 (defun org-find-olp (path &optional this-buffer)
16515 "Return a marker pointing to the entry at outline path OLP.
16516 If anything goes wrong, throw an error.
16517 You can wrap this call to catch the error like this:
16519 (condition-case msg
16520 (org-mobile-locate-entry (match-string 4))
16521 (error (nth 1 msg)))
16523 The return value will then be either a string with the error message,
16524 or a marker if everything is OK.
16526 If THIS-BUFFER is set, the outline path does not contain a file,
16527 only headings."
16528 (let* ((file (if this-buffer buffer-file-name (pop path)))
16529 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16530 (level 1)
16531 (lmin 1)
16532 (lmax 1)
16533 limit re end found pos heading cnt flevel)
16534 (unless buffer (error "File not found :%s" file))
16535 (with-current-buffer buffer
16536 (save-excursion
16537 (save-restriction
16538 (widen)
16539 (setq limit (point-max))
16540 (goto-char (point-min))
16541 (dolist (heading path)
16542 (setq re (format org-complex-heading-regexp-format
16543 (regexp-quote heading)))
16544 (setq cnt 0 pos (point))
16545 (while (re-search-forward re end t)
16546 (setq level (- (match-end 1) (match-beginning 1)))
16547 (if (and (>= level lmin) (<= level lmax))
16548 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16549 (when (= cnt 0) (error "Heading not found on level %d: %s"
16550 lmax heading))
16551 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16552 lmax heading))
16553 (goto-char found)
16554 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16555 (setq end (save-excursion (org-end-of-subtree t t))))
16556 (when (org-at-heading-p)
16557 (point-marker)))))))
16559 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16560 "Find node HEADING in BUFFER.
16561 Return a marker to the heading if it was found, or nil if not.
16562 If POS-ONLY is set, return just the position instead of a marker.
16564 The heading text must match exact, but it may have a TODO keyword,
16565 a priority cookie and tags in the standard locations."
16566 (with-current-buffer (or buffer (current-buffer))
16567 (save-excursion
16568 (save-restriction
16569 (widen)
16570 (goto-char (point-min))
16571 (let (case-fold-search)
16572 (if (re-search-forward
16573 (format org-complex-heading-regexp-format
16574 (regexp-quote heading)) nil t)
16575 (if pos-only
16576 (match-beginning 0)
16577 (move-marker (make-marker) (match-beginning 0)))))))))
16579 (defun org-find-exact-heading-in-directory (heading &optional dir)
16580 "Find Org node headline HEADING in all .org files in directory DIR.
16581 When the target headline is found, return a marker to this location."
16582 (let ((files (directory-files (or dir default-directory)
16583 t "\\`[^.#].*\\.org\\'"))
16584 visiting m buffer)
16585 (catch 'found
16586 (dolist (file files)
16587 (message "trying %s" file)
16588 (setq visiting (org-find-base-buffer-visiting file))
16589 (setq buffer (or visiting (find-file-noselect file)))
16590 (setq m (org-find-exact-headline-in-buffer
16591 heading buffer))
16592 (when (and (not m) (not visiting)) (kill-buffer buffer))
16593 (and m (throw 'found m))))))
16595 (defun org-find-entry-with-id (ident)
16596 "Locate the entry that contains the ID property with exact value IDENT.
16597 IDENT can be a string, a symbol or a number, this function will search for
16598 the string representation of it.
16599 Return the position where this entry starts, or nil if there is no such entry."
16600 (interactive "sID: ")
16601 (let ((id (cond
16602 ((stringp ident) ident)
16603 ((symbolp ident) (symbol-name ident))
16604 ((numberp ident) (number-to-string ident))
16605 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16606 (org-with-wide-buffer (org-find-property "ID" id))))
16608 ;;;; Timestamps
16610 (defvar org-last-changed-timestamp nil)
16611 (defvar org-last-inserted-timestamp nil
16612 "The last time stamp inserted with `org-insert-time-stamp'.")
16613 (defvar org-ts-what) ; dynamically scoped parameter
16615 (defun org-time-stamp (arg &optional inactive)
16616 "Prompt for a date/time and insert a time stamp.
16618 If the user specifies a time like HH:MM or if this command is
16619 called with at least one prefix argument, the time stamp contains
16620 the date and the time. Otherwise, only the date is included.
16622 All parts of a date not specified by the user are filled in from
16623 the timestamp at point, if any, or the current date/time
16624 otherwise.
16626 If there is already a timestamp at the cursor, it is replaced.
16628 With two universal prefix arguments, insert an active timestamp
16629 with the current time without prompting the user.
16631 When called from lisp, the timestamp is inactive if INACTIVE is
16632 non-nil."
16633 (interactive "P")
16634 (let* ((ts (cond
16635 ((org-at-date-range-p t)
16636 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16637 ((org-at-timestamp-p t) (match-string 0))))
16638 ;; Default time is either the timestamp at point or today.
16639 ;; When entering a range, only the range start is considered.
16640 (default-time (if (not ts) (current-time)
16641 (apply #'encode-time (org-parse-time-string ts))))
16642 (default-input (and ts (org-get-compact-tod ts)))
16643 (repeater (and ts
16644 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16645 (match-string 0 ts)))
16646 org-time-was-given
16647 org-end-time-was-given
16648 (time
16649 (and (if (equal arg '(16)) (current-time)
16650 ;; Preserve `this-command' and `last-command'.
16651 (let ((this-command this-command)
16652 (last-command last-command))
16653 (org-read-date
16654 arg 'totime nil nil default-time default-input
16655 inactive))))))
16656 (cond
16657 ((and ts
16658 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16659 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16660 (insert "--")
16661 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16663 ;; Make sure we're on a timestamp. When in the middle of a date
16664 ;; range, move arbitrarily to range end.
16665 (unless (org-at-timestamp-p t)
16666 (skip-chars-forward "-")
16667 (org-at-timestamp-p t))
16668 (replace-match "")
16669 (setq org-last-changed-timestamp
16670 (org-insert-time-stamp
16671 time (or org-time-was-given arg)
16672 inactive nil nil (list org-end-time-was-given)))
16673 (when repeater
16674 (backward-char)
16675 (insert " " repeater)
16676 (setq org-last-changed-timestamp
16677 (concat (substring org-last-inserted-timestamp 0 -1)
16678 " " repeater ">")))
16679 (message "Timestamp updated"))
16680 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16681 (t (org-insert-time-stamp
16682 time (or org-time-was-given arg) inactive nil nil
16683 (list org-end-time-was-given))))))
16685 ;; FIXME: can we use this for something else, like computing time differences?
16686 (defun org-get-compact-tod (s)
16687 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16688 (let* ((t1 (match-string 1 s))
16689 (h1 (string-to-number (match-string 2 s)))
16690 (m1 (string-to-number (match-string 3 s)))
16691 (t2 (and (match-end 4) (match-string 5 s)))
16692 (h2 (and t2 (string-to-number (match-string 6 s))))
16693 (m2 (and t2 (string-to-number (match-string 7 s))))
16694 dh dm)
16695 (if (not t2)
16697 (setq dh (- h2 h1) dm (- m2 m1))
16698 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16699 (concat t1 "+" (number-to-string dh)
16700 (and (/= 0 dm) (format ":%02d" dm)))))))
16702 (defun org-time-stamp-inactive (&optional arg)
16703 "Insert an inactive time stamp.
16704 An inactive time stamp is enclosed in square brackets instead of angle
16705 brackets. It is inactive in the sense that it does not trigger agenda entries,
16706 does not link to the calendar and cannot be changed with the S-cursor keys.
16707 So these are more for recording a certain time/date."
16708 (interactive "P")
16709 (org-time-stamp arg 'inactive))
16711 (defvar org-date-ovl (make-overlay 1 1))
16712 (overlay-put org-date-ovl 'face 'org-date-selected)
16713 (org-detach-overlay org-date-ovl)
16715 (defvar org-ans1) ; dynamically scoped parameter
16716 (defvar org-ans2) ; dynamically scoped parameter
16718 (defvar org-plain-time-of-day-regexp) ; defined below
16720 (defvar org-overriding-default-time nil) ; dynamically scoped
16721 (defvar org-read-date-overlay nil)
16722 (defvar org-dcst nil) ; dynamically scoped
16723 (defvar org-read-date-history nil)
16724 (defvar org-read-date-final-answer nil)
16725 (defvar org-read-date-analyze-futurep nil)
16726 (defvar org-read-date-analyze-forced-year nil)
16727 (defvar org-read-date-inactive)
16729 (defvar org-read-date-minibuffer-local-map
16730 (let* ((map (make-sparse-keymap)))
16731 (set-keymap-parent map minibuffer-local-map)
16732 (org-defkey map (kbd ".")
16733 (lambda () (interactive)
16734 ;; Are we at the beginning of the prompt?
16735 (if (org-looking-back "^[^:]+: "
16736 (let ((inhibit-field-text-motion t))
16737 (line-beginning-position)))
16738 (org-eval-in-calendar '(calendar-goto-today))
16739 (insert "."))))
16740 (org-defkey map (kbd "C-.")
16741 (lambda () (interactive)
16742 (org-eval-in-calendar '(calendar-goto-today))))
16743 (org-defkey map [(meta shift left)]
16744 (lambda () (interactive)
16745 (org-eval-in-calendar '(calendar-backward-month 1))))
16746 (org-defkey map [(meta shift right)]
16747 (lambda () (interactive)
16748 (org-eval-in-calendar '(calendar-forward-month 1))))
16749 (org-defkey map [(meta shift up)]
16750 (lambda () (interactive)
16751 (org-eval-in-calendar '(calendar-backward-year 1))))
16752 (org-defkey map [(meta shift down)]
16753 (lambda () (interactive)
16754 (org-eval-in-calendar '(calendar-forward-year 1))))
16755 (org-defkey map [?\e (shift left)]
16756 (lambda () (interactive)
16757 (org-eval-in-calendar '(calendar-backward-month 1))))
16758 (org-defkey map [?\e (shift right)]
16759 (lambda () (interactive)
16760 (org-eval-in-calendar '(calendar-forward-month 1))))
16761 (org-defkey map [?\e (shift up)]
16762 (lambda () (interactive)
16763 (org-eval-in-calendar '(calendar-backward-year 1))))
16764 (org-defkey map [?\e (shift down)]
16765 (lambda () (interactive)
16766 (org-eval-in-calendar '(calendar-forward-year 1))))
16767 (org-defkey map [(shift up)]
16768 (lambda () (interactive)
16769 (org-eval-in-calendar '(calendar-backward-week 1))))
16770 (org-defkey map [(shift down)]
16771 (lambda () (interactive)
16772 (org-eval-in-calendar '(calendar-forward-week 1))))
16773 (org-defkey map [(shift left)]
16774 (lambda () (interactive)
16775 (org-eval-in-calendar '(calendar-backward-day 1))))
16776 (org-defkey map [(shift right)]
16777 (lambda () (interactive)
16778 (org-eval-in-calendar '(calendar-forward-day 1))))
16779 (org-defkey map "!"
16780 (lambda () (interactive)
16781 (org-eval-in-calendar '(diary-view-entries))
16782 (message "")))
16783 (org-defkey map ">"
16784 (lambda () (interactive)
16785 (org-eval-in-calendar '(calendar-scroll-left 1))))
16786 (org-defkey map "<"
16787 (lambda () (interactive)
16788 (org-eval-in-calendar '(calendar-scroll-right 1))))
16789 (org-defkey map "\C-v"
16790 (lambda () (interactive)
16791 (org-eval-in-calendar
16792 '(calendar-scroll-left-three-months 1))))
16793 (org-defkey map "\M-v"
16794 (lambda () (interactive)
16795 (org-eval-in-calendar
16796 '(calendar-scroll-right-three-months 1))))
16797 map)
16798 "Keymap for minibuffer commands when using `org-read-date'.")
16800 (defvar org-def)
16801 (defvar org-defdecode)
16802 (defvar org-with-time)
16804 (defun org-read-date (&optional org-with-time to-time from-string prompt
16805 default-time default-input inactive)
16806 "Read a date, possibly a time, and make things smooth for the user.
16807 The prompt will suggest to enter an ISO date, but you can also enter anything
16808 which will at least partially be understood by `parse-time-string'.
16809 Unrecognized parts of the date will default to the current day, month, year,
16810 hour and minute. If this command is called to replace a timestamp at point,
16811 or to enter the second timestamp of a range, the default time is taken
16812 from the existing stamp. Furthermore, the command prefers the future,
16813 so if you are giving a date where the year is not given, and the day-month
16814 combination is already past in the current year, it will assume you
16815 mean next year. For details, see the manual. A few examples:
16817 3-2-5 --> 2003-02-05
16818 feb 15 --> currentyear-02-15
16819 2/15 --> currentyear-02-15
16820 sep 12 9 --> 2009-09-12
16821 12:45 --> today 12:45
16822 22 sept 0:34 --> currentyear-09-22 0:34
16823 12 --> currentyear-currentmonth-12
16824 Fri --> nearest Friday after today
16825 -Tue --> last Tuesday
16826 etc.
16828 Furthermore you can specify a relative date by giving, as the *first* thing
16829 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16830 change in days weeks, months, years.
16831 With a single plus or minus, the date is relative to today. With a double
16832 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16833 +4d --> four days from today
16834 +4 --> same as above
16835 +2w --> two weeks from today
16836 ++5 --> five days from default date
16838 The function understands only English month and weekday abbreviations.
16840 While prompting, a calendar is popped up - you can also select the
16841 date with the mouse (button 1). The calendar shows a period of three
16842 months. To scroll it to other months, use the keys `>' and `<'.
16843 If you don't like the calendar, turn it off with
16844 (setq org-read-date-popup-calendar nil)
16846 With optional argument TO-TIME, the date will immediately be converted
16847 to an internal time.
16848 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16849 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16850 still enter a time, and this function will inform the calling routine
16851 about this change. The calling routine may then choose to change the
16852 format used to insert the time stamp into the buffer to include the time.
16853 With optional argument FROM-STRING, read from this string instead from
16854 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16855 the time/date that is used for everything that is not specified by the
16856 user."
16857 (require 'parse-time)
16858 (let* ((org-time-stamp-rounding-minutes
16859 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16860 (org-dcst org-display-custom-times)
16861 (ct (org-current-time))
16862 (org-def (or org-overriding-default-time default-time ct))
16863 (org-defdecode (decode-time org-def))
16864 (dummy (progn
16865 (when (< (nth 2 org-defdecode) org-extend-today-until)
16866 (setcar (nthcdr 2 org-defdecode) -1)
16867 (setcar (nthcdr 1 org-defdecode) 59)
16868 (setq org-def (apply 'encode-time org-defdecode)
16869 org-defdecode (decode-time org-def)))))
16870 (cur-frame (selected-frame))
16871 (mouse-autoselect-window nil) ; Don't let the mouse jump
16872 (calendar-frame-setup nil)
16873 (calendar-setup (when (eq calendar-setup 'calendar-only) 'calendar-only))
16874 (calendar-move-hook nil)
16875 (calendar-view-diary-initially-flag nil)
16876 (calendar-view-holidays-initially-flag nil)
16877 (timestr (format-time-string
16878 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16879 (prompt (concat (if prompt (concat prompt " ") "")
16880 (format "Date+time [%s]: " timestr)))
16881 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16883 (cond
16884 (from-string (setq ans from-string))
16885 (org-read-date-popup-calendar
16886 (save-excursion
16887 (save-window-excursion
16888 (calendar)
16889 (when (eq calendar-setup 'calendar-only)
16890 (setq cal-frame
16891 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16892 (select-frame cal-frame))
16893 (org-eval-in-calendar '(setq cursor-type nil) t)
16894 (unwind-protect
16895 (progn
16896 (calendar-forward-day (- (time-to-days org-def)
16897 (calendar-absolute-from-gregorian
16898 (calendar-current-date))))
16899 (org-eval-in-calendar nil t)
16900 (let* ((old-map (current-local-map))
16901 (map (copy-keymap calendar-mode-map))
16902 (minibuffer-local-map
16903 (copy-keymap org-read-date-minibuffer-local-map)))
16904 (org-defkey map (kbd "RET") 'org-calendar-select)
16905 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16906 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16907 (unwind-protect
16908 (progn
16909 (use-local-map map)
16910 (setq org-read-date-inactive inactive)
16911 (add-hook 'post-command-hook 'org-read-date-display)
16912 (setq org-ans0 (read-string prompt default-input
16913 'org-read-date-history nil))
16914 ;; org-ans0: from prompt
16915 ;; org-ans1: from mouse click
16916 ;; org-ans2: from calendar motion
16917 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16918 (remove-hook 'post-command-hook 'org-read-date-display)
16919 (use-local-map old-map)
16920 (when org-read-date-overlay
16921 (delete-overlay org-read-date-overlay)
16922 (setq org-read-date-overlay nil)))))
16923 (bury-buffer "*Calendar*")
16924 (when cal-frame
16925 (delete-frame cal-frame)
16926 (select-frame-set-input-focus cur-frame))))))
16928 (t ; Naked prompt only
16929 (unwind-protect
16930 (setq ans (read-string prompt default-input
16931 'org-read-date-history timestr))
16932 (when org-read-date-overlay
16933 (delete-overlay org-read-date-overlay)
16934 (setq org-read-date-overlay nil)))))
16936 (setq final (org-read-date-analyze ans org-def org-defdecode))
16938 (when org-read-date-analyze-forced-year
16939 (message "Year was forced into %s"
16940 (if org-read-date-force-compatible-dates
16941 "compatible range (1970-2037)"
16942 "range representable on this machine"))
16943 (ding))
16945 ;; One round trip to get rid of 34th of August and stuff like that....
16946 (setq final (decode-time (apply 'encode-time final)))
16948 (setq org-read-date-final-answer ans)
16950 (if to-time
16951 (apply 'encode-time final)
16952 (if (and (boundp 'org-time-was-given) org-time-was-given)
16953 (format "%04d-%02d-%02d %02d:%02d"
16954 (nth 5 final) (nth 4 final) (nth 3 final)
16955 (nth 2 final) (nth 1 final))
16956 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16958 (defun org-read-date-display ()
16959 "Display the current date prompt interpretation in the minibuffer."
16960 (when org-read-date-display-live
16961 (when org-read-date-overlay
16962 (delete-overlay org-read-date-overlay))
16963 (when (minibufferp (current-buffer))
16964 (save-excursion
16965 (end-of-line 1)
16966 (while (not (equal (buffer-substring
16967 (max (point-min) (- (point) 4)) (point))
16968 " "))
16969 (insert " ")))
16970 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16971 " " (or org-ans1 org-ans2)))
16972 (org-end-time-was-given nil)
16973 (f (org-read-date-analyze ans org-def org-defdecode))
16974 (fmts (if org-dcst
16975 org-time-stamp-custom-formats
16976 org-time-stamp-formats))
16977 (fmt (if (or org-with-time
16978 (and (boundp 'org-time-was-given) org-time-was-given))
16979 (cdr fmts)
16980 (car fmts)))
16981 (txt (format-time-string fmt (apply 'encode-time f)))
16982 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16983 (txt (concat "=> " txt)))
16984 (when (and org-end-time-was-given
16985 (string-match org-plain-time-of-day-regexp txt))
16986 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16987 org-end-time-was-given
16988 (substring txt (match-end 0)))))
16989 (when org-read-date-analyze-futurep
16990 (setq txt (concat txt " (=>F)")))
16991 (setq org-read-date-overlay
16992 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16993 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16995 (defun org-read-date-analyze (ans org-def org-defdecode)
16996 "Analyze the combined answer of the date prompt."
16997 ;; FIXME: cleanup and comment
16998 ;; Pass `current-time' result to `decode-time' (instead of calling
16999 ;; without arguments) so that only `current-time' has to be
17000 ;; overriden in tests.
17001 (let ((nowdecode (decode-time (current-time)))
17002 delta deltan deltaw deltadef year month day
17003 hour minute second wday pm h2 m2 tl wday1
17004 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
17005 (setq org-read-date-analyze-futurep nil
17006 org-read-date-analyze-forced-year nil)
17007 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17008 (setq ans "+0"))
17010 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17011 (setq ans (replace-match "" t t ans)
17012 deltan (car delta)
17013 deltaw (nth 1 delta)
17014 deltadef (nth 2 delta)))
17016 ;; Check if there is an iso week date in there. If yes, store the
17017 ;; info and postpone interpreting it until the rest of the parsing
17018 ;; is done.
17019 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17020 (setq iso-year (if (match-end 1)
17021 (org-small-year-to-year
17022 (string-to-number (match-string 1 ans))))
17023 iso-weekday (if (match-end 3)
17024 (string-to-number (match-string 3 ans)))
17025 iso-week (string-to-number (match-string 2 ans)))
17026 (setq ans (replace-match "" t t ans)))
17028 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17029 (when (string-match
17030 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17031 (setq year (if (match-end 2)
17032 (string-to-number (match-string 2 ans))
17033 (progn (setq kill-year t)
17034 (string-to-number (format-time-string "%Y"))))
17035 month (string-to-number (match-string 3 ans))
17036 day (string-to-number (match-string 4 ans)))
17037 (if (< year 100) (setq year (+ 2000 year)))
17038 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17039 t nil ans)))
17041 ;; Help matching dotted european dates
17042 (when (string-match
17043 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17044 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17045 (setq kill-year t)
17046 (string-to-number (format-time-string "%Y")))
17047 day (string-to-number (match-string 1 ans))
17048 month (string-to-number (match-string 2 ans))
17049 ans (replace-match (format "%04d-%02d-%02d" year month day)
17050 t nil ans)))
17052 ;; Help matching american dates, like 5/30 or 5/30/7
17053 (when (string-match
17054 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17055 (setq year (if (match-end 4)
17056 (string-to-number (match-string 4 ans))
17057 (progn (setq kill-year t)
17058 (string-to-number (format-time-string "%Y"))))
17059 month (string-to-number (match-string 1 ans))
17060 day (string-to-number (match-string 2 ans)))
17061 (if (< year 100) (setq year (+ 2000 year)))
17062 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17063 t nil ans)))
17064 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17065 ;; If there is a time with am/pm, and *no* time without it, we convert
17066 ;; so that matching will be successful.
17067 (loop for i from 1 to 2 do ; twice, for end time as well
17068 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17069 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17070 (setq hour (string-to-number (match-string 1 ans))
17071 minute (if (match-end 3)
17072 (string-to-number (match-string 3 ans))
17074 pm (equal ?p
17075 (string-to-char (downcase (match-string 4 ans)))))
17076 (if (and (= hour 12) (not pm))
17077 (setq hour 0)
17078 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17079 (setq ans (replace-match (format "%02d:%02d" hour minute)
17080 t t ans))))
17082 ;; Check if a time range is given as a duration
17083 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17084 (setq hour (string-to-number (match-string 1 ans))
17085 h2 (+ hour (string-to-number (match-string 3 ans)))
17086 minute (string-to-number (match-string 2 ans))
17087 m2 (+ minute (if (match-end 5) (string-to-number
17088 (match-string 5 ans))0)))
17089 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17090 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17091 t t ans)))
17093 ;; Check if there is a time range
17094 (when (boundp 'org-end-time-was-given)
17095 (setq org-time-was-given nil)
17096 (when (and (string-match org-plain-time-of-day-regexp ans)
17097 (match-end 8))
17098 (setq org-end-time-was-given (match-string 8 ans))
17099 (setq ans (concat (substring ans 0 (match-beginning 7))
17100 (substring ans (match-end 7))))))
17102 (setq tl (parse-time-string ans)
17103 day (or (nth 3 tl) (nth 3 org-defdecode))
17104 month
17105 (cond ((nth 4 tl))
17106 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17107 ;; Day was specified. Make sure DAY+MONTH
17108 ;; combination happens in the future.
17109 ((nth 3 tl)
17110 (setq futurep t)
17111 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17112 (nth 4 nowdecode)))
17113 (t (nth 4 org-defdecode)))
17114 year
17115 (cond ((and (not kill-year) (nth 5 tl)))
17116 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17117 ;; Month was guessed in the future and is at least
17118 ;; equal to NOWDECODE's. Fix year accordingly.
17119 (futurep
17120 (if (or (> month (nth 4 nowdecode))
17121 (>= day (nth 3 nowdecode)))
17122 (nth 5 nowdecode)
17123 (1+ (nth 5 nowdecode))))
17124 ;; Month was specified. Make sure MONTH+YEAR
17125 ;; combination happens in the future.
17126 ((nth 4 tl)
17127 (setq futurep t)
17128 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17129 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17130 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17131 (t (nth 5 nowdecode))))
17132 (t (nth 5 org-defdecode)))
17133 hour (or (nth 2 tl) (nth 2 org-defdecode))
17134 minute (or (nth 1 tl) (nth 1 org-defdecode))
17135 second (or (nth 0 tl) 0)
17136 wday (nth 6 tl))
17138 (when (and (eq org-read-date-prefer-future 'time)
17139 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17140 (equal day (nth 3 nowdecode))
17141 (equal month (nth 4 nowdecode))
17142 (equal year (nth 5 nowdecode))
17143 (nth 2 tl)
17144 (or (< (nth 2 tl) (nth 2 nowdecode))
17145 (and (= (nth 2 tl) (nth 2 nowdecode))
17146 (nth 1 tl)
17147 (< (nth 1 tl) (nth 1 nowdecode)))))
17148 (setq day (1+ day)
17149 futurep t))
17151 ;; Special date definitions below
17152 (cond
17153 (iso-week
17154 ;; There was an iso week
17155 (require 'cal-iso)
17156 (setq futurep nil)
17157 (setq year (or iso-year year)
17158 day (or iso-weekday wday 1)
17159 wday nil ; to make sure that the trigger below does not match
17160 iso-date (calendar-gregorian-from-absolute
17161 (calendar-iso-to-absolute
17162 (list iso-week day year))))
17163 ; FIXME: Should we also push ISO weeks into the future?
17164 ; (when (and org-read-date-prefer-future
17165 ; (not iso-year)
17166 ; (< (calendar-absolute-from-gregorian iso-date)
17167 ; (time-to-days (current-time))))
17168 ; (setq year (1+ year)
17169 ; iso-date (calendar-gregorian-from-absolute
17170 ; (calendar-iso-to-absolute
17171 ; (list iso-week day year)))))
17172 (setq month (car iso-date)
17173 year (nth 2 iso-date)
17174 day (nth 1 iso-date)))
17175 (deltan
17176 (setq futurep nil)
17177 (unless deltadef
17178 ;; Pass `current-time' result to `decode-time' (instead of
17179 ;; calling without arguments) so that only `current-time' has
17180 ;; to be overriden in tests.
17181 (let ((now (decode-time (current-time))))
17182 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17183 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17184 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17185 ((equal deltaw "m") (setq month (+ month deltan)))
17186 ((equal deltaw "y") (setq year (+ year deltan)))))
17187 ((and wday (not (nth 3 tl)))
17188 ;; Weekday was given, but no day, so pick that day in the week
17189 ;; on or after the derived date.
17190 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17191 (unless (equal wday wday1)
17192 (setq day (+ day (% (- wday wday1 -7) 7))))))
17193 (if (and (boundp 'org-time-was-given)
17194 (nth 2 tl))
17195 (setq org-time-was-given t))
17196 (if (< year 100) (setq year (+ 2000 year)))
17197 ;; Check of the date is representable
17198 (if org-read-date-force-compatible-dates
17199 (progn
17200 (if (< year 1970)
17201 (setq year 1970 org-read-date-analyze-forced-year t))
17202 (if (> year 2037)
17203 (setq year 2037 org-read-date-analyze-forced-year t)))
17204 (condition-case nil
17205 (ignore (encode-time second minute hour day month year))
17206 (error
17207 (setq year (nth 5 org-defdecode))
17208 (setq org-read-date-analyze-forced-year t))))
17209 (setq org-read-date-analyze-futurep futurep)
17210 (list second minute hour day month year)))
17212 (defvar parse-time-weekdays)
17213 (defun org-read-date-get-relative (s today default)
17214 "Check string S for special relative date string.
17215 TODAY and DEFAULT are internal times, for today and for a default.
17216 Return shift list (N what def-flag)
17217 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17218 N is the number of WHATs to shift.
17219 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17220 the DEFAULT date rather than TODAY."
17221 (require 'parse-time)
17222 (when (and
17223 (string-match
17224 (concat
17225 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17226 "\\([0-9]+\\)?"
17227 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17228 "\\([ \t]\\|$\\)") s)
17229 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17230 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17231 (string-to-char (substring (match-string 1 s) -1))
17232 ?+))
17233 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17234 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17235 (what (if (match-end 3) (match-string 3 s) "d"))
17236 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17237 (date (if rel default today))
17238 (wday (nth 6 (decode-time date)))
17239 delta)
17240 (if wday1
17241 (progn
17242 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17243 (if (= delta 0) (setq delta 7))
17244 (if (= dir ?-)
17245 (progn
17246 (setq delta (- delta 7))
17247 (if (= delta 0) (setq delta -7))))
17248 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17249 (list delta "d" rel))
17250 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17252 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17253 "Turn a user-specified date into the internal representation.
17254 The internal representation needed by the calendar is (month day year).
17255 This is a wrapper to handle the brain-dead convention in calendar that
17256 user function argument order change dependent on argument order."
17257 (if (boundp 'calendar-date-style)
17258 (cond
17259 ((eq calendar-date-style 'american)
17260 (list arg1 arg2 arg3))
17261 ((eq calendar-date-style 'european)
17262 (list arg2 arg1 arg3))
17263 ((eq calendar-date-style 'iso)
17264 (list arg2 arg3 arg1)))
17265 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17266 (if (org-bound-and-true-p european-calendar-style)
17267 (list arg2 arg1 arg3)
17268 (list arg1 arg2 arg3)))))
17270 (defun org-eval-in-calendar (form &optional keepdate)
17271 "Eval FORM in the calendar window and return to current window.
17272 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17273 otherwise stick to the current value of `org-ans2'."
17274 (let ((sf (selected-frame))
17275 (sw (selected-window)))
17276 (select-window (get-buffer-window "*Calendar*" t))
17277 (eval form)
17278 (when (and (not keepdate) (calendar-cursor-to-date))
17279 (let* ((date (calendar-cursor-to-date))
17280 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17281 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17282 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17283 (select-window sw)
17284 (org-select-frame-set-input-focus sf)))
17286 (defun org-calendar-select ()
17287 "Return to `org-read-date' with the date currently selected.
17288 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17289 (interactive)
17290 (when (calendar-cursor-to-date)
17291 (let* ((date (calendar-cursor-to-date))
17292 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17293 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17294 (if (active-minibuffer-window) (exit-minibuffer))))
17296 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17297 "Insert a date stamp for the date given by the internal TIME.
17298 See `format-time-string' for the format of TIME.
17299 WITH-HM means use the stamp format that includes the time of the day.
17300 INACTIVE means use square brackets instead of angular ones, so that the
17301 stamp will not contribute to the agenda.
17302 PRE and POST are optional strings to be inserted before and after the
17303 stamp.
17304 The command returns the inserted time stamp."
17305 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17306 stamp)
17307 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17308 (insert-before-markers (or pre ""))
17309 (when (listp extra)
17310 (setq extra (car extra))
17311 (if (and (stringp extra)
17312 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17313 (setq extra (format "-%02d:%02d"
17314 (string-to-number (match-string 1 extra))
17315 (string-to-number (match-string 2 extra))))
17316 (setq extra nil)))
17317 (when extra
17318 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17319 (insert-before-markers (setq stamp (format-time-string fmt time)))
17320 (insert-before-markers (or post ""))
17321 (setq org-last-inserted-timestamp stamp)))
17323 (defun org-toggle-time-stamp-overlays ()
17324 "Toggle the use of custom time stamp formats."
17325 (interactive)
17326 (setq org-display-custom-times (not org-display-custom-times))
17327 (unless org-display-custom-times
17328 (let ((p (point-min)) (bmp (buffer-modified-p)))
17329 (while (setq p (next-single-property-change p 'display))
17330 (if (and (get-text-property p 'display)
17331 (eq (get-text-property p 'face) 'org-date))
17332 (remove-text-properties
17333 p (setq p (next-single-property-change p 'display))
17334 '(display t))))
17335 (set-buffer-modified-p bmp)))
17336 (if (featurep 'xemacs)
17337 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17338 (org-restart-font-lock)
17339 (setq org-table-may-need-update t)
17340 (if org-display-custom-times
17341 (message "Time stamps are overlaid with custom format")
17342 (message "Time stamp overlays removed")))
17344 (defun org-display-custom-time (beg end)
17345 "Overlay modified time stamp format over timestamp between BEG and END."
17346 (let* ((ts (buffer-substring beg end))
17347 t1 w1 with-hm tf time str w2 (off 0))
17348 (save-match-data
17349 (setq t1 (org-parse-time-string ts t))
17350 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17351 (setq off (- (match-end 0) (match-beginning 0)))))
17352 (setq end (- end off))
17353 (setq w1 (- end beg)
17354 with-hm (and (nth 1 t1) (nth 2 t1))
17355 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17356 time (org-fix-decoded-time t1)
17357 str (org-add-props
17358 (format-time-string
17359 (substring tf 1 -1) (apply 'encode-time time))
17360 nil 'mouse-face 'highlight)
17361 w2 (length str))
17362 (if (not (= w2 w1))
17363 (add-text-properties (1+ beg) (+ 2 beg)
17364 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17365 (if (featurep 'xemacs)
17366 (progn
17367 (put-text-property beg end 'invisible t)
17368 (put-text-property beg end 'end-glyph (make-glyph str)))
17369 (put-text-property beg end 'display str))))
17371 (defun org-fix-decoded-time (time)
17372 "Set 0 instead of nil for the first 6 elements of time.
17373 Don't touch the rest."
17374 (let ((n 0))
17375 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17377 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17379 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17380 "Difference between TIMESTAMP-STRING and now in days.
17381 If SECONDS is non-nil, return the difference in seconds."
17382 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17383 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17384 (funcall fdiff (current-time)))))
17386 (defun org-deadline-close (timestamp-string &optional ndays)
17387 "Is the time in TIMESTAMP-STRING close to the current date?"
17388 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17389 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17390 (not (org-entry-is-done-p))))
17392 (defun org-get-wdays (ts &optional delay zero-delay)
17393 "Get the deadline lead time appropriate for timestring TS.
17394 When DELAY is non-nil, get the delay time for scheduled items
17395 instead of the deadline lead time. When ZERO-DELAY is non-nil
17396 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17397 don't try to find the delay cookie in the scheduled timestamp."
17398 (let ((tv (if delay org-scheduled-delay-days
17399 org-deadline-warning-days)))
17400 (cond
17401 ((or (and delay (< tv 0))
17402 (and delay zero-delay (<= tv 0))
17403 (and (not delay) (<= tv 0)))
17404 ;; Enforce this value no matter what
17405 (- tv))
17406 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17407 ;; lead time is specified.
17408 (floor (* (string-to-number (match-string 1 ts))
17409 (cdr (assoc (match-string 2 ts)
17410 '(("d" . 1) ("w" . 7)
17411 ("m" . 30.4) ("y" . 365.25)
17412 ("h" . 0.041667)))))))
17413 ;; go for the default.
17414 (t tv))))
17416 (defun org-calendar-select-mouse (ev)
17417 "Return to `org-read-date' with the date currently selected.
17418 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17419 (interactive "e")
17420 (mouse-set-point ev)
17421 (when (calendar-cursor-to-date)
17422 (let* ((date (calendar-cursor-to-date))
17423 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17424 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17425 (if (active-minibuffer-window) (exit-minibuffer))))
17427 (defun org-check-deadlines (ndays)
17428 "Check if there are any deadlines due or past due.
17429 A deadline is considered due if it happens within `org-deadline-warning-days'
17430 days from today's date. If the deadline appears in an entry marked DONE,
17431 it is not shown. The prefix arg NDAYS can be used to test that many
17432 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17433 (interactive "P")
17434 (let* ((org-warn-days
17435 (cond
17436 ((equal ndays '(4)) 100000)
17437 (ndays (prefix-numeric-value ndays))
17438 (t (abs org-deadline-warning-days))))
17439 (case-fold-search nil)
17440 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17441 (callback
17442 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17443 (message "%d deadlines past-due or due within %d days"
17444 (org-occur regexp nil callback)
17445 org-warn-days)))
17447 (defsubst org-re-timestamp (type)
17448 "Return a regexp for timestamp TYPE.
17449 Allowed values for TYPE are:
17451 all: all timestamps
17452 active: only active timestamps (<...>)
17453 inactive: only inactive timestamps ([...])
17454 scheduled: only scheduled timestamps
17455 deadline: only deadline timestamps
17456 closed: only closed time-stamps
17458 When TYPE is nil, fall back on returning a regexp that matches
17459 both scheduled and deadline timestamps."
17460 (case type
17461 (all org-ts-regexp-both)
17462 (active org-ts-regexp)
17463 (inactive org-ts-regexp-inactive)
17464 (scheduled org-scheduled-time-regexp)
17465 (deadline org-deadline-time-regexp)
17466 (closed org-closed-time-regexp)
17467 (otherwise
17468 (concat "\\<"
17469 (regexp-opt (list org-deadline-string org-scheduled-string))
17470 " *<\\([^>]+\\)>"))))
17472 (defun org-check-before-date (date)
17473 "Check if there are deadlines or scheduled entries before DATE."
17474 (interactive (list (org-read-date)))
17475 (let ((case-fold-search nil)
17476 (regexp (org-re-timestamp org-ts-type))
17477 (callback
17478 `(lambda ()
17479 (let ((match (match-string 1)))
17480 (and ,(if (memq org-ts-type '(active inactive all))
17481 '(eq (org-element-type (org-element-context)) 'timestamp)
17482 '(org-at-planning-p))
17483 (time-less-p
17484 (org-time-string-to-time match)
17485 (org-time-string-to-time date)))))))
17486 (message "%d entries before %s"
17487 (org-occur regexp nil callback) date)))
17489 (defun org-check-after-date (date)
17490 "Check if there are deadlines or scheduled entries after DATE."
17491 (interactive (list (org-read-date)))
17492 (let ((case-fold-search nil)
17493 (regexp (org-re-timestamp org-ts-type))
17494 (callback
17495 `(lambda ()
17496 (let ((match (match-string 1)))
17497 (and ,(if (memq org-ts-type '(active inactive all))
17498 '(eq (org-element-type (org-element-context)) 'timestamp)
17499 '(org-at-planning-p))
17500 (not (time-less-p
17501 (org-time-string-to-time match)
17502 (org-time-string-to-time date))))))))
17503 (message "%d entries after %s"
17504 (org-occur regexp nil callback) date)))
17506 (defun org-check-dates-range (start-date end-date)
17507 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17508 (interactive (list (org-read-date nil nil nil "Range starts")
17509 (org-read-date nil nil nil "Range end")))
17510 (let ((case-fold-search nil)
17511 (regexp (org-re-timestamp org-ts-type))
17512 (callback
17513 `(lambda ()
17514 (let ((match (match-string 1)))
17515 (and
17516 ,(if (memq org-ts-type '(active inactive all))
17517 '(eq (org-element-type (org-element-context)) 'timestamp)
17518 '(org-at-planning-p))
17519 (not (time-less-p
17520 (org-time-string-to-time match)
17521 (org-time-string-to-time start-date)))
17522 (time-less-p
17523 (org-time-string-to-time match)
17524 (org-time-string-to-time end-date)))))))
17525 (message "%d entries between %s and %s"
17526 (org-occur regexp nil callback) start-date end-date)))
17528 (defun org-evaluate-time-range (&optional to-buffer)
17529 "Evaluate a time range by computing the difference between start and end.
17530 Normally the result is just printed in the echo area, but with prefix arg
17531 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17532 If the time range is actually in a table, the result is inserted into the
17533 next column.
17534 For time difference computation, a year is assumed to be exactly 365
17535 days in order to avoid rounding problems."
17536 (interactive "P")
17538 (org-clock-update-time-maybe)
17539 (save-excursion
17540 (unless (org-at-date-range-p t)
17541 (goto-char (point-at-bol))
17542 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17543 (if (not (org-at-date-range-p t))
17544 (user-error "Not at a time-stamp range, and none found in current line")))
17545 (let* ((ts1 (match-string 1))
17546 (ts2 (match-string 2))
17547 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17548 (match-end (match-end 0))
17549 (time1 (org-time-string-to-time ts1))
17550 (time2 (org-time-string-to-time ts2))
17551 (t1 (org-float-time time1))
17552 (t2 (org-float-time time2))
17553 (diff (abs (- t2 t1)))
17554 (negative (< (- t2 t1) 0))
17555 ;; (ys (floor (* 365 24 60 60)))
17556 (ds (* 24 60 60))
17557 (hs (* 60 60))
17558 (fy "%dy %dd %02d:%02d")
17559 (fy1 "%dy %dd")
17560 (fd "%dd %02d:%02d")
17561 (fd1 "%dd")
17562 (fh "%02d:%02d")
17563 y d h m align)
17564 (if havetime
17565 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17567 d (floor (/ diff ds)) diff (mod diff ds)
17568 h (floor (/ diff hs)) diff (mod diff hs)
17569 m (floor (/ diff 60)))
17570 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17572 d (floor (+ (/ diff ds) 0.5))
17573 h 0 m 0))
17574 (if (not to-buffer)
17575 (message "%s" (org-make-tdiff-string y d h m))
17576 (if (org-at-table-p)
17577 (progn
17578 (goto-char match-end)
17579 (setq align t)
17580 (and (looking-at " *|") (goto-char (match-end 0))))
17581 (goto-char match-end))
17582 (if (looking-at
17583 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17584 (replace-match ""))
17585 (if negative (insert " -"))
17586 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17587 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17588 (insert " " (format fh h m))))
17589 (if align (org-table-align))
17590 (message "Time difference inserted")))))
17592 (defun org-make-tdiff-string (y d h m)
17593 (let ((fmt "")
17594 (l nil))
17595 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17596 l (push y l)))
17597 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17598 l (push d l)))
17599 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17600 l (push h l)))
17601 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17602 l (push m l)))
17603 (apply 'format fmt (nreverse l))))
17605 (defun org-time-string-to-time (s &optional buffer pos)
17606 "Convert a timestamp string into internal time."
17607 (condition-case errdata
17608 (apply 'encode-time (org-parse-time-string s))
17609 (error (error "Bad timestamp `%s'%s\nError was: %s"
17610 s (if (not (and buffer pos))
17612 (format-message " at %d in buffer `%s'" pos buffer))
17613 (cdr errdata)))))
17615 (defun org-time-string-to-seconds (s)
17616 "Convert a timestamp string to a number of seconds."
17617 (org-float-time (org-time-string-to-time s)))
17619 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17621 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17622 "Convert time stamp S to an absolute day number.
17624 If DAYNR in non-nil, and there is a specifier for a cyclic time
17625 stamp, get the closest date to DAYNR. If PREFER is
17626 `past' (respectively `future') return a date past (respectively
17627 after) or equal to DAYNR.
17629 POS is the location of time stamp S, as a buffer position in
17630 BUFFER.
17632 Diary sexp timestamps are matched against DAYNR, when non-nil.
17633 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17634 signalled."
17635 (cond
17636 ((string-match "\\`%%\\((.*)\\)" s)
17637 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17638 ;; only able to match individual dates. If it fails, raise an
17639 ;; error.
17640 (if (and daynr
17641 (org-diary-sexp-entry
17642 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17643 daynr
17644 (signal 'org-diary-sexp-no-match (list s))))
17645 ((and daynr show-all) (org-closest-date s daynr prefer))
17646 (t (time-to-days
17647 (condition-case errdata
17648 (apply #'encode-time (org-parse-time-string s))
17649 (error (error "Bad timestamp `%s'%s\nError was: %s"
17651 (if (not (and buffer pos)) ""
17652 (format-message " at %d in buffer `%s'" pos buffer))
17653 (cdr errdata))))))))
17655 (defun org-days-to-iso-week (days)
17656 "Return the iso week number."
17657 (require 'cal-iso)
17658 (car (calendar-iso-from-absolute days)))
17660 (defun org-small-year-to-year (year)
17661 "Convert 2-digit years into 4-digit years.
17662 YEAR is expanded into one of the 30 next years, if possible, or
17663 into a past one. Any year larger than 99 is returned unchanged."
17664 (if (>= year 100) year
17665 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17666 (century (/ current 100))
17667 (offset (- year (% current 100))))
17668 (cond ((> offset 30) (+ (* (1- century) 100) year))
17669 ((> offset -70) (+ (* century 100) year))
17670 (t (+ (* (1+ century) 100) year))))))
17672 (defun org-time-from-absolute (d)
17673 "Return the time corresponding to date D.
17674 D may be an absolute day number, or a calendar-type list (month day year)."
17675 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17676 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17678 (defun org-calendar-holiday ()
17679 "List of holidays, for Diary display in Org-mode."
17680 (require 'holidays)
17681 (let ((hl (funcall
17682 (if (fboundp 'calendar-check-holidays)
17683 'calendar-check-holidays 'check-calendar-holidays) date)))
17684 (if hl (mapconcat 'identity hl "; "))))
17686 (defun org-diary-sexp-entry (sexp entry date)
17687 "Process a SEXP diary ENTRY for DATE."
17688 (require 'diary-lib)
17689 (let ((result (if calendar-debug-sexp
17690 (let ((stack-trace-on-error t))
17691 (eval (car (read-from-string sexp))))
17692 (condition-case nil
17693 (eval (car (read-from-string sexp)))
17694 (error
17695 (beep)
17696 (message "Bad sexp at line %d in %s: %s"
17697 (org-current-line)
17698 (buffer-file-name) sexp)
17699 (sleep-for 2))))))
17700 (cond ((stringp result) (split-string result "; "))
17701 ((and (consp result)
17702 (not (consp (cdr result)))
17703 (stringp (cdr result))) (cdr result))
17704 ((and (consp result)
17705 (stringp (car result))) result)
17706 (result entry))))
17708 (defun org-diary-to-ical-string (frombuf)
17709 "Get iCalendar entries from diary entries in buffer FROMBUF.
17710 This uses the icalendar.el library."
17711 (let* ((tmpdir (if (featurep 'xemacs)
17712 (temp-directory)
17713 temporary-file-directory))
17714 (tmpfile (make-temp-name
17715 (expand-file-name "orgics" tmpdir)))
17716 buf rtn b e)
17717 (with-current-buffer frombuf
17718 (icalendar-export-region (point-min) (point-max) tmpfile)
17719 (setq buf (find-buffer-visiting tmpfile))
17720 (set-buffer buf)
17721 (goto-char (point-min))
17722 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17723 (setq b (match-beginning 0)))
17724 (goto-char (point-max))
17725 (if (re-search-backward "^END:VEVENT" nil t)
17726 (setq e (match-end 0)))
17727 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17728 (kill-buffer buf)
17729 (delete-file tmpfile)
17730 rtn))
17732 (defun org-closest-date (start current prefer)
17733 "Return closest date to CURRENT starting from START.
17735 CURRENT and START are both time stamps.
17737 When PREFER is `past', return a date that is either CURRENT or
17738 past. When PREFER is `future', return a date that is either
17739 CURRENT or future.
17741 Only time stamps with a repeater are modified. Any other time
17742 stamp stay unchanged. In any case, return value is an absolute
17743 day number."
17744 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17745 ;; No repeater. Do not shift time stamp.
17746 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17747 (let ((value (string-to-number (match-string 1 start)))
17748 (type (match-string 2 start)))
17749 (if (= 0 value)
17750 ;; Repeater with a 0-value is considered as void.
17751 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17752 (let* ((base (org-date-to-gregorian start))
17753 (target (org-date-to-gregorian current))
17754 (sday (calendar-absolute-from-gregorian base))
17755 (cday (calendar-absolute-from-gregorian target))
17756 n1 n2)
17757 ;; If START is already past CURRENT, just return START.
17758 (if (<= cday sday) sday
17759 ;; Compute closest date before (N1) and closest date past
17760 ;; (N2) CURRENT.
17761 (pcase type
17762 ("h"
17763 (let ((missing-hours
17764 (mod (+ (- (* 24 (- cday sday))
17765 (nth 2 (org-parse-time-string start)))
17766 org-extend-today-until)
17767 value)))
17768 (setf n1 (if (= missing-hours 0) cday
17769 (- cday (1+ (/ missing-hours 24)))))
17770 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17771 ((or "d" "w")
17772 (let ((value (if (equal type "w") (* 7 value) value)))
17773 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17774 (setf n2 (+ n1 value))))
17775 ("m"
17776 (let* ((add-months
17777 (lambda (date n)
17778 ;; Add N months to gregorian DATE, i.e.,
17779 ;; a list (MONTH DAY YEAR). Return a valid
17780 ;; gregorian date.
17781 (let ((m (+ (nth 0 date) n)))
17782 (list (mod m 12)
17783 (nth 1 date)
17784 (+ (/ m 12) (nth 2 date))))))
17785 (months ; Complete months to TARGET.
17786 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17787 (- (nth 0 target) (nth 0 base))
17788 ;; If START's day is greater than
17789 ;; TARGET's, remove incomplete month.
17790 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17791 value)
17792 value))
17793 (before (funcall add-months base months)))
17794 (setf n1 (calendar-absolute-from-gregorian before))
17795 (setf n2
17796 (calendar-absolute-from-gregorian
17797 (funcall add-months before value)))))
17799 (let* ((d (nth 1 base))
17800 (m (nth 0 base))
17801 (y (nth 2 base))
17802 (years ; Complete years to TARGET.
17803 (* (/ (- (nth 2 target)
17805 ;; If START's month and day are
17806 ;; greater than TARGET's, remove
17807 ;; incomplete year.
17808 (if (or (> (nth 0 target) m)
17809 (and (= (nth 0 target) m)
17810 (> (nth 1 target) d)))
17813 value)
17814 value))
17815 (before (list m d (+ y years))))
17816 (setf n1 (calendar-absolute-from-gregorian before))
17817 (setf n2 (calendar-absolute-from-gregorian
17818 (list m d (+ (nth 2 before) value)))))))
17819 ;; Handle PREFER parameter, if any.
17820 (cond
17821 ((eq prefer 'past) (if (= cday n2) n2 n1))
17822 ((eq prefer 'future) (if (= cday n1) n1 n2))
17823 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17825 (defun org-date-to-gregorian (date)
17826 "Turn any specification of DATE into a Gregorian date for the calendar."
17827 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17828 ((and (listp date) (= (length date) 3)) date)
17829 ((stringp date)
17830 (setq date (org-parse-time-string date))
17831 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17832 ((listp date)
17833 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17835 (defun org-parse-time-string (s &optional nodefault)
17836 "Parse the standard Org-mode time string.
17837 This should be a lot faster than the normal `parse-time-string'.
17838 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17839 hour and minute fields will be nil if not given."
17840 (cond ((string-match org-ts-regexp0 s)
17841 (list 0
17842 (if (or (match-beginning 8) (not nodefault))
17843 (string-to-number (or (match-string 8 s) "0")))
17844 (if (or (match-beginning 7) (not nodefault))
17845 (string-to-number (or (match-string 7 s) "0")))
17846 (string-to-number (match-string 4 s))
17847 (string-to-number (match-string 3 s))
17848 (string-to-number (match-string 2 s))
17849 nil nil nil))
17850 ((string-match "^<[^>]+>$" s)
17851 (decode-time (seconds-to-time (org-matcher-time s))))
17852 (t (error "Not a standard Org-mode time string: %s" s))))
17854 (defun org-timestamp-up (&optional arg)
17855 "Increase the date item at the cursor by one.
17856 If the cursor is on the year, change the year. If it is on the month,
17857 the day or the time, change that.
17858 With prefix ARG, change by that many units."
17859 (interactive "p")
17860 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17862 (defun org-timestamp-down (&optional arg)
17863 "Decrease the date item at the cursor by one.
17864 If the cursor is on the year, change the year. If it is on the month,
17865 the day or the time, change that.
17866 With prefix ARG, change by that many units."
17867 (interactive "p")
17868 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17870 (defun org-timestamp-up-day (&optional arg)
17871 "Increase the date in the time stamp by one day.
17872 With prefix ARG, change that many days."
17873 (interactive "p")
17874 (if (and (not (org-at-timestamp-p t))
17875 (org-at-heading-p))
17876 (org-todo 'up)
17877 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17879 (defun org-timestamp-down-day (&optional arg)
17880 "Decrease the date in the time stamp by one day.
17881 With prefix ARG, change that many days."
17882 (interactive "p")
17883 (if (and (not (org-at-timestamp-p t))
17884 (org-at-heading-p))
17885 (org-todo 'down)
17886 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17888 (defun org-at-timestamp-p (&optional inactive-ok)
17889 "Non-nil if point is inside a timestamp.
17891 When optional argument INACTIVE-OK is non-nil, also consider
17892 inactive timestamps.
17894 When this function returns a non-nil value, match data is set
17895 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17896 INACTIVE-OK."
17897 (interactive)
17898 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17899 (pos (point))
17900 (ans (or (looking-at tsr)
17901 (save-excursion
17902 (skip-chars-backward "^[<\n\r\t")
17903 (if (> (point) (point-min)) (backward-char 1))
17904 (and (looking-at tsr)
17905 (> (- (match-end 0) pos) -1))))))
17906 (and ans
17907 (boundp 'org-ts-what)
17908 (setq org-ts-what
17909 (cond
17910 ((= pos (match-beginning 0)) 'bracket)
17911 ;; Point is considered to be "on the bracket" whether
17912 ;; it's really on it or right after it.
17913 ((= pos (1- (match-end 0))) 'bracket)
17914 ((= pos (match-end 0)) 'after)
17915 ((org-pos-in-match-range pos 2) 'year)
17916 ((org-pos-in-match-range pos 3) 'month)
17917 ((org-pos-in-match-range pos 7) 'hour)
17918 ((org-pos-in-match-range pos 8) 'minute)
17919 ((or (org-pos-in-match-range pos 4)
17920 (org-pos-in-match-range pos 5)) 'day)
17921 ((and (> pos (or (match-end 8) (match-end 5)))
17922 (< pos (match-end 0)))
17923 (- pos (or (match-end 8) (match-end 5))))
17924 (t 'day))))
17925 ans))
17927 (defun org-toggle-timestamp-type ()
17928 "Toggle the type (<active> or [inactive]) of a time stamp."
17929 (interactive)
17930 (when (org-at-timestamp-p t)
17931 (let ((beg (match-beginning 0)) (end (match-end 0))
17932 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17933 (save-excursion
17934 (goto-char beg)
17935 (while (re-search-forward "[][<>]" end t)
17936 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17937 t t)))
17938 (message "Timestamp is now %sactive"
17939 (if (equal (char-after beg) ?<) "" "in")))))
17941 (defun org-at-clock-log-p nil
17942 "Is the cursor on the clock log line?"
17943 (save-excursion
17944 (move-beginning-of-line 1)
17945 (looking-at org-clock-line-re)))
17947 (defvar org-clock-history) ; defined in org-clock.el
17948 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17949 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17950 "Change the date in the time stamp at point.
17951 The date will be changed by N times WHAT. WHAT can be `day', `month',
17952 `year', `minute', `second'. If WHAT is not given, the cursor position
17953 in the timestamp determines what will be changed.
17954 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17955 (let ((origin (point)) origin-cat
17956 with-hm inactive
17957 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17958 org-ts-what
17959 extra rem
17960 ts time time0 fixnext clrgx)
17961 (if (not (org-at-timestamp-p t))
17962 (user-error "Not at a timestamp"))
17963 (if (and (not what) (eq org-ts-what 'bracket))
17964 (org-toggle-timestamp-type)
17965 ;; Point isn't on brackets. Remember the part of the time-stamp
17966 ;; the point was in. Indeed, size of time-stamps may change,
17967 ;; but point must be kept in the same category nonetheless.
17968 (setq origin-cat org-ts-what)
17969 (if (and (not what) (not (eq org-ts-what 'day))
17970 org-display-custom-times
17971 (get-text-property (point) 'display)
17972 (not (get-text-property (1- (point)) 'display)))
17973 (setq org-ts-what 'day))
17974 (setq org-ts-what (or what org-ts-what)
17975 inactive (= (char-after (match-beginning 0)) ?\[)
17976 ts (match-string 0))
17977 (replace-match "")
17978 (when (string-match
17979 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17981 (setq extra (match-string 1 ts))
17982 (if suppress-tmp-delay
17983 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17984 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17985 (setq with-hm t))
17986 (setq time0 (org-parse-time-string ts))
17987 (when (and updown
17988 (eq org-ts-what 'minute)
17989 (not current-prefix-arg))
17990 ;; This looks like s-up and s-down. Change by one rounding step.
17991 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17992 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17993 (setcar (cdr time0) (+ (nth 1 time0)
17994 (if (> n 0) (- rem) (- dm rem))))))
17995 (setq time
17996 (encode-time (or (car time0) 0)
17997 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17998 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17999 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18000 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18001 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18002 (nthcdr 6 time0)))
18003 (when (and (member org-ts-what '(hour minute))
18004 extra
18005 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18006 (setq extra (org-modify-ts-extra
18007 extra
18008 (if (eq org-ts-what 'hour) 2 5)
18009 n dm)))
18010 (when (integerp org-ts-what)
18011 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18012 (if (eq what 'calendar)
18013 (let ((cal-date (org-get-date-from-calendar)))
18014 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18015 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18016 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18017 (setcar time0 (or (car time0) 0))
18018 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18019 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18020 (setq time (apply 'encode-time time0))))
18021 ;; Insert the new time-stamp, and ensure point stays in the same
18022 ;; category as before (i.e. not after the last position in that
18023 ;; category).
18024 (let ((pos (point)))
18025 ;; Stay before inserted string. `save-excursion' is of no use.
18026 (setq org-last-changed-timestamp
18027 (org-insert-time-stamp time with-hm inactive nil nil extra))
18028 (goto-char pos))
18029 (save-match-data
18030 (looking-at org-ts-regexp3)
18031 (goto-char (cond
18032 ;; `day' category ends before `hour' if any, or at
18033 ;; the end of the day name.
18034 ((eq origin-cat 'day)
18035 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18036 ((eq origin-cat 'hour) (min (match-end 7) origin))
18037 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18038 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18039 ;; `year' and `month' have both fixed size: point
18040 ;; couldn't have moved into another part.
18041 (t origin))))
18042 ;; Update clock if on a CLOCK line.
18043 (org-clock-update-time-maybe)
18044 ;; Maybe adjust the closest clock in `org-clock-history'
18045 (when org-clock-adjust-closest
18046 (if (not (and (org-at-clock-log-p)
18047 (< 1 (length (delq nil (mapcar 'marker-position
18048 org-clock-history))))))
18049 (message "No clock to adjust")
18050 (cond ((save-excursion ; fix previous clock?
18051 (re-search-backward org-ts-regexp0 nil t)
18052 (org-looking-back (concat org-clock-string " \\[")
18053 (line-beginning-position)))
18054 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18055 ((save-excursion ; fix next clock?
18056 (re-search-backward org-ts-regexp0 nil t)
18057 (looking-at (concat org-ts-regexp0 "\\] =>")))
18058 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18059 (save-window-excursion
18060 ;; Find closest clock to point, adjust the previous/next one in history
18061 (let* ((p (save-excursion (org-back-to-heading t)))
18062 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18063 (clfixnth
18064 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18065 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
18066 (if (not clfixpos)
18067 (message "No clock to adjust")
18068 (save-excursion
18069 (org-goto-marker-or-bmk clfixpos)
18070 (org-show-subtree)
18071 (when (re-search-forward clrgx nil t)
18072 (goto-char (match-beginning 1))
18073 (let (org-clock-adjust-closest)
18074 (org-timestamp-change n org-ts-what updown))
18075 (message "Clock adjusted in %s for heading: %s"
18076 (file-name-nondirectory (buffer-file-name))
18077 (org-get-heading t t)))))))))
18078 ;; Try to recenter the calendar window, if any.
18079 (if (and org-calendar-follow-timestamp-change
18080 (get-buffer-window "*Calendar*" t)
18081 (memq org-ts-what '(day month year)))
18082 (org-recenter-calendar (time-to-days time))))))
18084 (defun org-modify-ts-extra (s pos n dm)
18085 "Change the different parts of the lead-time and repeat fields in timestamp."
18086 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18087 ng h m new rem)
18088 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18089 (cond
18090 ((or (org-pos-in-match-range pos 2)
18091 (org-pos-in-match-range pos 3))
18092 (setq m (string-to-number (match-string 3 s))
18093 h (string-to-number (match-string 2 s)))
18094 (if (org-pos-in-match-range pos 2)
18095 (setq h (+ h n))
18096 (setq n (* dm (org-no-warnings (signum n))))
18097 (when (not (= 0 (setq rem (% m dm))))
18098 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18099 (setq m (+ m n)))
18100 (if (< m 0) (setq m (+ m 60) h (1- h)))
18101 (if (> m 59) (setq m (- m 60) h (1+ h)))
18102 (setq h (mod h 24))
18103 (setq ng 1 new (format "-%02d:%02d" h m)))
18104 ((org-pos-in-match-range pos 6)
18105 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18106 ((org-pos-in-match-range pos 5)
18107 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18109 ((org-pos-in-match-range pos 9)
18110 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18111 ((org-pos-in-match-range pos 8)
18112 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18114 (when ng
18115 (setq s (concat
18116 (substring s 0 (match-beginning ng))
18118 (substring s (match-end ng))))))
18121 (defun org-recenter-calendar (date)
18122 "If the calendar is visible, recenter it to DATE."
18123 (let ((cwin (get-buffer-window "*Calendar*" t)))
18124 (when cwin
18125 (let ((calendar-move-hook nil))
18126 (with-selected-window cwin
18127 (calendar-goto-date (if (listp date) date
18128 (calendar-gregorian-from-absolute date))))))))
18130 (defun org-goto-calendar (&optional arg)
18131 "Go to the Emacs calendar at the current date.
18132 If there is a time stamp in the current line, go to that date.
18133 A prefix ARG can be used to force the current date."
18134 (interactive "P")
18135 (let ((tsr org-ts-regexp) diff
18136 (calendar-move-hook nil)
18137 (calendar-view-holidays-initially-flag nil)
18138 (calendar-view-diary-initially-flag nil))
18139 (if (or (org-at-timestamp-p)
18140 (save-excursion
18141 (beginning-of-line 1)
18142 (looking-at (concat ".*" tsr))))
18143 (let ((d1 (time-to-days (current-time)))
18144 (d2 (time-to-days
18145 (org-time-string-to-time (match-string 1)))))
18146 (setq diff (- d2 d1))))
18147 (calendar)
18148 (calendar-goto-today)
18149 (if (and diff (not arg)) (calendar-forward-day diff))))
18151 (defun org-get-date-from-calendar ()
18152 "Return a list (month day year) of date at point in calendar."
18153 (with-current-buffer "*Calendar*"
18154 (save-match-data
18155 (calendar-cursor-to-date))))
18157 (defun org-date-from-calendar ()
18158 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18159 If there is already a time stamp at the cursor position, update it."
18160 (interactive)
18161 (if (org-at-timestamp-p t)
18162 (org-timestamp-change 0 'calendar)
18163 (let ((cal-date (org-get-date-from-calendar)))
18164 (org-insert-time-stamp
18165 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18167 (defcustom org-effort-durations
18168 `(("min" . 1)
18169 ("h" . 60)
18170 ("d" . ,(* 60 8))
18171 ("w" . ,(* 60 8 5))
18172 ("m" . ,(* 60 8 5 4))
18173 ("y" . ,(* 60 8 5 40)))
18174 "Conversion factor to minutes for an effort modifier.
18176 Each entry has the form (MODIFIER . MINUTES).
18178 In an effort string, a number followed by MODIFIER is multiplied
18179 by the specified number of MINUTES to obtain an effort in
18180 minutes.
18182 For example, if the value of this variable is ((\"hours\" . 60)), then an
18183 effort string \"2hours\" is equivalent to 120 minutes."
18184 :group 'org-agenda
18185 :version "25.1"
18186 :package-version '(Org . "8.3")
18187 :type '(alist :key-type (string :tag "Modifier")
18188 :value-type (number :tag "Minutes")))
18190 (defun org-minutes-to-clocksum-string (m)
18191 "Format number of minutes as a clocksum string.
18192 The format is determined by `org-time-clocksum-format',
18193 `org-time-clocksum-use-fractional' and
18194 `org-time-clocksum-fractional-format' and
18195 `org-time-clocksum-use-effort-durations'."
18196 (let ((clocksum "")
18197 (m (round m)) ; Don't allow fractions of minutes
18198 h d w mo y fmt n)
18199 (setq h (if org-time-clocksum-use-effort-durations
18200 (cdr (assoc "h" org-effort-durations)) 60)
18201 d (if org-time-clocksum-use-effort-durations
18202 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18203 w (if org-time-clocksum-use-effort-durations
18204 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18205 mo (if org-time-clocksum-use-effort-durations
18206 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18207 y (if org-time-clocksum-use-effort-durations
18208 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18209 ;; fractional format
18210 (if org-time-clocksum-use-fractional
18211 (cond
18212 ;; single format string
18213 ((stringp org-time-clocksum-fractional-format)
18214 (format org-time-clocksum-fractional-format (/ m (float h))))
18215 ;; choice of fractional formats for different time units
18216 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18217 (> (/ (truncate m) (* y d h)) 0))
18218 (format fmt (/ m (* y d (float h)))))
18219 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18220 (> (/ (truncate m) (* mo d h)) 0))
18221 (format fmt (/ m (* mo d (float h)))))
18222 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18223 (> (/ (truncate m) (* w d h)) 0))
18224 (format fmt (/ m (* w d (float h)))))
18225 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18226 (> (/ (truncate m) (* d h)) 0))
18227 (format fmt (/ m (* d (float h)))))
18228 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18229 (> (/ (truncate m) h) 0))
18230 (format fmt (/ m (float h))))
18231 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18232 (format fmt m))
18233 ;; fall back to smallest time unit with a format
18234 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18235 (format fmt (/ m (float h))))
18236 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18237 (format fmt (/ m (* d (float h)))))
18238 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18239 (format fmt (/ m (* w d (float h)))))
18240 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18241 (format fmt (/ m (* mo d (float h)))))
18242 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18243 (format fmt (/ m (* y d (float h))))))
18244 ;; standard (non-fractional) format, with single format string
18245 (if (stringp org-time-clocksum-format)
18246 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18247 ;; separate formats components
18248 (and (setq fmt (plist-get org-time-clocksum-format :years))
18249 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18250 (plist-get org-time-clocksum-format :require-years))
18251 (setq clocksum (concat clocksum (format fmt n))
18252 m (- m (* n y d h))))
18253 (and (setq fmt (plist-get org-time-clocksum-format :months))
18254 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18255 (plist-get org-time-clocksum-format :require-months))
18256 (setq clocksum (concat clocksum (format fmt n))
18257 m (- m (* n mo d h))))
18258 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18259 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18260 (plist-get org-time-clocksum-format :require-weeks))
18261 (setq clocksum (concat clocksum (format fmt n))
18262 m (- m (* n w d h))))
18263 (and (setq fmt (plist-get org-time-clocksum-format :days))
18264 (or (> (setq n (/ (truncate m) (* d h))) 0)
18265 (plist-get org-time-clocksum-format :require-days))
18266 (setq clocksum (concat clocksum (format fmt n))
18267 m (- m (* n d h))))
18268 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18269 (or (> (setq n (/ (truncate m) h)) 0)
18270 (plist-get org-time-clocksum-format :require-hours))
18271 (setq clocksum (concat clocksum (format fmt n))
18272 m (- m (* n h))))
18273 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18274 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18275 (setq clocksum (concat clocksum (format fmt m))))
18276 ;; return formatted time duration
18277 clocksum))))
18279 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18280 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18281 "Org mode version 8.0")
18283 (defun org-hours-to-clocksum-string (n)
18284 (org-minutes-to-clocksum-string (* n 60)))
18286 (defun org-hh:mm-string-to-minutes (s)
18287 "Convert a string H:MM to a number of minutes.
18288 If the string is just a number, interpret it as minutes.
18289 In fact, the first hh:mm or number in the string will be taken,
18290 there can be extra stuff in the string.
18291 If no number is found, the return value is 0."
18292 (cond
18293 ((integerp s) s)
18294 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18295 (+ (* (string-to-number (match-string 1 s)) 60)
18296 (string-to-number (match-string 2 s))))
18297 ((string-match "\\([0-9]+\\)" s)
18298 (string-to-number (match-string 1 s)))
18299 (t 0)))
18301 (defcustom org-image-actual-width t
18302 "Should we use the actual width of images when inlining them?
18304 When set to t, always use the image width.
18306 When set to a number, use imagemagick (when available) to set
18307 the image's width to this value.
18309 When set to a number in a list, try to get the width from any
18310 #+ATTR.* keyword if it matches a width specification like
18312 #+ATTR_HTML: :width 300px
18314 and fall back on that number if none is found.
18316 When set to nil, try to get the width from an #+ATTR.* keyword
18317 and fall back on the original width if none is found.
18319 This requires Emacs >= 24.1, build with imagemagick support."
18320 :group 'org-appearance
18321 :version "24.4"
18322 :package-version '(Org . "8.0")
18323 :type '(choice
18324 (const :tag "Use the image width" t)
18325 (integer :tag "Use a number of pixels")
18326 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18327 (const :tag "Use #+ATTR* or don't resize" nil)))
18329 (defcustom org-agenda-inhibit-startup nil
18330 "Inhibit startup when preparing agenda buffers.
18331 When this variable is t, the initialization of the Org agenda
18332 buffers is inhibited: e.g. the visibility state is not set, the
18333 tables are not re-aligned, etc."
18334 :type 'boolean
18335 :version "24.3"
18336 :group 'org-agenda)
18338 (define-obsolete-variable-alias
18339 'org-agenda-ignore-drawer-properties
18340 'org-agenda-ignore-properties "25.1")
18342 (defcustom org-agenda-ignore-properties nil
18343 "Avoid updating text properties when building the agenda.
18344 Properties are used to prepare buffers for effort estimates,
18345 appointments, statistics and subtree-local categories.
18346 If you don't use these in the agenda, you can add them to this
18347 list and agenda building will be a bit faster.
18348 The value is a list, with zero or more of the symbols `effort', `appt',
18349 `stats' or `category'."
18350 :type '(set :greedy t
18351 (const effort)
18352 (const appt)
18353 (const stats)
18354 (const category))
18355 :version "25.1"
18356 :package-version '(Org . "8.3")
18357 :group 'org-agenda)
18359 (defun org-duration-string-to-minutes (s &optional output-to-string)
18360 "Convert a duration string S to minutes.
18362 A bare number is interpreted as minutes, modifiers can be set by
18363 customizing `org-effort-durations' (which see).
18365 Entries containing a colon are interpreted as H:MM by
18366 `org-hh:mm-string-to-minutes'."
18367 (let ((result 0)
18368 (re (concat "\\([0-9.]+\\) *\\("
18369 (regexp-opt (mapcar 'car org-effort-durations))
18370 "\\)")))
18371 (while (string-match re s)
18372 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18373 (string-to-number (match-string 1 s))))
18374 (setq s (replace-match "" nil t s)))
18375 (setq result (floor result))
18376 (incf result (org-hh:mm-string-to-minutes s))
18377 (if output-to-string (number-to-string result) result)))
18379 ;;;; Files
18381 (defun org-save-all-org-buffers ()
18382 "Save all Org-mode buffers without user confirmation."
18383 (interactive)
18384 (message "Saving all Org-mode buffers...")
18385 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18386 (when (featurep 'org-id) (org-id-locations-save))
18387 (message "Saving all Org-mode buffers... done"))
18389 (defun org-revert-all-org-buffers ()
18390 "Revert all Org-mode buffers.
18391 Prompt for confirmation when there are unsaved changes.
18392 Be sure you know what you are doing before letting this function
18393 overwrite your changes.
18395 This function is useful in a setup where one tracks org files
18396 with a version control system, to revert on one machine after pulling
18397 changes from another. I believe the procedure must be like this:
18399 1. M-x org-save-all-org-buffers
18400 2. Pull changes from the other machine, resolve conflicts
18401 3. M-x org-revert-all-org-buffers"
18402 (interactive)
18403 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18404 (user-error "Abort"))
18405 (save-excursion
18406 (save-window-excursion
18407 (mapc
18408 (lambda (b)
18409 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18410 (with-current-buffer b buffer-file-name))
18411 (org-pop-to-buffer-same-window b)
18412 (revert-buffer t 'no-confirm)))
18413 (buffer-list))
18414 (when (and (featurep 'org-id) org-id-track-globally)
18415 (org-id-locations-load)))))
18417 ;;;; Agenda files
18419 ;;;###autoload
18420 (defun org-switchb (&optional arg)
18421 "Switch between Org buffers.
18422 With one prefix argument, restrict available buffers to files.
18423 With two prefix arguments, restrict available buffers to agenda files.
18425 Defaults to `iswitchb' for buffer name completion.
18426 Set `org-completion-use-ido' to make it use ido instead."
18427 (interactive "P")
18428 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18429 ((equal arg '(16)) (org-buffer-list 'agenda))
18430 (t (org-buffer-list))))
18431 (org-completion-use-iswitchb org-completion-use-iswitchb)
18432 (org-completion-use-ido org-completion-use-ido))
18433 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18434 (setq org-completion-use-iswitchb t))
18435 (org-pop-to-buffer-same-window
18436 (org-icompleting-read "Org buffer: "
18437 (mapcar 'list (mapcar 'buffer-name blist))
18438 nil t))))
18440 ;;; Define some older names previously used for this functionality
18441 ;;;###autoload
18442 (defalias 'org-ido-switchb 'org-switchb)
18443 ;;;###autoload
18444 (defalias 'org-iswitchb 'org-switchb)
18446 (defun org-buffer-list (&optional predicate exclude-tmp)
18447 "Return a list of Org buffers.
18448 PREDICATE can be `export', `files' or `agenda'.
18450 export restrict the list to Export buffers.
18451 files restrict the list to buffers visiting Org files.
18452 agenda restrict the list to buffers visiting agenda files.
18454 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18455 (let* ((bfn nil)
18456 (agenda-files (and (eq predicate 'agenda)
18457 (mapcar 'file-truename (org-agenda-files t))))
18458 (filter
18459 (cond
18460 ((eq predicate 'files)
18461 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18462 ((eq predicate 'export)
18463 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18464 ((eq predicate 'agenda)
18465 (lambda (b)
18466 (with-current-buffer b
18467 (and (derived-mode-p 'org-mode)
18468 (setq bfn (buffer-file-name b))
18469 (member (file-truename bfn) agenda-files)))))
18470 (t (lambda (b) (with-current-buffer b
18471 (or (derived-mode-p 'org-mode)
18472 (string-match "\\*Org .*Export"
18473 (buffer-name b)))))))))
18474 (delq nil
18475 (mapcar
18476 (lambda(b)
18477 (if (and (funcall filter b)
18478 (or (not exclude-tmp)
18479 (not (string-match "tmp" (buffer-name b)))))
18481 nil))
18482 (buffer-list)))))
18484 (defun org-agenda-files (&optional unrestricted archives)
18485 "Get the list of agenda files.
18486 Optional UNRESTRICTED means return the full list even if a restriction
18487 is currently in place.
18488 When ARCHIVES is t, include all archive files that are really being
18489 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18490 `org-agenda-archives-mode' is t."
18491 (let ((files
18492 (cond
18493 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18494 ((stringp org-agenda-files) (org-read-agenda-file-list))
18495 ((listp org-agenda-files) org-agenda-files)
18496 (t (error "Invalid value of `org-agenda-files'")))))
18497 (setq files (apply 'append
18498 (mapcar (lambda (f)
18499 (if (file-directory-p f)
18500 (directory-files
18501 f t org-agenda-file-regexp)
18502 (list f)))
18503 files)))
18504 (when org-agenda-skip-unavailable-files
18505 (setq files (delq nil
18506 (mapcar (function
18507 (lambda (file)
18508 (and (file-readable-p file) file)))
18509 files))))
18510 (when (or (eq archives t)
18511 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18512 (setq files (org-add-archive-files files)))
18513 files))
18515 (defun org-agenda-file-p (&optional file)
18516 "Return non-nil, if FILE is an agenda file.
18517 If FILE is omitted, use the file associated with the current
18518 buffer."
18519 (let ((fname (or file (buffer-file-name))))
18520 (and fname
18521 (member (file-truename fname)
18522 (mapcar #'file-truename (org-agenda-files t))))))
18524 (defun org-edit-agenda-file-list ()
18525 "Edit the list of agenda files.
18526 Depending on setup, this either uses customize to edit the variable
18527 `org-agenda-files', or it visits the file that is holding the list. In the
18528 latter case, the buffer is set up in a way that saving it automatically kills
18529 the buffer and restores the previous window configuration."
18530 (interactive)
18531 (if (stringp org-agenda-files)
18532 (let ((cw (current-window-configuration)))
18533 (find-file org-agenda-files)
18534 (setq-local org-window-configuration cw)
18535 (org-add-hook 'after-save-hook
18536 (lambda ()
18537 (set-window-configuration
18538 (prog1 org-window-configuration
18539 (kill-buffer (current-buffer))))
18540 (org-install-agenda-files-menu)
18541 (message "New agenda file list installed"))
18542 nil 'local)
18543 (message "%s" (substitute-command-keys
18544 "Edit list and finish with \\[save-buffer]")))
18545 (customize-variable 'org-agenda-files)))
18547 (defun org-store-new-agenda-file-list (list)
18548 "Set new value for the agenda file list and save it correctly."
18549 (if (stringp org-agenda-files)
18550 (let ((fe (org-read-agenda-file-list t)) b u)
18551 (while (setq b (find-buffer-visiting org-agenda-files))
18552 (kill-buffer b))
18553 (with-temp-file org-agenda-files
18554 (insert
18555 (mapconcat
18556 (lambda (f) ;; Keep un-expanded entries.
18557 (if (setq u (assoc f fe))
18558 (cdr u)
18560 list "\n")
18561 "\n")))
18562 (let ((org-mode-hook nil) (org-inhibit-startup t)
18563 (org-insert-mode-line-in-empty-file nil))
18564 (setq org-agenda-files list)
18565 (customize-save-variable 'org-agenda-files org-agenda-files))))
18567 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18568 "Read the list of agenda files from a file.
18569 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18570 filenames, used by `org-store-new-agenda-file-list' to write back
18571 un-expanded file names."
18572 (when (file-directory-p org-agenda-files)
18573 (error "`org-agenda-files' cannot be a single directory"))
18574 (when (stringp org-agenda-files)
18575 (with-temp-buffer
18576 (insert-file-contents org-agenda-files)
18577 (mapcar
18578 (lambda (f)
18579 (let ((e (expand-file-name (substitute-in-file-name f)
18580 org-directory)))
18581 (if pair-with-expansion
18582 (cons e f)
18583 e)))
18584 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18586 ;;;###autoload
18587 (defun org-cycle-agenda-files ()
18588 "Cycle through the files in `org-agenda-files'.
18589 If the current buffer visits an agenda file, find the next one in the list.
18590 If the current buffer does not, find the first agenda file."
18591 (interactive)
18592 (let* ((fs (or (org-agenda-files t)
18593 (user-error "No agenda files")))
18594 (files (copy-sequence fs))
18595 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18596 file)
18597 (when tcf
18598 (while (and (setq file (pop files))
18599 (not (equal (file-truename file) tcf)))))
18600 (find-file (car (or files fs)))
18601 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18603 (defun org-agenda-file-to-front (&optional to-end)
18604 "Move/add the current file to the top of the agenda file list.
18605 If the file is not present in the list, it is added to the front. If it is
18606 present, it is moved there. With optional argument TO-END, add/move to the
18607 end of the list."
18608 (interactive "P")
18609 (let ((org-agenda-skip-unavailable-files nil)
18610 (file-alist (mapcar (lambda (x)
18611 (cons (file-truename x) x))
18612 (org-agenda-files t)))
18613 (ctf (file-truename
18614 (or buffer-file-name
18615 (user-error "Please save the current buffer to a file"))))
18616 x had)
18617 (setq x (assoc ctf file-alist) had x)
18619 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18620 (if to-end
18621 (setq file-alist (append (delq x file-alist) (list x)))
18622 (setq file-alist (cons x (delq x file-alist))))
18623 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18624 (org-install-agenda-files-menu)
18625 (message "File %s to %s of agenda file list"
18626 (if had "moved" "added") (if to-end "end" "front"))))
18628 (defun org-remove-file (&optional file)
18629 "Remove current file from the list of files in variable `org-agenda-files'.
18630 These are the files which are being checked for agenda entries.
18631 Optional argument FILE means use this file instead of the current."
18632 (interactive)
18633 (let* ((org-agenda-skip-unavailable-files nil)
18634 (file (or file buffer-file-name
18635 (user-error "Current buffer does not visit a file")))
18636 (true-file (file-truename file))
18637 (afile (abbreviate-file-name file))
18638 (files (delq nil (mapcar
18639 (lambda (x)
18640 (if (equal true-file
18641 (file-truename x))
18642 nil x))
18643 (org-agenda-files t)))))
18644 (if (not (= (length files) (length (org-agenda-files t))))
18645 (progn
18646 (org-store-new-agenda-file-list files)
18647 (org-install-agenda-files-menu)
18648 (message "Removed from Org Agenda list: %s" afile))
18649 (message "File was not in list: %s (not removed)" afile))))
18651 (defun org-file-menu-entry (file)
18652 (vector file (list 'find-file file) t))
18654 (defun org-check-agenda-file (file)
18655 "Make sure FILE exists. If not, ask user what to do."
18656 (when (not (file-exists-p file))
18657 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18658 (abbreviate-file-name file))
18659 (let ((r (downcase (read-char-exclusive))))
18660 (cond
18661 ((equal r ?r)
18662 (org-remove-file file)
18663 (throw 'nextfile t))
18664 (t (user-error "Abort"))))))
18666 (defun org-get-agenda-file-buffer (file)
18667 "Get an agenda buffer visiting FILE.
18668 If the buffer needs to be created, add it to the list of buffers
18669 which might be released later."
18670 (let ((buf (org-find-base-buffer-visiting file)))
18671 (if buf
18672 buf ; just return it
18673 ;; Make a new buffer and remember it
18674 (setq buf (find-file-noselect file))
18675 (if buf (push buf org-agenda-new-buffers))
18676 buf)))
18678 (defun org-release-buffers (blist)
18679 "Release all buffers in list, asking the user for confirmation when needed.
18680 When a buffer is unmodified, it is just killed. When modified, it is saved
18681 \(if the user agrees) and then killed."
18682 (let (file)
18683 (dolist (buf blist)
18684 (setq file (buffer-file-name buf))
18685 (when (and (buffer-modified-p buf)
18686 file
18687 (y-or-n-p (format "Save file %s? " file)))
18688 (with-current-buffer buf (save-buffer)))
18689 (kill-buffer buf))))
18691 (defun org-agenda-prepare-buffers (files)
18692 "Create buffers for all agenda files, protect archived trees and comments."
18693 (interactive)
18694 (let ((pa '(:org-archived t))
18695 (pc '(:org-comment t))
18696 (pall '(:org-archived t :org-comment t))
18697 (inhibit-read-only t)
18698 (org-inhibit-startup org-agenda-inhibit-startup)
18699 (rea (concat ":" org-archive-tag ":"))
18700 file re pos)
18701 (setq org-tag-alist-for-agenda nil
18702 org-tag-groups-alist-for-agenda nil)
18703 (save-excursion
18704 (save-restriction
18705 (dolist (file files)
18706 (catch 'nextfile
18707 (if (bufferp file)
18708 (set-buffer file)
18709 (org-check-agenda-file file)
18710 (set-buffer (org-get-agenda-file-buffer file)))
18711 (widen)
18712 (org-set-regexps-and-options 'tags-only)
18713 (setq pos (point))
18714 (or (memq 'category org-agenda-ignore-properties)
18715 (org-refresh-category-properties))
18716 (or (memq 'stats org-agenda-ignore-properties)
18717 (org-refresh-stats-properties))
18718 (or (memq 'effort org-agenda-ignore-properties)
18719 (org-refresh-effort-properties))
18720 (or (memq 'appt org-agenda-ignore-properties)
18721 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18722 (setq org-todo-keywords-for-agenda
18723 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18724 (setq org-done-keywords-for-agenda
18725 (append org-done-keywords-for-agenda org-done-keywords))
18726 (setq org-todo-keyword-alist-for-agenda
18727 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18728 (setq org-tag-alist-for-agenda
18729 (org-uniquify
18730 (append org-tag-alist-for-agenda
18731 org-tag-alist
18732 org-tag-persistent-alist)))
18733 (if org-group-tags
18734 (setq org-tag-groups-alist-for-agenda
18735 (org-uniquify-alist
18736 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18737 (org-with-silent-modifications
18738 (save-excursion
18739 (remove-text-properties (point-min) (point-max) pall)
18740 (when org-agenda-skip-archived-trees
18741 (goto-char (point-min))
18742 (while (re-search-forward rea nil t)
18743 (if (org-at-heading-p t)
18744 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18745 (goto-char (point-min))
18746 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18747 (while (re-search-forward re nil t)
18748 (when (save-match-data (org-in-commented-heading-p t))
18749 (add-text-properties
18750 (match-beginning 0) (org-end-of-subtree t) pc)))))
18751 (goto-char pos)))))
18752 (setq org-todo-keywords-for-agenda
18753 (org-uniquify org-todo-keywords-for-agenda))
18754 (setq org-todo-keyword-alist-for-agenda
18755 (org-uniquify org-todo-keyword-alist-for-agenda))))
18758 ;;;; CDLaTeX minor mode
18760 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18761 "Keymap for the minor `org-cdlatex-mode'.")
18763 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18764 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18765 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18766 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18767 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18769 (defvar org-cdlatex-texmathp-advice-is-done nil
18770 "Flag remembering if we have applied the advice to texmathp already.")
18772 (define-minor-mode org-cdlatex-mode
18773 "Toggle the minor `org-cdlatex-mode'.
18774 This mode supports entering LaTeX environment and math in LaTeX fragments
18775 in Org-mode.
18776 \\{org-cdlatex-mode-map}"
18777 nil " OCDL" nil
18778 (when org-cdlatex-mode
18779 (require 'cdlatex)
18780 (run-hooks 'cdlatex-mode-hook)
18781 (cdlatex-compute-tables))
18782 (unless org-cdlatex-texmathp-advice-is-done
18783 (setq org-cdlatex-texmathp-advice-is-done t)
18784 (defadvice texmathp (around org-math-always-on activate)
18785 "Always return t in org-mode buffers.
18786 This is because we want to insert math symbols without dollars even outside
18787 the LaTeX math segments. If Orgmode thinks that point is actually inside
18788 an embedded LaTeX fragment, let texmathp do its job.
18789 \\[org-cdlatex-mode-map]"
18790 (interactive)
18791 (let (p)
18792 (cond
18793 ((not (derived-mode-p 'org-mode)) ad-do-it)
18794 ((eq this-command 'cdlatex-math-symbol)
18795 (setq ad-return-value t
18796 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18798 (let ((p (org-inside-LaTeX-fragment-p)))
18799 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18800 (setq ad-return-value t
18801 texmathp-why '("Org-mode embedded math" . 0))
18802 (if p ad-do-it)))))))))
18804 (defun turn-on-org-cdlatex ()
18805 "Unconditionally turn on `org-cdlatex-mode'."
18806 (org-cdlatex-mode 1))
18808 (defun org-try-cdlatex-tab ()
18809 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18810 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18811 - inside a LaTeX fragment, or
18812 - after the first word in a line, where an abbreviation expansion could
18813 insert a LaTeX environment."
18814 (when org-cdlatex-mode
18815 (cond
18816 ;; Before any word on the line: No expansion possible.
18817 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18818 ;; Just after first word on the line: Expand it. Make sure it
18819 ;; cannot happen on headlines, though.
18820 ((save-excursion
18821 (skip-chars-backward "a-zA-Z0-9*")
18822 (skip-chars-backward " \t")
18823 (and (bolp) (not (org-at-heading-p))))
18824 (cdlatex-tab) t)
18825 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18827 (defun org-cdlatex-underscore-caret (&optional arg)
18828 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18829 Revert to the normal definition outside of these fragments."
18830 (interactive "P")
18831 (if (org-inside-LaTeX-fragment-p)
18832 (call-interactively 'cdlatex-sub-superscript)
18833 (let (org-cdlatex-mode)
18834 (call-interactively (key-binding (vector last-input-event))))))
18836 (defun org-cdlatex-math-modify (&optional arg)
18837 "Execute `cdlatex-math-modify' in LaTeX fragments.
18838 Revert to the normal definition outside of these fragments."
18839 (interactive "P")
18840 (if (org-inside-LaTeX-fragment-p)
18841 (call-interactively 'cdlatex-math-modify)
18842 (let (org-cdlatex-mode)
18843 (call-interactively (key-binding (vector last-input-event))))))
18845 (defun org-cdlatex-environment-indent (&optional environment item)
18846 "Execute `cdlatex-environment' and indent the inserted environment.
18848 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18850 The inserted environment is indented to current indentation
18851 unless point is at the beginning of the line, in which the
18852 environment remains unintended."
18853 (interactive)
18854 ;; cdlatex-environment always return nil. Therefore, capture output
18855 ;; first and determine if an environment was selected.
18856 (let* ((beg (point-marker))
18857 (end (copy-marker (point) t))
18858 (inserted (progn
18859 (ignore-errors (cdlatex-environment environment item))
18860 (< beg end)))
18861 ;; Figure out how many lines to move forward after the
18862 ;; environment has been inserted.
18863 (lines (when inserted
18864 (save-excursion
18865 (- (loop while (< beg (point))
18866 with x = 0
18867 do (forward-line -1)
18868 (incf x)
18869 finally return x)
18870 (if (progn (goto-char beg)
18871 (and (progn (skip-chars-forward " \t") (eolp))
18872 (progn (skip-chars-backward " \t") (bolp))))
18873 1 0)))))
18874 (env (org-trim (delete-and-extract-region beg end))))
18875 (when inserted
18876 ;; Get indentation of next line unless at column 0.
18877 (let ((ind (if (bolp) 0
18878 (save-excursion
18879 (org-return-indent)
18880 (prog1 (org-get-indentation)
18881 (when (progn (skip-chars-forward " \t") (eolp))
18882 (delete-region beg (point)))))))
18883 (bol (progn (skip-chars-backward " \t") (bolp))))
18884 ;; Insert a newline before environment unless at column zero
18885 ;; to "escape" the current line. Insert a newline if
18886 ;; something is one the same line as \end{ENVIRONMENT}.
18887 (insert
18888 (concat (unless bol "\n") env
18889 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18890 (unless (zerop ind)
18891 (save-excursion
18892 (goto-char beg)
18893 (while (< (point) end)
18894 (unless (eolp) (org-indent-line-to ind))
18895 (forward-line))))
18896 (goto-char beg)
18897 (forward-line lines)
18898 (org-indent-line-to ind)))
18899 (set-marker beg nil)
18900 (set-marker end nil)))
18903 ;;;; LaTeX fragments
18905 (defun org-inside-LaTeX-fragment-p ()
18906 "Test if point is inside a LaTeX fragment.
18907 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18908 sequence appearing also before point.
18909 Even though the matchers for math are configurable, this function assumes
18910 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18911 delimiters are skipped when they have been removed by customization.
18912 The return value is nil, or a cons cell with the delimiter and the
18913 position of this delimiter.
18915 This function does a reasonably good job, but can locally be fooled by
18916 for example currency specifications. For example it will assume being in
18917 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18918 fragments that are properly closed, but during editing, we have to live
18919 with the uncertainty caused by missing closing delimiters. This function
18920 looks only before point, not after."
18921 (catch 'exit
18922 (let ((pos (point))
18923 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18924 (lim (progn
18925 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18926 (point)))
18927 dd-on str (start 0) m re)
18928 (goto-char pos)
18929 (when dodollar
18930 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18931 re (nth 1 (assoc "$" org-latex-regexps)))
18932 (while (string-match re str start)
18933 (cond
18934 ((= (match-end 0) (length str))
18935 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18936 ((= (match-end 0) (- (length str) 5))
18937 (throw 'exit nil))
18938 (t (setq start (match-end 0))))))
18939 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18940 (goto-char pos)
18941 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18942 (and (match-beginning 2) (throw 'exit nil))
18943 ;; count $$
18944 (while (re-search-backward "\\$\\$" lim t)
18945 (setq dd-on (not dd-on)))
18946 (goto-char pos)
18947 (if dd-on (cons "$$" m))))))
18949 (defun org-inside-latex-macro-p ()
18950 "Is point inside a LaTeX macro or its arguments?"
18951 (save-match-data
18952 (org-in-regexp
18953 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18955 (defvar-local org-latex-fragment-image-overlays nil
18956 "List of overlays carrying the images of latex fragments.")
18958 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18959 "Remove all overlays with LaTeX fragment images in current buffer.
18960 When optional arguments BEG and END are non-nil, remove all
18961 overlays between them instead. Return t when some overlays were
18962 removed, nil otherwise."
18963 (let (removedp)
18964 (setq org-latex-fragment-image-overlays
18965 (let ((beg (or beg (point-min)))
18966 (end (or end (point-max))))
18967 (org-remove-if
18968 (lambda (o)
18969 (cond ((not (overlay-buffer o)) (delete-overlay o) t)
18970 ((and (>= (overlay-start o) beg)
18971 (<= (overlay-end o) end))
18972 (delete-overlay o)
18973 (unless removedp (setq removedp t)))
18974 (t nil)))
18975 org-latex-fragment-image-overlays)))
18976 removedp))
18978 (define-obsolete-function-alias
18979 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18980 (defun org-toggle-latex-fragment (&optional arg)
18981 "Preview the LaTeX fragment at point, or all locally or globally.
18983 If the cursor is on a LaTeX fragment, create the image and overlay
18984 it over the source code, if there is none. Remove it otherwise.
18985 If there is no fragment at point, display all fragments in the
18986 current section.
18988 With prefix ARG, preview or clear image for all fragments in the
18989 current subtree or in the whole buffer when used before the first
18990 headline. With a double prefix ARG \\[universal-argument] \
18991 \\[universal-argument] preview or clear images
18992 for all fragments in the buffer."
18993 (interactive "P")
18994 (unless (buffer-file-name (buffer-base-buffer))
18995 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18996 (when (display-graphic-p)
18997 (catch 'exit
18998 (save-excursion
18999 (let ((window-start (window-start)) msg)
19000 (save-restriction
19001 (cond
19002 ((or (equal arg '(16))
19003 (and (equal arg '(4))
19004 (org-with-limited-levels (org-before-first-heading-p))))
19005 (if (org-remove-latex-fragment-image-overlays)
19006 (progn (message "LaTeX fragments images removed from buffer")
19007 (throw 'exit nil))
19008 (setq msg "Creating images for buffer...")))
19009 ((equal arg '(4))
19010 (org-with-limited-levels (org-back-to-heading t))
19011 (let ((beg (point))
19012 (end (progn (org-end-of-subtree t) (point))))
19013 (if (org-remove-latex-fragment-image-overlays beg end)
19014 (progn
19015 (message "LaTeX fragment images removed from subtree")
19016 (throw 'exit nil))
19017 (setq msg "Creating images for subtree...")
19018 (narrow-to-region beg end))))
19019 ((let ((datum (org-element-context)))
19020 (when (memq (org-element-type datum)
19021 '(latex-environment latex-fragment))
19022 (let* ((beg (org-element-property :begin datum))
19023 (end (org-element-property :end datum)))
19024 (if (org-remove-latex-fragment-image-overlays beg end)
19025 (progn (message "LaTeX fragment image removed")
19026 (throw 'exit nil))
19027 (narrow-to-region beg end)
19028 (setq msg "Creating image..."))))))
19030 (org-with-limited-levels
19031 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19032 (outline-previous-heading)
19033 (point)))
19034 (end (progn (outline-next-heading) (point))))
19035 (if (org-remove-latex-fragment-image-overlays beg end)
19036 (progn
19037 (message "LaTeX fragment images removed from section")
19038 (throw 'exit nil))
19039 (setq msg "Creating images for section...")
19040 (narrow-to-region beg end))))))
19041 (let ((file (buffer-file-name (buffer-base-buffer))))
19042 (org-format-latex
19043 (concat org-latex-preview-ltxpng-directory
19044 (file-name-sans-extension (file-name-nondirectory file)))
19045 ;; Emacs cannot overlay images from remote hosts.
19046 ;; Create it in `temporary-file-directory' instead.
19047 (if (file-remote-p file) temporary-file-directory
19048 default-directory)
19049 'overlays msg 'forbuffer
19050 org-latex-create-formula-image-program)))
19051 ;; Work around a bug that doesn't restore window's start
19052 ;; when widening back the buffer.
19053 (set-window-start nil window-start)
19054 (message (concat msg "done")))))))
19056 (defun org-format-latex
19057 (prefix &optional dir overlays msg forbuffer processing-type)
19058 "Replace LaTeX fragments with links to an image, and produce images.
19060 When optional argument OVERLAYS is non-nil, display the image on
19061 top of the fragment instead of replacing it.
19063 PROCESSING-TYPE is the conversion method to use, as a symbol.
19065 Some of the options can be changed using the variable
19066 `org-format-latex-options', which see."
19067 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19068 (unless (eq processing-type 'verbatim)
19069 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19070 (cnt 0)
19071 checkdir-flag)
19072 (goto-char (point-min))
19073 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19074 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19075 (overlay-recenter (point-max)))
19076 (while (re-search-forward math-regexp nil t)
19077 (unless (and overlays
19078 (eq (get-char-property (point) 'org-overlay-type)
19079 'org-latex-overlay))
19080 (let* ((context (org-element-context))
19081 (type (org-element-type context)))
19082 (when (memq type '(latex-environment latex-fragment))
19083 (let ((block-type (eq type 'latex-environment))
19084 (value (org-element-property :value context))
19085 (beg (org-element-property :begin context))
19086 (end (save-excursion
19087 (goto-char (org-element-property :end context))
19088 (skip-chars-backward " \r\t\n")
19089 (point))))
19090 (case processing-type
19091 (mathjax
19092 ;; Prepare for MathJax processing.
19093 (if (eq (char-after beg) ?$)
19094 (save-excursion
19095 (delete-region beg end)
19096 (insert "\\(" (substring value 1 -1) "\\)"))
19097 (goto-char end)))
19098 ((dvipng imagemagick)
19099 ;; Process to an image.
19100 (incf cnt)
19101 (goto-char beg)
19102 (let* ((face (face-at-point))
19103 ;; Get the colors from the face at point.
19105 (let ((color (plist-get org-format-latex-options
19106 :foreground)))
19107 (if (and forbuffer (eq color 'auto))
19108 (face-attribute face :foreground nil 'default)
19109 color)))
19111 (let ((color (plist-get org-format-latex-options
19112 :background)))
19113 (if (and forbuffer (eq color 'auto))
19114 (face-attribute face :background nil 'default)
19115 color)))
19116 (hash (sha1 (prin1-to-string
19117 (list org-format-latex-header
19118 org-latex-default-packages-alist
19119 org-latex-packages-alist
19120 org-format-latex-options
19121 forbuffer value fg bg))))
19122 (absprefix (expand-file-name prefix dir))
19123 (linkfile (format "%s_%s.png" prefix hash))
19124 (movefile (format "%s_%s.png" absprefix hash))
19125 (sep (and block-type "\n\n"))
19126 (link (concat sep "[[file:" linkfile "]]" sep))
19127 (options
19128 (org-combine-plists
19129 org-format-latex-options
19130 `(:foreground ,fg :background ,bg))))
19131 (when msg (message msg cnt))
19132 (unless checkdir-flag ; Ensure the directory exists.
19133 (setq checkdir-flag t)
19134 (let ((todir (file-name-directory absprefix)))
19135 (unless (file-directory-p todir)
19136 (make-directory todir t))))
19137 (unless (file-exists-p movefile)
19138 (org-create-formula-image
19139 value movefile options forbuffer processing-type))
19140 (if overlays
19141 (progn
19142 (dolist (o (overlays-in beg end))
19143 (when (eq (overlay-get o 'org-overlay-type)
19144 'org-latex-overlay)
19145 (delete-overlay o)))
19146 (let ((ov (make-overlay beg end)))
19147 (overlay-put ov
19148 'org-overlay-type
19149 'org-latex-overlay)
19150 (overlay-put ov 'evaporate t)
19151 (if (featurep 'xemacs)
19152 (progn
19153 (overlay-put ov 'invisible t)
19154 (overlay-put
19155 ov 'end-glyph
19156 (make-glyph
19157 (vector 'png :file movefile))))
19158 (overlay-put
19159 ov 'display
19160 (list 'image
19161 :type 'png
19162 :file movefile
19163 :ascent 'center)))
19164 (push ov org-latex-fragment-image-overlays))
19165 (goto-char end))
19166 (delete-region beg end)
19167 (insert
19168 (org-add-props link
19169 (list 'org-latex-src
19170 (replace-regexp-in-string "\"" "" value)
19171 'org-latex-src-embed-type
19172 (if block-type 'paragraph 'character)))))))
19173 (mathml
19174 ;; Process to MathML.
19175 (unless (org-format-latex-mathml-available-p)
19176 (user-error "LaTeX to MathML converter not configured"))
19177 (incf cnt)
19178 (when msg (message msg cnt))
19179 (goto-char beg)
19180 (delete-region beg end)
19181 (insert (org-format-latex-as-mathml
19182 value block-type prefix dir)))
19183 (otherwise
19184 (error "Unknown conversion type %s for LaTeX fragments"
19185 processing-type)))))))))))
19187 (defun org-create-math-formula (latex-frag &optional mathml-file)
19188 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19189 Use `org-latex-to-mathml-convert-command'. If the conversion is
19190 sucessful, return the portion between \"<math...> </math>\"
19191 elements otherwise return nil. When MATHML-FILE is specified,
19192 write the results in to that file. When invoked as an
19193 interactive command, prompt for LATEX-FRAG, with initial value
19194 set to the current active region and echo the results for user
19195 inspection."
19196 (interactive (list (let ((frag (when (org-region-active-p)
19197 (buffer-substring-no-properties
19198 (region-beginning) (region-end)))))
19199 (read-string "LaTeX Fragment: " frag nil frag))))
19200 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19201 (let* ((tmp-in-file (file-relative-name
19202 (make-temp-name (expand-file-name "ltxmathml-in"))))
19203 (ignore (write-region latex-frag nil tmp-in-file))
19204 (tmp-out-file (file-relative-name
19205 (make-temp-name (expand-file-name "ltxmathml-out"))))
19206 (cmd (format-spec
19207 org-latex-to-mathml-convert-command
19208 `((?j . ,(and org-latex-to-mathml-jar-file
19209 (shell-quote-argument
19210 (expand-file-name
19211 org-latex-to-mathml-jar-file))))
19212 (?I . ,(shell-quote-argument tmp-in-file))
19213 (?i . ,latex-frag)
19214 (?o . ,(shell-quote-argument tmp-out-file)))))
19215 mathml shell-command-output)
19216 (when (org-called-interactively-p 'any)
19217 (unless (org-format-latex-mathml-available-p)
19218 (user-error "LaTeX to MathML converter not configured")))
19219 (message "Running %s" cmd)
19220 (setq shell-command-output (shell-command-to-string cmd))
19221 (setq mathml
19222 (when (file-readable-p tmp-out-file)
19223 (with-current-buffer (find-file-noselect tmp-out-file t)
19224 (goto-char (point-min))
19225 (when (re-search-forward
19226 (concat
19227 (regexp-quote
19228 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19229 "[^>]*?>"
19230 "\\(.\\|\n\\)*"
19231 "</math>")
19232 nil t)
19233 (prog1 (match-string 0) (kill-buffer))))))
19234 (cond
19235 (mathml
19236 (setq mathml
19237 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19238 (when mathml-file
19239 (write-region mathml nil mathml-file))
19240 (when (org-called-interactively-p 'any)
19241 (message mathml)))
19242 ((message "LaTeX to MathML conversion failed")
19243 (message shell-command-output)))
19244 (delete-file tmp-in-file)
19245 (when (file-exists-p tmp-out-file)
19246 (delete-file tmp-out-file))
19247 mathml))
19249 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19250 prefix &optional dir)
19251 "Use `org-create-math-formula' but check local cache first."
19252 (let* ((absprefix (expand-file-name prefix dir))
19253 (print-length nil) (print-level nil)
19254 (formula-id (concat
19255 "formula-"
19256 (sha1
19257 (prin1-to-string
19258 (list latex-frag
19259 org-latex-to-mathml-convert-command)))))
19260 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19261 (formula-cache-dir (file-name-directory formula-cache)))
19263 (unless (file-directory-p formula-cache-dir)
19264 (make-directory formula-cache-dir t))
19266 (unless (file-exists-p formula-cache)
19267 (org-create-math-formula latex-frag formula-cache))
19269 (if (file-exists-p formula-cache)
19270 ;; Successful conversion. Return the link to MathML file.
19271 (org-add-props
19272 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19273 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19274 'org-latex-src-embed-type (if latex-frag-type
19275 'paragraph 'character)))
19276 ;; Failed conversion. Return the LaTeX fragment verbatim
19277 latex-frag)))
19279 (defun org-create-formula-image (string tofile options buffer &optional type)
19280 "Create an image from LaTeX source using dvipng or convert.
19281 This function calls either `org-create-formula-image-with-dvipng'
19282 or `org-create-formula-image-with-imagemagick' depending on the
19283 value of `org-latex-create-formula-image-program' or on the value
19284 of the optional TYPE variable.
19286 Note: ultimately these two function should be combined as they
19287 share a good deal of logic."
19288 (org-check-external-command
19289 "latex" "needed to convert LaTeX fragments to images")
19290 (funcall
19291 (case (or type org-latex-create-formula-image-program)
19292 (dvipng
19293 (org-check-external-command
19294 "dvipng" "needed to convert LaTeX fragments to images")
19295 #'org-create-formula-image-with-dvipng)
19296 (imagemagick
19297 (org-check-external-command
19298 "convert" "you need to install imagemagick")
19299 #'org-create-formula-image-with-imagemagick)
19300 (t (error
19301 "Invalid value of `org-latex-create-formula-image-program'")))
19302 string tofile options buffer))
19304 (declare-function org-export-get-backend "ox" (name))
19305 (declare-function org-export--get-global-options "ox" (&optional backend))
19306 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19307 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19308 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19309 (defun org-create-formula--latex-header ()
19310 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19311 (let ((info (org-combine-plists (org-export--get-global-options
19312 (org-export-get-backend 'latex))
19313 (org-export--get-inbuffer-options
19314 (org-export-get-backend 'latex)))))
19315 (org-latex-guess-babel-language
19316 (org-latex-guess-inputenc
19317 (org-splice-latex-header
19318 org-format-latex-header
19319 org-latex-default-packages-alist
19320 org-latex-packages-alist t
19321 (plist-get info :latex-header)))
19322 info)))
19324 (defun org--get-display-dpi ()
19325 "Get the DPI of the display.
19327 Assumes that the display has the same pixel width in the
19328 horizontal and vertical directions."
19329 (if (display-graphic-p)
19330 (round (/ (display-pixel-height)
19331 (/ (display-mm-height) 25.4)))
19332 (error "Attempt to calculate the dpi of a non-graphic display")))
19334 ;; This function borrows from Ganesh Swami's latex2png.el
19335 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19336 "This calls dvipng."
19337 (require 'ox-latex)
19338 (let* ((tmpdir (if (featurep 'xemacs)
19339 (temp-directory)
19340 temporary-file-directory))
19341 (texfilebase (make-temp-name
19342 (expand-file-name "orgtex" tmpdir)))
19343 (texfile (concat texfilebase ".tex"))
19344 (dvifile (concat texfilebase ".dvi"))
19345 (pngfile (concat texfilebase ".png"))
19346 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19347 ;; This assumes that the display has the same pixel width in
19348 ;; the horizontal and vertical directions
19349 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19350 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19351 "Black"))
19352 (bg (or (plist-get options (if buffer :background :html-background))
19353 "Transparent")))
19354 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19355 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19356 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19357 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19358 (let ((latex-header (org-create-formula--latex-header)))
19359 (with-temp-file texfile
19360 (insert latex-header)
19361 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19362 (let ((dir default-directory))
19363 (ignore-errors
19364 (cd tmpdir)
19365 (call-process "latex" nil nil nil texfile))
19366 (cd dir))
19367 (if (not (file-exists-p dvifile))
19368 (progn (message "Failed to create dvi file from %s" texfile) nil)
19369 (ignore-errors
19370 (if (featurep 'xemacs)
19371 (call-process "dvipng" nil nil nil
19372 "-fg" fg "-bg" bg
19373 "-T" "tight"
19374 "-o" pngfile
19375 dvifile)
19376 (call-process "dvipng" nil nil nil
19377 "-fg" fg "-bg" bg
19378 "-D" dpi
19379 ;;"-x" scale "-y" scale
19380 "-T" "tight"
19381 "-o" pngfile
19382 dvifile)))
19383 (if (not (file-exists-p pngfile))
19384 (if org-format-latex-signal-error
19385 (error "Failed to create png file from %s" texfile)
19386 (message "Failed to create png file from %s" texfile)
19387 nil)
19388 ;; Use the requested file name and clean up
19389 (copy-file pngfile tofile 'replace)
19390 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
19391 (if (file-exists-p (concat texfilebase e))
19392 (delete-file (concat texfilebase e))))
19393 pngfile))))
19395 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19396 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19397 "This calls convert, which is included into imagemagick."
19398 (require 'ox-latex)
19399 (let* ((tmpdir (if (featurep 'xemacs)
19400 (temp-directory)
19401 temporary-file-directory))
19402 (texfilebase (make-temp-name
19403 (expand-file-name "orgtex" tmpdir)))
19404 (texfile (concat texfilebase ".tex"))
19405 (pdffile (concat texfilebase ".pdf"))
19406 (pngfile (concat texfilebase ".png"))
19407 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19408 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19409 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19410 "black"))
19411 (bg (or (plist-get options (if buffer :background :html-background))
19412 "white")))
19413 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19414 (setq fg (org-latex-color-format fg)))
19415 (if (eq bg 'default) (setq bg (org-latex-color :background))
19416 (setq bg (org-latex-color-format
19417 (if (string= bg "Transparent") "white" bg))))
19418 (let ((latex-header (org-create-formula--latex-header)))
19419 (with-temp-file texfile
19420 (insert latex-header)
19421 (insert "\n\\begin{document}\n"
19422 "\\definecolor{fg}{rgb}{" fg "}\n"
19423 "\\definecolor{bg}{rgb}{" bg "}\n"
19424 "\n\\pagecolor{bg}\n"
19425 "\n{\\color{fg}\n"
19426 string
19427 "\n}\n"
19428 "\n\\end{document}\n")))
19429 (org-latex-compile texfile t)
19430 (if (not (file-exists-p pdffile))
19431 (progn (message "Failed to create pdf file from %s" texfile) nil)
19432 (ignore-errors
19433 (if (featurep 'xemacs)
19434 (call-process "convert" nil nil nil
19435 "-density" "96"
19436 "-trim"
19437 "-antialias"
19438 pdffile
19439 "-quality" "100"
19440 ;; "-sharpen" "0x1.0"
19441 pngfile)
19442 (call-process "convert" nil nil nil
19443 "-density" dpi
19444 "-trim"
19445 "-antialias"
19446 pdffile
19447 "-quality" "100"
19448 ;; "-sharpen" "0x1.0"
19449 pngfile)))
19450 (if (not (file-exists-p pngfile))
19451 (if org-format-latex-signal-error
19452 (error "Failed to create png file from %s" texfile)
19453 (message "Failed to create png file from %s" texfile)
19454 nil)
19455 ;; Use the requested file name and clean up
19456 (copy-file pngfile tofile 'replace)
19457 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19458 (if (file-exists-p (concat texfilebase e))
19459 (delete-file (concat texfilebase e))))
19460 pngfile))))
19462 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19463 "Fill a LaTeX header template TPL.
19464 In the template, the following place holders will be recognized:
19466 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19467 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19468 [PACKAGES] \\usepackage statements for PKG
19469 [NO-PACKAGES] do not include PKG
19470 [EXTRA] the string EXTRA
19471 [NO-EXTRA] do not include EXTRA
19473 For backward compatibility, if both the positive and the negative place
19474 holder is missing, the positive one (without the \"NO-\") will be
19475 assumed to be present at the end of the template.
19476 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19477 EXTRA is a string.
19478 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19479 (let (rpl (end ""))
19480 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19481 (setq rpl (if (or (match-end 1) (not def-pkg))
19482 "" (org-latex-packages-to-string def-pkg snippets-p t))
19483 tpl (replace-match rpl t t tpl))
19484 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19486 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19487 (setq rpl (if (or (match-end 1) (not pkg))
19488 "" (org-latex-packages-to-string pkg snippets-p t))
19489 tpl (replace-match rpl t t tpl))
19490 (if pkg (setq end
19491 (concat end "\n"
19492 (org-latex-packages-to-string pkg snippets-p)))))
19494 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19495 (setq rpl (if (or (match-end 1) (not extra))
19496 "" (concat extra "\n"))
19497 tpl (replace-match rpl t t tpl))
19498 (if (and extra (string-match "\\S-" extra))
19499 (setq end (concat end "\n" extra))))
19501 (if (string-match "\\S-" end)
19502 (concat tpl "\n" end)
19503 tpl)))
19505 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19506 "Turn an alist of packages into a string with the \\usepackage macros."
19507 (setq pkg (mapconcat (lambda(p)
19508 (cond
19509 ((stringp p) p)
19510 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19511 (format "%% Package %s omitted" (cadr p)))
19512 ((equal "" (car p))
19513 (format "\\usepackage{%s}" (cadr p)))
19515 (format "\\usepackage[%s]{%s}"
19516 (car p) (cadr p)))))
19518 "\n"))
19519 (if newline (concat pkg "\n") pkg))
19521 (defun org-dvipng-color (attr)
19522 "Return a RGB color specification for dvipng."
19523 (apply 'format "rgb %s %s %s"
19524 (mapcar 'org-normalize-color
19525 (if (featurep 'xemacs)
19526 (color-rgb-components
19527 (face-property 'default
19528 (cond ((eq attr :foreground) 'foreground)
19529 ((eq attr :background) 'background))))
19530 (color-values (face-attribute 'default attr nil))))))
19532 (defun org-dvipng-color-format (color-name)
19533 "Convert COLOR-NAME to a RGB color value for dvipng."
19534 (apply 'format "rgb %s %s %s"
19535 (mapcar 'org-normalize-color
19536 (color-values color-name))))
19538 (defun org-latex-color (attr)
19539 "Return a RGB color for the LaTeX color package."
19540 (apply 'format "%s,%s,%s"
19541 (mapcar 'org-normalize-color
19542 (if (featurep 'xemacs)
19543 (color-rgb-components
19544 (face-property 'default
19545 (cond ((eq attr :foreground) 'foreground)
19546 ((eq attr :background) 'background))))
19547 (color-values (face-attribute 'default attr nil))))))
19549 (defun org-latex-color-format (color-name)
19550 "Convert COLOR-NAME to a RGB color value."
19551 (apply 'format "%s,%s,%s"
19552 (mapcar 'org-normalize-color
19553 (color-values color-name))))
19555 (defun org-normalize-color (value)
19556 "Return string to be used as color value for an RGB component."
19557 (format "%g" (/ value 65535.0)))
19561 ;; Image display
19563 (defvar-local org-inline-image-overlays nil)
19565 (defun org-toggle-inline-images (&optional include-linked)
19566 "Toggle the display of inline images.
19567 INCLUDE-LINKED is passed to `org-display-inline-images'."
19568 (interactive "P")
19569 (if org-inline-image-overlays
19570 (progn
19571 (org-remove-inline-images)
19572 (when (org-called-interactively-p 'interactive)
19573 (message "Inline image display turned off")))
19574 (org-display-inline-images include-linked)
19575 (when (org-called-interactively-p 'interactive)
19576 (message (if org-inline-image-overlays
19577 (format "%d images displayed inline"
19578 (length org-inline-image-overlays))
19579 "No images to display inline")))))
19581 (defun org-redisplay-inline-images ()
19582 "Refresh the display of inline images."
19583 (interactive)
19584 (if (not org-inline-image-overlays)
19585 (org-toggle-inline-images)
19586 (org-toggle-inline-images)
19587 (org-toggle-inline-images)))
19589 (defun org-display-inline-images (&optional include-linked refresh beg end)
19590 "Display inline images.
19592 An inline image is a link which follows either of these
19593 conventions:
19595 1. Its path is a file with an extension matching return value
19596 from `image-file-name-regexp' and it has no contents.
19598 2. Its description consists in a single link of the previous
19599 type.
19601 When optional argument INCLUDE-LINKED is non-nil, also links with
19602 a text description part will be inlined. This can be nice for
19603 a quick look at those images, but it does not reflect what
19604 exported files will look like.
19606 When optional argument REFRESH is non-nil, refresh existing
19607 images between BEG and END. This will create new image displays
19608 only if necessary. BEG and END default to the buffer
19609 boundaries."
19610 (interactive "P")
19611 (when (display-graphic-p)
19612 (unless refresh
19613 (org-remove-inline-images)
19614 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19615 (org-with-wide-buffer
19616 (goto-char (or beg (point-min)))
19617 (let ((case-fold-search t)
19618 (file-extension-re (org-image-file-name-regexp)))
19619 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19620 (let ((link (save-match-data (org-element-context))))
19621 ;; Check if we're at an inline image.
19622 (when (and (equal (org-element-property :type link) "file")
19623 (or include-linked
19624 (not (org-element-property :contents-begin link)))
19625 (let ((parent (org-element-property :parent link)))
19626 (or (not (eq (org-element-type parent) 'link))
19627 (not (cdr (org-element-contents parent)))))
19628 (org-string-match-p file-extension-re
19629 (org-element-property :path link)))
19630 (let ((file (expand-file-name
19631 (org-link-unescape
19632 (org-element-property :path link)))))
19633 (when (file-exists-p file)
19634 (let ((width
19635 ;; Apply `org-image-actual-width' specifications.
19636 (cond
19637 ((not (image-type-available-p 'imagemagick)) nil)
19638 ((eq org-image-actual-width t) nil)
19639 ((listp org-image-actual-width)
19641 ;; First try to find a width among
19642 ;; attributes associated to the paragraph
19643 ;; containing link.
19644 (let ((paragraph
19645 (let ((e link))
19646 (while (and (setq e (org-element-property
19647 :parent e))
19648 (not (eq (org-element-type e)
19649 'paragraph))))
19650 e)))
19651 (when paragraph
19652 (save-excursion
19653 (goto-char (org-element-property :begin paragraph))
19654 (when
19655 (re-search-forward
19656 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19657 (org-element-property
19658 :post-affiliated paragraph)
19660 (string-to-number (match-string 1))))))
19661 ;; Otherwise, fall-back to provided number.
19662 (car org-image-actual-width)))
19663 ((numberp org-image-actual-width)
19664 org-image-actual-width)))
19665 (old (get-char-property-and-overlay
19666 (org-element-property :begin link)
19667 'org-image-overlay)))
19668 (if (and (car-safe old) refresh)
19669 (image-refresh (overlay-get (cdr old) 'display))
19670 (let ((image (create-image file
19671 (and width 'imagemagick)
19673 :width width)))
19674 (when image
19675 (let* ((link
19676 ;; If inline image is the description
19677 ;; of another link, be sure to
19678 ;; consider the latter as the one to
19679 ;; apply the overlay on.
19680 (let ((parent
19681 (org-element-property :parent link)))
19682 (if (eq (org-element-type parent) 'link)
19683 parent
19684 link)))
19685 (ov (make-overlay
19686 (org-element-property :begin link)
19687 (progn
19688 (goto-char
19689 (org-element-property :end link))
19690 (skip-chars-backward " \t")
19691 (point)))))
19692 (overlay-put ov 'display image)
19693 (overlay-put ov 'face 'default)
19694 (overlay-put ov 'org-image-overlay t)
19695 (overlay-put
19696 ov 'modification-hooks
19697 (list 'org-display-inline-remove-overlay))
19698 (push ov org-inline-image-overlays)))))))))))))))
19700 (define-obsolete-function-alias
19701 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19703 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19704 "Remove inline-display overlay if a corresponding region is modified."
19705 (let ((inhibit-modification-hooks t))
19706 (when (and ov after)
19707 (delete ov org-inline-image-overlays)
19708 (delete-overlay ov))))
19710 (defun org-remove-inline-images ()
19711 "Remove inline display of images."
19712 (interactive)
19713 (mapc 'delete-overlay org-inline-image-overlays)
19714 (setq org-inline-image-overlays nil))
19716 ;;;; Key bindings
19718 ;; Outline functions from `outline-mode-prefix-map'
19719 ;; that can be remapped in Org:
19720 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19721 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19722 (define-key org-mode-map [remap outline-forward-same-level]
19723 'org-forward-heading-same-level)
19724 (define-key org-mode-map [remap outline-backward-same-level]
19725 'org-backward-heading-same-level)
19726 (define-key org-mode-map [remap outline-show-branches]
19727 'org-kill-note-or-show-branches)
19728 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19729 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19730 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19731 (define-key org-mode-map [remap outline-next-visible-heading]
19732 'org-next-visible-heading)
19733 (define-key org-mode-map [remap outline-previous-visible-heading]
19734 'org-previous-visible-heading)
19735 (define-key org-mode-map [remap show-children] 'org-show-children)
19737 ;; Outline functions from `outline-mode-prefix-map' that can not
19738 ;; be remapped in Org:
19740 ;; - the column "key binding" shows whether the Outline function is still
19741 ;; available in Org mode on the same key that it has been bound to in
19742 ;; Outline mode:
19743 ;; - "overridden": key used for a different functionality in Org mode
19744 ;; - else: key still bound to the same Outline function in Org mode
19746 ;; | Outline function | key binding | Org replacement |
19747 ;; |------------------------------------+-------------+--------------------------|
19748 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19749 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19750 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19751 ;; | `show-entry' | overridden | no replacement |
19752 ;; | `show-branches' | `C-c C-k' | still same function |
19753 ;; | `show-subtree' | overridden | visibility cycling |
19754 ;; | `show-all' | overridden | no replacement |
19755 ;; | `hide-subtree' | overridden | visibility cycling |
19756 ;; | `hide-body' | overridden | no replacement |
19757 ;; | `hide-entry' | overridden | visibility cycling |
19758 ;; | `hide-leaves' | overridden | no replacement |
19759 ;; | `hide-sublevels' | overridden | no replacement |
19760 ;; | `hide-other' | overridden | no replacement |
19762 ;; Make `C-c C-x' a prefix key
19763 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19765 ;; TAB key with modifiers
19766 (org-defkey org-mode-map "\C-i" 'org-cycle)
19767 (org-defkey org-mode-map [(tab)] 'org-cycle)
19768 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19769 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19770 ;; The following line is necessary under Suse GNU/Linux
19771 (unless (featurep 'xemacs)
19772 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19773 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19774 (define-key org-mode-map [backtab] 'org-shifttab)
19776 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19777 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19778 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19780 ;; Cursor keys with modifiers
19781 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19782 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19783 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19784 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19786 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19787 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19788 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19789 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19790 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19791 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19793 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19794 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19795 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19796 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19798 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19799 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19800 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19801 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19803 ;; Babel keys
19804 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19805 (mapc (lambda (pair)
19806 (define-key org-babel-map (car pair) (cdr pair)))
19807 org-babel-key-bindings)
19809 ;;; Extra keys for tty access.
19810 ;; We only set them when really needed because otherwise the
19811 ;; menus don't show the simple keys
19813 (when (or org-use-extra-keys
19814 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19815 (not window-system))
19816 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19817 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19818 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19819 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19820 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19821 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19822 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19823 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19824 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19825 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19826 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19827 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19828 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19829 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19830 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19831 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19832 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19833 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19834 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19835 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19836 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19837 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19838 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19839 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19840 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19841 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19842 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19843 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19845 ;; All the other keys
19847 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19848 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19849 (if (boundp 'narrow-map)
19850 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19851 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19852 (if (boundp 'narrow-map)
19853 (org-defkey narrow-map "b" 'org-narrow-to-block)
19854 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19855 (if (boundp 'narrow-map)
19856 (org-defkey narrow-map "e" 'org-narrow-to-element)
19857 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19858 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19859 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19860 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19861 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19862 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19863 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19864 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19865 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19866 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19867 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19868 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19869 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19870 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19871 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19872 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19873 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19874 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19875 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19876 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19877 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19878 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19879 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19880 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19881 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19882 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19883 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19884 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19885 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19886 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19887 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19888 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19889 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19890 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19891 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19892 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19893 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19894 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19895 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19896 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19897 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19898 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19899 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19900 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19901 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19902 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19903 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19904 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19905 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19906 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19907 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19908 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19909 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19910 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19911 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19912 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19913 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19914 (org-defkey org-mode-map "\C-c^" 'org-sort)
19915 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19916 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19917 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19918 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19919 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19920 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19921 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19922 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19923 (org-defkey org-mode-map "\C-m" 'org-return)
19924 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19925 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19926 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19927 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19928 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19929 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19930 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19931 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19932 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19933 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19934 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19935 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19936 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19937 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19938 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19939 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19940 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19941 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19942 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19943 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19944 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19945 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19946 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19947 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19948 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19950 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19951 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19952 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19954 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19955 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19956 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19957 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19958 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19959 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19960 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19961 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19962 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19963 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19964 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19965 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19966 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19967 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19968 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19969 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19970 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19971 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19972 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19973 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19974 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19975 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19977 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19978 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19979 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19980 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19981 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19983 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19985 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19987 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19988 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19990 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19993 (when (featurep 'xemacs)
19994 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19997 (defconst org-speed-commands-default
19999 ("Outline Navigation")
20000 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20001 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20002 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20003 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20004 ("F" . org-next-block)
20005 ("B" . org-previous-block)
20006 ("u" . (org-speed-move-safe 'outline-up-heading))
20007 ("j" . org-goto)
20008 ("g" . (org-refile t))
20009 ("Outline Visibility")
20010 ("c" . org-cycle)
20011 ("C" . org-shifttab)
20012 (" " . org-display-outline-path)
20013 ("s" . org-narrow-to-subtree)
20014 ("=" . org-columns)
20015 ("Outline Structure Editing")
20016 ("U" . org-metaup)
20017 ("D" . org-metadown)
20018 ("r" . org-metaright)
20019 ("l" . org-metaleft)
20020 ("R" . org-shiftmetaright)
20021 ("L" . org-shiftmetaleft)
20022 ("i" . (progn (forward-char 1) (call-interactively
20023 'org-insert-heading-respect-content)))
20024 ("^" . org-sort)
20025 ("w" . org-refile)
20026 ("a" . org-archive-subtree-default-with-confirmation)
20027 ("@" . org-mark-subtree)
20028 ("#" . org-toggle-comment)
20029 ("Clock Commands")
20030 ("I" . org-clock-in)
20031 ("O" . org-clock-out)
20032 ("Meta Data Editing")
20033 ("t" . org-todo)
20034 ("," . (org-priority))
20035 ("0" . (org-priority ?\ ))
20036 ("1" . (org-priority ?A))
20037 ("2" . (org-priority ?B))
20038 ("3" . (org-priority ?C))
20039 (":" . org-set-tags-command)
20040 ("e" . org-set-effort)
20041 ("E" . org-inc-effort)
20042 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20043 (org-entry-put (point) "APPT_WARNTIME" m)))
20044 ("Agenda Views etc")
20045 ("v" . org-agenda)
20046 ("/" . org-sparse-tree)
20047 ("Misc")
20048 ("o" . org-open-at-point)
20049 ("?" . org-speed-command-help)
20050 ("<" . (org-agenda-set-restriction-lock 'subtree))
20051 (">" . (org-agenda-remove-restriction-lock))
20053 "The default speed commands.")
20055 (defun org-print-speed-command (e)
20056 (if (> (length (car e)) 1)
20057 (progn
20058 (princ "\n")
20059 (princ (car e))
20060 (princ "\n")
20061 (princ (make-string (length (car e)) ?-))
20062 (princ "\n"))
20063 (princ (car e))
20064 (princ " ")
20065 (if (symbolp (cdr e))
20066 (princ (symbol-name (cdr e)))
20067 (prin1 (cdr e)))
20068 (princ "\n")))
20070 (defun org-speed-command-help ()
20071 "Show the available speed commands."
20072 (interactive)
20073 (if (not org-use-speed-commands)
20074 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20075 (with-output-to-temp-buffer "*Help*"
20076 (princ "User-defined Speed commands\n===========================\n")
20077 (mapc 'org-print-speed-command org-speed-commands-user)
20078 (princ "\n")
20079 (princ "Built-in Speed commands\n=======================\n")
20080 (mapc 'org-print-speed-command org-speed-commands-default))
20081 (with-current-buffer "*Help*"
20082 (setq truncate-lines t))))
20084 (defun org-speed-move-safe (cmd)
20085 "Execute CMD, but make sure that the cursor always ends up in a headline.
20086 If not, return to the original position and throw an error."
20087 (interactive)
20088 (let ((pos (point)))
20089 (call-interactively cmd)
20090 (unless (and (bolp) (org-at-heading-p))
20091 (goto-char pos)
20092 (error "Boundary reached while executing %s" cmd))))
20094 (defvar org-self-insert-command-undo-counter 0)
20096 (defvar org-table-auto-blank-field) ; defined in org-table.el
20097 (defvar org-speed-command nil)
20099 (define-obsolete-function-alias
20100 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20102 (defun org-speed-command-activate (keys)
20103 "Hook for activating single-letter speed commands.
20104 `org-speed-commands-default' specifies a minimal command set.
20105 Use `org-speed-commands-user' for further customization."
20106 (when (or (and (bolp) (looking-at org-outline-regexp))
20107 (and (functionp org-use-speed-commands)
20108 (funcall org-use-speed-commands)))
20109 (cdr (assoc keys (append org-speed-commands-user
20110 org-speed-commands-default)))))
20112 (define-obsolete-function-alias
20113 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20115 (defun org-babel-speed-command-activate (keys)
20116 "Hook for activating single-letter code block commands."
20117 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20118 (cdr (assoc keys org-babel-key-bindings))))
20120 (defcustom org-speed-command-hook
20121 '(org-speed-command-default-hook org-babel-speed-command-hook)
20122 "Hook for activating speed commands at strategic locations.
20123 Hook functions are called in sequence until a valid handler is
20124 found.
20126 Each hook takes a single argument, a user-pressed command key
20127 which is also a `self-insert-command' from the global map.
20129 Within the hook, examine the cursor position and the command key
20130 and return nil or a valid handler as appropriate. Handler could
20131 be one of an interactive command, a function, or a form.
20133 Set `org-use-speed-commands' to non-nil value to enable this
20134 hook. The default setting is `org-speed-command-activate'."
20135 :group 'org-structure
20136 :version "24.1"
20137 :type 'hook)
20139 (defun org-self-insert-command (N)
20140 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20141 If the cursor is in a table looking at whitespace, the whitespace is
20142 overwritten, and the table is not marked as requiring realignment."
20143 (interactive "p")
20144 (org-check-before-invisible-edit 'insert)
20145 (cond
20146 ((and org-use-speed-commands
20147 (let ((kv (this-command-keys-vector)))
20148 (setq org-speed-command
20149 (run-hook-with-args-until-success
20150 'org-speed-command-hook
20151 (make-string 1 (aref kv (1- (length kv))))))))
20152 (cond
20153 ((commandp org-speed-command)
20154 (setq this-command org-speed-command)
20155 (call-interactively org-speed-command))
20156 ((functionp org-speed-command)
20157 (funcall org-speed-command))
20158 ((and org-speed-command (listp org-speed-command))
20159 (eval org-speed-command))
20160 (t (let (org-use-speed-commands)
20161 (call-interactively 'org-self-insert-command)))))
20162 ((and
20163 (org-table-p)
20164 (progn
20165 ;; Check if we blank the field, and if that triggers align.
20166 (and (featurep 'org-table) org-table-auto-blank-field
20167 (memq last-command
20168 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20169 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20170 ;; Got extra space, this field does not determine
20171 ;; column width.
20172 (let (org-table-may-need-update) (org-table-blank-field))
20173 ;; No extra space, this field may determine column
20174 ;; width.
20175 (org-table-blank-field)))
20177 (eq N 1)
20178 (looking-at "[^|\n]* \\( \\)|"))
20179 ;; There is room for insertion without re-aligning the table.
20180 (delete-region (match-beginning 1) (match-end 1))
20181 (self-insert-command N))
20183 (setq org-table-may-need-update t)
20184 (self-insert-command N)
20185 (org-fix-tags-on-the-fly)
20186 (if org-self-insert-cluster-for-undo
20187 (if (not (eq last-command 'org-self-insert-command))
20188 (setq org-self-insert-command-undo-counter 1)
20189 (if (>= org-self-insert-command-undo-counter 20)
20190 (setq org-self-insert-command-undo-counter 1)
20191 (and (> org-self-insert-command-undo-counter 0)
20192 buffer-undo-list (listp buffer-undo-list)
20193 (not (cadr buffer-undo-list)) ; remove nil entry
20194 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20195 (setq org-self-insert-command-undo-counter
20196 (1+ org-self-insert-command-undo-counter))))))))
20198 (defun org-check-before-invisible-edit (kind)
20199 "Check is editing if kind KIND would be dangerous with invisible text around.
20200 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20201 ;; First, try to get out of here as quickly as possible, to reduce overhead
20202 (if (and org-catch-invisible-edits
20203 (or (not (boundp 'visible-mode)) (not visible-mode))
20204 (or (get-char-property (point) 'invisible)
20205 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20206 ;; OK, we need to take a closer look
20207 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20208 (invisible-before-point (if (bobp) nil (get-char-property
20209 (1- (point)) 'invisible)))
20210 (border-and-ok-direction
20212 ;; Check if we are acting predictably before invisible text
20213 (and invisible-at-point (not invisible-before-point)
20214 (memq kind '(insert delete-backward)))
20215 ;; Check if we are acting predictably after invisible text
20216 ;; This works not well, and I have turned it off. It seems
20217 ;; better to always show and stop after invisible text.
20218 ;; (and (not invisible-at-point) invisible-before-point
20219 ;; (memq kind '(insert delete)))
20221 (when (or (memq invisible-at-point '(outline org-hide-block t))
20222 (memq invisible-before-point '(outline org-hide-block t)))
20223 (if (eq org-catch-invisible-edits 'error)
20224 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20225 (if (and org-custom-properties-overlays
20226 (y-or-n-p "Display invisible properties in this buffer? "))
20227 (org-toggle-custom-properties-visibility)
20228 ;; Make the area visible
20229 (save-excursion
20230 (if invisible-before-point
20231 (goto-char (previous-single-char-property-change
20232 (point) 'invisible)))
20233 (outline-show-subtree))
20234 (cond
20235 ((eq org-catch-invisible-edits 'show)
20236 ;; That's it, we do the edit after showing
20237 (message
20238 "Unfolding invisible region around point before editing")
20239 (sit-for 1))
20240 ((and (eq org-catch-invisible-edits 'smart)
20241 border-and-ok-direction)
20242 (message "Unfolding invisible region around point before editing"))
20244 ;; Don't do the edit, make the user repeat it in full visibility
20245 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20247 (defun org-fix-tags-on-the-fly ()
20248 (when (and (equal (char-after (point-at-bol)) ?*)
20249 (org-at-heading-p))
20250 (org-align-tags-here org-tags-column)))
20252 (defun org-delete-backward-char (N)
20253 "Like `delete-backward-char', insert whitespace at field end in tables.
20254 When deleting backwards, in tables this function will insert whitespace in
20255 front of the next \"|\" separator, to keep the table aligned. The table will
20256 still be marked for re-alignment if the field did fill the entire column,
20257 because, in this case the deletion might narrow the column."
20258 (interactive "p")
20259 (save-match-data
20260 (org-check-before-invisible-edit 'delete-backward)
20261 (if (and (org-table-p)
20262 (eq N 1)
20263 (string-match "|" (buffer-substring (point-at-bol) (point)))
20264 (looking-at ".*?|"))
20265 (let ((pos (point))
20266 (noalign (looking-at "[^|\n\r]* |"))
20267 (c org-table-may-need-update))
20268 (backward-delete-char N)
20269 (if (not overwrite-mode)
20270 (progn
20271 (skip-chars-forward "^|")
20272 (insert " ")
20273 (goto-char (1- pos))))
20274 ;; noalign: if there were two spaces at the end, this field
20275 ;; does not determine the width of the column.
20276 (if noalign (setq org-table-may-need-update c)))
20277 (backward-delete-char N)
20278 (org-fix-tags-on-the-fly))))
20280 (defun org-delete-char (N)
20281 "Like `delete-char', but insert whitespace at field end in tables.
20282 When deleting characters, in tables this function will insert whitespace in
20283 front of the next \"|\" separator, to keep the table aligned. The table will
20284 still be marked for re-alignment if the field did fill the entire column,
20285 because, in this case the deletion might narrow the column."
20286 (interactive "p")
20287 (save-match-data
20288 (org-check-before-invisible-edit 'delete)
20289 (if (and (org-table-p)
20290 (not (bolp))
20291 (not (= (char-after) ?|))
20292 (eq N 1))
20293 (if (looking-at ".*?|")
20294 (let ((pos (point))
20295 (noalign (looking-at "[^|\n\r]* |"))
20296 (c org-table-may-need-update))
20297 (replace-match
20298 (concat (substring (match-string 0) 1 -1) " |") nil t)
20299 (goto-char pos)
20300 ;; noalign: if there were two spaces at the end, this field
20301 ;; does not determine the width of the column.
20302 (if noalign (setq org-table-may-need-update c)))
20303 (delete-char N))
20304 (delete-char N)
20305 (org-fix-tags-on-the-fly))))
20307 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20308 (put 'org-self-insert-command 'delete-selection
20309 (lambda ()
20310 (not (run-hook-with-args-until-success
20311 'self-insert-uses-region-functions))))
20312 (put 'orgtbl-self-insert-command 'delete-selection
20313 (lambda ()
20314 (not (run-hook-with-args-until-success
20315 'self-insert-uses-region-functions))))
20316 (put 'org-delete-char 'delete-selection 'supersede)
20317 (put 'org-delete-backward-char 'delete-selection 'supersede)
20318 (put 'org-yank 'delete-selection 'yank)
20320 ;; Make `flyspell-mode' delay after some commands
20321 (put 'org-self-insert-command 'flyspell-delayed t)
20322 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20323 (put 'org-delete-char 'flyspell-delayed t)
20324 (put 'org-delete-backward-char 'flyspell-delayed t)
20326 ;; Make pabbrev-mode expand after org-mode commands
20327 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20328 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20330 (defun org-remap (map &rest commands)
20331 "In MAP, remap the functions given in COMMANDS.
20332 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20333 (let (new old)
20334 (while commands
20335 (setq old (pop commands) new (pop commands))
20336 (if (fboundp 'command-remapping)
20337 (org-defkey map (vector 'remap old) new)
20338 (substitute-key-definition old new map global-map)))))
20340 (defun org-transpose-words ()
20341 "Transpose words for Org.
20342 This uses the `org-mode-transpose-word-syntax-table' syntax
20343 table, which interprets characters in `org-emphasis-alist' as
20344 word constituents."
20345 (interactive)
20346 (with-syntax-table org-mode-transpose-word-syntax-table
20347 (call-interactively 'transpose-words)))
20348 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20350 (when (eq org-enable-table-editor 'optimized)
20351 ;; If the user wants maximum table support, we need to hijack
20352 ;; some standard editing functions
20353 (org-remap org-mode-map
20354 'self-insert-command 'org-self-insert-command
20355 'delete-char 'org-delete-char
20356 'delete-backward-char 'org-delete-backward-char)
20357 (org-defkey org-mode-map "|" 'org-force-self-insert))
20359 (defvar org-ctrl-c-ctrl-c-hook nil
20360 "Hook for functions attaching themselves to `C-c C-c'.
20362 This can be used to add additional functionality to the C-c C-c
20363 key which executes context-dependent commands. This hook is run
20364 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20365 run after the last test.
20367 Each function will be called with no arguments. The function
20368 must check if the context is appropriate for it to act. If yes,
20369 it should do its thing and then return a non-nil value. If the
20370 context is wrong, just do nothing and return nil.")
20372 (defvar org-ctrl-c-ctrl-c-final-hook nil
20373 "Hook for functions attaching themselves to `C-c C-c'.
20375 This can be used to add additional functionality to the C-c C-c
20376 key which executes context-dependent commands. This hook is run
20377 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20378 before the first test.
20380 Each function will be called with no arguments. The function
20381 must check if the context is appropriate for it to act. If yes,
20382 it should do its thing and then return a non-nil value. If the
20383 context is wrong, just do nothing and return nil.")
20385 (defvar org-tab-first-hook nil
20386 "Hook for functions to attach themselves to TAB.
20387 See `org-ctrl-c-ctrl-c-hook' for more information.
20388 This hook runs as the first action when TAB is pressed, even before
20389 `org-cycle' messes around with the `outline-regexp' to cater for
20390 inline tasks and plain list item folding.
20391 If any function in this hook returns t, any other actions that
20392 would have been caused by TAB (such as table field motion or visibility
20393 cycling) will not occur.")
20395 (defvar org-tab-after-check-for-table-hook nil
20396 "Hook for functions to attach themselves to TAB.
20397 See `org-ctrl-c-ctrl-c-hook' for more information.
20398 This hook runs after it has been established that the cursor is not in a
20399 table, but before checking if the cursor is in a headline or if global cycling
20400 should be done.
20401 If any function in this hook returns t, not other actions like visibility
20402 cycling will be done.")
20404 (defvar org-tab-after-check-for-cycling-hook nil
20405 "Hook for functions to attach themselves to TAB.
20406 See `org-ctrl-c-ctrl-c-hook' for more information.
20407 This hook runs after it has been established that not table field motion and
20408 not visibility should be done because of current context. This is probably
20409 the place where a package like yasnippets can hook in.")
20411 (defvar org-tab-before-tab-emulation-hook nil
20412 "Hook for functions to attach themselves to TAB.
20413 See `org-ctrl-c-ctrl-c-hook' for more information.
20414 This hook runs after every other options for TAB have been exhausted, but
20415 before indentation and \t insertion takes place.")
20417 (defvar org-metaleft-hook nil
20418 "Hook for functions attaching themselves to `M-left'.
20419 See `org-ctrl-c-ctrl-c-hook' for more information.")
20420 (defvar org-metaright-hook nil
20421 "Hook for functions attaching themselves to `M-right'.
20422 See `org-ctrl-c-ctrl-c-hook' for more information.")
20423 (defvar org-metaup-hook nil
20424 "Hook for functions attaching themselves to `M-up'.
20425 See `org-ctrl-c-ctrl-c-hook' for more information.")
20426 (defvar org-metadown-hook nil
20427 "Hook for functions attaching themselves to `M-down'.
20428 See `org-ctrl-c-ctrl-c-hook' for more information.")
20429 (defvar org-shiftmetaleft-hook nil
20430 "Hook for functions attaching themselves to `M-S-left'.
20431 See `org-ctrl-c-ctrl-c-hook' for more information.")
20432 (defvar org-shiftmetaright-hook nil
20433 "Hook for functions attaching themselves to `M-S-right'.
20434 See `org-ctrl-c-ctrl-c-hook' for more information.")
20435 (defvar org-shiftmetaup-hook nil
20436 "Hook for functions attaching themselves to `M-S-up'.
20437 See `org-ctrl-c-ctrl-c-hook' for more information.")
20438 (defvar org-shiftmetadown-hook nil
20439 "Hook for functions attaching themselves to `M-S-down'.
20440 See `org-ctrl-c-ctrl-c-hook' for more information.")
20441 (defvar org-metareturn-hook nil
20442 "Hook for functions attaching themselves to `M-RET'.
20443 See `org-ctrl-c-ctrl-c-hook' for more information.")
20444 (defvar org-shiftup-hook nil
20445 "Hook for functions attaching themselves to `S-up'.
20446 See `org-ctrl-c-ctrl-c-hook' for more information.")
20447 (defvar org-shiftup-final-hook nil
20448 "Hook for functions attaching themselves to `S-up'.
20449 This one runs after all other options except shift-select have been excluded.
20450 See `org-ctrl-c-ctrl-c-hook' for more information.")
20451 (defvar org-shiftdown-hook nil
20452 "Hook for functions attaching themselves to `S-down'.
20453 See `org-ctrl-c-ctrl-c-hook' for more information.")
20454 (defvar org-shiftdown-final-hook nil
20455 "Hook for functions attaching themselves to `S-down'.
20456 This one runs after all other options except shift-select have been excluded.
20457 See `org-ctrl-c-ctrl-c-hook' for more information.")
20458 (defvar org-shiftleft-hook nil
20459 "Hook for functions attaching themselves to `S-left'.
20460 See `org-ctrl-c-ctrl-c-hook' for more information.")
20461 (defvar org-shiftleft-final-hook nil
20462 "Hook for functions attaching themselves to `S-left'.
20463 This one runs after all other options except shift-select have been excluded.
20464 See `org-ctrl-c-ctrl-c-hook' for more information.")
20465 (defvar org-shiftright-hook nil
20466 "Hook for functions attaching themselves to `S-right'.
20467 See `org-ctrl-c-ctrl-c-hook' for more information.")
20468 (defvar org-shiftright-final-hook nil
20469 "Hook for functions attaching themselves to `S-right'.
20470 This one runs after all other options except shift-select have been excluded.
20471 See `org-ctrl-c-ctrl-c-hook' for more information.")
20473 (defun org-modifier-cursor-error ()
20474 "Throw an error, a modified cursor command was applied in wrong context."
20475 (user-error "This command is active in special context like tables, headlines or items"))
20477 (defun org-shiftselect-error ()
20478 "Throw an error because Shift-Cursor command was applied in wrong context."
20479 (if (and (boundp 'shift-select-mode) shift-select-mode)
20480 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20481 (user-error "This command works only in special context like headlines or timestamps")))
20483 (defun org-call-for-shift-select (cmd)
20484 (let ((this-command-keys-shift-translated t))
20485 (call-interactively cmd)))
20487 (defun org-shifttab (&optional arg)
20488 "Global visibility cycling or move to previous table field.
20489 Call `org-table-previous-field' within a table.
20490 When ARG is nil, cycle globally through visibility states.
20491 When ARG is a numeric prefix, show contents of this level."
20492 (interactive "P")
20493 (cond
20494 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20495 ((integerp arg)
20496 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20497 (message "Content view to level: %d" arg)
20498 (org-content (prefix-numeric-value arg2))
20499 (org-cycle-show-empty-lines t)
20500 (setq org-cycle-global-status 'overview)))
20501 (t (call-interactively 'org-global-cycle))))
20503 (defun org-shiftmetaleft ()
20504 "Promote subtree or delete table column.
20505 Calls `org-promote-subtree', `org-outdent-item-tree', or
20506 `org-table-delete-column', depending on context. See the
20507 individual commands for more information."
20508 (interactive)
20509 (cond
20510 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20511 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20512 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20513 ((if (not (org-region-active-p)) (org-at-item-p)
20514 (save-excursion (goto-char (region-beginning))
20515 (org-at-item-p)))
20516 (call-interactively 'org-outdent-item-tree))
20517 (t (org-modifier-cursor-error))))
20519 (defun org-shiftmetaright ()
20520 "Demote subtree or insert table column.
20521 Calls `org-demote-subtree', `org-indent-item-tree', or
20522 `org-table-insert-column', depending on context. See the
20523 individual commands for more information."
20524 (interactive)
20525 (cond
20526 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20527 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20528 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20529 ((if (not (org-region-active-p)) (org-at-item-p)
20530 (save-excursion (goto-char (region-beginning))
20531 (org-at-item-p)))
20532 (call-interactively 'org-indent-item-tree))
20533 (t (org-modifier-cursor-error))))
20535 (defun org-shiftmetaup (&optional arg)
20536 "Drag the line at point up.
20537 In a table, kill the current row.
20538 On a clock timestamp, update the value of the timestamp like `S-<up>'
20539 but also adjust the previous clocked item in the clock history.
20540 Everywhere else, drag the line at point up."
20541 (interactive "P")
20542 (cond
20543 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20544 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20545 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20546 (call-interactively 'org-timestamp-up)))
20547 (t (call-interactively 'org-drag-line-backward))))
20549 (defun org-shiftmetadown (&optional arg)
20550 "Drag the line at point down.
20551 In a table, insert an empty row at the current line.
20552 On a clock timestamp, update the value of the timestamp like `S-<down>'
20553 but also adjust the previous clocked item in the clock history.
20554 Everywhere else, drag the line at point down."
20555 (interactive "P")
20556 (cond
20557 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20558 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20559 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20560 (call-interactively 'org-timestamp-down)))
20561 (t (call-interactively 'org-drag-line-forward))))
20563 (defsubst org-hidden-tree-error ()
20564 (user-error
20565 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20567 (defun org-metaleft (&optional arg)
20568 "Promote heading, list item at point or move table column left.
20570 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20571 depending on context. With no specific context, calls the Emacs
20572 default `backward-word'. See the individual commands for more
20573 information.
20575 This function runs the hook `org-metaleft-hook' as a first step,
20576 and returns at first non-nil value."
20577 (interactive "P")
20578 (cond
20579 ((run-hook-with-args-until-success 'org-metaleft-hook))
20580 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20581 ((org-with-limited-levels
20582 (or (org-at-heading-p)
20583 (and (org-region-active-p)
20584 (save-excursion
20585 (goto-char (region-beginning))
20586 (org-at-heading-p)))))
20587 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20588 (call-interactively 'org-do-promote))
20589 ;; At an inline task.
20590 ((org-at-heading-p)
20591 (call-interactively 'org-inlinetask-promote))
20592 ((or (org-at-item-p)
20593 (and (org-region-active-p)
20594 (save-excursion
20595 (goto-char (region-beginning))
20596 (org-at-item-p))))
20597 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20598 (call-interactively 'org-outdent-item))
20599 (t (call-interactively 'backward-word))))
20601 (defun org-metaright (&optional arg)
20602 "Demote heading, list item at point or move table column right.
20604 In front of a drawer or a block keyword, indent it correctly.
20606 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20607 `org-indnet-drawer' or `org-indent-block' depending on context.
20608 With no specific context, calls the Emacs default `forward-word'.
20609 See the individual commands for more information.
20611 This function runs the hook `org-metaright-hook' as a first step,
20612 and returns at first non-nil value."
20613 (interactive "P")
20614 (cond
20615 ((run-hook-with-args-until-success 'org-metaright-hook))
20616 ((org-at-table-p) (call-interactively 'org-table-move-column))
20617 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20618 ((org-at-block-p) (call-interactively 'org-indent-block))
20619 ((org-with-limited-levels
20620 (or (org-at-heading-p)
20621 (and (org-region-active-p)
20622 (save-excursion
20623 (goto-char (region-beginning))
20624 (org-at-heading-p)))))
20625 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20626 (call-interactively 'org-do-demote))
20627 ;; At an inline task.
20628 ((org-at-heading-p)
20629 (call-interactively 'org-inlinetask-demote))
20630 ((or (org-at-item-p)
20631 (and (org-region-active-p)
20632 (save-excursion
20633 (goto-char (region-beginning))
20634 (org-at-item-p))))
20635 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20636 (call-interactively 'org-indent-item))
20637 (t (call-interactively 'forward-word))))
20639 (defun org-check-for-hidden (what)
20640 "Check if there are hidden headlines/items in the current visual line.
20641 WHAT can be either `headlines' or `items'. If the current line is
20642 an outline or item heading and it has a folded subtree below it,
20643 this function returns t, nil otherwise."
20644 (let ((re (cond
20645 ((eq what 'headlines) org-outline-regexp-bol)
20646 ((eq what 'items) (org-item-beginning-re))
20647 (t (error "This should not happen"))))
20648 beg end)
20649 (save-excursion
20650 (catch 'exit
20651 (unless (org-region-active-p)
20652 (setq beg (point-at-bol))
20653 (beginning-of-line 2)
20654 (while (and (not (eobp)) ;; this is like `next-line'
20655 (get-char-property (1- (point)) 'invisible))
20656 (beginning-of-line 2))
20657 (setq end (point))
20658 (goto-char beg)
20659 (goto-char (point-at-eol))
20660 (setq end (max end (point)))
20661 (while (re-search-forward re end t)
20662 (if (get-char-property (match-beginning 0) 'invisible)
20663 (throw 'exit t))))
20664 nil))))
20666 (defun org-metaup (&optional arg)
20667 "Move subtree up or move table row up.
20668 Calls `org-move-subtree-up' or `org-table-move-row' or
20669 `org-move-item-up', depending on context. See the individual commands
20670 for more information."
20671 (interactive "P")
20672 (cond
20673 ((run-hook-with-args-until-success 'org-metaup-hook))
20674 ((org-region-active-p)
20675 (let* ((a (min (region-beginning) (region-end)))
20676 (b (1- (max (region-beginning) (region-end))))
20677 (c (save-excursion (goto-char a)
20678 (move-beginning-of-line 0)))
20679 (d (save-excursion (goto-char a)
20680 (move-end-of-line 0) (point))))
20681 (transpose-regions a b c d)
20682 (goto-char c)))
20683 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20684 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20685 ((org-at-item-p) (call-interactively 'org-move-item-up))
20686 (t (org-drag-element-backward))))
20688 (defun org-metadown (&optional arg)
20689 "Move subtree down or move table row down.
20690 Calls `org-move-subtree-down' or `org-table-move-row' or
20691 `org-move-item-down', depending on context. See the individual
20692 commands for more information."
20693 (interactive "P")
20694 (cond
20695 ((run-hook-with-args-until-success 'org-metadown-hook))
20696 ((org-region-active-p)
20697 (let* ((a (min (region-beginning) (region-end)))
20698 (b (max (region-beginning) (region-end)))
20699 (c (save-excursion (goto-char b)
20700 (move-beginning-of-line 1)))
20701 (d (save-excursion (goto-char b)
20702 (move-end-of-line 1) (1+ (point)))))
20703 (transpose-regions a b c d)
20704 (goto-char d)))
20705 ((org-at-table-p) (call-interactively 'org-table-move-row))
20706 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20707 ((org-at-item-p) (call-interactively 'org-move-item-down))
20708 (t (org-drag-element-forward))))
20710 (defun org-shiftup (&optional arg)
20711 "Increase item in timestamp or increase priority of current headline.
20712 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20713 depending on context. See the individual commands for more information."
20714 (interactive "P")
20715 (cond
20716 ((run-hook-with-args-until-success 'org-shiftup-hook))
20717 ((and org-support-shift-select (org-region-active-p))
20718 (org-call-for-shift-select 'previous-line))
20719 ((org-at-timestamp-p t)
20720 (call-interactively (if org-edit-timestamp-down-means-later
20721 'org-timestamp-down 'org-timestamp-up)))
20722 ((and (not (eq org-support-shift-select 'always))
20723 org-enable-priority-commands
20724 (org-at-heading-p))
20725 (call-interactively 'org-priority-up))
20726 ((and (not org-support-shift-select) (org-at-item-p))
20727 (call-interactively 'org-previous-item))
20728 ((org-clocktable-try-shift 'up arg))
20729 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20730 (org-support-shift-select
20731 (org-call-for-shift-select 'previous-line))
20732 (t (org-shiftselect-error))))
20734 (defun org-shiftdown (&optional arg)
20735 "Decrease item in timestamp or decrease priority of current headline.
20736 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20737 depending on context. See the individual commands for more information."
20738 (interactive "P")
20739 (cond
20740 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20741 ((and org-support-shift-select (org-region-active-p))
20742 (org-call-for-shift-select 'next-line))
20743 ((org-at-timestamp-p t)
20744 (call-interactively (if org-edit-timestamp-down-means-later
20745 'org-timestamp-up 'org-timestamp-down)))
20746 ((and (not (eq org-support-shift-select 'always))
20747 org-enable-priority-commands
20748 (org-at-heading-p))
20749 (call-interactively 'org-priority-down))
20750 ((and (not org-support-shift-select) (org-at-item-p))
20751 (call-interactively 'org-next-item))
20752 ((org-clocktable-try-shift 'down arg))
20753 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20754 (org-support-shift-select
20755 (org-call-for-shift-select 'next-line))
20756 (t (org-shiftselect-error))))
20758 (defun org-shiftright (&optional arg)
20759 "Cycle the thing at point or in the current line, depending on context.
20760 Depending on context, this does one of the following:
20762 - switch a timestamp at point one day into the future
20763 - on a headline, switch to the next TODO keyword.
20764 - on an item, switch entire list to the next bullet type
20765 - on a property line, switch to the next allowed value
20766 - on a clocktable definition line, move time block into the future"
20767 (interactive "P")
20768 (cond
20769 ((run-hook-with-args-until-success 'org-shiftright-hook))
20770 ((and org-support-shift-select (org-region-active-p))
20771 (org-call-for-shift-select 'forward-char))
20772 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20773 ((and (not (eq org-support-shift-select 'always))
20774 (org-at-heading-p))
20775 (let ((org-inhibit-logging
20776 (not org-treat-S-cursor-todo-selection-as-state-change))
20777 (org-inhibit-blocking
20778 (not org-treat-S-cursor-todo-selection-as-state-change)))
20779 (org-call-with-arg 'org-todo 'right)))
20780 ((or (and org-support-shift-select
20781 (not (eq org-support-shift-select 'always))
20782 (org-at-item-bullet-p))
20783 (and (not org-support-shift-select) (org-at-item-p)))
20784 (org-call-with-arg 'org-cycle-list-bullet nil))
20785 ((and (not (eq org-support-shift-select 'always))
20786 (org-at-property-p))
20787 (call-interactively 'org-property-next-allowed-value))
20788 ((org-clocktable-try-shift 'right arg))
20789 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20790 (org-support-shift-select
20791 (org-call-for-shift-select 'forward-char))
20792 (t (org-shiftselect-error))))
20794 (defun org-shiftleft (&optional arg)
20795 "Cycle the thing at point or in the current line, depending on context.
20796 Depending on context, this does one of the following:
20798 - switch a timestamp at point one day into the past
20799 - on a headline, switch to the previous TODO keyword.
20800 - on an item, switch entire list to the previous bullet type
20801 - on a property line, switch to the previous allowed value
20802 - on a clocktable definition line, move time block into the past"
20803 (interactive "P")
20804 (cond
20805 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20806 ((and org-support-shift-select (org-region-active-p))
20807 (org-call-for-shift-select 'backward-char))
20808 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20809 ((and (not (eq org-support-shift-select 'always))
20810 (org-at-heading-p))
20811 (let ((org-inhibit-logging
20812 (not org-treat-S-cursor-todo-selection-as-state-change))
20813 (org-inhibit-blocking
20814 (not org-treat-S-cursor-todo-selection-as-state-change)))
20815 (org-call-with-arg 'org-todo 'left)))
20816 ((or (and org-support-shift-select
20817 (not (eq org-support-shift-select 'always))
20818 (org-at-item-bullet-p))
20819 (and (not org-support-shift-select) (org-at-item-p)))
20820 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20821 ((and (not (eq org-support-shift-select 'always))
20822 (org-at-property-p))
20823 (call-interactively 'org-property-previous-allowed-value))
20824 ((org-clocktable-try-shift 'left arg))
20825 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20826 (org-support-shift-select
20827 (org-call-for-shift-select 'backward-char))
20828 (t (org-shiftselect-error))))
20830 (defun org-shiftcontrolright ()
20831 "Switch to next TODO set."
20832 (interactive)
20833 (cond
20834 ((and org-support-shift-select (org-region-active-p))
20835 (org-call-for-shift-select 'forward-word))
20836 ((and (not (eq org-support-shift-select 'always))
20837 (org-at-heading-p))
20838 (org-call-with-arg 'org-todo 'nextset))
20839 (org-support-shift-select
20840 (org-call-for-shift-select 'forward-word))
20841 (t (org-shiftselect-error))))
20843 (defun org-shiftcontrolleft ()
20844 "Switch to previous TODO set."
20845 (interactive)
20846 (cond
20847 ((and org-support-shift-select (org-region-active-p))
20848 (org-call-for-shift-select 'backward-word))
20849 ((and (not (eq org-support-shift-select 'always))
20850 (org-at-heading-p))
20851 (org-call-with-arg 'org-todo 'previousset))
20852 (org-support-shift-select
20853 (org-call-for-shift-select 'backward-word))
20854 (t (org-shiftselect-error))))
20856 (defun org-shiftcontrolup (&optional n)
20857 "Change timestamps synchronously up in CLOCK log lines.
20858 Optional argument N tells to change by that many units."
20859 (interactive "P")
20860 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20861 (let (org-support-shift-select)
20862 (org-clock-timestamps-up n))
20863 (user-error "Not at a clock log")))
20865 (defun org-shiftcontroldown (&optional n)
20866 "Change timestamps synchronously down in CLOCK log lines.
20867 Optional argument N tells to change by that many units."
20868 (interactive "P")
20869 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20870 (let (org-support-shift-select)
20871 (org-clock-timestamps-down n))
20872 (user-error "Not at a clock log")))
20874 (defun org-increase-number-at-point (&optional inc)
20875 "Increment the number at point.
20876 With an optional prefix numeric argument INC, increment using
20877 this numeric value."
20878 (interactive "p")
20879 (if (not (number-at-point))
20880 (user-error "Not on a number")
20881 (unless inc (setq inc 1))
20882 (let ((pos (point))
20883 (beg (skip-chars-backward "-+^/*0-9eE."))
20884 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20885 (setq nap (buffer-substring-no-properties
20886 (+ pos beg) (+ pos beg end)))
20887 (delete-region (+ pos beg) (+ pos beg end))
20888 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20889 (when (org-at-table-p)
20890 (org-table-align)
20891 (org-table-end-of-field 1))))
20893 (defun org-decrease-number-at-point (&optional inc)
20894 "Decrement the number at point.
20895 With an optional prefix numeric argument INC, decrement using
20896 this numeric value."
20897 (interactive "p")
20898 (org-increase-number-at-point (- (or inc 1))))
20900 (defun org-ctrl-c-ret ()
20901 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20902 (interactive)
20903 (cond
20904 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20905 (t (call-interactively 'org-insert-heading))))
20907 (defun org-find-visible ()
20908 (let ((s (point)))
20909 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20910 (get-char-property s 'invisible)))
20912 (defun org-find-invisible ()
20913 (let ((s (point)))
20914 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20915 (not (get-char-property s 'invisible))))
20918 (defun org-copy-visible (beg end)
20919 "Copy the visible parts of the region."
20920 (interactive "r")
20921 (let (snippets s)
20922 (save-excursion
20923 (save-restriction
20924 (narrow-to-region beg end)
20925 (setq s (goto-char (point-min)))
20926 (while (not (= (point) (point-max)))
20927 (goto-char (org-find-invisible))
20928 (push (buffer-substring s (point)) snippets)
20929 (setq s (goto-char (org-find-visible))))))
20930 (kill-new (apply 'concat (nreverse snippets)))))
20932 (defun org-copy-special ()
20933 "Copy region in table or copy current subtree.
20934 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20935 See the individual commands for more information."
20936 (interactive)
20937 (call-interactively
20938 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20940 (defun org-cut-special ()
20941 "Cut region in table or cut current subtree.
20942 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20943 See the individual commands for more information."
20944 (interactive)
20945 (call-interactively
20946 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20948 (defun org-paste-special (arg)
20949 "Paste rectangular region into table, or past subtree relative to level.
20950 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20951 See the individual commands for more information."
20952 (interactive "P")
20953 (if (org-at-table-p)
20954 (org-table-paste-rectangle)
20955 (org-paste-subtree arg)))
20957 (defsubst org-in-fixed-width-region-p ()
20958 "Is point in a fixed-width region?"
20959 (save-match-data
20960 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20962 (defun org-edit-special (&optional arg)
20963 "Call a special editor for the element at point.
20964 When at a table, call the formula editor with `org-table-edit-formulas'.
20965 When in a source code block, call `org-edit-src-code'.
20966 When in a fixed-width region, call `org-edit-fixed-width-region'.
20967 When in an export block, call `org-edit-export-block'.
20968 When at an #+INCLUDE keyword, visit the included file.
20969 When at a footnote reference, call `org-edit-footnote-reference'
20970 On a link, call `ffap' to visit the link at point.
20971 Otherwise, return a user error."
20972 (interactive "P")
20973 (let ((element (org-element-at-point)))
20974 (assert (not buffer-read-only) nil
20975 "Buffer is read-only: %s" (buffer-name))
20976 (case (org-element-type element)
20977 (src-block
20978 (if (not arg) (org-edit-src-code)
20979 (let* ((info (org-babel-get-src-block-info))
20980 (lang (nth 0 info))
20981 (params (nth 2 info))
20982 (session (cdr (assq :session params))))
20983 (if (not session) (org-edit-src-code)
20984 ;; At a src-block with a session and function called with
20985 ;; an ARG: switch to the buffer related to the inferior
20986 ;; process.
20987 (switch-to-buffer
20988 (funcall (intern (concat "org-babel-prep-session:" lang))
20989 session params))))))
20990 (keyword
20991 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20992 (org-open-link-from-string
20993 (format "[[%s]]"
20994 (expand-file-name
20995 (let ((value (org-element-property :value element)))
20996 (cond ((not (org-string-nw-p value))
20997 (user-error "No file to edit"))
20998 ((string-match "\\`\"\\(.*?\\)\"" value)
20999 (match-string 1 value))
21000 ((string-match "\\`[^ \t\"]\\S-*" value)
21001 (match-string 0 value))
21002 (t (user-error "No valid file specified")))))))
21003 (user-error "No special environment to edit here")))
21004 (table
21005 (if (eq (org-element-property :type element) 'table.el)
21006 (org-edit-table.el)
21007 (call-interactively 'org-table-edit-formulas)))
21008 ;; Only Org tables contain `table-row' type elements.
21009 (table-row (call-interactively 'org-table-edit-formulas))
21010 (example-block (org-edit-src-code))
21011 (export-block (org-edit-export-block))
21012 (fixed-width (org-edit-fixed-width-region))
21013 (otherwise
21014 ;; No notable element at point. Though, we may be at a link or
21015 ;; a footnote reference, which are objects. Thus, scan deeper.
21016 (let ((context (org-element-context element)))
21017 (case (org-element-type context)
21018 (link (call-interactively #'ffap))
21019 (footnote-reference (org-edit-footnote-reference))
21020 (t (user-error "No special environment to edit here"))))))))
21022 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21023 (defun org-ctrl-c-ctrl-c (&optional arg)
21024 "Set tags in headline, or update according to changed information at point.
21026 This command does many different things, depending on context:
21028 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21029 this is what we do.
21031 - If the cursor is on a statistics cookie, update it.
21033 - If the cursor is in a headline, prompt for tags and insert them
21034 into the current line, aligned to `org-tags-column'. When called
21035 with prefix arg, realign all tags in the current buffer.
21037 - If the cursor is in one of the special #+KEYWORD lines, this
21038 triggers scanning the buffer for these lines and updating the
21039 information.
21041 - If the cursor is inside a table, realign the table. This command
21042 works even if the automatic table editor has been turned off.
21044 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21045 the entire table.
21047 - If the cursor is at a footnote reference or definition, jump to
21048 the corresponding definition or references, respectively.
21050 - If the cursor is a the beginning of a dynamic block, update it.
21052 - If the current buffer is a capture buffer, close note and file it.
21054 - If the cursor is on a <<<target>>>, update radio targets and
21055 corresponding links in this buffer.
21057 - If the cursor is on a numbered item in a plain list, renumber the
21058 ordered list.
21060 - If the cursor is on a checkbox, toggle it.
21062 - If the cursor is on a code block, evaluate it. The variable
21063 `org-confirm-babel-evaluate' can be used to control prompting
21064 before code block evaluation, by default every code block
21065 evaluation requires confirmation. Code block evaluation can be
21066 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21067 (interactive "P")
21068 (cond
21069 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21070 org-occur-highlights)
21071 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21072 (org-remove-occur-highlights)
21073 (message "Temporary highlights/overlays removed from current buffer"))
21074 ((and (local-variable-p 'org-finish-function (current-buffer))
21075 (fboundp org-finish-function))
21076 (funcall org-finish-function))
21077 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21079 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21080 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21081 (user-error "C-c C-c can do nothing useful at this location"))
21082 (let* ((context (org-element-context))
21083 (type (org-element-type context)))
21084 (case type
21085 ;; When at a link, act according to the parent instead.
21086 (link (setq context (org-element-property :parent context))
21087 (setq type (org-element-type context)))
21088 ;; Unsupported object types: refer to the first supported
21089 ;; element or object containing it.
21090 ((bold code entity export-snippet inline-babel-call inline-src-block
21091 italic latex-fragment line-break macro strike-through subscript
21092 superscript underline verbatim)
21093 (setq context
21094 (org-element-lineage
21095 context '(radio-target paragraph verse-block table-cell)))))
21096 ;; For convenience: at the first line of a paragraph on the
21097 ;; same line as an item, apply function on that item instead.
21098 (when (eq type 'paragraph)
21099 (let ((parent (org-element-property :parent context)))
21100 (when (and (eq (org-element-type parent) 'item)
21101 (= (line-beginning-position)
21102 (org-element-property :begin parent)))
21103 (setq context parent type 'item))))
21104 ;; Act according to type of element or object at point.
21105 (case type
21106 (clock (org-clock-update-time-maybe))
21107 (dynamic-block
21108 (save-excursion
21109 (goto-char (org-element-property :post-affiliated context))
21110 (org-update-dblock)))
21111 (footnote-definition
21112 (goto-char (org-element-property :post-affiliated context))
21113 (call-interactively 'org-footnote-action))
21114 (footnote-reference (call-interactively 'org-footnote-action))
21115 ((headline inlinetask)
21116 (save-excursion (goto-char (org-element-property :begin context))
21117 (call-interactively 'org-set-tags)))
21118 (item
21119 ;; At an item: a double C-u set checkbox to "[-]"
21120 ;; unconditionally, whereas a single one will toggle its
21121 ;; presence. Without a universal argument, if the item
21122 ;; has a checkbox, toggle it. Otherwise repair the list.
21123 (let* ((box (org-element-property :checkbox context))
21124 (struct (org-element-property :structure context))
21125 (old-struct (copy-tree struct))
21126 (parents (org-list-parents-alist struct))
21127 (prevs (org-list-prevs-alist struct))
21128 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21129 (org-list-set-checkbox
21130 (org-element-property :begin context) struct
21131 (cond ((equal arg '(16)) "[-]")
21132 ((and (not box) (equal arg '(4))) "[ ]")
21133 ((or (not box) (equal arg '(4))) nil)
21134 ((eq box 'on) "[ ]")
21135 (t "[X]")))
21136 ;; Mimic `org-list-write-struct' but with grabbing
21137 ;; a return value from `org-list-struct-fix-box'.
21138 (org-list-struct-fix-ind struct parents 2)
21139 (org-list-struct-fix-item-end struct)
21140 (org-list-struct-fix-bul struct prevs)
21141 (org-list-struct-fix-ind struct parents)
21142 (let ((block-item
21143 (org-list-struct-fix-box struct parents prevs orderedp)))
21144 (if (and box (equal struct old-struct))
21145 (if (equal arg '(16))
21146 (message "Checkboxes already reset")
21147 (user-error "Cannot toggle this checkbox: %s"
21148 (if (eq box 'on)
21149 "all subitems checked"
21150 "unchecked subitems")))
21151 (org-list-struct-apply-struct struct old-struct)
21152 (org-update-checkbox-count-maybe))
21153 (when block-item
21154 (message "Checkboxes were removed due to empty box at line %d"
21155 (org-current-line block-item))))))
21156 (keyword
21157 (let ((org-inhibit-startup-visibility-stuff t)
21158 (org-startup-align-all-tables nil))
21159 (when (boundp 'org-table-coordinate-overlays)
21160 (mapc 'delete-overlay org-table-coordinate-overlays)
21161 (setq org-table-coordinate-overlays nil))
21162 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21163 (message "Local setup has been refreshed"))
21164 (plain-list
21165 ;; At a plain list, with a double C-u argument, set
21166 ;; checkboxes of each item to "[-]", whereas a single one
21167 ;; will toggle their presence according to the state of the
21168 ;; first item in the list. Without an argument, repair the
21169 ;; list.
21170 (let* ((begin (org-element-property :contents-begin context))
21171 (beginm (move-marker (make-marker) begin))
21172 (struct (org-element-property :structure context))
21173 (old-struct (copy-tree struct))
21174 (first-box (save-excursion
21175 (goto-char begin)
21176 (looking-at org-list-full-item-re)
21177 (match-string-no-properties 3)))
21178 (new-box (cond ((equal arg '(16)) "[-]")
21179 ((equal arg '(4)) (unless first-box "[ ]"))
21180 ((equal first-box "[X]") "[ ]")
21181 (t "[X]"))))
21182 (cond
21183 (arg
21184 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
21185 (org-list-get-all-items
21186 begin struct (org-list-prevs-alist struct))))
21187 ((and first-box (eq (point) begin))
21188 ;; For convenience, when point is at bol on the first
21189 ;; item of the list and no argument is provided, simply
21190 ;; toggle checkbox of that item, if any.
21191 (org-list-set-checkbox begin struct new-box)))
21192 (org-list-write-struct
21193 struct (org-list-parents-alist struct) old-struct)
21194 (org-update-checkbox-count-maybe)
21195 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21196 ((property-drawer node-property)
21197 (call-interactively 'org-property-action))
21198 ((radio-target target)
21199 (call-interactively 'org-update-radio-target-regexp))
21200 (statistics-cookie
21201 (call-interactively 'org-update-statistics-cookies))
21202 ((table table-cell table-row)
21203 ;; At a table, recalculate every field and align it. Also
21204 ;; send the table if necessary. If the table has
21205 ;; a `table.el' type, just give up. At a table row or
21206 ;; cell, maybe recalculate line but always align table.
21207 (if (eq (org-element-property :type context) 'table.el)
21208 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21209 Use \\[org-edit-special] to edit table.el tables"))
21210 (let ((org-enable-table-editor t))
21211 (if (or (eq type 'table)
21212 ;; Check if point is at a TBLFM line.
21213 (and (eq type 'table-row)
21214 (= (point) (org-element-property :end context))))
21215 (save-excursion
21216 (if (org-at-TBLFM-p)
21217 (progn (require 'org-table)
21218 (org-table-calc-current-TBLFM))
21219 (goto-char (org-element-property :contents-begin context))
21220 (org-call-with-arg 'org-table-recalculate (or arg t))
21221 (orgtbl-send-table 'maybe)))
21222 (org-table-maybe-eval-formula)
21223 (cond (arg (call-interactively 'org-table-recalculate))
21224 ((org-table-maybe-recalculate-line))
21225 (t (org-table-align)))))))
21226 (timestamp (org-timestamp-change 0 'day))
21227 (otherwise
21228 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21229 (user-error
21230 "C-c C-c can do nothing useful at this location")))))))))
21232 (defun org-mode-restart ()
21233 (interactive)
21234 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21235 (funcall major-mode)
21236 (hack-local-variables)
21237 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21238 (org-indent-mode -1)))
21239 (message "%s restarted" major-mode))
21241 (defun org-kill-note-or-show-branches ()
21242 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21243 (interactive)
21244 (if (not org-finish-function)
21245 (progn
21246 (outline-hide-subtree)
21247 (call-interactively 'outline-show-branches))
21248 (let ((org-note-abort t))
21249 (funcall org-finish-function))))
21251 (defun org-delete-indentation (&optional ARG)
21252 "Join current line to previous and fix whitespace at join.
21254 If previous line is a headline add to headline title. Otherwise
21255 the function calls `delete-indentation'.
21257 With argument, join this line to following line."
21258 (interactive "*P")
21259 (if (save-excursion
21260 (if ARG (beginning-of-line)
21261 (forward-line -1))
21262 (looking-at org-complex-heading-regexp))
21263 ;; At headline.
21264 (let ((tags-column (when (match-beginning 5)
21265 (save-excursion (goto-char (match-beginning 5))
21266 (current-column))))
21267 (string (concat " " (progn (when ARG (forward-line 1))
21268 (org-trim (delete-and-extract-region
21269 (line-beginning-position)
21270 (line-end-position)))))))
21271 (unless (bobp) (delete-region (point) (1- (point))))
21272 (goto-char (or (match-end 4)
21273 (match-beginning 5)
21274 (match-end 0)))
21275 (skip-chars-backward " \t")
21276 (save-excursion (insert string))
21277 ;; Adjust alignment of tags.
21278 (when tags-column
21279 (org-align-tags-here (if org-auto-align-tags
21280 org-tags-column
21281 tags-column))))
21282 (delete-indentation ARG)))
21284 (defun org-open-line (n)
21285 "Insert a new row in tables, call `open-line' elsewhere.
21286 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21287 (interactive "*p")
21288 (cond
21289 ((not org-special-ctrl-o)
21290 (open-line n))
21291 ((org-at-table-p)
21292 (org-table-insert-row))
21294 (open-line n))))
21296 (defun org-return (&optional indent)
21297 "Goto next table row or insert a newline.
21299 Calls `org-table-next-row' or `newline', depending on context.
21301 When optional INDENT argument is non-nil, call
21302 `newline-and-indent' instead of `newline'.
21304 When `org-return-follows-link' is non-nil and point is on
21305 a timestamp or a link, call `org-open-at-point'. However, it
21306 will not happen if point is in a table or on a \"dead\"
21307 object (e.g., within a comment). In these case, you need to use
21308 `org-open-at-point' directly."
21309 (interactive)
21310 (let ((context (if org-return-follows-link (org-element-context)
21311 (org-element-at-point))))
21312 (cond
21313 ;; In a table, call `org-table-next-row'.
21314 ((or (and (eq (org-element-type context) 'table)
21315 (>= (point) (org-element-property :contents-begin context))
21316 (< (point) (org-element-property :contents-end context)))
21317 (org-element-lineage context '(table-row table-cell) t))
21318 (org-table-justify-field-maybe)
21319 (call-interactively #'org-table-next-row))
21320 ;; On a link or a timestamp, call `org-open-at-point' if
21321 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21322 ;; locations, e.g., in a comment, as `org-open-at-point'.
21323 ((and org-return-follows-link
21324 (or (org-in-regexp org-ts-regexp-both nil t)
21325 (org-in-regexp org-tsr-regexp-both nil t)
21326 (org-in-regexp org-any-link-re nil t)))
21327 (call-interactively #'org-open-at-point))
21328 ;; Insert newline in heading, but preserve tags.
21329 ((and (not (bolp))
21330 (save-excursion (beginning-of-line)
21331 (looking-at org-complex-heading-regexp)))
21332 ;; At headline. Split line. However, if point is on keyword,
21333 ;; priority cookie or tags, do not break any of them: add
21334 ;; a newline after the headline instead.
21335 (let ((tags-column (and (match-beginning 5)
21336 (save-excursion (goto-char (match-beginning 5))
21337 (current-column))))
21338 (string
21339 (when (and (match-end 4)
21340 (>= (point)
21341 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21342 (<= (point) (match-end 4)))
21343 (delete-and-extract-region (point) (match-end 4)))))
21344 (when (and tags-column string) ; Adjust tag alignment.
21345 (org-align-tags-here
21346 (if org-auto-align-tags org-tags-column tags-column)))
21347 (end-of-line)
21348 (org-show-entry)
21349 (if indent (newline-and-indent) (newline))
21350 (when string (save-excursion (insert (org-trim string))))))
21351 ;; In a list, make sure indenting keeps trailing text within.
21352 ((and indent
21353 (not (eolp))
21354 (org-element-lineage context '(item)))
21355 (let ((trailing-data
21356 (delete-and-extract-region (point) (line-end-position))))
21357 (newline-and-indent)
21358 (save-excursion (insert trailing-data))))
21359 (t (if indent (newline-and-indent) (newline))))))
21361 (defun org-return-indent ()
21362 "Goto next table row or insert a newline and indent.
21363 Calls `org-table-next-row' or `newline-and-indent', depending on
21364 context. See the individual commands for more information."
21365 (interactive)
21366 (org-return t))
21368 (defun org-ctrl-c-star ()
21369 "Compute table, or change heading status of lines.
21370 Calls `org-table-recalculate' or `org-toggle-heading',
21371 depending on context."
21372 (interactive)
21373 (cond
21374 ((org-at-table-p)
21375 (call-interactively 'org-table-recalculate))
21377 ;; Convert all lines in region to list items
21378 (call-interactively 'org-toggle-heading))))
21380 (defun org-ctrl-c-minus ()
21381 "Insert separator line in table or modify bullet status of line.
21382 Also turns a plain line or a region of lines into list items.
21383 Calls `org-table-insert-hline', `org-toggle-item', or
21384 `org-cycle-list-bullet', depending on context."
21385 (interactive)
21386 (cond
21387 ((org-at-table-p)
21388 (call-interactively 'org-table-insert-hline))
21389 ((org-region-active-p)
21390 (call-interactively 'org-toggle-item))
21391 ((org-in-item-p)
21392 (call-interactively 'org-cycle-list-bullet))
21394 (call-interactively 'org-toggle-item))))
21396 (defun org-toggle-item (arg)
21397 "Convert headings or normal lines to items, items to normal lines.
21398 If there is no active region, only the current line is considered.
21400 If the first non blank line in the region is a headline, convert
21401 all headlines to items, shifting text accordingly.
21403 If it is an item, convert all items to normal lines.
21405 If it is normal text, change region into a list of items.
21406 With a prefix argument ARG, change the region in a single item."
21407 (interactive "P")
21408 (let ((shift-text
21409 (function
21410 ;; Shift text in current section to IND, from point to END.
21411 ;; The function leaves point to END line.
21412 (lambda (ind end)
21413 (let ((min-i 1000) (end (copy-marker end)))
21414 ;; First determine the minimum indentation (MIN-I) of
21415 ;; the text.
21416 (save-excursion
21417 (catch 'exit
21418 (while (< (point) end)
21419 (let ((i (org-get-indentation)))
21420 (cond
21421 ;; Skip blank lines and inline tasks.
21422 ((looking-at "^[ \t]*$"))
21423 ((looking-at org-outline-regexp-bol))
21424 ;; We can't find less than 0 indentation.
21425 ((zerop i) (throw 'exit (setq min-i 0)))
21426 ((< i min-i) (setq min-i i))))
21427 (forward-line))))
21428 ;; Then indent each line so that a line indented to
21429 ;; MIN-I becomes indented to IND. Ignore blank lines
21430 ;; and inline tasks in the process.
21431 (let ((delta (- ind min-i)))
21432 (while (< (point) end)
21433 (unless (or (looking-at "^[ \t]*$")
21434 (looking-at org-outline-regexp-bol))
21435 (org-indent-line-to (+ (org-get-indentation) delta)))
21436 (forward-line)))))))
21437 (skip-blanks
21438 (function
21439 ;; Return beginning of first non-blank line, starting from
21440 ;; line at POS.
21441 (lambda (pos)
21442 (save-excursion
21443 (goto-char pos)
21444 (skip-chars-forward " \r\t\n")
21445 (point-at-bol)))))
21446 beg end)
21447 ;; Determine boundaries of changes.
21448 (if (org-region-active-p)
21449 (setq beg (funcall skip-blanks (region-beginning))
21450 end (copy-marker (region-end)))
21451 (setq beg (funcall skip-blanks (point-at-bol))
21452 end (copy-marker (point-at-eol))))
21453 ;; Depending on the starting line, choose an action on the text
21454 ;; between BEG and END.
21455 (org-with-limited-levels
21456 (save-excursion
21457 (goto-char beg)
21458 (cond
21459 ;; Case 1. Start at an item: de-itemize. Note that it only
21460 ;; happens when a region is active: `org-ctrl-c-minus'
21461 ;; would call `org-cycle-list-bullet' otherwise.
21462 ((org-at-item-p)
21463 (while (< (point) end)
21464 (when (org-at-item-p)
21465 (skip-chars-forward " \t")
21466 (delete-region (point) (match-end 0)))
21467 (forward-line)))
21468 ;; Case 2. Start at an heading: convert to items.
21469 ((org-at-heading-p)
21470 (let* ((bul (org-list-bullet-string "-"))
21471 (bul-len (length bul))
21472 (done (org-entry-is-done-p))
21473 (todo (org-entry-is-todo-p))
21474 ;; Indentation of the first heading. It should be
21475 ;; relative to the indentation of its parent, if any.
21476 (start-ind (save-excursion
21477 (cond
21478 ((not org-adapt-indentation) 0)
21479 ((not (outline-previous-heading)) 0)
21480 (t (length (match-string 0))))))
21481 ;; Level of first heading. Further headings will be
21482 ;; compared to it to determine hierarchy in the list.
21483 (ref-level (org-reduced-level (org-outline-level))))
21484 (when (or done todo) (org-todo ""))
21485 (while (< (point) end)
21486 (let* ((level (org-reduced-level (org-outline-level)))
21487 (delta (max 0 (- level ref-level))))
21488 ;; If current headline is less indented than the first
21489 ;; one, set it as reference, in order to preserve
21490 ;; subtrees.
21491 (when (< level ref-level) (setq ref-level level))
21492 (replace-match bul t t)
21493 (org-indent-line-to (+ start-ind (* delta bul-len)))
21494 (when (or done todo)
21495 (let* ((struct (org-list-struct))
21496 (old (copy-tree struct)))
21497 (org-list-set-checkbox (line-beginning-position)
21498 struct
21499 (if done "[X]" "[ ]"))
21500 (org-list-write-struct struct
21501 (org-list-parents-alist struct)
21502 old)))
21503 ;; Ensure all text down to END (or SECTION-END) belongs
21504 ;; to the newly created item.
21505 (let ((section-end (save-excursion
21506 (or (outline-next-heading) (point)))))
21507 (forward-line)
21508 (funcall shift-text
21509 (+ start-ind (* (1+ delta) bul-len))
21510 (min end section-end)))))))
21511 ;; Case 3. Normal line with ARG: make the first line of region
21512 ;; an item, and shift indentation of others lines to
21513 ;; set them as item's body.
21514 (arg (let* ((bul (org-list-bullet-string "-"))
21515 (bul-len (length bul))
21516 (ref-ind (org-get-indentation)))
21517 (skip-chars-forward " \t")
21518 (insert bul)
21519 (forward-line)
21520 (while (< (point) end)
21521 ;; Ensure that lines less indented than first one
21522 ;; still get included in item body.
21523 (funcall shift-text
21524 (+ ref-ind bul-len)
21525 (min end (save-excursion (or (outline-next-heading)
21526 (point)))))
21527 (forward-line))))
21528 ;; Case 4. Normal line without ARG: turn each non-item line
21529 ;; into an item.
21531 (while (< (point) end)
21532 (unless (or (org-at-heading-p) (org-at-item-p))
21533 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21534 (replace-match
21535 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21536 (forward-line))))))))
21538 (defun org-toggle-heading (&optional nstars)
21539 "Convert headings to normal text, or items or text to headings.
21540 If there is no active region, only convert the current line.
21542 With a \\[universal-argument] prefix, convert the whole list at
21543 point into heading.
21545 In a region:
21547 - If the first non blank line is a headline, remove the stars
21548 from all headlines in the region.
21550 - If it is a normal line, turn each and every normal line (i.e.,
21551 not an heading or an item) in the region into headings. If you
21552 want to convert only the first line of this region, use one
21553 universal prefix argument.
21555 - If it is a plain list item, turn all plain list items into headings.
21557 When converting a line into a heading, the number of stars is chosen
21558 such that the lines become children of the current entry. However,
21559 when a numeric prefix argument is given, its value determines the
21560 number of stars to add."
21561 (interactive "P")
21562 (let ((skip-blanks
21563 (function
21564 ;; Return beginning of first non-blank line, starting from
21565 ;; line at POS.
21566 (lambda (pos)
21567 (save-excursion
21568 (goto-char pos)
21569 (while (org-at-comment-p) (forward-line))
21570 (skip-chars-forward " \r\t\n")
21571 (point-at-bol)))))
21572 beg end toggled)
21573 ;; Determine boundaries of changes. If a universal prefix has
21574 ;; been given, put the list in a region. If region ends at a bol,
21575 ;; do not consider the last line to be in the region.
21577 (when (and current-prefix-arg (org-at-item-p))
21578 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21579 (org-mark-element))
21581 (if (org-region-active-p)
21582 (setq beg (funcall skip-blanks (region-beginning))
21583 end (copy-marker (save-excursion
21584 (goto-char (region-end))
21585 (if (bolp) (point) (point-at-eol)))))
21586 (setq beg (funcall skip-blanks (point-at-bol))
21587 end (copy-marker (point-at-eol))))
21588 ;; Ensure inline tasks don't count as headings.
21589 (org-with-limited-levels
21590 (save-excursion
21591 (goto-char beg)
21592 (cond
21593 ;; Case 1. Started at an heading: de-star headings.
21594 ((org-at-heading-p)
21595 (while (< (point) end)
21596 (when (org-at-heading-p t)
21597 (looking-at org-outline-regexp) (replace-match "")
21598 (setq toggled t))
21599 (forward-line)))
21600 ;; Case 2. Started at an item: change items into headlines.
21601 ;; One star will be added by `org-list-to-subtree'.
21602 ((org-at-item-p)
21603 (while (< (point) end)
21604 (when (org-at-item-p)
21605 ;; Pay attention to cases when region ends before list.
21606 (let* ((struct (org-list-struct))
21607 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21608 (save-restriction
21609 (narrow-to-region (point) list-end)
21610 (insert (org-list-to-subtree (org-list-parse-list t)))))
21611 (setq toggled t))
21612 (forward-line)))
21613 ;; Case 3. Started at normal text: make every line an heading,
21614 ;; skipping headlines and items.
21615 (t (let* ((stars
21616 (make-string
21617 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21618 (add-stars
21619 (cond (nstars "") ; stars from prefix only
21620 ((equal stars "") "*") ; before first heading
21621 (org-odd-levels-only "**") ; inside heading, odd
21622 (t "*"))) ; inside heading, oddeven
21623 (rpl (concat stars add-stars " "))
21624 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21625 (while (< (point) (if (equal nstars '(4)) lend end))
21626 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21627 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21628 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21629 (forward-line)))))))
21630 (unless toggled (message "Cannot toggle heading from here"))))
21632 (defun org-meta-return (&optional _arg)
21633 "Insert a new heading or wrap a region in a table.
21634 Calls `org-insert-heading' or `org-table-wrap-region', depending
21635 on context. See the individual commands for more information."
21636 (interactive)
21637 (org-check-before-invisible-edit 'insert)
21638 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21639 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21640 #'org-insert-heading))))
21642 ;;; Menu entries
21644 (defsubst org-in-subtree-not-table-p ()
21645 "Are we in a subtree and not in a table?"
21646 (and (not (org-before-first-heading-p))
21647 (not (org-at-table-p))))
21649 ;; Define the Org-mode menus
21650 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21651 '("Tbl"
21652 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21653 ["Next Field" org-cycle (org-at-table-p)]
21654 ["Previous Field" org-shifttab (org-at-table-p)]
21655 ["Next Row" org-return (org-at-table-p)]
21656 "--"
21657 ["Blank Field" org-table-blank-field (org-at-table-p)]
21658 ["Edit Field" org-table-edit-field (org-at-table-p)]
21659 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21660 "--"
21661 ("Column"
21662 ["Move Column Left" org-metaleft (org-at-table-p)]
21663 ["Move Column Right" org-metaright (org-at-table-p)]
21664 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21665 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21666 ("Row"
21667 ["Move Row Up" org-metaup (org-at-table-p)]
21668 ["Move Row Down" org-metadown (org-at-table-p)]
21669 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21670 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21671 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21672 "--"
21673 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21674 ("Rectangle"
21675 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21676 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21677 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21678 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21679 "--"
21680 ("Calculate"
21681 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21682 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21683 ["Edit Formulas" org-edit-special (org-at-table-p)]
21684 "--"
21685 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21686 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21687 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21688 "--"
21689 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21690 "--"
21691 ["Sum Column/Rectangle" org-table-sum
21692 (or (org-at-table-p) (org-region-active-p))]
21693 ["Which Column?" org-table-current-column (org-at-table-p)])
21694 ["Debug Formulas"
21695 org-table-toggle-formula-debugger
21696 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21697 ["Show Col/Row Numbers"
21698 org-table-toggle-coordinate-overlays
21699 :style toggle
21700 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21701 "--"
21702 ["Create" org-table-create (and (not (org-at-table-p))
21703 org-enable-table-editor)]
21704 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21705 ["Import from File" org-table-import (not (org-at-table-p))]
21706 ["Export to File" org-table-export (org-at-table-p)]
21707 "--"
21708 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21709 "--"
21710 ("Plot"
21711 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21712 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21714 (easy-menu-define org-org-menu org-mode-map "Org menu"
21715 '("Org"
21716 ("Show/Hide"
21717 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21718 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21719 ["Sparse Tree..." org-sparse-tree t]
21720 ["Reveal Context" org-reveal t]
21721 ["Show All" outline-show-all t]
21722 "--"
21723 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21724 "--"
21725 ["New Heading" org-insert-heading t]
21726 ("Navigate Headings"
21727 ["Up" outline-up-heading t]
21728 ["Next" outline-next-visible-heading t]
21729 ["Previous" outline-previous-visible-heading t]
21730 ["Next Same Level" outline-forward-same-level t]
21731 ["Previous Same Level" outline-backward-same-level t]
21732 "--"
21733 ["Jump" org-goto t])
21734 ("Edit Structure"
21735 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21736 "--"
21737 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21738 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21739 "--"
21740 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21741 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21742 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21743 "--"
21744 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21745 "--"
21746 ["Copy visible text" org-copy-visible t]
21747 "--"
21748 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21749 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21750 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21751 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21752 "--"
21753 ["Sort Region/Children" org-sort t]
21754 "--"
21755 ["Convert to odd levels" org-convert-to-odd-levels t]
21756 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21757 ("Editing"
21758 ["Emphasis..." org-emphasize t]
21759 ["Edit Source Example" org-edit-special t]
21760 "--"
21761 ["Footnote new/jump" org-footnote-action t]
21762 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21763 ("Archive"
21764 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21765 "--"
21766 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21767 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21768 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21770 "--"
21771 ("Hyperlinks"
21772 ["Store Link (Global)" org-store-link t]
21773 ["Find existing link to here" org-occur-link-in-agenda-files t]
21774 ["Insert Link" org-insert-link t]
21775 ["Follow Link" org-open-at-point t]
21776 "--"
21777 ["Next link" org-next-link t]
21778 ["Previous link" org-previous-link t]
21779 "--"
21780 ["Descriptive Links"
21781 org-toggle-link-display
21782 :style radio
21783 :selected org-descriptive-links
21785 ["Literal Links"
21786 org-toggle-link-display
21787 :style radio
21788 :selected (not org-descriptive-links)])
21789 "--"
21790 ("TODO Lists"
21791 ["TODO/DONE/-" org-todo t]
21792 ("Select keyword"
21793 ["Next keyword" org-shiftright (org-at-heading-p)]
21794 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21795 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21796 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21797 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21798 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21799 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21800 "--"
21801 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21802 :selected org-enforce-todo-dependencies :style toggle :active t]
21803 "Settings for tree at point"
21804 ["Do Children sequentially" org-toggle-ordered-property :style radio
21805 :selected (org-entry-get nil "ORDERED")
21806 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21807 ["Do Children parallel" org-toggle-ordered-property :style radio
21808 :selected (not (org-entry-get nil "ORDERED"))
21809 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21810 "--"
21811 ["Set Priority" org-priority t]
21812 ["Priority Up" org-shiftup t]
21813 ["Priority Down" org-shiftdown t]
21814 "--"
21815 ["Get news from all feeds" org-feed-update-all t]
21816 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21817 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21818 ("TAGS and Properties"
21819 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21820 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21821 "--"
21822 ["Set property" org-set-property (not (org-before-first-heading-p))]
21823 ["Column view of properties" org-columns t]
21824 ["Insert Column View DBlock" org-insert-columns-dblock t])
21825 ("Dates and Scheduling"
21826 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21827 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21828 ("Change Date"
21829 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21830 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21831 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21832 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21833 ["Compute Time Range" org-evaluate-time-range t]
21834 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21835 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21836 "--"
21837 ["Custom time format" org-toggle-time-stamp-overlays
21838 :style radio :selected org-display-custom-times]
21839 "--"
21840 ["Goto Calendar" org-goto-calendar t]
21841 ["Date from Calendar" org-date-from-calendar t]
21842 "--"
21843 ["Start/Restart Timer" org-timer-start t]
21844 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21845 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21846 ["Insert Timer String" org-timer t]
21847 ["Insert Timer Item" org-timer-item t])
21848 ("Logging work"
21849 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21850 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21851 ["Clock out" org-clock-out t]
21852 ["Clock cancel" org-clock-cancel t]
21853 "--"
21854 ["Mark as default task" org-clock-mark-default-task t]
21855 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21856 ["Goto running clock" org-clock-goto t]
21857 "--"
21858 ["Display times" org-clock-display t]
21859 ["Create clock table" org-clock-report t]
21860 "--"
21861 ["Record DONE time"
21862 (progn (setq org-log-done (not org-log-done))
21863 (message "Switching to %s will %s record a timestamp"
21864 (car org-done-keywords)
21865 (if org-log-done "automatically" "not")))
21866 :style toggle :selected org-log-done])
21867 "--"
21868 ["Agenda Command..." org-agenda t]
21869 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21870 ("File List for Agenda")
21871 ("Special views current file"
21872 ["TODO Tree" org-show-todo-tree t]
21873 ["Check Deadlines" org-check-deadlines t]
21874 ["Timeline" org-timeline t]
21875 ["Tags/Property tree" org-match-sparse-tree t])
21876 "--"
21877 ["Export/Publish..." org-export-dispatch t]
21878 ("LaTeX"
21879 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21880 :selected org-cdlatex-mode]
21881 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21882 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21883 ["Modify math symbol" org-cdlatex-math-modify
21884 (org-inside-LaTeX-fragment-p)]
21885 ["Insert citation" org-reftex-citation t]
21886 "--"
21887 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21888 "--"
21889 ("MobileOrg"
21890 ["Push Files and Views" org-mobile-push t]
21891 ["Get Captured and Flagged" org-mobile-pull t]
21892 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21893 "--"
21894 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21895 "--"
21896 ("Documentation"
21897 ["Show Version" org-version t]
21898 ["Info Documentation" org-info t])
21899 ("Customize"
21900 ["Browse Org Group" org-customize t]
21901 "--"
21902 ["Expand This Menu" org-create-customize-menu
21903 (fboundp 'customize-menu-create)])
21904 ["Send bug report" org-submit-bug-report t]
21905 "--"
21906 ("Refresh/Reload"
21907 ["Refresh setup current buffer" org-mode-restart t]
21908 ["Reload Org (after update)" org-reload t]
21909 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21912 (defun org-info (&optional node)
21913 "Read documentation for Org-mode in the info system.
21914 With optional NODE, go directly to that node."
21915 (interactive)
21916 (info (format "(org)%s" (or node ""))))
21918 ;;;###autoload
21919 (defun org-submit-bug-report ()
21920 "Submit a bug report on Org-mode via mail.
21922 Don't hesitate to report any problems or inaccurate documentation.
21924 If you don't have setup sending mail from (X)Emacs, please copy the
21925 output buffer into your mail program, as it gives us important
21926 information about your Org-mode version and configuration."
21927 (interactive)
21928 (require 'reporter)
21929 (defvar reporter-prompt-for-summary-p)
21930 (org-load-modules-maybe)
21931 (org-require-autoloaded-modules)
21932 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21933 (reporter-submit-bug-report
21934 "emacs-orgmode@gnu.org"
21935 (org-version nil 'full)
21936 (let (list)
21937 (save-window-excursion
21938 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21939 (delete-other-windows)
21940 (erase-buffer)
21941 (insert "You are about to submit a bug report to the Org-mode mailing list.
21943 We would like to add your full Org-mode and Outline configuration to the
21944 bug report. This greatly simplifies the work of the maintainer and
21945 other experts on the mailing list.
21947 HOWEVER, some variables you have customized may contain private
21948 information. The names of customers, colleagues, or friends, might
21949 appear in the form of file names, tags, todo states, or search strings.
21950 If you answer yes to the prompt, you might want to check and remove
21951 such private information before sending the email.")
21952 (add-text-properties (point-min) (point-max) '(face org-warning))
21953 (when (yes-or-no-p "Include your Org-mode configuration ")
21954 (mapatoms
21955 (lambda (v)
21956 (and (boundp v)
21957 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21958 (or (and (symbol-value v)
21959 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21960 (and
21961 (get v 'custom-type) (get v 'standard-value)
21962 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21963 (push v list)))))
21964 (kill-buffer (get-buffer "*Warn about privacy*"))
21965 list))
21966 nil nil
21967 "Remember to cover the basics, that is, what you expected to happen and
21968 what in fact did happen. You don't know how to make a good report? See
21970 http://orgmode.org/manual/Feedback.html#Feedback
21972 Your bug report will be posted to the Org-mode mailing list.
21973 ------------------------------------------------------------------------")
21974 (save-excursion
21975 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21976 (replace-match "\\1Bug: \\3 [\\2]")))))
21979 (defun org-install-agenda-files-menu ()
21980 (let ((bl (buffer-list)))
21981 (save-excursion
21982 (while bl
21983 (set-buffer (pop bl))
21984 (if (derived-mode-p 'org-mode) (setq bl nil)))
21985 (when (derived-mode-p 'org-mode)
21986 (easy-menu-change
21987 '("Org") "File List for Agenda"
21988 (append
21989 (list
21990 ["Edit File List" (org-edit-agenda-file-list) t]
21991 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21992 ["Remove Current File from List" org-remove-file t]
21993 ["Cycle through agenda files" org-cycle-agenda-files t]
21994 ["Occur in all agenda files" org-occur-in-agenda-files t]
21995 "--")
21996 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21998 ;;;; Documentation
22000 (defun org-require-autoloaded-modules ()
22001 (interactive)
22002 (mapc 'require
22003 '(org-agenda org-archive org-attach org-clock org-colview org-id
22004 org-table org-timer)))
22006 ;;;###autoload
22007 (defun org-reload (&optional uncompiled)
22008 "Reload all org lisp files.
22009 With prefix arg UNCOMPILED, load the uncompiled versions."
22010 (interactive "P")
22011 (require 'loadhist)
22012 (let* ((org-dir (org-find-library-dir "org"))
22013 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
22014 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
22015 (remove-re (mapconcat 'identity
22016 (mapcar (lambda (f) (concat "^" f "$"))
22017 (list (if (featurep 'xemacs)
22018 "org-colview"
22019 "org-colview-xemacs")
22020 "org" "org-loaddefs" "org-version"))
22021 "\\|"))
22022 (feats (delete-dups
22023 (mapcar 'file-name-sans-extension
22024 (mapcar 'file-name-nondirectory
22025 (delq nil
22026 (mapcar 'feature-file
22027 features))))))
22028 (lfeat (append
22029 (sort
22030 (setq feats
22031 (delq nil (mapcar
22032 (lambda (f)
22033 (if (and (string-match feature-re f)
22034 (not (string-match remove-re f)))
22035 f nil))
22036 feats)))
22037 'string-lessp)
22038 (list "org-version" "org")))
22039 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22040 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22041 load-uncore load-misses)
22042 (setq load-misses
22043 (delq 't
22044 (mapcar (lambda (f)
22045 (or (org-load-noerror-mustsuffix (concat org-dir f))
22046 (and (string= org-dir contrib-dir)
22047 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22048 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22049 (add-to-list 'load-uncore f 'append)
22052 lfeat)))
22053 (if load-uncore
22054 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22055 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22056 (if load-misses
22057 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22058 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22059 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22061 ;;;###autoload
22062 (defun org-customize ()
22063 "Call the customize function with org as argument."
22064 (interactive)
22065 (org-load-modules-maybe)
22066 (org-require-autoloaded-modules)
22067 (customize-browse 'org))
22069 (defun org-create-customize-menu ()
22070 "Create a full customization menu for Org-mode, insert it into the menu."
22071 (interactive)
22072 (org-load-modules-maybe)
22073 (org-require-autoloaded-modules)
22074 (if (fboundp 'customize-menu-create)
22075 (progn
22076 (easy-menu-change
22077 '("Org") "Customize"
22078 `(["Browse Org group" org-customize t]
22079 "--"
22080 ,(customize-menu-create 'org)
22081 ["Set" Custom-set t]
22082 ["Save" Custom-save t]
22083 ["Reset to Current" Custom-reset-current t]
22084 ["Reset to Saved" Custom-reset-saved t]
22085 ["Reset to Standard Settings" Custom-reset-standard t]))
22086 (message "\"Org\"-menu now contains full customization menu"))
22087 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22089 ;;;; Miscellaneous stuff
22091 ;;; Generally useful functions
22093 (defsubst org-get-at-eol (property n)
22094 "Get text property PROPERTY at the end of line less N characters."
22095 (get-text-property (- (point-at-eol) n) property))
22097 (defun org-find-text-property-in-string (prop s)
22098 "Return the first non-nil value of property PROP in string S."
22099 (or (get-text-property 0 prop s)
22100 (get-text-property (or (next-single-property-change 0 prop s) 0)
22101 prop s)))
22103 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22104 "Display the given MESSAGE as a warning."
22105 (if (fboundp 'display-warning)
22106 (display-warning 'org message
22107 (if (featurep 'xemacs) 'warning :warning))
22108 (let ((buf (get-buffer-create "*Org warnings*")))
22109 (with-current-buffer buf
22110 (goto-char (point-max))
22111 (insert "Warning (Org): " message)
22112 (unless (bolp)
22113 (newline)))
22114 (display-buffer buf)
22115 (sit-for 0))))
22117 (defun org-eval (form)
22118 "Eval FORM and return result."
22119 (condition-case error
22120 (eval form)
22121 (error (format "%%![Error: %s]" error))))
22123 (defun org-in-clocktable-p ()
22124 "Check if the cursor is in a clocktable."
22125 (let ((pos (point)) start)
22126 (save-excursion
22127 (end-of-line 1)
22128 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22129 (setq start (match-beginning 0))
22130 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22131 (>= (match-end 0) pos)
22132 start))))
22134 (defun org-in-verbatim-emphasis ()
22135 (save-match-data
22136 (and (org-in-regexp org-emph-re 2)
22137 (>= (point) (match-beginning 3))
22138 (<= (point) (match-end 4))
22139 (member (match-string 3) '("=" "~")))))
22141 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22142 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22143 (if (and marker (marker-buffer marker)
22144 (buffer-live-p (marker-buffer marker)))
22145 (progn
22146 (org-pop-to-buffer-same-window (marker-buffer marker))
22147 (if (or (> marker (point-max)) (< marker (point-min)))
22148 (widen))
22149 (goto-char marker)
22150 (org-show-context 'org-goto))
22151 (if bookmark
22152 (bookmark-jump bookmark)
22153 (error "Cannot find location"))))
22155 (defun org-quote-csv-field (s)
22156 "Quote field for inclusion in CSV material."
22157 (if (string-match "[\",]" s)
22158 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22161 (defun org-force-self-insert (N)
22162 "Needed to enforce self-insert under remapping."
22163 (interactive "p")
22164 (self-insert-command N))
22166 (defun org-string-width (s)
22167 "Compute width of string, ignoring invisible characters.
22168 This ignores character with invisibility property `org-link', and also
22169 characters with property `org-cwidth', because these will become invisible
22170 upon the next fontification round."
22171 (let (b l)
22172 (when (or (eq t buffer-invisibility-spec)
22173 (assq 'org-link buffer-invisibility-spec))
22174 (while (setq b (text-property-any 0 (length s)
22175 'invisible 'org-link s))
22176 (setq s (concat (substring s 0 b)
22177 (substring s (or (next-single-property-change
22178 b 'invisible s)
22179 (length s)))))))
22180 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22181 (setq s (concat (substring s 0 b)
22182 (substring s (or (next-single-property-change
22183 b 'org-cwidth s)
22184 (length s))))))
22185 (setq l (string-width s) b -1)
22186 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22187 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22190 (defun org-shorten-string (s maxlength)
22191 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22192 If the string is shorter or has length MAXLENGTH, just return the
22193 original string. If it is longer, the functions finds a space in the
22194 string, breaks this string off at that locations and adds three dots
22195 as ellipsis. Including the ellipsis, the string will not be longer
22196 than MAXLENGTH. If finding a good breaking point in the string does
22197 not work, the string is just chopped off in the middle of a word
22198 if necessary."
22199 (if (<= (length s) maxlength)
22201 (let* ((n (max (- maxlength 4) 1))
22202 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22203 (if (string-match re s)
22204 (concat (match-string 1 s) "...")
22205 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22207 (defun org-get-indentation (&optional line)
22208 "Get the indentation of the current line, interpreting tabs.
22209 When LINE is given, assume it represents a line and compute its indentation."
22210 (if line
22211 (if (string-match "^ *" (org-remove-tabs line))
22212 (match-end 0))
22213 (save-excursion
22214 (beginning-of-line 1)
22215 (skip-chars-forward " \t")
22216 (current-column))))
22218 (defun org-get-string-indentation (s)
22219 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22220 (let ((n -1) (i 0) (w tab-width) c)
22221 (catch 'exit
22222 (while (< (setq n (1+ n)) (length s))
22223 (setq c (aref s n))
22224 (cond ((= c ?\ ) (setq i (1+ i)))
22225 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22226 (t (throw 'exit t)))))
22229 (defun org-remove-tabs (s &optional width)
22230 "Replace tabulators in S with spaces.
22231 Assumes that s is a single line, starting in column 0."
22232 (setq width (or width tab-width))
22233 (while (string-match "\t" s)
22234 (setq s (replace-match
22235 (make-string
22236 (- (* width (/ (+ (match-beginning 0) width) width))
22237 (match-beginning 0)) ?\ )
22238 t t s)))
22241 (defun org-fix-indentation (line ind)
22242 "Fix indentation in LINE.
22243 IND is a cons cell with target and minimum indentation.
22244 If the current indentation in LINE is smaller than the minimum,
22245 leave it alone. If it is larger than ind, set it to the target."
22246 (let* ((l (org-remove-tabs line))
22247 (i (org-get-indentation l))
22248 (i1 (car ind)) (i2 (cdr ind)))
22249 (if (>= i i2) (setq l (substring line i2)))
22250 (if (> i1 0)
22251 (concat (make-string i1 ?\ ) l)
22252 l)))
22254 (defun org-remove-indentation (code &optional n)
22255 "Remove maximum common indentation in string CODE and return it.
22256 N may optionally be the number of columns to remove. Return CODE
22257 as-is if removal failed."
22258 (with-temp-buffer
22259 (insert code)
22260 (if (org-do-remove-indentation n) (buffer-string) code)))
22262 (defun org-do-remove-indentation (&optional n)
22263 "Remove the maximum common indentation from the buffer.
22264 When optional argument N is a positive integer, remove exactly
22265 that much characters from indentation, if possible. Return nil
22266 if it fails."
22267 (catch :exit
22268 (goto-char (point-min))
22269 ;; Find maximum common indentation, if not specified.
22270 (let ((n (or n
22271 (let ((min-ind (point-max)))
22272 (save-excursion
22273 (while (re-search-forward "^[ \t]*\\S-" nil t)
22274 (let ((ind (1- (current-column))))
22275 (if (zerop ind) (throw :exit nil)
22276 (setq min-ind (min min-ind ind))))))
22277 min-ind))))
22278 (if (zerop n) (throw :exit nil)
22279 ;; Remove exactly N indentation, but give up if not possible.
22280 (while (not (eobp))
22281 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22282 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22283 ((< ind n) (throw :exit nil))
22284 (t (org-indent-line-to (- ind n))))
22285 (forward-line)))
22286 ;; Signal success.
22287 t))))
22289 (defun org-fill-template (template alist)
22290 "Find each %key of ALIST in TEMPLATE and replace it."
22291 (let ((case-fold-search nil))
22292 (dolist (entry (sort (copy-sequence alist)
22293 (lambda (a b) (< (length (car a)) (length (car b))))))
22294 (setq template
22295 (replace-regexp-in-string
22296 (concat "%" (regexp-quote (car entry)))
22297 (or (cdr entry) "") template t t)))
22298 template))
22300 (defun org-base-buffer (buffer)
22301 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22302 (if (not buffer)
22303 buffer
22304 (or (buffer-base-buffer buffer)
22305 buffer)))
22307 (defun org-wrap (string &optional width lines)
22308 "Wrap string to either a number of lines, or a width in characters.
22309 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22310 that costs. If there is a word longer than WIDTH, the text is actually
22311 wrapped to the length of that word.
22312 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22313 many lines, whatever width that takes.
22314 The return value is a list of lines, without newlines at the end."
22315 (let* ((words (org-split-string string "[ \t\n]+"))
22316 (maxword (apply 'max (mapcar 'org-string-width words)))
22317 w ll)
22318 (cond (width
22319 (org-do-wrap words (max maxword width)))
22320 (lines
22321 (setq w maxword)
22322 (setq ll (org-do-wrap words maxword))
22323 (if (<= (length ll) lines)
22325 (setq ll words)
22326 (while (> (length ll) lines)
22327 (setq w (1+ w))
22328 (setq ll (org-do-wrap words w)))
22329 ll))
22330 (t (error "Cannot wrap this")))))
22332 (defun org-do-wrap (words width)
22333 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22334 (let (lines line)
22335 (while words
22336 (setq line (pop words))
22337 (while (and words (< (+ (length line) (length (car words))) width))
22338 (setq line (concat line " " (pop words))))
22339 (setq lines (push line lines)))
22340 (nreverse lines)))
22342 (defun org-split-string (string &optional separators)
22343 "Splits STRING into substrings at SEPARATORS.
22344 SEPARATORS is a regular expression.
22345 No empty strings are returned if there are matches at the beginning
22346 and end of string."
22347 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22348 (let ((start 0) notfirst list)
22349 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22350 (if (and notfirst
22351 (= start (match-beginning 0))
22352 (< start (length string)))
22353 (1+ start) start))
22354 (< (match-beginning 0) (length string)))
22355 (setq notfirst t)
22356 (or (eq (match-beginning 0) 0)
22357 (and (eq (match-beginning 0) (match-end 0))
22358 (eq (match-beginning 0) start))
22359 (push (substring string start (match-beginning 0)) list))
22360 (setq start (match-end 0)))
22361 (or (eq start (length string))
22362 (push (substring string start) list))
22363 (nreverse list)))
22365 (defun org-quote-vert (s)
22366 "Replace \"|\" with \"\\vert\"."
22367 (while (string-match "|" s)
22368 (setq s (replace-match "\\vert" t t s)))
22371 (defun org-uuidgen-p (s)
22372 "Is S an ID created by UUIDGEN?"
22373 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22375 (defun org-in-src-block-p (&optional inside)
22376 "Whether point is in a code source block.
22377 When INSIDE is non-nil, don't consider we are within a src block
22378 when point is at #+BEGIN_SRC or #+END_SRC."
22379 (let ((case-fold-search t) ov)
22380 (or (and (eq (get-char-property (point) 'src-block) t))
22381 (and (not inside)
22382 (save-match-data
22383 (save-excursion
22384 (beginning-of-line)
22385 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22387 (defun org-context ()
22388 "Return a list of contexts of the current cursor position.
22389 If several contexts apply, all are returned.
22390 Each context entry is a list with a symbol naming the context, and
22391 two positions indicating start and end of the context. Possible
22392 contexts are:
22394 :headline anywhere in a headline
22395 :headline-stars on the leading stars in a headline
22396 :todo-keyword on a TODO keyword (including DONE) in a headline
22397 :tags on the TAGS in a headline
22398 :priority on the priority cookie in a headline
22399 :item on the first line of a plain list item
22400 :item-bullet on the bullet/number of a plain list item
22401 :checkbox on the checkbox in a plain list item
22402 :table in an org-mode table
22403 :table-special on a special filed in a table
22404 :table-table in a table.el table
22405 :clocktable in a clocktable
22406 :src-block in a source block
22407 :link on a hyperlink
22408 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22409 :target on a <<target>>
22410 :radio-target on a <<<radio-target>>>
22411 :latex-fragment on a LaTeX fragment
22412 :latex-preview on a LaTeX fragment with overlaid preview image
22414 This function expects the position to be visible because it uses font-lock
22415 faces as a help to recognize the following contexts: :table-special, :link,
22416 and :keyword."
22417 (let* ((f (get-text-property (point) 'face))
22418 (faces (if (listp f) f (list f)))
22419 (case-fold-search t)
22420 (p (point)) clist o)
22421 ;; First the large context
22422 (cond
22423 ((org-at-heading-p t)
22424 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22425 (when (progn
22426 (beginning-of-line 1)
22427 (looking-at org-todo-line-tags-regexp))
22428 (push (org-point-in-group p 1 :headline-stars) clist)
22429 (push (org-point-in-group p 2 :todo-keyword) clist)
22430 (push (org-point-in-group p 4 :tags) clist))
22431 (goto-char p)
22432 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22433 (if (looking-at "\\[#[A-Z0-9]\\]")
22434 (push (org-point-in-group p 0 :priority) clist)))
22436 ((org-at-item-p)
22437 (push (org-point-in-group p 2 :item-bullet) clist)
22438 (push (list :item (point-at-bol)
22439 (save-excursion (org-end-of-item) (point)))
22440 clist)
22441 (and (org-at-item-checkbox-p)
22442 (push (org-point-in-group p 0 :checkbox) clist)))
22444 ((org-at-table-p)
22445 (push (list :table (org-table-begin) (org-table-end)) clist)
22446 (if (memq 'org-formula faces)
22447 (push (list :table-special
22448 (previous-single-property-change p 'face)
22449 (next-single-property-change p 'face)) clist)))
22450 ((org-at-table-p 'any)
22451 (push (list :table-table) clist)))
22452 (goto-char p)
22454 (let ((case-fold-search t))
22455 ;; New the "medium" contexts: clocktables, source blocks
22456 (cond ((org-in-clocktable-p)
22457 (push (list :clocktable
22458 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22459 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22460 (match-beginning 1))
22461 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22462 (match-end 0))) clist))
22463 ((org-in-src-block-p)
22464 (push (list :src-block
22465 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22466 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22467 (match-beginning 1))
22468 (and (search-forward "#+END_SRC" nil t)
22469 (match-beginning 0))) clist))))
22470 (goto-char p)
22472 ;; Now the small context
22473 (cond
22474 ((org-at-timestamp-p)
22475 (push (org-point-in-group p 0 :timestamp) clist))
22476 ((memq 'org-link faces)
22477 (push (list :link
22478 (previous-single-property-change p 'face)
22479 (next-single-property-change p 'face)) clist))
22480 ((memq 'org-special-keyword faces)
22481 (push (list :keyword
22482 (previous-single-property-change p 'face)
22483 (next-single-property-change p 'face)) clist))
22484 ((org-at-target-p)
22485 (push (org-point-in-group p 0 :target) clist)
22486 (goto-char (1- (match-beginning 0)))
22487 (if (looking-at org-radio-target-regexp)
22488 (push (org-point-in-group p 0 :radio-target) clist))
22489 (goto-char p))
22490 ((setq o (car (delq nil
22491 (mapcar
22492 (lambda (x)
22493 (if (memq x org-latex-fragment-image-overlays) x))
22494 (overlays-at (point))))))
22495 (push (list :latex-fragment
22496 (overlay-start o) (overlay-end o)) clist)
22497 (push (list :latex-preview
22498 (overlay-start o) (overlay-end o)) clist))
22499 ((org-inside-LaTeX-fragment-p)
22500 ;; FIXME: positions wrong.
22501 (push (list :latex-fragment (point) (point)) clist)))
22503 (setq clist (nreverse (delq nil clist)))
22504 clist))
22506 (defun org-in-regexp (regexp &optional nlines visually)
22507 "Check if point is inside a match of REGEXP.
22509 Normally only the current line is checked, but you can include
22510 NLINES extra lines around point into the search. If VISUALLY is
22511 set, require that the cursor is not after the match but really
22512 on, so that the block visually is on the match.
22514 Return nil or a cons cell (BEG . END) where BEG and END are,
22515 respectively, the positions at the beginning and the end of the
22516 match."
22517 (catch :exit
22518 (let ((pos (point))
22519 (eol (line-end-position (if nlines (1+ nlines) 1))))
22520 (save-excursion
22521 (beginning-of-line (- 1 (or nlines 0)))
22522 (while (and (re-search-forward regexp eol t)
22523 (<= (match-beginning 0) pos))
22524 (let ((end (match-end 0)))
22525 (when (or (> end pos) (and (= end pos) (not visually)))
22526 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22527 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22528 "Org mode 8.3")
22530 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22531 "Non-nil when point is between matches of START-RE and END-RE.
22533 Also return a non-nil value when point is on one of the matches.
22535 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22536 buffer positions. Default values are the positions of headlines
22537 surrounding the point.
22539 The functions returns a cons cell whose car (resp. cdr) is the
22540 position before START-RE (resp. after END-RE)."
22541 (save-match-data
22542 (let ((pos (point))
22543 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22544 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22545 beg end)
22546 (save-excursion
22547 ;; Point is on a block when on START-RE or if START-RE can be
22548 ;; found before it...
22549 (and (or (org-in-regexp start-re)
22550 (re-search-backward start-re limit-up t))
22551 (setq beg (match-beginning 0))
22552 ;; ... and END-RE after it...
22553 (goto-char (match-end 0))
22554 (re-search-forward end-re limit-down t)
22555 (> (setq end (match-end 0)) pos)
22556 ;; ... without another START-RE in-between.
22557 (goto-char (match-beginning 0))
22558 (not (re-search-backward start-re (1+ beg) t))
22559 ;; Return value.
22560 (cons beg end))))))
22562 (defun org-in-block-p (names)
22563 "Non-nil when point belongs to a block whose name belongs to NAMES.
22565 NAMES is a list of strings containing names of blocks.
22567 Return first block name matched, or nil. Beware that in case of
22568 nested blocks, the returned name may not belong to the closest
22569 block from point."
22570 (save-match-data
22571 (catch 'exit
22572 (let ((case-fold-search t)
22573 (lim-up (save-excursion (outline-previous-heading)))
22574 (lim-down (save-excursion (outline-next-heading))))
22575 (mapc (lambda (name)
22576 (let ((n (regexp-quote name)))
22577 (when (org-between-regexps-p
22578 (concat "^[ \t]*#\\+begin_" n)
22579 (concat "^[ \t]*#\\+end_" n)
22580 lim-up lim-down)
22581 (throw 'exit n))))
22582 names))
22583 nil)))
22585 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22586 "Call `multi-occur' with buffers for all agenda files."
22587 (interactive "sOrg-files matching: ")
22588 (let* ((files (org-agenda-files))
22589 (tnames (mapcar #'file-truename files))
22590 (extra org-agenda-text-search-extra-files))
22591 (when (eq (car extra) 'agenda-archives)
22592 (setq extra (cdr extra))
22593 (setq files (org-add-archive-files files)))
22594 (dolist (f extra)
22595 (unless (member (file-truename f) tnames)
22596 (unless (member f files) (setq files (append files (list f))))
22597 (setq tnames (append tnames (list (file-truename f))))))
22598 (multi-occur
22599 (mapcar (lambda (x)
22600 (with-current-buffer
22601 ;; FIXME: Why not just (find-file-noselect x)?
22602 ;; Is it to avoid the "revert buffer" prompt?
22603 (or (get-file-buffer x) (find-file-noselect x))
22604 (widen)
22605 (current-buffer)))
22606 files)
22607 regexp)))
22609 (if (boundp 'occur-mode-find-occurrence-hook)
22610 ;; Emacs 23
22611 (add-hook 'occur-mode-find-occurrence-hook
22612 (lambda ()
22613 (when (derived-mode-p 'org-mode)
22614 (org-reveal))))
22615 ;; Emacs 22
22616 (defadvice occur-mode-goto-occurrence
22617 (after org-occur-reveal activate)
22618 (and (derived-mode-p 'org-mode) (org-reveal)))
22619 (defadvice occur-mode-goto-occurrence-other-window
22620 (after org-occur-reveal activate)
22621 (and (derived-mode-p 'org-mode) (org-reveal)))
22622 (defadvice occur-mode-display-occurrence
22623 (after org-occur-reveal activate)
22624 (when (derived-mode-p 'org-mode)
22625 (let ((pos (occur-mode-find-occurrence)))
22626 (with-current-buffer (marker-buffer pos)
22627 (save-excursion
22628 (goto-char pos)
22629 (org-reveal)))))))
22631 (defun org-occur-link-in-agenda-files ()
22632 "Create a link and search for it in the agendas.
22633 The link is not stored in `org-stored-links', it is just created
22634 for the search purpose."
22635 (interactive)
22636 (let ((link (condition-case nil
22637 (org-store-link nil)
22638 (error "Unable to create a link to here"))))
22639 (org-occur-in-agenda-files (regexp-quote link))))
22641 (defun org-reverse-string (string)
22642 "Return the reverse of STRING."
22643 (apply 'string (reverse (string-to-list string))))
22645 ;; defsubst org-uniquify must be defined before first use
22647 (defun org-uniquify-alist (alist)
22648 "Merge elements of ALIST with the same key.
22650 For example, in this alist:
22652 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22653 => \\='((a 1 3) (b 2))
22655 merge (a 1) and (a 3) into (a 1 3).
22657 The function returns the new ALIST."
22658 (let (rtn)
22659 (mapc
22660 (lambda (e)
22661 (let (n)
22662 (if (not (assoc (car e) rtn))
22663 (push e rtn)
22664 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22665 (setq rtn (assq-delete-all (car e) rtn))
22666 (push n rtn))))
22667 alist)
22668 rtn))
22670 (defun org-delete-all (elts list)
22671 "Remove all elements in ELTS from LIST."
22672 (while elts
22673 (setq list (delete (pop elts) list)))
22674 list)
22676 (defun org-count (cl-item cl-seq)
22677 "Count the number of occurrences of ITEM in SEQ.
22678 Taken from `count' in cl-seq.el with all keyword arguments removed."
22679 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22680 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22681 (while (< cl-start cl-end)
22682 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22683 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22684 (setq cl-start (1+ cl-start)))
22685 cl-count))
22687 (defun org-remove-if (predicate seq)
22688 "Remove everything from SEQ that fulfills PREDICATE."
22689 (let (res e)
22690 (while seq
22691 (setq e (pop seq))
22692 (if (not (funcall predicate e)) (push e res)))
22693 (nreverse res)))
22695 (defun org-remove-if-not (predicate seq)
22696 "Remove everything from SEQ that does not fulfill PREDICATE."
22697 (let (res e)
22698 (while seq
22699 (setq e (pop seq))
22700 (if (funcall predicate e) (push e res)))
22701 (nreverse res)))
22703 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22704 "Reduce two-argument FUNCTION across SEQ.
22705 Taken from `reduce' in cl-seq.el with all keyword arguments but
22706 \":initial-value\" removed."
22707 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22708 (cadr (memq :initial-value cl-keys)))
22709 (cl-seq (pop cl-seq))
22710 (t (funcall cl-func)))))
22711 (while cl-seq
22712 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22713 cl-accum))
22715 (defun org-every (pred seq)
22716 "Return true if PREDICATE is true of every element of SEQ.
22717 Adapted from `every' in cl.el."
22718 (catch 'org-every
22719 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22722 (defun org-some (pred seq)
22723 "Return true if PREDICATE is true of any element of SEQ.
22724 Adapted from `some' in cl.el."
22725 (catch 'org-some
22726 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22727 nil))
22729 (defun org-back-over-empty-lines ()
22730 "Move backwards over whitespace, to the beginning of the first empty line.
22731 Returns the number of empty lines passed."
22732 (let ((pos (point)))
22733 (if (cdr (assoc 'heading org-blank-before-new-entry))
22734 (skip-chars-backward " \t\n\r")
22735 (unless (eobp)
22736 (forward-line -1)))
22737 (beginning-of-line 2)
22738 (goto-char (min (point) pos))
22739 (count-lines (point) pos)))
22741 (defun org-skip-whitespace ()
22742 (skip-chars-forward " \t\n\r"))
22744 (defun org-point-in-group (point group &optional context)
22745 "Check if POINT is in match-group GROUP.
22746 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22747 match. If the match group does not exist or point is not inside it,
22748 return nil."
22749 (and (match-beginning group)
22750 (>= point (match-beginning group))
22751 (<= point (match-end group))
22752 (if context
22753 (list context (match-beginning group) (match-end group))
22754 t)))
22756 (defun org-switch-to-buffer-other-window (&rest args)
22757 "Switch to buffer in a second window on the current frame.
22758 In particular, do not allow pop-up frames.
22759 Returns the newly created buffer."
22760 (org-no-popups
22761 (apply 'switch-to-buffer-other-window args)))
22763 (defun org-combine-plists (&rest plists)
22764 "Create a single property list from all plists in PLISTS.
22765 The process starts by copying the first list, and then setting properties
22766 from the other lists. Settings in the last list are the most significant
22767 ones and overrule settings in the other lists."
22768 (let ((rtn (copy-sequence (pop plists)))
22769 p v ls)
22770 (while plists
22771 (setq ls (pop plists))
22772 (while ls
22773 (setq p (pop ls) v (pop ls))
22774 (setq rtn (plist-put rtn p v))))
22775 rtn))
22777 (defun org-replace-escapes (string table)
22778 "Replace %-escapes in STRING with values in TABLE.
22779 TABLE is an association list with keys like \"%a\" and string values.
22780 The sequences in STRING may contain normal field width and padding information,
22781 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22782 so values can contain further %-escapes if they are define later in TABLE."
22783 (let ((tbl (copy-alist table))
22784 (case-fold-search nil)
22785 (pchg 0)
22786 e re rpl)
22787 (dolist (e tbl)
22788 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22789 (when (and (cdr e) (string-match re (cdr e)))
22790 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22791 (safe "SREF"))
22792 (add-text-properties 0 3 (list 'sref sref) safe)
22793 (setcdr e (replace-match safe t t (cdr e)))))
22794 (while (string-match re string)
22795 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22796 (cdr e)))
22797 (setq string (replace-match rpl t t string))))
22798 (while (setq pchg (next-property-change pchg string))
22799 (let ((sref (get-text-property pchg 'sref string)))
22800 (when (and sref (string-match "SREF" string pchg))
22801 (setq string (replace-match sref t t string)))))
22802 string))
22804 (defun org-sublist (list start end)
22805 "Return a section of LIST, from START to END.
22806 Counting starts at 1."
22807 (let (rtn (c start))
22808 (setq list (nthcdr (1- start) list))
22809 (while (and list (<= c end))
22810 (push (pop list) rtn)
22811 (setq c (1+ c)))
22812 (nreverse rtn)))
22814 (defun org-find-base-buffer-visiting (file)
22815 "Like `find-buffer-visiting' but always return the base buffer and
22816 not an indirect buffer."
22817 (let ((buf (or (get-file-buffer file)
22818 (find-buffer-visiting file))))
22819 (if buf
22820 (or (buffer-base-buffer buf) buf)
22821 nil)))
22823 (defun org-image-file-name-regexp (&optional extensions)
22824 "Return regexp matching the file names of images.
22825 If EXTENSIONS is given, only match these."
22826 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22827 (image-file-name-regexp)
22828 (let ((image-file-name-extensions
22829 (or extensions
22830 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22831 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22832 (concat "\\."
22833 (regexp-opt (nconc (mapcar 'upcase
22834 image-file-name-extensions)
22835 image-file-name-extensions)
22837 "\\'"))))
22839 (defun org-file-image-p (file &optional extensions)
22840 "Return non-nil if FILE is an image."
22841 (save-match-data
22842 (string-match (org-image-file-name-regexp extensions) file)))
22844 (defun org-get-cursor-date (&optional with-time)
22845 "Return the date at cursor in as a time.
22846 This works in the calendar and in the agenda, anywhere else it just
22847 returns the current time.
22848 If WITH-TIME is non-nil, returns the time of the event at point (in
22849 the agenda) or the current time of the day."
22850 (let (date day defd tp hod mod)
22851 (when with-time
22852 (setq tp (get-text-property (point) 'time))
22853 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22854 (setq hod (string-to-number (match-string 1 tp))
22855 mod (string-to-number (match-string 2 tp))))
22856 (or tp (let ((now (decode-time)))
22857 (setq hod (nth 2 now)
22858 mod (nth 1 now)))))
22859 (cond
22860 ((eq major-mode 'calendar-mode)
22861 (setq date (calendar-cursor-to-date)
22862 defd (encode-time 0 (or mod 0) (or hod 0)
22863 (nth 1 date) (nth 0 date) (nth 2 date))))
22864 ((eq major-mode 'org-agenda-mode)
22865 (setq day (get-text-property (point) 'day))
22866 (if day
22867 (setq date (calendar-gregorian-from-absolute day)
22868 defd (encode-time 0 (or mod 0) (or hod 0)
22869 (nth 1 date) (nth 0 date) (nth 2 date))))))
22870 (or defd (current-time))))
22872 (defun org-mark-subtree (&optional up)
22873 "Mark the current subtree.
22874 This puts point at the start of the current subtree, and mark at
22875 the end. If a numeric prefix UP is given, move up into the
22876 hierarchy of headlines by UP levels before marking the subtree."
22877 (interactive "P")
22878 (org-with-limited-levels
22879 (cond ((org-at-heading-p) (beginning-of-line))
22880 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22881 (t (outline-previous-visible-heading 1))))
22882 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22883 (if (org-called-interactively-p 'any)
22884 (call-interactively 'org-mark-element)
22885 (org-mark-element)))
22888 ;;; Indentation
22890 (defun org--get-expected-indentation (element contentsp)
22891 "Expected indentation column for current line, according to ELEMENT.
22892 ELEMENT is an element containing point. CONTENTSP is non-nil
22893 when indentation is to be computed according to contents of
22894 ELEMENT."
22895 (let ((type (org-element-type element))
22896 (start (org-element-property :begin element))
22897 (post-affiliated (org-element-property :post-affiliated element)))
22898 (org-with-wide-buffer
22899 (cond
22900 (contentsp
22901 (case type
22902 ((diary-sexp footnote-definition) 0)
22903 ((headline inlinetask nil)
22904 (if (not org-adapt-indentation) 0
22905 (let ((level (org-current-level)))
22906 (if level (1+ level) 0))))
22907 ((item plain-list) (org-list-item-body-column post-affiliated))
22909 (goto-char start)
22910 (org-get-indentation))))
22911 ((memq type '(headline inlinetask nil))
22912 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22913 (org--get-expected-indentation element t)
22915 ((memq type '(diary-sexp footnote-definition)) 0)
22916 ;; First paragraph of a footnote definition or an item.
22917 ;; Indent like parent.
22918 ((< (line-beginning-position) start)
22919 (org--get-expected-indentation
22920 (org-element-property :parent element) t))
22921 ;; At first line: indent according to previous sibling, if any,
22922 ;; ignoring footnote definitions and inline tasks, or parent's
22923 ;; contents.
22924 ((= (line-beginning-position) start)
22925 (catch 'exit
22926 (while t
22927 (if (= (point-min) start) (throw 'exit 0)
22928 (goto-char (1- start))
22929 (let* ((previous (org-element-at-point))
22930 (parent previous))
22931 (while (and parent (<= (org-element-property :end parent) start))
22932 (setq previous parent
22933 parent (org-element-property :parent parent)))
22934 (cond
22935 ((not previous) (throw 'exit 0))
22936 ((> (org-element-property :end previous) start)
22937 (throw 'exit (org--get-expected-indentation previous t)))
22938 ((memq (org-element-type previous)
22939 '(footnote-definition inlinetask))
22940 (setq start (org-element-property :begin previous)))
22941 (t (goto-char (org-element-property :begin previous))
22942 (throw 'exit
22943 (if (bolp) (org-get-indentation)
22944 ;; At first paragraph in an item or
22945 ;; a footnote definition.
22946 (org--get-expected-indentation
22947 (org-element-property :parent previous) t))))))))))
22948 ;; Otherwise, move to the first non-blank line above.
22950 (beginning-of-line)
22951 (let ((pos (point)))
22952 (skip-chars-backward " \r\t\n")
22953 (cond
22954 ;; Two blank lines end a footnote definition or a plain
22955 ;; list. When we indent an empty line after them, the
22956 ;; containing list or footnote definition is over, so it
22957 ;; qualifies as a previous sibling. Therefore, we indent
22958 ;; like its first line.
22959 ((and (memq type '(footnote-definition plain-list))
22960 (> (count-lines (point) pos) 2))
22961 (goto-char start)
22962 (org-get-indentation))
22963 ;; Line above is the first one of a paragraph at the
22964 ;; beginning of an item or a footnote definition. Indent
22965 ;; like parent.
22966 ((< (line-beginning-position) start)
22967 (org--get-expected-indentation
22968 (org-element-property :parent element) t))
22969 ;; Line above is the beginning of an element, i.e., point
22970 ;; was originally on the blank lines between element's start
22971 ;; and contents.
22972 ((= (line-beginning-position) post-affiliated)
22973 (org--get-expected-indentation element t))
22974 ;; POS is after contents in a greater element. Indent like
22975 ;; the beginning of the element.
22977 ;; As a special case, if point is at the end of a footnote
22978 ;; definition or an item, indent like the very last element
22979 ;; within.
22980 ((and (not (eq type 'paragraph))
22981 (let ((cend (org-element-property :contents-end element)))
22982 (and cend (<= cend pos))))
22983 (if (memq type '(footnote-definition item plain-list))
22984 (let ((last (org-element-at-point)))
22985 (org--get-expected-indentation
22986 last
22987 (memq (org-element-type last)
22988 '(footnote-definition item plain-list))))
22989 (goto-char start)
22990 (org-get-indentation)))
22991 ;; In any other case, indent like the current line.
22992 (t (org-get-indentation)))))))))
22994 (defun org--align-node-property ()
22995 "Align node property at point.
22996 Alignment is done according to `org-property-format', which see."
22997 (when (save-excursion
22998 (beginning-of-line)
22999 (looking-at org-property-re))
23000 (replace-match
23001 (concat (match-string 4)
23002 (org-trim
23003 (format org-property-format (match-string 1) (match-string 3))))
23004 t t)))
23006 (defun org-indent-line ()
23007 "Indent line depending on context.
23009 Indentation is done according to the following rules:
23011 - Footnote definitions, diary sexps, headlines and inline tasks
23012 have to start at column 0.
23014 - On the very first line of an element, consider, in order, the
23015 next rules until one matches:
23017 1. If there's a sibling element before, ignoring footnote
23018 definitions and inline tasks, indent like its first line.
23020 2. If element has a parent, indent like its contents. More
23021 precisely, if parent is an item, indent after the
23022 description part, if any, or the bullet (see
23023 `org-list-description-max-indent'). Else, indent like
23024 parent's first line.
23026 3. Otherwise, indent relatively to current level, if
23027 `org-adapt-indentation' is non-nil, or to left margin.
23029 - On a blank line at the end of an element, indent according to
23030 the type of the element. More precisely
23032 1. If element is a plain list, an item, or a footnote
23033 definition, indent like the very last element within.
23035 2. If element is a paragraph, indent like its last non blank
23036 line.
23038 3. Otherwise, indent like its very first line.
23040 - In the code part of a source block, use language major mode
23041 to indent current line if `org-src-tab-acts-natively' is
23042 non-nil. If it is nil, do nothing.
23044 - Otherwise, indent like the first non-blank line above.
23046 The function doesn't indent an item as it could break the whole
23047 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
23048 \\[org-shiftmetaright].
23050 Also align node properties according to `org-property-format'."
23051 (interactive)
23052 (cond
23053 (orgstruct-is-++
23054 (let ((indent-line-function
23055 (cadadr (assq 'indent-line-function org-fb-vars))))
23056 (indent-according-to-mode)))
23057 ((org-at-heading-p) 'noindent)
23059 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
23060 (type (org-element-type element)))
23061 (cond ((and (memq type '(plain-list item))
23062 (= (line-beginning-position)
23063 (org-element-property :post-affiliated element)))
23064 'noindent)
23065 ((and (eq type 'src-block)
23066 org-src-tab-acts-natively
23067 (> (line-beginning-position)
23068 (org-element-property :post-affiliated element))
23069 (< (line-beginning-position)
23070 (org-with-wide-buffer
23071 (goto-char (org-element-property :end element))
23072 (skip-chars-backward " \r\t\n")
23073 (line-beginning-position))))
23074 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
23076 (let ((column (org--get-expected-indentation element nil)))
23077 ;; Preserve current column.
23078 (if (<= (current-column) (current-indentation))
23079 (org-indent-line-to column)
23080 (save-excursion (org-indent-line-to column))))
23081 ;; Align node property. Also preserve current column.
23082 (when (eq type 'node-property)
23083 (let ((column (current-column)))
23084 (org--align-node-property)
23085 (org-move-to-column column)))))))))
23087 (defun org-indent-region (start end)
23088 "Indent each non-blank line in the region.
23089 Called from a program, START and END specify the region to
23090 indent. The function will not indent contents of example blocks,
23091 verse blocks and export blocks as leading white spaces are
23092 assumed to be significant there."
23093 (interactive "r")
23094 (save-excursion
23095 (goto-char start)
23096 (skip-chars-forward " \r\t\n")
23097 (unless (eobp) (beginning-of-line))
23098 (let ((indent-to
23099 (lambda (ind pos)
23100 ;; Set IND as indentation for all lines between point and
23101 ;; POS or END, whichever comes first. Blank lines are
23102 ;; ignored. Leave point after POS once done.
23103 (let ((limit (copy-marker (min end pos))))
23104 (while (< (point) limit)
23105 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
23106 (forward-line))
23107 (set-marker limit nil))))
23108 (end (copy-marker end)))
23109 (while (< (point) end)
23110 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23111 (let* ((element (org-element-at-point))
23112 (type (org-element-type element))
23113 (element-end (copy-marker (org-element-property :end element)))
23114 (ind (org--get-expected-indentation element nil)))
23115 (cond
23116 ((or (memq type '(paragraph table table-row))
23117 (not (or (org-element-property :contents-begin element)
23118 (memq type
23119 '(example-block export-block src-block)))))
23120 ;; Elements here are indented as a single block. Also
23121 ;; align node properties.
23122 (when (eq type 'node-property)
23123 (org--align-node-property)
23124 (beginning-of-line))
23125 (funcall indent-to ind element-end))
23127 ;; Elements in this category consist of three parts:
23128 ;; before the contents, the contents, and after the
23129 ;; contents. The contents are treated specially,
23130 ;; according to the element type, or not indented at
23131 ;; all. Other parts are indented as a single block.
23132 (let* ((post (copy-marker
23133 (org-element-property :post-affiliated element)))
23134 (cbeg
23135 (copy-marker
23136 (cond
23137 ((not (org-element-property :contents-begin element))
23138 ;; Fake contents for source blocks.
23139 (org-with-wide-buffer
23140 (goto-char post)
23141 (forward-line)
23142 (point)))
23143 ((memq type '(footnote-definition item plain-list))
23144 ;; Contents in these elements could start on
23145 ;; the same line as the beginning of the
23146 ;; element. Make sure we start indenting
23147 ;; from the second line.
23148 (org-with-wide-buffer
23149 (goto-char post)
23150 (end-of-line)
23151 (skip-chars-forward " \r\t\n")
23152 (if (eobp) (point) (line-beginning-position))))
23153 (t (org-element-property :contents-begin element)))))
23154 (cend (copy-marker
23155 (or (org-element-property :contents-end element)
23156 ;; Fake contents for source blocks.
23157 (org-with-wide-buffer
23158 (goto-char element-end)
23159 (skip-chars-backward " \r\t\n")
23160 (line-beginning-position)))
23161 t)))
23162 ;; Do not change items indentation individually as it
23163 ;; might break the list as a whole. On the other
23164 ;; hand, when at a plain list, indent it as a whole.
23165 (cond ((eq type 'plain-list)
23166 (let ((offset (- ind (org-get-indentation))))
23167 (unless (zerop offset)
23168 (indent-rigidly (org-element-property :begin element)
23169 (org-element-property :end element)
23170 offset))
23171 (goto-char cbeg)))
23172 ((eq type 'item) (goto-char cbeg))
23173 (t (funcall indent-to ind cbeg)))
23174 (when (< (point) end)
23175 (case type
23176 ((example-block export-block verse-block))
23177 (src-block
23178 ;; In a source block, indent source code
23179 ;; according to language major mode, but only if
23180 ;; `org-src-tab-acts-natively' is non-nil.
23181 (when (and (< (point) end) org-src-tab-acts-natively)
23182 (ignore-errors
23183 (org-babel-do-in-edit-buffer
23184 (indent-region (point-min) (point-max))))))
23185 (t (org-indent-region (point) (min cend end))))
23186 (goto-char (min cend end))
23187 (when (< (point) end) (funcall indent-to ind element-end)))
23188 (set-marker post nil)
23189 (set-marker cbeg nil)
23190 (set-marker cend nil))))
23191 (set-marker element-end nil))))
23192 (set-marker end nil))))
23194 (defun org-indent-drawer ()
23195 "Indent the drawer at point."
23196 (interactive)
23197 (unless (save-excursion
23198 (beginning-of-line)
23199 (org-looking-at-p org-drawer-regexp))
23200 (user-error "Not at a drawer"))
23201 (let ((element (org-element-at-point)))
23202 (unless (memq (org-element-type element) '(drawer property-drawer))
23203 (user-error "Not at a drawer"))
23204 (org-with-wide-buffer
23205 (org-indent-region (org-element-property :begin element)
23206 (org-element-property :end element))))
23207 (message "Drawer at point indented"))
23209 (defun org-indent-block ()
23210 "Indent the block at point."
23211 (interactive)
23212 (unless (save-excursion
23213 (beginning-of-line)
23214 (let ((case-fold-search t))
23215 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23216 (user-error "Not at a block"))
23217 (let ((element (org-element-at-point)))
23218 (unless (memq (org-element-type element)
23219 '(comment-block center-block dynamic-block example-block
23220 export-block quote-block special-block
23221 src-block verse-block))
23222 (user-error "Not at a block"))
23223 (org-with-wide-buffer
23224 (org-indent-region (org-element-property :begin element)
23225 (org-element-property :end element))))
23226 (message "Block at point indented"))
23229 ;;; Filling
23231 ;; We use our own fill-paragraph and auto-fill functions.
23233 ;; `org-fill-paragraph' relies on adaptive filling and context
23234 ;; checking. Appropriate `fill-prefix' is computed with
23235 ;; `org-adaptive-fill-function'.
23237 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23238 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23239 ;; `org-adaptive-fill-function' value. Internally,
23240 ;; `org-comment-line-break-function' breaks the line.
23242 ;; `org-setup-filling' installs filling and auto-filling related
23243 ;; variables during `org-mode' initialization.
23245 (defvar org-element-paragraph-separate) ; org-element.el
23246 (defun org-setup-filling ()
23247 (require 'org-element)
23248 ;; Prevent auto-fill from inserting unwanted new items.
23249 (when (boundp 'fill-nobreak-predicate)
23250 (setq-local
23251 fill-nobreak-predicate
23252 (org-uniquify
23253 (append fill-nobreak-predicate
23254 '(org-fill-line-break-nobreak-p
23255 org-fill-paragraph-with-timestamp-nobreak-p)))))
23256 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23257 (setq-local paragraph-start paragraph-ending)
23258 (setq-local paragraph-separate paragraph-ending))
23259 (setq-local fill-paragraph-function 'org-fill-paragraph)
23260 (setq-local auto-fill-inhibit-regexp nil)
23261 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23262 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23263 (setq-local comment-line-break-function 'org-comment-line-break-function))
23265 (defun org-fill-line-break-nobreak-p ()
23266 "Non-nil when a new line at point would create an Org line break."
23267 (save-excursion
23268 (skip-chars-backward "[ \t]")
23269 (skip-chars-backward "\\\\")
23270 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23272 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23273 "Non-nil when a new line at point would split a timestamp."
23274 (and (org-at-timestamp-p t)
23275 (not (looking-at org-ts-regexp-both))))
23277 (declare-function message-in-body-p "message" ())
23278 (defvar orgtbl-line-start-regexp) ; From org-table.el
23279 (defun org-adaptive-fill-function ()
23280 "Compute a fill prefix for the current line.
23281 Return fill prefix, as a string, or nil if current line isn't
23282 meant to be filled. For convenience, if `adaptive-fill-regexp'
23283 matches in paragraphs or comments, use it."
23284 (catch 'exit
23285 (when (derived-mode-p 'message-mode)
23286 (save-excursion
23287 (beginning-of-line)
23288 (cond ((not (message-in-body-p)) (throw 'exit nil))
23289 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23290 ((looking-at message-cite-prefix-regexp)
23291 (throw 'exit (match-string-no-properties 0)))
23292 ((looking-at org-outline-regexp)
23293 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23294 (org-with-wide-buffer
23295 (unless (org-at-heading-p)
23296 (let* ((p (line-beginning-position))
23297 (element (save-excursion
23298 (beginning-of-line)
23299 (org-element-at-point)))
23300 (type (org-element-type element))
23301 (post-affiliated (org-element-property :post-affiliated element)))
23302 (unless (< p post-affiliated)
23303 (case type
23304 (comment
23305 (save-excursion
23306 (beginning-of-line)
23307 (looking-at "[ \t]*")
23308 (concat (match-string 0) "# ")))
23309 (footnote-definition "")
23310 ((item plain-list)
23311 (make-string (org-list-item-body-column post-affiliated) ?\s))
23312 (paragraph
23313 ;; Fill prefix is usually the same as the current line,
23314 ;; unless the paragraph is at the beginning of an item.
23315 (let ((parent (org-element-property :parent element)))
23316 (save-excursion
23317 (beginning-of-line)
23318 (cond ((eq (org-element-type parent) 'item)
23319 (make-string (org-list-item-body-column
23320 (org-element-property :begin parent))
23321 ?\s))
23322 ((and adaptive-fill-regexp
23323 ;; Locally disable
23324 ;; `adaptive-fill-function' to let
23325 ;; `fill-context-prefix' handle
23326 ;; `adaptive-fill-regexp' variable.
23327 (let (adaptive-fill-function)
23328 (fill-context-prefix
23329 post-affiliated
23330 (org-element-property :end element)))))
23331 ((looking-at "[ \t]+") (match-string 0))
23332 (t "")))))
23333 (comment-block
23334 ;; Only fill contents if P is within block boundaries.
23335 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23336 (forward-line)
23337 (point)))
23338 (cend (save-excursion
23339 (goto-char (org-element-property :end element))
23340 (skip-chars-backward " \r\t\n")
23341 (line-beginning-position))))
23342 (when (and (>= p cbeg) (< p cend))
23343 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23344 (match-string 0)
23345 "")))))))))))
23347 (declare-function message-goto-body "message" ())
23348 (defvar message-cite-prefix-regexp) ; From message.el
23349 (defun org-fill-paragraph (&optional justify)
23350 "Fill element at point, when applicable.
23352 This function only applies to comment blocks, comments, example
23353 blocks and paragraphs. Also, as a special case, re-align table
23354 when point is at one.
23356 If JUSTIFY is non-nil (interactively, with prefix argument),
23357 justify as well. If `sentence-end-double-space' is non-nil, then
23358 period followed by one space does not end a sentence, so don't
23359 break a line there. The variable `fill-column' controls the
23360 width for filling.
23362 For convenience, when point is at a plain list, an item or
23363 a footnote definition, try to fill the first paragraph within."
23364 (interactive)
23365 (if (and (derived-mode-p 'message-mode)
23366 (or (not (message-in-body-p))
23367 (save-excursion (move-beginning-of-line 1)
23368 (looking-at message-cite-prefix-regexp))))
23369 ;; First ensure filling is correct in message-mode.
23370 (let ((fill-paragraph-function
23371 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
23372 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
23373 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
23374 (paragraph-separate
23375 (cadadr (assoc 'paragraph-separate org-fb-vars))))
23376 (fill-paragraph nil))
23377 (with-syntax-table org-mode-transpose-word-syntax-table
23378 ;; Move to end of line in order to get the first paragraph
23379 ;; within a plain list or a footnote definition.
23380 (let ((element (save-excursion
23381 (end-of-line)
23382 (or (ignore-errors (org-element-at-point))
23383 (user-error "An element cannot be parsed line %d"
23384 (line-number-at-pos (point)))))))
23385 ;; First check if point is in a blank line at the beginning of
23386 ;; the buffer. In that case, ignore filling.
23387 (case (org-element-type element)
23388 ;; Use major mode filling function is src blocks.
23389 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23390 ;; Align Org tables, leave table.el tables as-is.
23391 (table-row (org-table-align) t)
23392 (table
23393 (when (eq (org-element-property :type element) 'org)
23394 (save-excursion
23395 (goto-char (org-element-property :post-affiliated element))
23396 (org-table-align)))
23398 (paragraph
23399 ;; Paragraphs may contain `line-break' type objects.
23400 (let ((beg (max (point-min)
23401 (org-element-property :contents-begin element)))
23402 (end (min (point-max)
23403 (org-element-property :contents-end element))))
23404 ;; Do nothing if point is at an affiliated keyword.
23405 (if (< (line-end-position) beg) t
23406 (when (derived-mode-p 'message-mode)
23407 ;; In `message-mode', do not fill following citation
23408 ;; in current paragraph nor text before message body.
23409 (let ((body-start (save-excursion (message-goto-body))))
23410 (when body-start (setq beg (max body-start beg))))
23411 (when (save-excursion
23412 (re-search-forward
23413 (concat "^" message-cite-prefix-regexp) end t))
23414 (setq end (match-beginning 0))))
23415 ;; Fill paragraph, taking line breaks into account.
23416 (save-excursion
23417 (goto-char beg)
23418 (let ((cuts (list beg)))
23419 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23420 (when (eq 'line-break
23421 (org-element-type
23422 (save-excursion (backward-char)
23423 (org-element-context))))
23424 (push (point) cuts)))
23425 (dolist (c (delq end cuts))
23426 (fill-region-as-paragraph c end justify)
23427 (setq end c))))
23428 t)))
23429 ;; Contents of `comment-block' type elements should be
23430 ;; filled as plain text, but only if point is within block
23431 ;; markers.
23432 (comment-block
23433 (let* ((case-fold-search t)
23434 (beg (save-excursion
23435 (goto-char (org-element-property :begin element))
23436 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23437 (forward-line)
23438 (point)))
23439 (end (save-excursion
23440 (goto-char (org-element-property :end element))
23441 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23442 (line-beginning-position))))
23443 (if (or (< (point) beg) (> (point) end)) t
23444 (fill-region-as-paragraph
23445 (save-excursion (end-of-line)
23446 (re-search-backward "^[ \t]*$" beg 'move)
23447 (line-beginning-position))
23448 (save-excursion (beginning-of-line)
23449 (re-search-forward "^[ \t]*$" end 'move)
23450 (line-beginning-position))
23451 justify))))
23452 ;; Fill comments.
23453 (comment
23454 (let ((begin (org-element-property :post-affiliated element))
23455 (end (org-element-property :end element)))
23456 (when (and (>= (point) begin) (<= (point) end))
23457 (let ((begin (save-excursion
23458 (end-of-line)
23459 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23460 (progn (forward-line) (point))
23461 begin)))
23462 (end (save-excursion
23463 (end-of-line)
23464 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23465 (1- (line-beginning-position))
23466 (skip-chars-backward " \r\t\n")
23467 (line-end-position)))))
23468 ;; Do not fill comments when at a blank line.
23469 (when (> end begin)
23470 (let ((fill-prefix
23471 (save-excursion
23472 (beginning-of-line)
23473 (looking-at "[ \t]*#")
23474 (let ((comment-prefix (match-string 0)))
23475 (goto-char (match-end 0))
23476 (if (looking-at adaptive-fill-regexp)
23477 (concat comment-prefix (match-string 0))
23478 (concat comment-prefix " "))))))
23479 (save-excursion
23480 (fill-region-as-paragraph begin end justify))))))
23482 ;; Ignore every other element.
23483 (otherwise t))))))
23485 (defun org-auto-fill-function ()
23486 "Auto-fill function."
23487 ;; Check if auto-filling is meaningful.
23488 (let ((fc (current-fill-column)))
23489 (when (and fc (> (current-column) fc))
23490 (let* ((fill-prefix (org-adaptive-fill-function))
23491 ;; Enforce empty fill prefix, if required. Otherwise, it
23492 ;; will be computed again.
23493 (adaptive-fill-mode (not (equal fill-prefix ""))))
23494 (when fill-prefix (do-auto-fill))))))
23496 (defun org-comment-line-break-function (&optional soft)
23497 "Break line at point and indent, continuing comment if within one.
23498 The inserted newline is marked hard if variable
23499 `use-hard-newlines' is true, unless optional argument SOFT is
23500 non-nil."
23501 (if soft (insert-and-inherit ?\n) (newline 1))
23502 (save-excursion (forward-char -1) (delete-horizontal-space))
23503 (delete-horizontal-space)
23504 (indent-to-left-margin)
23505 (insert-before-markers-and-inherit fill-prefix))
23508 ;;; Fixed Width Areas
23510 (defun org-toggle-fixed-width ()
23511 "Toggle fixed-width markup.
23513 Add or remove fixed-width markup on current line, whenever it
23514 makes sense. Return an error otherwise.
23516 If a region is active and if it contains only fixed-width areas
23517 or blank lines, remove all fixed-width markup in it. If the
23518 region contains anything else, convert all non-fixed-width lines
23519 to fixed-width ones.
23521 Blank lines at the end of the region are ignored unless the
23522 region only contains such lines."
23523 (interactive)
23524 (if (not (org-region-active-p))
23525 ;; No region:
23527 ;; Remove fixed width marker only in a fixed-with element.
23529 ;; Add fixed width maker in paragraphs, in blank lines after
23530 ;; elements or at the beginning of a headline or an inlinetask,
23531 ;; and before any one-line elements (e.g., a clock).
23532 (progn
23533 (beginning-of-line)
23534 (let* ((element (org-element-at-point))
23535 (type (org-element-type element)))
23536 (cond
23537 ((and (eq type 'fixed-width)
23538 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23539 (replace-match
23540 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23541 ((and (memq type '(babel-call clock comment diary-sexp headline
23542 horizontal-rule keyword paragraph
23543 planning))
23544 (<= (org-element-property :post-affiliated element) (point)))
23545 (skip-chars-forward " \t")
23546 (insert ": "))
23547 ((and (org-looking-at-p "[ \t]*$")
23548 (or (eq type 'inlinetask)
23549 (save-excursion
23550 (skip-chars-forward " \r\t\n")
23551 (<= (org-element-property :end element) (point)))))
23552 (delete-region (point) (line-end-position))
23553 (org-indent-line)
23554 (insert ": "))
23555 (t (user-error "Cannot insert a fixed-width line here")))))
23556 ;; Region active.
23557 (let* ((begin (save-excursion
23558 (goto-char (region-beginning))
23559 (line-beginning-position)))
23560 (end (copy-marker
23561 (save-excursion
23562 (goto-char (region-end))
23563 (unless (eolp) (beginning-of-line))
23564 (if (save-excursion (re-search-backward "\\S-" begin t))
23565 (progn (skip-chars-backward " \r\t\n") (point))
23566 (point)))))
23567 (all-fixed-width-p
23568 (catch 'not-all-p
23569 (save-excursion
23570 (goto-char begin)
23571 (skip-chars-forward " \r\t\n")
23572 (when (eobp) (throw 'not-all-p nil))
23573 (while (< (point) end)
23574 (let ((element (org-element-at-point)))
23575 (if (eq (org-element-type element) 'fixed-width)
23576 (goto-char (org-element-property :end element))
23577 (throw 'not-all-p nil))))
23578 t))))
23579 (if all-fixed-width-p
23580 (save-excursion
23581 (goto-char begin)
23582 (while (< (point) end)
23583 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23584 (replace-match
23585 "" nil nil nil
23586 (if (= (line-end-position) (match-end 0)) 0 1)))
23587 (forward-line)))
23588 (let ((min-ind (point-max)))
23589 ;; Find minimum indentation across all lines.
23590 (save-excursion
23591 (goto-char begin)
23592 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23593 (setq min-ind 0)
23594 (catch 'zerop
23595 (while (< (point) end)
23596 (unless (org-looking-at-p "[ \t]*$")
23597 (let ((ind (org-get-indentation)))
23598 (setq min-ind (min min-ind ind))
23599 (when (zerop ind) (throw 'zerop t))))
23600 (forward-line)))))
23601 ;; Loop over all lines and add fixed-width markup everywhere
23602 ;; but in fixed-width lines.
23603 (save-excursion
23604 (goto-char begin)
23605 (while (< (point) end)
23606 (cond
23607 ((org-at-heading-p)
23608 (insert ": ")
23609 (forward-line)
23610 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23611 (insert ":")
23612 (forward-line)))
23613 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23614 (let* ((element (org-element-at-point))
23615 (element-end (org-element-property :end element)))
23616 (if (eq (org-element-type element) 'fixed-width)
23617 (progn (goto-char element-end)
23618 (skip-chars-backward " \r\t\n")
23619 (forward-line))
23620 (let ((limit (min end element-end)))
23621 (while (< (point) limit)
23622 (org-move-to-column min-ind t)
23623 (insert ": ")
23624 (forward-line))))))
23626 (org-move-to-column min-ind t)
23627 (insert ": ")
23628 (forward-line)))))))
23629 (set-marker end nil))))
23632 ;;; Comments
23634 ;; Org comments syntax is quite complex. It requires the entire line
23635 ;; to be just a comment. Also, even with the right syntax at the
23636 ;; beginning of line, some some elements (i.e. verse-block or
23637 ;; example-block) don't accept comments. Usual Emacs comment commands
23638 ;; cannot cope with those requirements. Therefore, Org replaces them.
23640 ;; Org still relies on `comment-dwim', but cannot trust
23641 ;; `comment-only-p'. So, `comment-region-function' and
23642 ;; `uncomment-region-function' both point
23643 ;; to`org-comment-or-uncomment-region'. Eventually,
23644 ;; `org-insert-comment' takes care of insertion of comments at the
23645 ;; beginning of line.
23647 ;; `org-setup-comments-handling' install comments related variables
23648 ;; during `org-mode' initialization.
23650 (defun org-setup-comments-handling ()
23651 (interactive)
23652 (setq-local comment-use-syntax nil)
23653 (setq-local comment-start "# ")
23654 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23655 (setq-local comment-insert-comment-function 'org-insert-comment)
23656 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23657 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23659 (defun org-insert-comment ()
23660 "Insert an empty comment above current line.
23661 If the line is empty, insert comment at its beginning. When
23662 point is within a source block, comment according to the related
23663 major mode."
23664 (if (let ((element (org-element-at-point)))
23665 (and (eq (org-element-type element) 'src-block)
23666 (< (save-excursion
23667 (goto-char (org-element-property :post-affiliated element))
23668 (line-end-position))
23669 (point))
23670 (> (save-excursion
23671 (goto-char (org-element-property :end element))
23672 (skip-chars-backward " \r\t\n")
23673 (line-beginning-position))
23674 (point))))
23675 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23676 (beginning-of-line)
23677 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23678 (open-line 1))
23679 (org-indent-line)
23680 (insert "# ")))
23682 (defvar comment-empty-lines) ; From newcomment.el.
23683 (defun org-comment-or-uncomment-region (beg end &rest _)
23684 "Comment or uncomment each non-blank line in the region.
23685 Uncomment each non-blank line between BEG and END if it only
23686 contains commented lines. Otherwise, comment them. If region is
23687 strictly within a source block, use appropriate comment syntax."
23688 (if (let ((element (org-element-at-point)))
23689 (and (eq (org-element-type element) 'src-block)
23690 (< (save-excursion
23691 (goto-char (org-element-property :post-affiliated element))
23692 (line-end-position))
23693 beg)
23694 (>= (save-excursion
23695 (goto-char (org-element-property :end element))
23696 (skip-chars-backward " \r\t\n")
23697 (line-beginning-position))
23698 end)))
23699 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23700 (save-restriction
23701 ;; Restrict region
23702 (narrow-to-region (save-excursion (goto-char beg)
23703 (skip-chars-forward " \r\t\n" end)
23704 (line-beginning-position))
23705 (save-excursion (goto-char end)
23706 (skip-chars-backward " \r\t\n" beg)
23707 (line-end-position)))
23708 (let ((uncommentp
23709 ;; UNCOMMENTP is non-nil when every non blank line between
23710 ;; BEG and END is a comment.
23711 (save-excursion
23712 (goto-char (point-min))
23713 (while (and (not (eobp))
23714 (let ((element (org-element-at-point)))
23715 (and (eq (org-element-type element) 'comment)
23716 (goto-char (min (point-max)
23717 (org-element-property
23718 :end element)))))))
23719 (eobp))))
23720 (if uncommentp
23721 ;; Only blank lines and comments in region: uncomment it.
23722 (save-excursion
23723 (goto-char (point-min))
23724 (while (not (eobp))
23725 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23726 (replace-match "" nil nil nil 1))
23727 (forward-line)))
23728 ;; Comment each line in region.
23729 (let ((min-indent (point-max)))
23730 ;; First find the minimum indentation across all lines.
23731 (save-excursion
23732 (goto-char (point-min))
23733 (while (and (not (eobp)) (not (zerop min-indent)))
23734 (unless (looking-at "[ \t]*$")
23735 (setq min-indent (min min-indent (current-indentation))))
23736 (forward-line)))
23737 ;; Then loop over all lines.
23738 (save-excursion
23739 (goto-char (point-min))
23740 (while (not (eobp))
23741 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23742 ;; Don't get fooled by invisible text (e.g. link path)
23743 ;; when moving to column MIN-INDENT.
23744 (let ((buffer-invisibility-spec nil))
23745 (org-move-to-column min-indent t))
23746 (insert comment-start))
23747 (forward-line)))))))))
23749 (defun org-comment-dwim (arg)
23750 "Call `comment-dwim' within a source edit buffer if needed."
23751 (interactive "*P")
23752 (if (org-in-src-block-p)
23753 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23754 (call-interactively 'comment-dwim)))
23757 ;;; Timestamps API
23759 ;; This section contains tools to operate on timestamp objects, as
23760 ;; returned by, e.g. `org-element-context'.
23762 (defun org-timestamp--to-internal-time (timestamp &optional end)
23763 "Encode TIMESTAMP object into Emacs internal time.
23764 Use end of date range or time range when END is non-nil."
23765 (apply #'encode-time
23766 (cons 0
23767 (mapcar
23768 (lambda (prop) (or (org-element-property prop timestamp) 0))
23769 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23770 '(:minute-start :hour-start :day-start :month-start
23771 :year-start))))))
23773 (defun org-timestamp-has-time-p (timestamp)
23774 "Non-nil when TIMESTAMP has a time specified."
23775 (org-element-property :hour-start timestamp))
23777 (defun org-timestamp-format (timestamp format &optional end utc)
23778 "Format a TIMESTAMP object into a string.
23780 FORMAT is a format specifier to be passed to
23781 `format-time-string'.
23783 When optional argument END is non-nil, use end of date-range or
23784 time-range, if possible.
23786 When optional argument UTC is non-nil, time will be expressed as
23787 Universal Time."
23788 (format-time-string
23789 format (org-timestamp--to-internal-time timestamp end) utc))
23791 (defun org-timestamp-split-range (timestamp &optional end)
23792 "Extract a TIMESTAMP object from a date or time range.
23794 END, when non-nil, means extract the end of the range.
23795 Otherwise, extract its start.
23797 Return a new timestamp object."
23798 (let ((type (org-element-property :type timestamp)))
23799 (if (memq type '(active inactive diary)) timestamp
23800 (let ((split-ts (org-element-copy timestamp)))
23801 ;; Set new type.
23802 (org-element-put-property
23803 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23804 ;; Copy start properties over end properties if END is
23805 ;; non-nil. Otherwise, copy end properties over `start' ones.
23806 (let ((p-alist '((:minute-start . :minute-end)
23807 (:hour-start . :hour-end)
23808 (:day-start . :day-end)
23809 (:month-start . :month-end)
23810 (:year-start . :year-end))))
23811 (dolist (p-cell p-alist)
23812 (org-element-put-property
23813 split-ts
23814 (funcall (if end #'car #'cdr) p-cell)
23815 (org-element-property
23816 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23817 ;; Eventually refresh `:raw-value'.
23818 (org-element-put-property split-ts :raw-value nil)
23819 (org-element-put-property
23820 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23822 (defun org-timestamp-translate (timestamp &optional boundary)
23823 "Translate TIMESTAMP object to custom format.
23825 Format string is defined in `org-time-stamp-custom-formats',
23826 which see.
23828 When optional argument BOUNDARY is non-nil, it is either the
23829 symbol `start' or `end'. In this case, only translate the
23830 starting or ending part of TIMESTAMP if it is a date or time
23831 range. Otherwise, translate both parts.
23833 Return timestamp as-is if `org-display-custom-times' is nil or if
23834 it has a `diary' type."
23835 (let ((type (org-element-property :type timestamp)))
23836 (if (or (not org-display-custom-times) (eq type 'diary))
23837 (org-element-interpret-data timestamp)
23838 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23839 org-time-stamp-custom-formats)))
23840 (if (and (not boundary) (memq type '(active-range inactive-range)))
23841 (concat (org-timestamp-format timestamp fmt)
23842 "--"
23843 (org-timestamp-format timestamp fmt t))
23844 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23848 ;;; Other stuff.
23850 (defvar reftex-docstruct-symbol)
23851 (defvar reftex-cite-format)
23852 (defvar org--rds)
23854 (defun org-reftex-citation ()
23855 "Use reftex-citation to insert a citation into the buffer.
23856 This looks for a line like
23858 #+BIBLIOGRAPHY: foo plain option:-d
23860 and derives from it that foo.bib is the bibliography file relevant
23861 for this document. It then installs the necessary environment for RefTeX
23862 to work in this buffer and calls `reftex-citation' to insert a citation
23863 into the buffer.
23865 Export of such citations to both LaTeX and HTML is handled by the contributed
23866 package ox-bibtex by Taru Karttunen."
23867 (interactive)
23868 (let ((reftex-docstruct-symbol 'org--rds)
23869 (reftex-cite-format "\\cite{%l}")
23870 org--rds bib)
23871 (save-excursion
23872 (save-restriction
23873 (widen)
23874 (let ((case-fold-search t)
23875 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23876 (if (not (save-excursion
23877 (or (re-search-forward re nil t)
23878 (re-search-backward re nil t))))
23879 (user-error "No bibliography defined in file")
23880 (setq bib (concat (match-string 1) ".bib")
23881 org--rds (list (list 'bib bib)))))))
23882 (call-interactively 'reftex-citation)))
23884 ;;;; Functions extending outline functionality
23886 (defun org-beginning-of-line (&optional arg)
23887 "Go to the beginning of the current line. If that is invisible, continue
23888 to a visible line beginning. This makes the function of C-a more intuitive.
23889 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23890 first attempt, and only move to after the tags when the cursor is already
23891 beyond the end of the headline."
23892 (interactive "P")
23893 (let ((pos (point))
23894 (special (if (consp org-special-ctrl-a/e)
23895 (car org-special-ctrl-a/e)
23896 org-special-ctrl-a/e))
23897 deactivate-mark refpos)
23898 (if (org-bound-and-true-p visual-line-mode)
23899 (beginning-of-visual-line 1)
23900 (beginning-of-line 1))
23901 (if (and arg (fboundp 'move-beginning-of-line))
23902 (call-interactively 'move-beginning-of-line)
23903 (if (bobp)
23905 (backward-char 1)
23906 (if (org-truely-invisible-p)
23907 (while (and (not (bobp)) (org-truely-invisible-p))
23908 (backward-char 1)
23909 (beginning-of-line 1))
23910 (forward-char 1))))
23911 (when special
23912 (cond
23913 ((and (looking-at org-complex-heading-regexp)
23914 (eq (char-after (match-end 1)) ?\s))
23915 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23916 (point-at-eol)))
23917 (goto-char
23918 (if (eq special t)
23919 (cond ((> pos refpos) refpos)
23920 ((= pos (point)) refpos)
23921 (t (point)))
23922 (cond ((> pos (point)) (point))
23923 ((not (eq last-command this-command)) (point))
23924 (t refpos)))))
23925 ((org-at-item-p)
23926 ;; Being at an item and not looking at an the item means point
23927 ;; was previously moved to beginning of a visual line, which
23928 ;; doesn't contain the item. Therefore, do nothing special,
23929 ;; just stay here.
23930 (when (looking-at org-list-full-item-re)
23931 ;; Set special position at first white space character after
23932 ;; bullet, and check-box, if any.
23933 (let ((after-bullet
23934 (let ((box (match-end 3)))
23935 (if (not box) (match-end 1)
23936 (let ((after (char-after box)))
23937 (if (and after (= after ? )) (1+ box) box))))))
23938 ;; Special case: Move point to special position when
23939 ;; currently after it or at beginning of line.
23940 (if (eq special t)
23941 (when (or (> pos after-bullet) (= (point) pos))
23942 (goto-char after-bullet))
23943 ;; Reversed case: Move point to special position when
23944 ;; point was already at beginning of line and command is
23945 ;; repeated.
23946 (when (and (= (point) pos) (eq last-command this-command))
23947 (goto-char after-bullet))))))))
23948 (org-no-warnings
23949 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23950 (setq disable-point-adjustment
23951 (or (not (invisible-p (point)))
23952 (not (invisible-p (max (point-min) (1- (point))))))))
23954 (defun org-end-of-line (&optional arg)
23955 "Go to the end of the line.
23956 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23957 tags on the first attempt, and only move to after the tags when
23958 the cursor is already beyond the end of the headline."
23959 (interactive "P")
23960 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23961 org-special-ctrl-a/e))
23962 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23963 'end-of-visual-line)
23964 ((fboundp 'move-end-of-line) 'move-end-of-line)
23965 (t 'end-of-line)))
23966 deactivate-mark)
23967 (if (or (not special) arg) (call-interactively move-fun)
23968 (let* ((element (save-excursion (beginning-of-line)
23969 (org-element-at-point)))
23970 (type (org-element-type element)))
23971 (cond
23972 ((memq type '(headline inlinetask))
23973 (let ((pos (point)))
23974 (beginning-of-line 1)
23975 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23976 (if (eq special t)
23977 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23978 (goto-char (match-beginning 1))
23979 (goto-char (match-end 0)))
23980 (if (or (< pos (match-end 0))
23981 (not (eq this-command last-command)))
23982 (goto-char (match-end 0))
23983 (goto-char (match-beginning 1))))
23984 (call-interactively move-fun))))
23985 ((outline-invisible-p (line-end-position))
23986 ;; If element is hidden, `move-end-of-line' would put point
23987 ;; after it. Use `end-of-line' to stay on current line.
23988 (call-interactively 'end-of-line))
23989 (t (call-interactively move-fun)))))
23990 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23991 (setq disable-point-adjustment
23992 (or (not (invisible-p (point)))
23993 (not (invisible-p (max (point-min) (1- (point))))))))
23995 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23996 (define-key org-mode-map "\C-e" 'org-end-of-line)
23998 (defun org-backward-sentence (&optional _arg)
23999 "Go to beginning of sentence, or beginning of table field.
24000 This will call `backward-sentence' or `org-table-beginning-of-field',
24001 depending on context."
24002 (interactive)
24003 (let* ((element (org-element-at-point))
24004 (contents-begin (org-element-property :contents-begin element))
24005 (table (org-element-lineage element '(table) t)))
24006 (if (and table
24007 (> (point) contents-begin)
24008 (<= (point) (org-element-property :contents-end table)))
24009 (call-interactively #'org-table-beginning-of-field)
24010 (save-restriction
24011 (when (and contents-begin
24012 (< (point-min) contents-begin)
24013 (> (point) contents-begin))
24014 (narrow-to-region contents-begin
24015 (org-element-property :contents-end element)))
24016 (call-interactively #'backward-sentence)))))
24018 (defun org-forward-sentence (&optional _arg)
24019 "Go to end of sentence, or end of table field.
24020 This will call `forward-sentence' or `org-table-end-of-field',
24021 depending on context."
24022 (interactive)
24023 (let* ((element (org-element-at-point))
24024 (contents-end (org-element-property :contents-end element))
24025 (table (org-element-lineage element '(table) t)))
24026 (if (and table
24027 (>= (point) (org-element-property :contents-begin table))
24028 (< (point) contents-end))
24029 (call-interactively #'org-table-end-of-field)
24030 (save-restriction
24031 (when (and contents-end
24032 (> (point-max) contents-end)
24033 ;; Skip blank lines between elements.
24034 (< (org-element-property :end element)
24035 (save-excursion (goto-char contents-end)
24036 (skip-chars-forward " \r\t\n"))))
24037 (narrow-to-region (org-element-property :contents-begin element)
24038 contents-end))
24039 (call-interactively #'forward-sentence)))))
24041 (define-key org-mode-map "\M-a" 'org-backward-sentence)
24042 (define-key org-mode-map "\M-e" 'org-forward-sentence)
24044 (defun org-kill-line (&optional _arg)
24045 "Kill line, to tags or end of line."
24046 (interactive)
24047 (cond
24048 ((or (not org-special-ctrl-k)
24049 (bolp)
24050 (not (org-at-heading-p)))
24051 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
24052 org-ctrl-k-protect-subtree)
24053 (if (or (eq org-ctrl-k-protect-subtree 'error)
24054 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
24055 (user-error "C-k aborted as it would kill a hidden subtree")))
24056 (call-interactively
24057 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
24058 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
24059 (kill-region (point) (match-beginning 1))
24060 (org-set-tags nil t))
24061 (t (kill-region (point) (point-at-eol)))))
24063 (define-key org-mode-map "\C-k" 'org-kill-line)
24065 (defun org-yank (&optional arg)
24066 "Yank. If the kill is a subtree, treat it specially.
24067 This command will look at the current kill and check if is a single
24068 subtree, or a series of subtrees[1]. If it passes the test, and if the
24069 cursor is at the beginning of a line or after the stars of a currently
24070 empty headline, then the yank is handled specially. How exactly depends
24071 on the value of the following variables, both set by default.
24073 `org-yank-folded-subtrees'
24074 When set, the subtree(s) will be folded after insertion, but only
24075 if doing so would now swallow text after the yanked text.
24077 `org-yank-adjusted-subtrees'
24078 When set, the subtree will be promoted or demoted in order to
24079 fit into the local outline tree structure, which means that the
24080 level will be adjusted so that it becomes the smaller one of the
24081 two *visible* surrounding headings.
24083 Any prefix to this command will cause `yank' to be called directly with
24084 no special treatment. In particular, a simple \\[universal-argument] prefix \
24085 will just
24086 plainly yank the text as it is.
24088 \[1] The test checks if the first non-white line is a heading
24089 and if there are no other headings with fewer stars."
24090 (interactive "P")
24091 (org-yank-generic 'yank arg))
24093 (defun org-yank-generic (command arg)
24094 "Perform some yank-like command.
24096 This function implements the behavior described in the `org-yank'
24097 documentation. However, it has been generalized to work for any
24098 interactive command with similar behavior."
24100 ;; pretend to be command COMMAND
24101 (setq this-command command)
24103 (if arg
24104 (call-interactively command)
24106 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24107 (and (org-kill-is-subtree-p)
24108 (or (bolp)
24109 (and (looking-at "[ \t]*$")
24110 (string-match
24111 "\\`\\*+\\'"
24112 (buffer-substring (point-at-bol) (point)))))))
24113 swallowp)
24114 (cond
24115 ((and subtreep org-yank-folded-subtrees)
24116 (let ((beg (point))
24117 end)
24118 (if (and subtreep org-yank-adjusted-subtrees)
24119 (org-paste-subtree nil nil 'for-yank)
24120 (call-interactively command))
24122 (setq end (point))
24123 (goto-char beg)
24124 (when (and (bolp) subtreep
24125 (not (setq swallowp
24126 (org-yank-folding-would-swallow-text beg end))))
24127 (org-with-limited-levels
24128 (or (looking-at org-outline-regexp)
24129 (re-search-forward org-outline-regexp-bol end t))
24130 (while (and (< (point) end) (looking-at org-outline-regexp))
24131 (outline-hide-subtree)
24132 (org-cycle-show-empty-lines 'folded)
24133 (condition-case nil
24134 (outline-forward-same-level 1)
24135 (error (goto-char end))))))
24136 (when swallowp
24137 (message
24138 "Inserted text not folded because that would swallow text"))
24140 (goto-char end)
24141 (skip-chars-forward " \t\n\r")
24142 (beginning-of-line 1)
24143 (push-mark beg 'nomsg)))
24144 ((and subtreep org-yank-adjusted-subtrees)
24145 (let ((beg (point-at-bol)))
24146 (org-paste-subtree nil nil 'for-yank)
24147 (push-mark beg 'nomsg)))
24149 (call-interactively command))))))
24151 (defun org-yank-folding-would-swallow-text (beg end)
24152 "Would hide-subtree at BEG swallow any text after END?"
24153 (let (level)
24154 (org-with-limited-levels
24155 (save-excursion
24156 (goto-char beg)
24157 (when (or (looking-at org-outline-regexp)
24158 (re-search-forward org-outline-regexp-bol end t))
24159 (setq level (org-outline-level)))
24160 (goto-char end)
24161 (skip-chars-forward " \t\r\n\v\f")
24162 (if (or (eobp)
24163 (and (bolp) (looking-at org-outline-regexp)
24164 (<= (org-outline-level) level)))
24165 nil ; Nothing would be swallowed
24166 t))))) ; something would swallow
24168 (define-key org-mode-map "\C-y" 'org-yank)
24170 (defun org-truely-invisible-p ()
24171 "Check if point is at a character currently not visible.
24172 This version does not only check the character property, but also
24173 `visible-mode'."
24174 ;; Early versions of noutline don't have `outline-invisible-p'.
24175 (if (org-bound-and-true-p visible-mode)
24177 (outline-invisible-p)))
24179 (defun org-invisible-p2 ()
24180 "Check if point is at a character currently not visible."
24181 (save-excursion
24182 (if (and (eolp) (not (bobp))) (backward-char 1))
24183 ;; Early versions of noutline don't have `outline-invisible-p'.
24184 (outline-invisible-p)))
24186 (defun org-back-to-heading (&optional invisible-ok)
24187 "Call `outline-back-to-heading', but provide a better error message."
24188 (condition-case nil
24189 (outline-back-to-heading invisible-ok)
24190 (error (error "Before first headline at position %d in buffer %s"
24191 (point) (current-buffer)))))
24193 (defun org-before-first-heading-p ()
24194 "Before first heading?"
24195 (save-excursion
24196 (end-of-line)
24197 (null (re-search-backward org-outline-regexp-bol nil t))))
24199 (defun org-at-heading-p (&optional ignored)
24200 (outline-on-heading-p t))
24201 ;; Compatibility alias with Org versions < 7.8.03
24202 (defalias 'org-on-heading-p 'org-at-heading-p)
24204 (defun org-in-commented-heading-p (&optional no-inheritance)
24205 "Non-nil if point is under a commented heading.
24206 This function also checks ancestors of the current headline,
24207 unless optional argument NO-INHERITANCE is non-nil."
24208 (cond
24209 ((org-before-first-heading-p) nil)
24210 ((let ((headline (nth 4 (org-heading-components))))
24211 (and headline
24212 (let ((case-fold-search nil))
24213 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24214 headline)))))
24215 (no-inheritance nil)
24217 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24219 (defun org-at-comment-p nil
24220 "Is cursor in a commented line?"
24221 (save-excursion
24222 (save-match-data
24223 (beginning-of-line)
24224 (looking-at "^[ \t]*# "))))
24226 (defun org-at-drawer-p nil
24227 "Is cursor at a drawer keyword?"
24228 (save-excursion
24229 (move-beginning-of-line 1)
24230 (looking-at org-drawer-regexp)))
24232 (defun org-at-block-p nil
24233 "Is cursor at a block keyword?"
24234 (save-excursion
24235 (move-beginning-of-line 1)
24236 (looking-at org-block-regexp)))
24238 (defun org-point-at-end-of-empty-headline ()
24239 "If point is at the end of an empty headline, return t, else nil.
24240 If the heading only contains a TODO keyword, it is still still considered
24241 empty."
24242 (and (looking-at "[ \t]*$")
24243 (when org-todo-line-regexp
24244 (save-excursion
24245 (beginning-of-line 1)
24246 (let ((case-fold-search nil))
24247 (looking-at org-todo-line-regexp)
24248 (string= (match-string 3) ""))))))
24250 (defun org-at-heading-or-item-p ()
24251 (or (org-at-heading-p) (org-at-item-p)))
24253 (defun org-at-target-p ()
24254 (or (org-in-regexp org-radio-target-regexp)
24255 (org-in-regexp org-target-regexp)))
24256 ;; Compatibility alias with Org versions < 7.8.03
24257 (defalias 'org-on-target-p 'org-at-target-p)
24259 (defun org-up-heading-all (arg)
24260 "Move to the heading line of which the present line is a subheading.
24261 This function considers both visible and invisible heading lines.
24262 With argument, move up ARG levels."
24263 (if (fboundp 'outline-up-heading-all)
24264 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24265 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24267 (defun org-up-heading-safe ()
24268 "Move to the heading line of which the present line is a subheading.
24269 This version will not throw an error. It will return the level of the
24270 headline found, or nil if no higher level is found.
24272 Also, this function will be a lot faster than `outline-up-heading',
24273 because it relies on stars being the outline starters. This can really
24274 make a significant difference in outlines with very many siblings."
24275 (when (ignore-errors (org-back-to-heading t))
24276 (let ((level-up (1- (funcall outline-level))))
24277 (and (> level-up 0)
24278 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24279 (funcall outline-level)))))
24281 (defun org-first-sibling-p ()
24282 "Is this heading the first child of its parents?"
24283 (interactive)
24284 (let ((re org-outline-regexp-bol)
24285 level l)
24286 (unless (org-at-heading-p t)
24287 (user-error "Not at a heading"))
24288 (setq level (funcall outline-level))
24289 (save-excursion
24290 (if (not (re-search-backward re nil t))
24292 (setq l (funcall outline-level))
24293 (< l level)))))
24295 (defun org-goto-sibling (&optional previous)
24296 "Goto the next sibling, even if it is invisible.
24297 When PREVIOUS is set, go to the previous sibling instead. Returns t
24298 when a sibling was found. When none is found, return nil and don't
24299 move point."
24300 (let ((fun (if previous 're-search-backward 're-search-forward))
24301 (pos (point))
24302 (re org-outline-regexp-bol)
24303 level l)
24304 (when (ignore-errors (org-back-to-heading t))
24305 (setq level (funcall outline-level))
24306 (catch 'exit
24307 (or previous (forward-char 1))
24308 (while (funcall fun re nil t)
24309 (setq l (funcall outline-level))
24310 (when (< l level) (goto-char pos) (throw 'exit nil))
24311 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24312 (goto-char pos)
24313 nil))))
24315 (defun org-show-siblings ()
24316 "Show all siblings of the current headline."
24317 (save-excursion
24318 (while (org-goto-sibling) (org-flag-heading nil)))
24319 (save-excursion
24320 (while (org-goto-sibling 'previous)
24321 (org-flag-heading nil))))
24323 (defun org-goto-first-child ()
24324 "Goto the first child, even if it is invisible.
24325 Return t when a child was found. Otherwise don't move point and
24326 return nil."
24327 (let (level (pos (point)) (re org-outline-regexp-bol))
24328 (when (ignore-errors (org-back-to-heading t))
24329 (setq level (outline-level))
24330 (forward-char 1)
24331 (if (and (re-search-forward re nil t) (> (outline-level) level))
24332 (progn (goto-char (match-beginning 0)) t)
24333 (goto-char pos) nil))))
24335 (defun org-show-hidden-entry ()
24336 "Show an entry where even the heading is hidden."
24337 (save-excursion
24338 (org-show-entry)))
24340 (defun org-flag-heading (flag &optional entry)
24341 "Flag the current heading. FLAG non-nil means make invisible.
24342 When ENTRY is non-nil, show the entire entry."
24343 (save-excursion
24344 (org-back-to-heading t)
24345 ;; Check if we should show the entire entry
24346 (if entry
24347 (progn
24348 (org-show-entry)
24349 (save-excursion
24350 (and (outline-next-heading)
24351 (org-flag-heading nil))))
24352 (outline-flag-region (max (point-min) (1- (point)))
24353 (save-excursion (outline-end-of-heading) (point))
24354 flag))))
24356 (defun org-get-next-sibling ()
24357 "Move to next heading of the same level, and return point.
24358 If there is no such heading, return nil.
24359 This is like outline-next-sibling, but invisible headings are ok."
24360 (let ((level (funcall outline-level)))
24361 (outline-next-heading)
24362 (while (and (not (eobp)) (> (funcall outline-level) level))
24363 (outline-next-heading))
24364 (if (or (eobp) (< (funcall outline-level) level))
24366 (point))))
24368 (defun org-get-last-sibling ()
24369 "Move to previous heading of the same level, and return point.
24370 If there is no such heading, return nil."
24371 (let ((opoint (point))
24372 (level (funcall outline-level)))
24373 (outline-previous-heading)
24374 (when (and (/= (point) opoint) (outline-on-heading-p t))
24375 (while (and (> (funcall outline-level) level)
24376 (not (bobp)))
24377 (outline-previous-heading))
24378 (if (< (funcall outline-level) level)
24380 (point)))))
24382 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24383 "Goto to the end of a subtree."
24384 ;; This contains an exact copy of the original function, but it uses
24385 ;; `org-back-to-heading', to make it work also in invisible
24386 ;; trees. And is uses an invisible-ok argument.
24387 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24388 ;; Furthermore, when used inside Org, finding the end of a large subtree
24389 ;; with many children and grandchildren etc, this can be much faster
24390 ;; than the outline version.
24391 (org-back-to-heading invisible-ok)
24392 (let ((first t)
24393 (level (funcall outline-level)))
24394 (if (and (derived-mode-p 'org-mode) (< level 1000))
24395 ;; A true heading (not a plain list item), in Org-mode
24396 ;; This means we can easily find the end by looking
24397 ;; only for the right number of stars. Using a regexp to do
24398 ;; this is so much faster than using a Lisp loop.
24399 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24400 (forward-char 1)
24401 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24402 ;; something else, do it the slow way
24403 (while (and (not (eobp))
24404 (or first (> (funcall outline-level) level)))
24405 (setq first nil)
24406 (outline-next-heading)))
24407 (unless to-heading
24408 (if (memq (preceding-char) '(?\n ?\^M))
24409 (progn
24410 ;; Go to end of line before heading
24411 (forward-char -1)
24412 (if (memq (preceding-char) '(?\n ?\^M))
24413 ;; leave blank line before heading
24414 (forward-char -1))))))
24415 (point))
24417 (defun org-end-of-meta-data (&optional full)
24418 "Skip planning line and properties drawer in current entry.
24419 When optional argument FULL is non-nil, also skip empty lines,
24420 clocking lines and regular drawers at the beginning of the
24421 entry."
24422 (org-back-to-heading t)
24423 (forward-line)
24424 (when (org-looking-at-p org-planning-line-re) (forward-line))
24425 (when (looking-at org-property-drawer-re)
24426 (goto-char (match-end 0))
24427 (forward-line))
24428 (when (and full (not (org-at-heading-p)))
24429 (catch 'exit
24430 (let ((end (save-excursion (outline-next-heading) (point)))
24431 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24432 (while (not (eobp))
24433 (cond ((org-looking-at-p org-drawer-regexp)
24434 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24435 (forward-line)
24436 (throw 'exit t)))
24437 ((org-looking-at-p re) (forward-line))
24438 (t (throw 'exit t))))))))
24440 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24441 "Move forward to the ARG'th subheading at same level as this one.
24442 Stop at the first and last subheadings of a superior heading.
24443 Normally this only looks at visible headings, but when INVISIBLE-OK is
24444 non-nil it will also look at invisible ones."
24445 (interactive "p")
24446 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24447 (if (and arg (< arg 0))
24448 (goto-char (point-min))
24449 (outline-next-heading))
24450 (org-at-heading-p)
24451 (let ((level (- (match-end 0) (match-beginning 0) 1))
24452 (f (if (and arg (< arg 0))
24453 're-search-backward
24454 're-search-forward))
24455 (count (if arg (abs arg) 1))
24456 (result (point)))
24457 (while (and (prog1 (> count 0)
24458 (forward-char (if (and arg (< arg 0)) -1 1)))
24459 (funcall f org-outline-regexp-bol nil 'move))
24460 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24461 (cond ((< l level) (setq count 0))
24462 ((and (= l level)
24463 (or invisible-ok
24464 (progn
24465 (goto-char (line-beginning-position))
24466 (not (outline-invisible-p)))))
24467 (setq count (1- count))
24468 (when (eq l level)
24469 (setq result (point)))))))
24470 (goto-char result))
24471 (beginning-of-line 1)))
24473 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24474 "Move backward to the ARG'th subheading at same level as this one.
24475 Stop at the first and last subheadings of a superior heading."
24476 (interactive "p")
24477 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24479 (defun org-next-visible-heading (arg)
24480 "Move to the next visible heading.
24482 This function wraps `outline-next-visible-heading' with
24483 `org-with-limited-levels' in order to skip over inline tasks and
24484 respect customization of `org-odd-levels-only'."
24485 (interactive "p")
24486 (org-with-limited-levels
24487 (outline-next-visible-heading arg)))
24489 (defun org-previous-visible-heading (arg)
24490 "Move to the next visible heading.
24492 This function wraps `outline-previous-visible-heading' with
24493 `org-with-limited-levels' in order to skip over inline tasks and
24494 respect customization of `org-odd-levels-only'."
24495 (interactive "p")
24496 (org-with-limited-levels
24497 (outline-previous-visible-heading arg)))
24499 (defun org-next-block (arg &optional backward block-regexp)
24500 "Jump to the next block.
24502 With a prefix argument ARG, jump forward ARG many blocks.
24504 When BACKWARD is non-nil, jump to the previous block.
24506 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24507 Match data is set according to this regexp when the function
24508 returns.
24510 Return point at beginning of the opening line of found block.
24511 Throw an error if no block is found."
24512 (interactive "p")
24513 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24514 (case-fold-search t)
24515 (search-fn (if backward #'re-search-backward #'re-search-forward))
24516 (count (or arg 1))
24517 (origin (point))
24518 last-element)
24519 (if backward (beginning-of-line) (end-of-line))
24520 (while (and (> count 0) (funcall search-fn re nil t))
24521 (let ((element (save-excursion
24522 (goto-char (match-beginning 0))
24523 (save-match-data (org-element-at-point)))))
24524 (when (and (memq (org-element-type element)
24525 '(center-block comment-block dynamic-block
24526 example-block export-block quote-block
24527 special-block src-block verse-block))
24528 (<= (match-beginning 0)
24529 (org-element-property :post-affiliated element)))
24530 (setq last-element element)
24531 (decf count))))
24532 (if (= count 0)
24533 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24534 (save-match-data (org-show-context)))
24535 (goto-char origin)
24536 (user-error "No %s code blocks" (if backward "previous" "further")))))
24538 (defun org-previous-block (arg &optional block-regexp)
24539 "Jump to the previous block.
24540 With a prefix argument ARG, jump backward ARG many source blocks.
24541 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24542 (interactive "p")
24543 (org-next-block arg t block-regexp))
24545 (defun org-forward-paragraph ()
24546 "Move forward to beginning of next paragraph or equivalent.
24548 The function moves point to the beginning of the next visible
24549 structural element, which can be a paragraph, a table, a list
24550 item, etc. It also provides some special moves for convenience:
24552 - On an affiliated keyword, jump to the beginning of the
24553 relative element.
24554 - On an item or a footnote definition, move to the second
24555 element inside, if any.
24556 - On a table or a property drawer, jump after it.
24557 - On a verse or source block, stop after blank lines."
24558 (interactive)
24559 (when (eobp) (user-error "Cannot move further down"))
24560 (let* ((deactivate-mark nil)
24561 (element (org-element-at-point))
24562 (type (org-element-type element))
24563 (post-affiliated (org-element-property :post-affiliated element))
24564 (contents-begin (org-element-property :contents-begin element))
24565 (contents-end (org-element-property :contents-end element))
24566 (end (let ((end (org-element-property :end element)) (parent element))
24567 (while (and (setq parent (org-element-property :parent parent))
24568 (= (org-element-property :contents-end parent) end))
24569 (setq end (org-element-property :end parent)))
24570 end)))
24571 (cond ((not element)
24572 (skip-chars-forward " \r\t\n")
24573 (or (eobp) (beginning-of-line)))
24574 ;; On affiliated keywords, move to element's beginning.
24575 ((< (point) post-affiliated)
24576 (goto-char post-affiliated))
24577 ;; At a table row, move to the end of the table. Similarly,
24578 ;; at a node property, move to the end of the property
24579 ;; drawer.
24580 ((memq type '(node-property table-row))
24581 (goto-char (org-element-property
24582 :end (org-element-property :parent element))))
24583 ((memq type '(property-drawer table)) (goto-char end))
24584 ;; Consider blank lines as separators in verse and source
24585 ;; blocks to ease editing.
24586 ((memq type '(src-block verse-block))
24587 (when (eq type 'src-block)
24588 (setq contents-end
24589 (save-excursion (goto-char end)
24590 (skip-chars-backward " \r\t\n")
24591 (line-beginning-position))))
24592 (beginning-of-line)
24593 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24594 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24595 (goto-char end)
24596 (skip-chars-forward " \r\t\n")
24597 (if (= (point) contents-end) (goto-char end)
24598 (beginning-of-line))))
24599 ;; With no contents, just skip element.
24600 ((not contents-begin) (goto-char end))
24601 ;; If contents are invisible, skip the element altogether.
24602 ((outline-invisible-p (line-end-position))
24603 (case type
24604 (headline
24605 (org-with-limited-levels (outline-next-visible-heading 1)))
24606 ;; At a plain list, make sure we move to the next item
24607 ;; instead of skipping the whole list.
24608 (plain-list (forward-char)
24609 (org-forward-paragraph))
24610 (otherwise (goto-char end))))
24611 ((>= (point) contents-end) (goto-char end))
24612 ((>= (point) contents-begin)
24613 ;; This can only happen on paragraphs and plain lists.
24614 (case type
24615 (paragraph (goto-char end))
24616 ;; At a plain list, try to move to second element in
24617 ;; first item, if possible.
24618 (plain-list (end-of-line)
24619 (org-forward-paragraph))))
24620 ;; When contents start on the middle of a line (e.g. in
24621 ;; items and footnote definitions), try to reach first
24622 ;; element starting after current line.
24623 ((> (line-end-position) contents-begin)
24624 (end-of-line)
24625 (org-forward-paragraph))
24626 (t (goto-char contents-begin)))))
24628 (defun org-backward-paragraph ()
24629 "Move backward to start of previous paragraph or equivalent.
24631 The function moves point to the beginning of the current
24632 structural element, which can be a paragraph, a table, a list
24633 item, etc., or to the beginning of the previous visible one if
24634 point is already there. It also provides some special moves for
24635 convenience:
24637 - On an affiliated keyword, jump to the first one.
24638 - On a table or a property drawer, move to its beginning.
24639 - On a verse or source block, stop before blank lines."
24640 (interactive)
24641 (when (bobp) (user-error "Cannot move further up"))
24642 (let* ((deactivate-mark nil)
24643 (element (org-element-at-point))
24644 (type (org-element-type element))
24645 (contents-begin (org-element-property :contents-begin element))
24646 (contents-end (org-element-property :contents-end element))
24647 (post-affiliated (org-element-property :post-affiliated element))
24648 (begin (org-element-property :begin element)))
24649 (cond
24650 ((not element) (goto-char (point-min)))
24651 ((= (point) begin)
24652 (backward-char)
24653 (org-backward-paragraph))
24654 ((<= (point) post-affiliated) (goto-char begin))
24655 ((memq type '(node-property table-row))
24656 (goto-char (org-element-property
24657 :post-affiliated (org-element-property :parent element))))
24658 ((memq type '(property-drawer table)) (goto-char begin))
24659 ((memq type '(src-block verse-block))
24660 (when (eq type 'src-block)
24661 (setq contents-begin
24662 (save-excursion (goto-char begin) (forward-line) (point))))
24663 (if (= (point) contents-begin) (goto-char post-affiliated)
24664 ;; Inside a verse block, see blank lines as paragraph
24665 ;; separators.
24666 (let ((origin (point)))
24667 (skip-chars-backward " \r\t\n" contents-begin)
24668 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24669 (skip-chars-forward " \r\t\n" origin)
24670 (if (= (point) origin) (goto-char contents-begin)
24671 (beginning-of-line))))))
24672 ((not contents-begin) (goto-char (or post-affiliated begin)))
24673 ((eq type 'paragraph)
24674 (goto-char contents-begin)
24675 ;; When at first paragraph in an item or a footnote definition,
24676 ;; move directly to beginning of line.
24677 (let ((parent-contents
24678 (org-element-property
24679 :contents-begin (org-element-property :parent element))))
24680 (when (and parent-contents (= parent-contents contents-begin))
24681 (beginning-of-line))))
24682 ;; At the end of a greater element, move to the beginning of the
24683 ;; last element within.
24684 ((>= (point) contents-end)
24685 (goto-char (1- contents-end))
24686 (org-backward-paragraph))
24687 (t (goto-char (or post-affiliated begin))))
24688 ;; Ensure we never leave point invisible.
24689 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24691 (defun org-forward-element ()
24692 "Move forward by one element.
24693 Move to the next element at the same level, when possible."
24694 (interactive)
24695 (cond ((eobp) (user-error "Cannot move further down"))
24696 ((org-with-limited-levels (org-at-heading-p))
24697 (let ((origin (point)))
24698 (goto-char (org-end-of-subtree nil t))
24699 (unless (org-with-limited-levels (org-at-heading-p))
24700 (goto-char origin)
24701 (user-error "Cannot move further down"))))
24703 (let* ((elem (org-element-at-point))
24704 (end (org-element-property :end elem))
24705 (parent (org-element-property :parent elem)))
24706 (cond ((and parent (= (org-element-property :contents-end parent) end))
24707 (goto-char (org-element-property :end parent)))
24708 ((integer-or-marker-p end) (goto-char end))
24709 (t (message "No element at point")))))))
24711 (defun org-backward-element ()
24712 "Move backward by one element.
24713 Move to the previous element at the same level, when possible."
24714 (interactive)
24715 (cond ((bobp) (user-error "Cannot move further up"))
24716 ((org-with-limited-levels (org-at-heading-p))
24717 ;; At a headline, move to the previous one, if any, or stay
24718 ;; here.
24719 (let ((origin (point)))
24720 (org-with-limited-levels (org-backward-heading-same-level 1))
24721 ;; When current headline has no sibling above, move to its
24722 ;; parent.
24723 (when (= (point) origin)
24724 (or (org-with-limited-levels (org-up-heading-safe))
24725 (progn (goto-char origin)
24726 (user-error "Cannot move further up"))))))
24728 (let* ((elem (org-element-at-point))
24729 (beg (org-element-property :begin elem)))
24730 (cond
24731 ;; Move to beginning of current element if point isn't
24732 ;; there already.
24733 ((null beg) (message "No element at point"))
24734 ((/= (point) beg) (goto-char beg))
24735 (t (goto-char beg)
24736 (skip-chars-backward " \r\t\n")
24737 (unless (bobp)
24738 (let ((prev (org-element-at-point)))
24739 (goto-char (org-element-property :begin prev))
24740 (while (and (setq prev (org-element-property :parent prev))
24741 (<= (org-element-property :end prev) beg))
24742 (goto-char (org-element-property :begin prev)))))))))))
24744 (defun org-up-element ()
24745 "Move to upper element."
24746 (interactive)
24747 (if (org-with-limited-levels (org-at-heading-p))
24748 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24749 (let* ((elem (org-element-at-point))
24750 (parent (org-element-property :parent elem)))
24751 (if parent (goto-char (org-element-property :begin parent))
24752 (if (org-with-limited-levels (org-before-first-heading-p))
24753 (user-error "No surrounding element")
24754 (org-with-limited-levels (org-back-to-heading)))))))
24756 (defvar org-element-greater-elements)
24757 (defun org-down-element ()
24758 "Move to inner element."
24759 (interactive)
24760 (let ((element (org-element-at-point)))
24761 (cond
24762 ((memq (org-element-type element) '(plain-list table))
24763 (goto-char (org-element-property :contents-begin element))
24764 (forward-char))
24765 ((memq (org-element-type element) org-element-greater-elements)
24766 ;; If contents are hidden, first disclose them.
24767 (when (outline-invisible-p (line-end-position)) (org-cycle))
24768 (goto-char (or (org-element-property :contents-begin element)
24769 (user-error "No content for this element"))))
24770 (t (user-error "No inner element")))))
24772 (defun org-drag-element-backward ()
24773 "Move backward element at point."
24774 (interactive)
24775 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24776 (let* ((elem (org-element-at-point))
24777 (prev-elem
24778 (save-excursion
24779 (goto-char (org-element-property :begin elem))
24780 (skip-chars-backward " \r\t\n")
24781 (unless (bobp)
24782 (let* ((beg (org-element-property :begin elem))
24783 (prev (org-element-at-point))
24784 (up prev))
24785 (while (and (setq up (org-element-property :parent up))
24786 (<= (org-element-property :end up) beg))
24787 (setq prev up))
24788 prev)))))
24789 ;; Error out if no previous element or previous element is
24790 ;; a parent of the current one.
24791 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24792 (user-error "Cannot drag element backward")
24793 (let ((pos (point)))
24794 (org-element-swap-A-B prev-elem elem)
24795 (goto-char (+ (org-element-property :begin prev-elem)
24796 (- pos (org-element-property :begin elem)))))))))
24798 (defun org-drag-element-forward ()
24799 "Move forward element at point."
24800 (interactive)
24801 (let* ((pos (point))
24802 (elem (org-element-at-point)))
24803 (when (= (point-max) (org-element-property :end elem))
24804 (user-error "Cannot drag element forward"))
24805 (goto-char (org-element-property :end elem))
24806 (let ((next-elem (org-element-at-point)))
24807 (when (or (org-element-nested-p elem next-elem)
24808 (and (eq (org-element-type next-elem) 'headline)
24809 (not (eq (org-element-type elem) 'headline))))
24810 (goto-char pos)
24811 (user-error "Cannot drag element forward"))
24812 ;; Compute new position of point: it's shifted by NEXT-ELEM
24813 ;; body's length (without final blanks) and by the length of
24814 ;; blanks between ELEM and NEXT-ELEM.
24815 (let ((size-next (- (save-excursion
24816 (goto-char (org-element-property :end next-elem))
24817 (skip-chars-backward " \r\t\n")
24818 (forward-line)
24819 ;; Small correction if buffer doesn't end
24820 ;; with a newline character.
24821 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24822 (org-element-property :begin next-elem)))
24823 (size-blank (- (org-element-property :end elem)
24824 (save-excursion
24825 (goto-char (org-element-property :end elem))
24826 (skip-chars-backward " \r\t\n")
24827 (forward-line)
24828 (point)))))
24829 (org-element-swap-A-B elem next-elem)
24830 (goto-char (+ pos size-next size-blank))))))
24832 (defun org-drag-line-forward (arg)
24833 "Drag the line at point ARG lines forward."
24834 (interactive "p")
24835 (dotimes (n (abs arg))
24836 (let ((c (current-column)))
24837 (if (< 0 arg)
24838 (progn
24839 (beginning-of-line 2)
24840 (transpose-lines 1)
24841 (beginning-of-line 0))
24842 (transpose-lines 1)
24843 (beginning-of-line -1))
24844 (org-move-to-column c))))
24846 (defun org-drag-line-backward (arg)
24847 "Drag the line at point ARG lines backward."
24848 (interactive "p")
24849 (org-drag-line-forward (- arg)))
24851 (defun org-mark-element ()
24852 "Put point at beginning of this element, mark at end.
24854 Interactively, if this command is repeated or (in Transient Mark
24855 mode) if the mark is active, it marks the next element after the
24856 ones already marked."
24857 (interactive)
24858 (let (deactivate-mark)
24859 (if (and (org-called-interactively-p 'any)
24860 (or (and (eq last-command this-command) (mark t))
24861 (and transient-mark-mode mark-active)))
24862 (set-mark
24863 (save-excursion
24864 (goto-char (mark))
24865 (goto-char (org-element-property :end (org-element-at-point)))))
24866 (let ((element (org-element-at-point)))
24867 (end-of-line)
24868 (push-mark (org-element-property :end element) t t)
24869 (goto-char (org-element-property :begin element))))))
24871 (defun org-narrow-to-element ()
24872 "Narrow buffer to current element."
24873 (interactive)
24874 (let ((elem (org-element-at-point)))
24875 (cond
24876 ((eq (car elem) 'headline)
24877 (narrow-to-region
24878 (org-element-property :begin elem)
24879 (org-element-property :end elem)))
24880 ((memq (car elem) org-element-greater-elements)
24881 (narrow-to-region
24882 (org-element-property :contents-begin elem)
24883 (org-element-property :contents-end elem)))
24885 (narrow-to-region
24886 (org-element-property :begin elem)
24887 (org-element-property :end elem))))))
24889 (defun org-transpose-element ()
24890 "Transpose current and previous elements, keeping blank lines between.
24891 Point is moved after both elements."
24892 (interactive)
24893 (org-skip-whitespace)
24894 (let ((end (org-element-property :end (org-element-at-point))))
24895 (org-drag-element-backward)
24896 (goto-char end)))
24898 (defun org-unindent-buffer ()
24899 "Un-indent the visible part of the buffer.
24900 Relative indentation (between items, inside blocks, etc.) isn't
24901 modified."
24902 (interactive)
24903 (unless (eq major-mode 'org-mode)
24904 (user-error "Cannot un-indent a buffer not in Org mode"))
24905 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24906 unindent-tree ; For byte-compiler.
24907 (unindent-tree
24908 (function
24909 (lambda (contents)
24910 (mapc
24911 (lambda (element)
24912 (if (memq (org-element-type element) '(headline section))
24913 (funcall unindent-tree (org-element-contents element))
24914 (save-excursion
24915 (save-restriction
24916 (narrow-to-region
24917 (org-element-property :begin element)
24918 (org-element-property :end element))
24919 (org-do-remove-indentation)))))
24920 (reverse contents))))))
24921 (funcall unindent-tree (org-element-contents parse-tree))))
24923 (defun org-show-children (&optional level)
24924 "Show all direct subheadings of this heading.
24925 Prefix arg LEVEL is how many levels below the current level
24926 should be shown. Default is enough to cause the following
24927 heading to appear."
24928 (interactive "p")
24929 (save-excursion
24930 (org-back-to-heading t)
24931 (let* ((current-level (funcall outline-level))
24932 (max-level (org-get-valid-level
24933 current-level (if level (prefix-numeric-value level) 1)))
24934 (end (save-excursion (org-end-of-subtree t t)))
24935 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24936 (past-first-child nil)
24937 ;; Make sure to skip inlinetasks.
24938 (re (format regexp-fmt
24939 current-level
24940 (cond
24941 ((not (featurep 'org-inlinetask)) "")
24942 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24944 (t (1- org-inlinetask-min-level))))))
24945 ;; Display parent heading.
24946 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24947 (forward-line)
24948 ;; Display children. First child may be deeper than expected
24949 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24950 ;; MAX-LEVEL accordingly.
24951 (while (re-search-forward re end t)
24952 (unless past-first-child
24953 (setq re (format regexp-fmt
24954 current-level
24955 (max (funcall outline-level) max-level)))
24956 (setq past-first-child t))
24957 (outline-flag-region (line-end-position 0) (line-end-position) nil)))))
24959 (defun org-show-subtree ()
24960 "Show everything after this heading at deeper levels."
24961 (interactive)
24962 (outline-flag-region
24963 (point)
24964 (save-excursion
24965 (org-end-of-subtree t t))
24966 nil))
24968 (defun org-show-entry ()
24969 "Show the body directly following this heading.
24970 Show the heading too, if it is currently invisible."
24971 (interactive)
24972 (save-excursion
24973 (ignore-errors
24974 (org-back-to-heading t)
24975 (outline-flag-region
24976 (max (point-min) (1- (point)))
24977 (save-excursion
24978 (if (re-search-forward
24979 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24980 (match-beginning 1)
24981 (point-max)))
24982 nil)
24983 (org-cycle-hide-drawers 'children))))
24985 (defun org-make-options-regexp (kwds &optional extra)
24986 "Make a regular expression for keyword lines.
24987 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24988 when non-nil, is a regexp matching keywords names."
24989 (concat "^[ \t]*#\\+\\("
24990 (regexp-opt kwds)
24991 (and extra (concat (and kwds "\\|") extra))
24992 "\\):[ \t]*\\(.*\\)"))
24994 ;; Make isearch reveal the necessary context
24995 (defun org-isearch-end ()
24996 "Reveal context after isearch exits."
24997 (when isearch-success ; only if search was successful
24998 (if (featurep 'xemacs)
24999 ;; Under XEmacs, the hook is run in the correct place,
25000 ;; we directly show the context.
25001 (org-show-context 'isearch)
25002 ;; In Emacs the hook runs *before* restoring the overlays.
25003 ;; So we have to use a one-time post-command-hook to do this.
25004 ;; (Emacs 22 has a special variable, see function `org-mode')
25005 (unless (and (boundp 'isearch-mode-end-hook-quit)
25006 isearch-mode-end-hook-quit)
25007 ;; Only when the isearch was not quitted.
25008 (org-add-hook 'post-command-hook 'org-isearch-post-command
25009 'append 'local)))))
25011 (defun org-isearch-post-command ()
25012 "Remove self from hook, and show context."
25013 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
25014 (org-show-context 'isearch))
25017 ;;;; Integration with and fixes for other packages
25019 ;;; Imenu support
25021 (defvar-local org-imenu-markers nil
25022 "All markers currently used by Imenu.")
25024 (defun org-imenu-new-marker (&optional pos)
25025 "Return a new marker for use by Imenu, and remember the marker."
25026 (let ((m (make-marker)))
25027 (move-marker m (or pos (point)))
25028 (push m org-imenu-markers)
25031 (defun org-imenu-get-tree ()
25032 "Produce the index for Imenu."
25033 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
25034 (setq org-imenu-markers nil)
25035 (let* ((n org-imenu-depth)
25036 (re (concat "^" (org-get-limited-outline-regexp)))
25037 (subs (make-vector (1+ n) nil))
25038 (last-level 0)
25039 m level head0 head)
25040 (save-excursion
25041 (save-restriction
25042 (widen)
25043 (goto-char (point-max))
25044 (while (re-search-backward re nil t)
25045 (setq level (org-reduced-level (funcall outline-level)))
25046 (when (and (<= level n)
25047 (looking-at org-complex-heading-regexp)
25048 (setq head0 (org-match-string-no-properties 4)))
25049 (setq head (org-link-display-format head0)
25050 m (org-imenu-new-marker))
25051 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
25052 (if (>= level last-level)
25053 (push (cons head m) (aref subs level))
25054 (push (cons head (aref subs (1+ level))) (aref subs level))
25055 (loop for i from (1+ level) to n do (aset subs i nil)))
25056 (setq last-level level)))))
25057 (aref subs 1)))
25059 (eval-after-load "imenu"
25060 '(progn
25061 (add-hook 'imenu-after-jump-hook
25062 (lambda ()
25063 (if (derived-mode-p 'org-mode)
25064 (org-show-context 'org-goto))))))
25066 (defun org-link-display-format (link)
25067 "Replace a link with its the description.
25068 If there is no description, use the link target."
25069 (save-match-data
25070 (if (string-match org-bracket-link-analytic-regexp link)
25071 (replace-match (if (match-end 5)
25072 (match-string 5 link)
25073 (concat (match-string 1 link)
25074 (match-string 3 link)))
25075 nil t link)
25076 link)))
25078 (defun org-toggle-link-display ()
25079 "Toggle the literal or descriptive display of links."
25080 (interactive)
25081 (if org-descriptive-links
25082 (progn (org-remove-from-invisibility-spec '(org-link))
25083 (org-restart-font-lock)
25084 (setq org-descriptive-links nil))
25085 (progn (add-to-invisibility-spec '(org-link))
25086 (org-restart-font-lock)
25087 (setq org-descriptive-links t))))
25089 ;; Speedbar support
25091 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
25092 "Overlay marking the agenda restriction line in speedbar.")
25093 (overlay-put org-speedbar-restriction-lock-overlay
25094 'face 'org-agenda-restriction-lock)
25095 (overlay-put org-speedbar-restriction-lock-overlay
25096 'help-echo "Agendas are currently limited to this item.")
25097 (org-detach-overlay org-speedbar-restriction-lock-overlay)
25099 (defun org-speedbar-set-agenda-restriction ()
25100 "Restrict future agenda commands to the location at point in speedbar.
25101 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
25102 (interactive)
25103 (require 'org-agenda)
25104 (let (p m tp np dir txt)
25105 (cond
25106 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25107 'org-imenu t))
25108 (setq m (get-text-property p 'org-imenu-marker))
25109 (with-current-buffer (marker-buffer m)
25110 (goto-char m)
25111 (org-agenda-set-restriction-lock 'subtree)))
25112 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25113 'speedbar-function 'speedbar-find-file))
25114 (setq tp (previous-single-property-change
25115 (1+ p) 'speedbar-function)
25116 np (next-single-property-change
25117 tp 'speedbar-function)
25118 dir (speedbar-line-directory)
25119 txt (buffer-substring-no-properties (or tp (point-min))
25120 (or np (point-max))))
25121 (with-current-buffer (find-file-noselect
25122 (let ((default-directory dir))
25123 (expand-file-name txt)))
25124 (unless (derived-mode-p 'org-mode)
25125 (user-error "Cannot restrict to non-Org-mode file"))
25126 (org-agenda-set-restriction-lock 'file)))
25127 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25128 (move-overlay org-speedbar-restriction-lock-overlay
25129 (point-at-bol) (point-at-eol))
25130 (setq current-prefix-arg nil)
25131 (org-agenda-maybe-redo)))
25133 (defvar speedbar-file-key-map)
25134 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25135 (eval-after-load "speedbar"
25136 '(progn
25137 (speedbar-add-supported-extension ".org")
25138 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25139 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25140 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25141 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25142 (add-hook 'speedbar-visiting-tag-hook
25143 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25145 ;;; Fixes and Hacks for problems with other packages
25147 (defun org--flyspell-object-check-p (element)
25148 "Non-nil when Flyspell can check object at point.
25149 ELEMENT is the element at point."
25150 (let ((object (save-excursion
25151 (when (org-looking-at-p "\\>") (backward-char))
25152 (org-element-context element))))
25153 (case (org-element-type object)
25154 ;; Prevent checks in links due to keybinding conflict with
25155 ;; Flyspell.
25156 ((code entity export-snippet inline-babel-call
25157 inline-src-block line-break latex-fragment link macro
25158 statistics-cookie target timestamp verbatim)
25159 nil)
25160 (footnote-reference
25161 ;; Only in inline footnotes, within the definition.
25162 (and (eq (org-element-property :type object) 'inline)
25163 (< (save-excursion
25164 (goto-char (org-element-property :begin object))
25165 (search-forward ":" nil t 2))
25166 (point))))
25167 (otherwise t))))
25169 (defun org-mode-flyspell-verify ()
25170 "Function used for `flyspell-generic-check-word-predicate'."
25171 (if (org-at-heading-p)
25172 ;; At a headline or an inlinetask, check title only. This is
25173 ;; faster than relying on `org-element-at-point'.
25174 (and (save-excursion (beginning-of-line)
25175 (and (let ((case-fold-search t))
25176 (not (looking-at "\\*+ END[ \t]*$")))
25177 (looking-at org-complex-heading-regexp)))
25178 (match-beginning 4)
25179 (>= (point) (match-beginning 4))
25180 (or (not (match-beginning 5))
25181 (< (point) (match-beginning 5))))
25182 (let* ((element (org-element-at-point))
25183 (post-affiliated (org-element-property :post-affiliated element)))
25184 (cond
25185 ;; Ignore checks in all affiliated keywords but captions.
25186 ((< (point) post-affiliated)
25187 (and (save-excursion
25188 (beginning-of-line)
25189 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25190 (> (point) (match-end 0))
25191 (org--flyspell-object-check-p element)))
25192 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25193 ((let ((log (org-log-into-drawer)))
25194 (and log
25195 (let ((drawer (org-element-lineage element '(drawer))))
25196 (and drawer
25197 (eq (compare-strings
25198 log nil nil
25199 (org-element-property :drawer-name drawer) nil nil t)
25200 t)))))
25201 nil)
25203 (case (org-element-type element)
25204 ((comment quote-section) t)
25205 (comment-block
25206 ;; Allow checks between block markers, not on them.
25207 (and (> (line-beginning-position) post-affiliated)
25208 (save-excursion
25209 (end-of-line)
25210 (skip-chars-forward " \r\t\n")
25211 (< (point) (org-element-property :end element)))))
25212 ;; Arbitrary list of keywords where checks are meaningful.
25213 ;; Make sure point is on the value part of the element.
25214 (keyword
25215 (and (member (org-element-property :key element)
25216 '("DESCRIPTION" "TITLE"))
25217 (save-excursion
25218 (search-backward ":" (line-beginning-position) t))))
25219 ;; Check is globally allowed in paragraphs verse blocks and
25220 ;; table rows (after affiliated keywords) but some objects
25221 ;; must not be affected.
25222 ((paragraph table-row verse-block)
25223 (let ((cbeg (org-element-property :contents-begin element))
25224 (cend (org-element-property :contents-end element)))
25225 (and cbeg (>= (point) cbeg) (< (point) cend)
25226 (org--flyspell-object-check-p element))))))))))
25227 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25229 (defun org-remove-flyspell-overlays-in (beg end)
25230 "Remove flyspell overlays in region."
25231 (and (org-bound-and-true-p flyspell-mode)
25232 (fboundp 'flyspell-delete-region-overlays)
25233 (flyspell-delete-region-overlays beg end)))
25235 (defvar flyspell-delayed-commands)
25236 (eval-after-load "flyspell"
25237 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25239 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25240 (eval-after-load "bookmark"
25241 '(if (boundp 'bookmark-after-jump-hook)
25242 ;; We can use the hook
25243 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25244 ;; Hook not available, use advice
25245 (defadvice bookmark-jump (after org-make-visible activate)
25246 "Make the position visible."
25247 (org-bookmark-jump-unhide))))
25249 ;; Make sure saveplace shows the location if it was hidden
25250 (eval-after-load "saveplace"
25251 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25252 "Make the position visible."
25253 (org-bookmark-jump-unhide)))
25255 ;; Make sure ecb shows the location if it was hidden
25256 (eval-after-load "ecb"
25257 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25258 "Make hierarchy visible when jumping into location from ECB tree buffer."
25259 (if (derived-mode-p 'org-mode)
25260 (org-show-context))))
25262 (defun org-bookmark-jump-unhide ()
25263 "Unhide the current position, to show the bookmark location."
25264 (and (derived-mode-p 'org-mode)
25265 (or (outline-invisible-p)
25266 (save-excursion (goto-char (max (point-min) (1- (point))))
25267 (outline-invisible-p)))
25268 (org-show-context 'bookmark-jump)))
25270 (defun org-mark-jump-unhide ()
25271 "Make the point visible with `org-show-context' after jumping to the mark."
25272 (when (and (derived-mode-p 'org-mode)
25273 (outline-invisible-p))
25274 (org-show-context 'mark-goto)))
25276 (eval-after-load "simple"
25277 '(defadvice pop-to-mark-command (after org-make-visible activate)
25278 "Make the point visible with `org-show-context'."
25279 (org-mark-jump-unhide)))
25281 (eval-after-load "simple"
25282 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25283 "Make the point visible with `org-show-context'."
25284 (org-mark-jump-unhide)))
25286 (eval-after-load "simple"
25287 '(defadvice pop-global-mark (after org-make-visible activate)
25288 "Make the point visible with `org-show-context'."
25289 (org-mark-jump-unhide)))
25291 ;; Make session.el ignore our circular variable
25292 (defvar session-globals-exclude)
25293 (eval-after-load "session"
25294 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25296 ;;;; Finish up
25298 (provide 'org)
25300 (run-hooks 'org-load-hook)
25302 ;;; org.el ends here