Refactor logging code
[org-mode/org-tableheadings.git] / lisp / org.el
blob6c355adc2c7a9b9265c4aafa0807c931b2b875de
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2014 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (equal this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
96 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
97 ;; some places -- e.g. see the macro `org-with-limited-levels'.
99 ;; In Org buffers, the value of `outline-regexp' is that of
100 ;; `org-outline-regexp'. The only function still directly relying on
101 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
102 ;; job when `orgstruct-mode' is active.
103 (defvar org-outline-regexp "\\*+ "
104 "Regexp to match Org headlines.")
106 (defvar org-outline-regexp-bol "^\\*+ "
107 "Regexp to match Org headlines.
108 This is similar to `org-outline-regexp' but additionally makes
109 sure that we are at the beginning of the line.")
111 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
112 "Matches a headline, putting stars and text into groups.
113 Stars are put in group 1 and the trimmed body in group 2.")
115 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
116 (unless (boundp 'calendar-view-holidays-initially-flag)
117 (org-defvaralias 'calendar-view-holidays-initially-flag
118 'view-calendar-holidays-initially))
119 (unless (boundp 'calendar-view-diary-initially-flag)
120 (org-defvaralias 'calendar-view-diary-initially-flag
121 'view-diary-entries-initially))
122 (unless (boundp 'diary-fancy-buffer)
123 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
125 (declare-function org-add-archive-files "org-archive" (files))
127 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
128 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
129 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
130 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
131 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
132 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
133 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
134 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
135 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
136 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
137 (declare-function org-clock-update-time-maybe "org-clock" ())
138 (declare-function org-clocktable-shift "org-clock" (dir n))
140 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
141 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
142 (declare-function orgtbl-mode "org-table" (&optional arg))
143 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
144 (declare-function org-beamer-mode "ox-beamer" ())
145 (declare-function org-table-blank-field "org-table" ())
146 (declare-function org-table-edit-field "org-table" (arg))
147 (declare-function org-table-insert-row "org-table" (&optional arg))
148 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
149 (declare-function org-table-set-constants "org-table" ())
150 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
151 (declare-function org-id-get-create "org-id" (&optional force))
152 (declare-function org-add-archive-files "org-archive" (files))
153 (declare-function org-id-find-id-file "org-id" (id))
154 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
155 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
156 (declare-function org-agenda-redo "org-agenda" (&optional all))
157 (declare-function org-table-align "org-table" ())
158 (declare-function org-table-begin "org-table" (&optional table-type))
159 (declare-function org-table-blank-field "org-table" ())
160 (declare-function org-table-end "org-table" (&optional table-type))
161 (declare-function org-table-end-of-field "org-table" (&optional n))
162 (declare-function org-table-insert-row "org-table" (&optional arg))
163 (declare-function org-table-paste-rectangle "org-table" ())
164 (declare-function org-table-maybe-eval-formula "org-table" ())
165 (declare-function org-table-maybe-recalculate-line "org-table" ())
166 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
167 (declare-function org-plot/gnuplot "org-plot" (&optional params))
169 (declare-function org-element-at-point "org-element" ())
170 (declare-function org-element-cache-reset "org-element" (&optional all))
171 (declare-function org-element-cache-refresh "org-element" (pos))
172 (declare-function org-element-contents "org-element" (element))
173 (declare-function org-element-context "org-element" (&optional element))
174 (declare-function org-element-interpret-data "org-element"
175 (data &optional parent))
176 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
177 (declare-function org-element-parse-buffer "org-element"
178 (&optional granularity visible-only))
179 (declare-function org-element-property "org-element" (property element))
180 (declare-function org-element-put-property "org-element"
181 (element property value))
182 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
183 (declare-function org-element-parse-buffer "org-element"
184 (&optional granularity visible-only))
185 (declare-function org-element-type "org-element" (element))
187 (defsubst org-uniquify (list)
188 "Non-destructively remove duplicate elements from LIST."
189 (let ((res (copy-sequence list))) (delete-dups res)))
191 (defsubst org-get-at-bol (property)
192 "Get text property PROPERTY at the beginning of line."
193 (get-text-property (point-at-bol) property))
195 (defsubst org-trim (s)
196 "Remove whitespace at the beginning and the end of string S."
197 (replace-regexp-in-string
198 "\\`[ \t\n\r]+" ""
199 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
201 ;; load languages based on value of `org-babel-load-languages'
202 (defvar org-babel-load-languages)
204 ;;;###autoload
205 (defun org-babel-do-load-languages (sym value)
206 "Load the languages defined in `org-babel-load-languages'."
207 (set-default sym value)
208 (mapc (lambda (pair)
209 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
210 (if active
211 (progn
212 (require (intern (concat "ob-" lang))))
213 (progn
214 (funcall 'fmakunbound
215 (intern (concat "org-babel-execute:" lang)))
216 (funcall 'fmakunbound
217 (intern (concat "org-babel-expand-body:" lang)))))))
218 org-babel-load-languages))
220 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
221 ;;;###autoload
222 (defun org-babel-load-file (file &optional compile)
223 "Load Emacs Lisp source code blocks in the Org-mode FILE.
224 This function exports the source code using `org-babel-tangle'
225 and then loads the resulting file using `load-file'. With prefix
226 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
227 file to byte-code before it is loaded."
228 (interactive "fFile to load: \nP")
229 (let* ((age (lambda (file)
230 (float-time
231 (time-subtract (current-time)
232 (nth 5 (or (file-attributes (file-truename file))
233 (file-attributes file)))))))
234 (base-name (file-name-sans-extension file))
235 (exported-file (concat base-name ".el")))
236 ;; tangle if the org-mode file is newer than the elisp file
237 (unless (and (file-exists-p exported-file)
238 (> (funcall age file) (funcall age exported-file)))
239 (setq exported-file
240 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
241 (message "%s %s"
242 (if compile
243 (progn (byte-compile-file exported-file 'load)
244 "Compiled and loaded")
245 (progn (load-file exported-file) "Loaded"))
246 exported-file)))
248 (defcustom org-babel-load-languages '((emacs-lisp . t))
249 "Languages which can be evaluated in Org-mode buffers.
250 This list can be used to load support for any of the languages
251 below, note that each language will depend on a different set of
252 system executables and/or Emacs modes. When a language is
253 \"loaded\", then code blocks in that language can be evaluated
254 with `org-babel-execute-src-block' bound by default to C-c
255 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
256 be set to remove code block evaluation from the C-c C-c
257 keybinding. By default only Emacs Lisp (which has no
258 requirements) is loaded."
259 :group 'org-babel
260 :set 'org-babel-do-load-languages
261 :version "24.1"
262 :type '(alist :tag "Babel Languages"
263 :key-type
264 (choice
265 (const :tag "Awk" awk)
266 (const :tag "C" C)
267 (const :tag "R" R)
268 (const :tag "Asymptote" asymptote)
269 (const :tag "Calc" calc)
270 (const :tag "Clojure" clojure)
271 (const :tag "CSS" css)
272 (const :tag "Ditaa" ditaa)
273 (const :tag "Dot" dot)
274 (const :tag "Emacs Lisp" emacs-lisp)
275 (const :tag "Forth" forth)
276 (const :tag "Fortran" fortran)
277 (const :tag "Gnuplot" gnuplot)
278 (const :tag "Haskell" haskell)
279 (const :tag "IO" io)
280 (const :tag "J" J)
281 (const :tag "Java" java)
282 (const :tag "Javascript" js)
283 (const :tag "LaTeX" latex)
284 (const :tag "Ledger" ledger)
285 (const :tag "Lilypond" lilypond)
286 (const :tag "Lisp" lisp)
287 (const :tag "Makefile" makefile)
288 (const :tag "Maxima" maxima)
289 (const :tag "Matlab" matlab)
290 (const :tag "Mscgen" mscgen)
291 (const :tag "Ocaml" ocaml)
292 (const :tag "Octave" octave)
293 (const :tag "Org" org)
294 (const :tag "Perl" perl)
295 (const :tag "Pico Lisp" picolisp)
296 (const :tag "PlantUML" plantuml)
297 (const :tag "Python" python)
298 (const :tag "Ruby" ruby)
299 (const :tag "Sass" sass)
300 (const :tag "Scala" scala)
301 (const :tag "Scheme" scheme)
302 (const :tag "Screen" screen)
303 (const :tag "Shell Script" shell)
304 (const :tag "Shen" shen)
305 (const :tag "Sql" sql)
306 (const :tag "Sqlite" sqlite)
307 (const :tag "ebnf2ps" ebnf2ps))
308 :value-type (boolean :tag "Activate" :value t)))
310 ;;;; Customization variables
311 (defcustom org-clone-delete-id nil
312 "Remove ID property of clones of a subtree.
313 When non-nil, clones of a subtree don't inherit the ID property.
314 Otherwise they inherit the ID property with a new unique
315 identifier."
316 :type 'boolean
317 :version "24.1"
318 :group 'org-id)
320 ;;; Version
321 (org-check-version)
323 ;;;###autoload
324 (defun org-version (&optional here full message)
325 "Show the org-mode version.
326 Interactively, or when MESSAGE is non-nil, show it in echo area.
327 With prefix argument, or when HERE is non-nil, insert it at point.
328 In non-interactive uses, a reduced version string is output unless
329 FULL is given."
330 (interactive (list current-prefix-arg t (not current-prefix-arg)))
331 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
332 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
333 (load-suffixes (list ".el"))
334 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
335 (org-trash (or
336 (and (fboundp 'org-release) (fboundp 'org-git-version))
337 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
338 (load-suffixes save-load-suffixes)
339 (org-version (org-release))
340 (git-version (org-git-version))
341 (version (format "Org-mode version %s (%s @ %s)"
342 org-version
343 git-version
344 (if org-install-dir
345 (if (string= org-dir org-install-dir)
346 org-install-dir
347 (concat "mixed installation! " org-install-dir " and " org-dir))
348 "org-loaddefs.el can not be found!")))
349 (version1 (if full version org-version)))
350 (when here (insert version1))
351 (when message (message "%s" version1))
352 version1))
354 (defconst org-version (org-version))
357 ;;; Syntax Constants
359 ;;;; Block
361 (defconst org-block-regexp
362 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
363 "Regular expression for hiding blocks.")
365 (defconst org-dblock-start-re
366 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
367 "Matches the start line of a dynamic block, with parameters.")
369 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
370 "Matches the end of a dynamic block.")
372 ;;;; Clock and Planning
374 (defconst org-clock-string "CLOCK:"
375 "String used as prefix for timestamps clocking work hours on an item.")
377 (defconst org-closed-string "CLOSED:"
378 "String used as the prefix for timestamps logging closing a TODO entry.")
380 (defconst org-deadline-string "DEADLINE:"
381 "String to mark deadline entries.
382 A deadline is this string, followed by a time stamp. Should be a word,
383 terminated by a colon. You can insert a schedule keyword and
384 a timestamp with \\[org-deadline].")
386 (defconst org-scheduled-string "SCHEDULED:"
387 "String to mark scheduled TODO entries.
388 A schedule is this string, followed by a time stamp. Should be a word,
389 terminated by a colon. You can insert a schedule keyword and
390 a timestamp with \\[org-schedule].")
392 (defconst org-ds-keyword-length
393 (+ 2
394 (apply #'max
395 (mapcar #'length
396 (list org-deadline-string org-scheduled-string
397 org-clock-string org-closed-string))))
398 "Maximum length of the DEADLINE and SCHEDULED keywords.")
400 (defconst org-planning-line-re
401 (concat "^[ \t]*"
402 (regexp-opt
403 (list org-closed-string org-deadline-string org-scheduled-string)
405 "Matches a line with planning info.
406 Matched keyword is in group 1.")
408 (defconst org-clock-line-re
409 (concat "^[ \t]*" org-clock-string)
410 "Matches a line with clock info.")
412 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
413 "Matches the DEADLINE keyword.")
415 (defconst org-deadline-time-regexp
416 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
417 "Matches the DEADLINE keyword together with a time stamp.")
419 (defconst org-deadline-time-hour-regexp
420 (concat "\\<" org-deadline-string
421 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
422 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
424 (defconst org-deadline-line-regexp
425 (concat "\\<\\(" org-deadline-string "\\).*")
426 "Matches the DEADLINE keyword and the rest of the line.")
428 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
429 "Matches the SCHEDULED keyword.")
431 (defconst org-scheduled-time-regexp
432 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
433 "Matches the SCHEDULED keyword together with a time stamp.")
435 (defconst org-scheduled-time-hour-regexp
436 (concat "\\<" org-scheduled-string
437 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
438 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
440 (defconst org-closed-time-regexp
441 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
442 "Matches the CLOSED keyword together with a time stamp.")
444 (defconst org-keyword-time-regexp
445 (concat "\\<"
446 (regexp-opt
447 (list org-scheduled-string org-deadline-string org-closed-string
448 org-clock-string)
450 " *[[<]\\([^]>]+\\)[]>]")
451 "Matches any of the 4 keywords, together with the time stamp.")
453 (defconst org-keyword-time-not-clock-regexp
454 (concat
455 "\\<"
456 (regexp-opt
457 (list org-scheduled-string org-deadline-string org-closed-string) t)
458 " *[[<]\\([^]>]+\\)[]>]")
459 "Matches any of the 3 keywords, together with the time stamp.")
461 (defconst org-maybe-keyword-time-regexp
462 (concat "\\(\\<"
463 (regexp-opt
464 (list org-scheduled-string org-deadline-string org-closed-string
465 org-clock-string)
467 "\\)?"
468 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
469 "\\|"
470 "<%%([^\r\n>]*>\\)")
471 "Matches a timestamp, possibly preceded by a keyword.")
473 (defconst org-all-time-keywords
474 (mapcar (lambda (w) (substring w 0 -1))
475 (list org-scheduled-string org-deadline-string
476 org-clock-string org-closed-string))
477 "List of time keywords.")
479 ;;;; Drawer
481 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
482 "Matches first or last line of a hidden block.
483 Group 1 contains drawer's name or \"END\".")
485 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
486 "Regular expression matching the first line of a property drawer.")
488 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
489 "Regular expression matching the last line of a property drawer.")
491 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
492 "Regular expression matching the first line of a clock drawer.")
494 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
495 "Regular expression matching the last line of a clock drawer.")
497 (defconst org-property-drawer-re
498 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
499 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*"
500 "[ \t]*:END:[ \t]*$")
501 "Matches an entire property drawer.")
503 (defconst org-clock-drawer-re
504 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
505 org-clock-drawer-end-re "\\)\n?")
506 "Matches an entire clock drawer.")
508 ;;;; Headline
510 (defconst org-heading-keyword-regexp-format
511 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
512 "Printf format for a regexp matching a headline with some keyword.
513 This regexp will match the headline of any node which has the
514 exact keyword that is put into the format. The keyword isn't in
515 any group by default, but the stars and the body are.")
517 (defconst org-heading-keyword-maybe-regexp-format
518 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
519 "Printf format for a regexp matching a headline, possibly with some keyword.
520 This regexp can match any headline with the specified keyword, or
521 without a keyword. The keyword isn't in any group by default,
522 but the stars and the body are.")
524 (defconst org-archive-tag "ARCHIVE"
525 "The tag that marks a subtree as archived.
526 An archived subtree does not open during visibility cycling, and does
527 not contribute to the agenda listings.")
529 (defconst org-comment-string "COMMENT"
530 "Entries starting with this keyword will never be exported.
531 An entry can be toggled between COMMENT and normal with
532 \\[org-toggle-comment].")
535 ;;;; LaTeX Environments and Fragments
537 (defconst org-latex-regexps
538 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
539 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
540 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
541 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
542 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
543 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
544 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
545 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
546 "Regular expressions for matching embedded LaTeX.")
548 ;;;; Node Property
550 (defconst org-effort-property "Effort"
551 "The property that is being used to keep track of effort estimates.
552 Effort estimates given in this property need to have the format H:MM.")
554 ;;;; Table
556 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
557 "Detect an org-type or table-type table.")
559 (defconst org-table-line-regexp "^[ \t]*|"
560 "Detect an org-type table line.")
562 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
563 "Detect an org-type table line.")
565 (defconst org-table-hline-regexp "^[ \t]*|-"
566 "Detect an org-type table hline.")
568 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
569 "Detect a table-type table hline.")
571 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
572 "Detect the first line outside a table when searching from within it.
573 This works for both table types.")
575 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
576 "Detect a #+TBLFM line.")
578 ;;;; Timestamp
580 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
581 "Regular expression for fast time stamp matching.")
583 (defconst org-ts-regexp-inactive
584 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
585 "Regular expression for fast inactive time stamp matching.")
587 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
588 "Regular expression for fast time stamp matching.")
590 (defconst org-ts-regexp0
591 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
592 "Regular expression matching time strings for analysis.
593 This one does not require the space after the date, so it can be used
594 on a string that terminates immediately after the date.")
596 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
597 "Regular expression matching time strings for analysis.")
599 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
600 "Regular expression matching time stamps, with groups.")
602 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
603 "Regular expression matching time stamps (also [..]), with groups.")
605 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
606 "Regular expression matching a time stamp range.")
608 (defconst org-tr-regexp-both
609 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
610 "Regular expression matching a time stamp range.")
612 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
613 org-ts-regexp "\\)?")
614 "Regular expression matching a time stamp or time stamp range.")
616 (defconst org-tsr-regexp-both
617 (concat org-ts-regexp-both "\\(--?-?"
618 org-ts-regexp-both "\\)?")
619 "Regular expression matching a time stamp or time stamp range.
620 The time stamps may be either active or inactive.")
622 (defconst org-repeat-re
623 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
624 "Regular expression for specifying repeated events.
625 After a match, group 1 contains the repeat expression.")
627 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
628 "Formats for `format-time-string' which are used for time stamps.")
631 ;;; The custom variables
633 (defgroup org nil
634 "Outline-based notes management and organizer."
635 :tag "Org"
636 :group 'outlines
637 :group 'calendar)
639 (defcustom org-mode-hook nil
640 "Mode hook for Org-mode, run after the mode was turned on."
641 :group 'org
642 :type 'hook)
644 (defcustom org-load-hook nil
645 "Hook that is run after org.el has been loaded."
646 :group 'org
647 :type 'hook)
649 (defcustom org-log-buffer-setup-hook nil
650 "Hook that is run after an Org log buffer is created."
651 :group 'org
652 :version "24.1"
653 :type 'hook)
655 (defvar org-modules) ; defined below
656 (defvar org-modules-loaded nil
657 "Have the modules been loaded already?")
659 (defun org-load-modules-maybe (&optional force)
660 "Load all extensions listed in `org-modules'."
661 (when (or force (not org-modules-loaded))
662 (mapc (lambda (ext)
663 (condition-case nil (require ext)
664 (error (message "Problems while trying to load feature `%s'" ext))))
665 org-modules)
666 (setq org-modules-loaded t)))
668 (defun org-set-modules (var value)
669 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
670 (set var value)
671 (when (featurep 'org)
672 (org-load-modules-maybe 'force)
673 (org-element-cache-reset 'all)))
675 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
676 "Modules that should always be loaded together with org.el.
678 If a description starts with <C>, the file is not part of Emacs
679 and loading it will require that you have downloaded and properly
680 installed the Org mode distribution.
682 You can also use this system to load external packages (i.e. neither Org
683 core modules, nor modules from the CONTRIB directory). Just add symbols
684 to the end of the list. If the package is called org-xyz.el, then you need
685 to add the symbol `xyz', and the package must have a call to:
687 \(provide 'org-xyz)
689 For export specific modules, see also `org-export-backends'."
690 :group 'org
691 :set 'org-set-modules
692 :version "24.4"
693 :package-version '(Org . "8.0")
694 :type
695 '(set :greedy t
696 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
697 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
698 (const :tag " crypt: Encryption of subtrees" org-crypt)
699 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
700 (const :tag " docview: Links to doc-view buffers" org-docview)
701 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
702 (const :tag " habit: Track your consistency with habits" org-habit)
703 (const :tag " id: Global IDs for identifying entries" org-id)
704 (const :tag " info: Links to Info nodes" org-info)
705 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
706 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
707 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
708 (const :tag " mouse: Additional mouse support" org-mouse)
709 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
710 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
711 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
713 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
714 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
715 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
716 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
717 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
718 (const :tag "C collector: Collect properties into tables" org-collector)
719 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
720 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
721 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
722 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
723 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
724 (const :tag "C eval: Include command output as text" org-eval)
725 (const :tag "C eww: Store link to url of eww" org-eww)
726 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
727 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
728 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
729 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
730 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
731 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
732 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
733 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
734 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
735 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
736 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
737 (const :tag "C mew: Links to Mew folders/messages" org-mew)
738 (const :tag "C mtags: Support for muse-like tags" org-mtags)
739 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
740 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
741 (const :tag "C registry: A registry for Org-mode links" org-registry)
742 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
743 (const :tag "C secretary: Team management with org-mode" org-secretary)
744 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
745 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
746 (const :tag "C track: Keep up with Org-mode development" org-track)
747 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
748 (const :tag "C vm: Links to VM folders/messages" org-vm)
749 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
750 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
751 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
753 (defvar org-export--registered-backends) ; From ox.el.
754 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
755 (declare-function org-export-backend-name "ox" (backend))
756 (defcustom org-export-backends '(ascii html icalendar latex)
757 "List of export back-ends that should be always available.
759 If a description starts with <C>, the file is not part of Emacs
760 and loading it will require that you have downloaded and properly
761 installed the Org mode distribution.
763 Unlike to `org-modules', libraries in this list will not be
764 loaded along with Org, but only once the export framework is
765 needed.
767 This variable needs to be set before org.el is loaded. If you
768 need to make a change while Emacs is running, use the customize
769 interface or run the following code, where VAL stands for the new
770 value of the variable, after updating it:
772 \(progn
773 \(setq org-export--registered-backends
774 \(org-remove-if-not
775 \(lambda (backend)
776 \(let ((name (org-export-backend-name backend)))
777 \(or (memq name val)
778 \(catch 'parentp
779 \(dolist (b val)
780 \(and (org-export-derived-backend-p b name)
781 \(throw 'parentp t)))))))
782 org-export--registered-backends))
783 \(let ((new-list (mapcar 'org-export-backend-name
784 org-export--registered-backends)))
785 \(dolist (backend val)
786 \(cond
787 \((not (load (format \"ox-%s\" backend) t t))
788 \(message \"Problems while trying to load export back-end `%s'\"
789 backend))
790 \((not (memq backend new-list)) (push backend new-list))))
791 \(set-default 'org-export-backends new-list)))
793 Adding a back-end to this list will also pull the back-end it
794 depends on, if any."
795 :group 'org
796 :group 'org-export
797 :version "24.4"
798 :package-version '(Org . "8.0")
799 :initialize 'custom-initialize-set
800 :set (lambda (var val)
801 (if (not (featurep 'ox)) (set-default var val)
802 ;; Any back-end not required anymore (not present in VAL and not
803 ;; a parent of any back-end in the new value) is removed from the
804 ;; list of registered back-ends.
805 (setq org-export--registered-backends
806 (org-remove-if-not
807 (lambda (backend)
808 (let ((name (org-export-backend-name backend)))
809 (or (memq name val)
810 (catch 'parentp
811 (dolist (b val)
812 (and (org-export-derived-backend-p b name)
813 (throw 'parentp t)))))))
814 org-export--registered-backends))
815 ;; Now build NEW-LIST of both new back-ends and required
816 ;; parents.
817 (let ((new-list (mapcar 'org-export-backend-name
818 org-export--registered-backends)))
819 (dolist (backend val)
820 (cond
821 ((not (load (format "ox-%s" backend) t t))
822 (message "Problems while trying to load export back-end `%s'"
823 backend))
824 ((not (memq backend new-list)) (push backend new-list))))
825 ;; Set VAR to that list with fixed dependencies.
826 (set-default var new-list))))
827 :type '(set :greedy t
828 (const :tag " ascii Export buffer to ASCII format" ascii)
829 (const :tag " beamer Export buffer to Beamer presentation" beamer)
830 (const :tag " html Export buffer to HTML format" html)
831 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
832 (const :tag " latex Export buffer to LaTeX format" latex)
833 (const :tag " man Export buffer to MAN format" man)
834 (const :tag " md Export buffer to Markdown format" md)
835 (const :tag " odt Export buffer to ODT format" odt)
836 (const :tag " org Export buffer to Org format" org)
837 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
838 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
839 (const :tag "C deck Export buffer to deck.js presentations" deck)
840 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
841 (const :tag "C groff Export buffer to Groff format" groff)
842 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
843 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
844 (const :tag "C s5 Export buffer to s5 presentations" s5)
845 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
847 (eval-after-load 'ox
848 '(mapc
849 (lambda (backend)
850 (condition-case nil (require (intern (format "ox-%s" backend)))
851 (error (message "Problems while trying to load export back-end `%s'"
852 backend))))
853 org-export-backends))
855 (defcustom org-support-shift-select nil
856 "Non-nil means make shift-cursor commands select text when possible.
858 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
859 start selecting a region, or enlarge regions started in this way.
860 In Org-mode, in special contexts, these same keys are used for
861 other purposes, important enough to compete with shift selection.
862 Org tries to balance these needs by supporting `shift-select-mode'
863 outside these special contexts, under control of this variable.
865 The default of this variable is nil, to avoid confusing behavior. Shifted
866 cursor keys will then execute Org commands in the following contexts:
867 - on a headline, changing TODO state (left/right) and priority (up/down)
868 - on a time stamp, changing the time
869 - in a plain list item, changing the bullet type
870 - in a property definition line, switching between allowed values
871 - in the BEGIN line of a clock table (changing the time block).
872 Outside these contexts, the commands will throw an error.
874 When this variable is t and the cursor is not in a special
875 context, Org-mode will support shift-selection for making and
876 enlarging regions. To make this more effective, the bullet
877 cycling will no longer happen anywhere in an item line, but only
878 if the cursor is exactly on the bullet.
880 If you set this variable to the symbol `always', then the keys
881 will not be special in headlines, property lines, and item lines,
882 to make shift selection work there as well. If this is what you
883 want, you can use the following alternative commands: `C-c C-t'
884 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
885 can be used to switch TODO sets, `C-c -' to cycle item bullet
886 types, and properties can be edited by hand or in column view.
888 However, when the cursor is on a timestamp, shift-cursor commands
889 will still edit the time stamp - this is just too good to give up.
891 XEmacs user should have this variable set to nil, because
892 `shift-select-mode' is in Emacs 23 or later only."
893 :group 'org
894 :type '(choice
895 (const :tag "Never" nil)
896 (const :tag "When outside special context" t)
897 (const :tag "Everywhere except timestamps" always)))
899 (defcustom org-loop-over-headlines-in-active-region nil
900 "Shall some commands act upon headlines in the active region?
902 When set to `t', some commands will be performed in all headlines
903 within the active region.
905 When set to `start-level', some commands will be performed in all
906 headlines within the active region, provided that these headlines
907 are of the same level than the first one.
909 When set to a string, those commands will be performed on the
910 matching headlines within the active region. Such string must be
911 a tags/property/todo match as it is used in the agenda tags view.
913 The list of commands is: `org-schedule', `org-deadline',
914 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
915 `org-archive-to-archive-sibling'. The archiving commands skip
916 already archived entries."
917 :type '(choice (const :tag "Don't loop" nil)
918 (const :tag "All headlines in active region" t)
919 (const :tag "In active region, headlines at the same level than the first one" start-level)
920 (string :tag "Tags/Property/Todo matcher"))
921 :version "24.1"
922 :group 'org-todo
923 :group 'org-archive)
925 (defgroup org-startup nil
926 "Options concerning startup of Org-mode."
927 :tag "Org Startup"
928 :group 'org)
930 (defcustom org-startup-folded t
931 "Non-nil means entering Org-mode will switch to OVERVIEW.
932 This can also be configured on a per-file basis by adding one of
933 the following lines anywhere in the buffer:
935 #+STARTUP: fold (or `overview', this is equivalent)
936 #+STARTUP: nofold (or `showall', this is equivalent)
937 #+STARTUP: content
938 #+STARTUP: showeverything
940 By default, this option is ignored when Org opens agenda files
941 for the first time. If you want the agenda to honor the startup
942 option, set `org-agenda-inhibit-startup' to nil."
943 :group 'org-startup
944 :type '(choice
945 (const :tag "nofold: show all" nil)
946 (const :tag "fold: overview" t)
947 (const :tag "content: all headlines" content)
948 (const :tag "show everything, even drawers" showeverything)))
950 (defcustom org-startup-truncated t
951 "Non-nil means entering Org-mode will set `truncate-lines'.
952 This is useful since some lines containing links can be very long and
953 uninteresting. Also tables look terrible when wrapped."
954 :group 'org-startup
955 :type 'boolean)
957 (defcustom org-startup-indented nil
958 "Non-nil means turn on `org-indent-mode' on startup.
959 This can also be configured on a per-file basis by adding one of
960 the following lines anywhere in the buffer:
962 #+STARTUP: indent
963 #+STARTUP: noindent"
964 :group 'org-structure
965 :type '(choice
966 (const :tag "Not" nil)
967 (const :tag "Globally (slow on startup in large files)" t)))
969 (defcustom org-use-sub-superscripts t
970 "Non-nil means interpret \"_\" and \"^\" for display.
972 If you want to control how Org exports those characters, see
973 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
974 used to be an alias for `org-export-with-sub-superscripts' in
975 Org <8.0, it is not anymore.
977 When this option is turned on, you can use TeX-like syntax for
978 sub- and superscripts within the buffer. Several characters after
979 \"_\" or \"^\" will be considered as a single item - so grouping
980 with {} is normally not needed. For example, the following things
981 will be parsed as single sub- or superscripts:
983 10^24 or 10^tau several digits will be considered 1 item.
984 10^-12 or 10^-tau a leading sign with digits or a word
985 x^2-y^3 will be read as x^2 - y^3, because items are
986 terminated by almost any nonword/nondigit char.
987 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
989 Still, ambiguity is possible. So when in doubt, use {} to enclose
990 the sub/superscript. If you set this variable to the symbol `{}',
991 the braces are *required* in order to trigger interpretations as
992 sub/superscript. This can be helpful in documents that need \"_\"
993 frequently in plain text."
994 :group 'org-startup
995 :version "24.4"
996 :package-version '(Org . "8.0")
997 :type '(choice
998 (const :tag "Always interpret" t)
999 (const :tag "Only with braces" {})
1000 (const :tag "Never interpret" nil)))
1002 (defcustom org-startup-with-beamer-mode nil
1003 "Non-nil means turn on `org-beamer-mode' on startup.
1004 This can also be configured on a per-file basis by adding one of
1005 the following lines anywhere in the buffer:
1007 #+STARTUP: beamer"
1008 :group 'org-startup
1009 :version "24.1"
1010 :type 'boolean)
1012 (defcustom org-startup-align-all-tables nil
1013 "Non-nil means align all tables when visiting a file.
1014 This is useful when the column width in tables is forced with <N> cookies
1015 in table fields. Such tables will look correct only after the first re-align.
1016 This can also be configured on a per-file basis by adding one of
1017 the following lines anywhere in the buffer:
1018 #+STARTUP: align
1019 #+STARTUP: noalign"
1020 :group 'org-startup
1021 :type 'boolean)
1023 (defcustom org-startup-with-inline-images nil
1024 "Non-nil means show inline images when loading a new Org file.
1025 This can also be configured on a per-file basis by adding one of
1026 the following lines anywhere in the buffer:
1027 #+STARTUP: inlineimages
1028 #+STARTUP: noinlineimages"
1029 :group 'org-startup
1030 :version "24.1"
1031 :type 'boolean)
1033 (defcustom org-startup-with-latex-preview nil
1034 "Non-nil means preview LaTeX fragments when loading a new Org file.
1036 This can also be configured on a per-file basis by adding one of
1037 the following lines anywhere in the buffer:
1038 #+STARTUP: latexpreview
1039 #+STARTUP: nolatexpreview"
1040 :group 'org-startup
1041 :version "24.4"
1042 :package-version '(Org . "8.0")
1043 :type 'boolean)
1045 (defcustom org-insert-mode-line-in-empty-file nil
1046 "Non-nil means insert the first line setting Org-mode in empty files.
1047 When the function `org-mode' is called interactively in an empty file, this
1048 normally means that the file name does not automatically trigger Org-mode.
1049 To ensure that the file will always be in Org-mode in the future, a
1050 line enforcing Org-mode will be inserted into the buffer, if this option
1051 has been set."
1052 :group 'org-startup
1053 :type 'boolean)
1055 (defcustom org-replace-disputed-keys nil
1056 "Non-nil means use alternative key bindings for some keys.
1057 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1058 These keys are also used by other packages like shift-selection-mode'
1059 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1060 If you want to use Org-mode together with one of these other modes,
1061 or more generally if you would like to move some Org-mode commands to
1062 other keys, set this variable and configure the keys with the variable
1063 `org-disputed-keys'.
1065 This option is only relevant at load-time of Org-mode, and must be set
1066 *before* org.el is loaded. Changing it requires a restart of Emacs to
1067 become effective."
1068 :group 'org-startup
1069 :type 'boolean)
1071 (defcustom org-use-extra-keys nil
1072 "Non-nil means use extra key sequence definitions for certain commands.
1073 This happens automatically if you run XEmacs or if `window-system'
1074 is nil. This variable lets you do the same manually. You must
1075 set it before loading org.
1077 Example: on Carbon Emacs 22 running graphically, with an external
1078 keyboard on a Powerbook, the default way of setting M-left might
1079 not work for either Alt or ESC. Setting this variable will make
1080 it work for ESC."
1081 :group 'org-startup
1082 :type 'boolean)
1084 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1086 (defcustom org-disputed-keys
1087 '(([(shift up)] . [(meta p)])
1088 ([(shift down)] . [(meta n)])
1089 ([(shift left)] . [(meta -)])
1090 ([(shift right)] . [(meta +)])
1091 ([(control shift right)] . [(meta shift +)])
1092 ([(control shift left)] . [(meta shift -)]))
1093 "Keys for which Org-mode and other modes compete.
1094 This is an alist, cars are the default keys, second element specifies
1095 the alternative to use when `org-replace-disputed-keys' is t.
1097 Keys can be specified in any syntax supported by `define-key'.
1098 The value of this option takes effect only at Org-mode's startup,
1099 therefore you'll have to restart Emacs to apply it after changing."
1100 :group 'org-startup
1101 :type 'alist)
1103 (defun org-key (key)
1104 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1105 Or return the original if not disputed.
1106 Also apply the translations defined in `org-xemacs-key-equivalents'."
1107 (when org-replace-disputed-keys
1108 (let* ((nkey (key-description key))
1109 (x (org-find-if (lambda (x)
1110 (equal (key-description (car x)) nkey))
1111 org-disputed-keys)))
1112 (setq key (if x (cdr x) key))))
1113 (when (featurep 'xemacs)
1114 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1115 key)
1117 (defun org-find-if (predicate seq)
1118 (catch 'exit
1119 (while seq
1120 (if (funcall predicate (car seq))
1121 (throw 'exit (car seq))
1122 (pop seq)))))
1124 (defun org-defkey (keymap key def)
1125 "Define a key, possibly translated, as returned by `org-key'."
1126 (define-key keymap (org-key key) def))
1128 (defcustom org-ellipsis nil
1129 "The ellipsis to use in the Org-mode outline.
1130 When nil, just use the standard three dots.
1131 When a string, use that string instead.
1132 When a face, use the standard 3 dots, but with the specified face.
1133 The change affects only Org-mode (which will then use its own display table).
1134 Changing this requires executing \\[org-mode] in a buffer to become
1135 effective."
1136 :group 'org-startup
1137 :type '(choice (const :tag "Default" nil)
1138 (face :tag "Face" :value org-warning)
1139 (string :tag "String" :value "...#")))
1141 (defvar org-display-table nil
1142 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1144 (defgroup org-keywords nil
1145 "Keywords in Org-mode."
1146 :tag "Org Keywords"
1147 :group 'org)
1149 (defcustom org-closed-keep-when-no-todo nil
1150 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1151 :group 'org-todo
1152 :group 'org-keywords
1153 :version "24.4"
1154 :package-version '(Org . "8.0")
1155 :type 'boolean)
1157 (defgroup org-structure nil
1158 "Options concerning the general structure of Org-mode files."
1159 :tag "Org Structure"
1160 :group 'org)
1162 (defgroup org-reveal-location nil
1163 "Options about how to make context of a location visible."
1164 :tag "Org Reveal Location"
1165 :group 'org-structure)
1167 (defconst org-context-choice
1168 '(choice
1169 (const :tag "Always" t)
1170 (const :tag "Never" nil)
1171 (repeat :greedy t :tag "Individual contexts"
1172 (cons
1173 (choice :tag "Context"
1174 (const agenda)
1175 (const org-goto)
1176 (const occur-tree)
1177 (const tags-tree)
1178 (const link-search)
1179 (const mark-goto)
1180 (const bookmark-jump)
1181 (const isearch)
1182 (const default))
1183 (boolean))))
1184 "Contexts for the reveal options.")
1186 (defcustom org-show-hierarchy-above '((default . t))
1187 "Non-nil means show full hierarchy when revealing a location.
1188 Org-mode often shows locations in an org-mode file which might have
1189 been invisible before. When this is set, the hierarchy of headings
1190 above the exposed location is shown.
1191 Turning this off for example for sparse trees makes them very compact.
1192 Instead of t, this can also be an alist specifying this option for different
1193 contexts. Valid contexts are
1194 agenda when exposing an entry from the agenda
1195 org-goto when using the command `org-goto' on key C-c C-j
1196 occur-tree when using the command `org-occur' on key C-c /
1197 tags-tree when constructing a sparse tree based on tags matches
1198 link-search when exposing search matches associated with a link
1199 mark-goto when exposing the jump goal of a mark
1200 bookmark-jump when exposing a bookmark location
1201 isearch when exiting from an incremental search
1202 default default for all contexts not set explicitly"
1203 :group 'org-reveal-location
1204 :type org-context-choice)
1206 (defcustom org-show-following-heading '((default . nil))
1207 "Non-nil means show following heading when revealing a location.
1208 Org-mode often shows locations in an org-mode file which might have
1209 been invisible before. When this is set, the heading following the
1210 match is shown.
1211 Turning this off for example for sparse trees makes them very compact,
1212 but makes it harder to edit the location of the match. In such a case,
1213 use the command \\[org-reveal] to show more context.
1214 Instead of t, this can also be an alist specifying this option for different
1215 contexts. See `org-show-hierarchy-above' for valid contexts."
1216 :group 'org-reveal-location
1217 :type org-context-choice)
1219 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1220 "Non-nil means show all sibling heading when revealing a location.
1221 Org-mode often shows locations in an org-mode file which might have
1222 been invisible before. When this is set, the sibling of the current entry
1223 heading are all made visible. If `org-show-hierarchy-above' is t,
1224 the same happens on each level of the hierarchy above the current entry.
1226 By default this is on for the isearch context, off for all other contexts.
1227 Turning this off for example for sparse trees makes them very compact,
1228 but makes it harder to edit the location of the match. In such a case,
1229 use the command \\[org-reveal] to show more context.
1230 Instead of t, this can also be an alist specifying this option for different
1231 contexts. See `org-show-hierarchy-above' for valid contexts."
1232 :group 'org-reveal-location
1233 :type org-context-choice
1234 :version "24.4"
1235 :package-version '(Org . "8.0"))
1237 (defcustom org-show-entry-below '((default . nil))
1238 "Non-nil means show the entry below a headline when revealing a location.
1239 Org-mode often shows locations in an org-mode file which might have
1240 been invisible before. When this is set, the text below the headline that is
1241 exposed is also shown.
1243 By default this is off for all contexts.
1244 Instead of t, this can also be an alist specifying this option for different
1245 contexts. See `org-show-hierarchy-above' for valid contexts."
1246 :group 'org-reveal-location
1247 :type org-context-choice)
1249 (defcustom org-indirect-buffer-display 'other-window
1250 "How should indirect tree buffers be displayed?
1251 This applies to indirect buffers created with the commands
1252 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1253 Valid values are:
1254 current-window Display in the current window
1255 other-window Just display in another window.
1256 dedicated-frame Create one new frame, and re-use it each time.
1257 new-frame Make a new frame each time. Note that in this case
1258 previously-made indirect buffers are kept, and you need to
1259 kill these buffers yourself."
1260 :group 'org-structure
1261 :group 'org-agenda-windows
1262 :type '(choice
1263 (const :tag "In current window" current-window)
1264 (const :tag "In current frame, other window" other-window)
1265 (const :tag "Each time a new frame" new-frame)
1266 (const :tag "One dedicated frame" dedicated-frame)))
1268 (defcustom org-use-speed-commands nil
1269 "Non-nil means activate single letter commands at beginning of a headline.
1270 This may also be a function to test for appropriate locations where speed
1271 commands should be active.
1273 For example, to activate speed commands when the point is on any
1274 star at the beginning of the headline, you can do this:
1276 (setq org-use-speed-commands
1277 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1278 :group 'org-structure
1279 :type '(choice
1280 (const :tag "Never" nil)
1281 (const :tag "At beginning of headline stars" t)
1282 (function)))
1284 (defcustom org-speed-commands-user nil
1285 "Alist of additional speed commands.
1286 This list will be checked before `org-speed-commands-default'
1287 when the variable `org-use-speed-commands' is non-nil
1288 and when the cursor is at the beginning of a headline.
1289 The car if each entry is a string with a single letter, which must
1290 be assigned to `self-insert-command' in the global map.
1291 The cdr is either a command to be called interactively, a function
1292 to be called, or a form to be evaluated.
1293 An entry that is just a list with a single string will be interpreted
1294 as a descriptive headline that will be added when listing the speed
1295 commands in the Help buffer using the `?' speed command."
1296 :group 'org-structure
1297 :type '(repeat :value ("k" . ignore)
1298 (choice :value ("k" . ignore)
1299 (list :tag "Descriptive Headline" (string :tag "Headline"))
1300 (cons :tag "Letter and Command"
1301 (string :tag "Command letter")
1302 (choice
1303 (function)
1304 (sexp))))))
1306 (defcustom org-bookmark-names-plist
1307 '(:last-capture "org-capture-last-stored"
1308 :last-refile "org-refile-last-stored"
1309 :last-capture-marker "org-capture-last-stored-marker")
1310 "Names for bookmarks automatically set by some Org commands.
1311 This can provide strings as names for a number of bookmarks Org sets
1312 automatically. The following keys are currently implemented:
1313 :last-capture
1314 :last-capture-marker
1315 :last-refile
1316 When a key does not show up in the property list, the corresponding bookmark
1317 is not set."
1318 :group 'org-structure
1319 :type 'plist)
1321 (defgroup org-cycle nil
1322 "Options concerning visibility cycling in Org-mode."
1323 :tag "Org Cycle"
1324 :group 'org-structure)
1326 (defcustom org-cycle-skip-children-state-if-no-children t
1327 "Non-nil means skip CHILDREN state in entries that don't have any."
1328 :group 'org-cycle
1329 :type 'boolean)
1331 (defcustom org-cycle-max-level nil
1332 "Maximum level which should still be subject to visibility cycling.
1333 Levels higher than this will, for cycling, be treated as text, not a headline.
1334 When `org-odd-levels-only' is set, a value of N in this variable actually
1335 means 2N-1 stars as the limiting headline.
1336 When nil, cycle all levels.
1337 Note that the limiting level of cycling is also influenced by
1338 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1339 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1340 than its value."
1341 :group 'org-cycle
1342 :type '(choice
1343 (const :tag "No limit" nil)
1344 (integer :tag "Maximum level")))
1346 (defcustom org-hide-block-startup nil
1347 "Non-nil means entering Org-mode will fold all blocks.
1348 This can also be set in on a per-file basis with
1350 #+STARTUP: hideblocks
1351 #+STARTUP: showblocks"
1352 :group 'org-startup
1353 :group 'org-cycle
1354 :type 'boolean)
1356 (defcustom org-cycle-global-at-bob nil
1357 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1358 This makes it possible to do global cycling without having to use S-TAB or
1359 \\[universal-argument] TAB. For this special case to work, the first line
1360 of the buffer must not be a headline -- it may be empty or some other text.
1361 When used in this way, `org-cycle-hook' is disabled temporarily to make
1362 sure the cursor stays at the beginning of the buffer. When this option is
1363 nil, don't do anything special at the beginning of the buffer."
1364 :group 'org-cycle
1365 :type 'boolean)
1367 (defcustom org-cycle-level-after-item/entry-creation t
1368 "Non-nil means cycle entry level or item indentation in new empty entries.
1370 When the cursor is at the end of an empty headline, i.e., with only stars
1371 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1372 and then all possible ancestor states, before returning to the original state.
1373 This makes data entry extremely fast: M-RET to create a new headline,
1374 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1376 When the cursor is at the end of an empty plain list item, one TAB will
1377 make it a subitem, two or more tabs will back up to make this an item
1378 higher up in the item hierarchy."
1379 :group 'org-cycle
1380 :type 'boolean)
1382 (defcustom org-cycle-emulate-tab t
1383 "Where should `org-cycle' emulate TAB.
1384 nil Never
1385 white Only in completely white lines
1386 whitestart Only at the beginning of lines, before the first non-white char
1387 t Everywhere except in headlines
1388 exc-hl-bol Everywhere except at the start of a headline
1389 If TAB is used in a place where it does not emulate TAB, the current subtree
1390 visibility is cycled."
1391 :group 'org-cycle
1392 :type '(choice (const :tag "Never" nil)
1393 (const :tag "Only in completely white lines" white)
1394 (const :tag "Before first char in a line" whitestart)
1395 (const :tag "Everywhere except in headlines" t)
1396 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1398 (defcustom org-cycle-separator-lines 2
1399 "Number of empty lines needed to keep an empty line between collapsed trees.
1400 If you leave an empty line between the end of a subtree and the following
1401 headline, this empty line is hidden when the subtree is folded.
1402 Org-mode will leave (exactly) one empty line visible if the number of
1403 empty lines is equal or larger to the number given in this variable.
1404 So the default 2 means at least 2 empty lines after the end of a subtree
1405 are needed to produce free space between a collapsed subtree and the
1406 following headline.
1408 If the number is negative, and the number of empty lines is at least -N,
1409 all empty lines are shown.
1411 Special case: when 0, never leave empty lines in collapsed view."
1412 :group 'org-cycle
1413 :type 'integer)
1414 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1416 (defcustom org-pre-cycle-hook nil
1417 "Hook that is run before visibility cycling is happening.
1418 The function(s) in this hook must accept a single argument which indicates
1419 the new state that will be set right after running this hook. The
1420 argument is a symbol. Before a global state change, it can have the values
1421 `overview', `content', or `all'. Before a local state change, it can have
1422 the values `folded', `children', or `subtree'."
1423 :group 'org-cycle
1424 :type 'hook)
1426 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1427 org-cycle-hide-drawers
1428 org-cycle-hide-inline-tasks
1429 org-cycle-show-empty-lines
1430 org-optimize-window-after-visibility-change)
1431 "Hook that is run after `org-cycle' has changed the buffer visibility.
1432 The function(s) in this hook must accept a single argument which indicates
1433 the new state that was set by the most recent `org-cycle' command. The
1434 argument is a symbol. After a global state change, it can have the values
1435 `overview', `contents', or `all'. After a local state change, it can have
1436 the values `folded', `children', or `subtree'."
1437 :group 'org-cycle
1438 :type 'hook)
1440 (defgroup org-edit-structure nil
1441 "Options concerning structure editing in Org-mode."
1442 :tag "Org Edit Structure"
1443 :group 'org-structure)
1445 (defcustom org-odd-levels-only nil
1446 "Non-nil means skip even levels and only use odd levels for the outline.
1447 This has the effect that two stars are being added/taken away in
1448 promotion/demotion commands. It also influences how levels are
1449 handled by the exporters.
1450 Changing it requires restart of `font-lock-mode' to become effective
1451 for fontification also in regions already fontified.
1452 You may also set this on a per-file basis by adding one of the following
1453 lines to the buffer:
1455 #+STARTUP: odd
1456 #+STARTUP: oddeven"
1457 :group 'org-edit-structure
1458 :group 'org-appearance
1459 :type 'boolean)
1461 (defcustom org-adapt-indentation t
1462 "Non-nil means adapt indentation to outline node level.
1464 When this variable is set, Org assumes that you write outlines by
1465 indenting text in each node to align with the headline (after the stars).
1466 The following issues are influenced by this variable:
1468 - When this is set and the *entire* text in an entry is indented, the
1469 indentation is increased by one space in a demotion command, and
1470 decreased by one in a promotion command. If any line in the entry
1471 body starts with text at column 0, indentation is not changed at all.
1473 - Property drawers and planning information is inserted indented when
1474 this variable s set. When nil, they will not be indented.
1476 - TAB indents a line relative to context. The lines below a headline
1477 will be indented when this variable is set.
1479 Note that this is all about true indentation, by adding and removing
1480 space characters. See also `org-indent.el' which does level-dependent
1481 indentation in a virtual way, i.e. at display time in Emacs."
1482 :group 'org-edit-structure
1483 :type 'boolean)
1485 (defcustom org-special-ctrl-a/e nil
1486 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1488 When t, `C-a' will bring back the cursor to the beginning of the
1489 headline text, i.e. after the stars and after a possible TODO
1490 keyword. In an item, this will be the position after bullet and
1491 check-box, if any. When the cursor is already at that position,
1492 another `C-a' will bring it to the beginning of the line.
1494 `C-e' will jump to the end of the headline, ignoring the presence
1495 of tags in the headline. A second `C-e' will then jump to the
1496 true end of the line, after any tags. This also means that, when
1497 this variable is non-nil, `C-e' also will never jump beyond the
1498 end of the heading of a folded section, i.e. not after the
1499 ellipses.
1501 When set to the symbol `reversed', the first `C-a' or `C-e' works
1502 normally, going to the true line boundary first. Only a directly
1503 following, identical keypress will bring the cursor to the
1504 special positions.
1506 This may also be a cons cell where the behavior for `C-a' and
1507 `C-e' is set separately."
1508 :group 'org-edit-structure
1509 :type '(choice
1510 (const :tag "off" nil)
1511 (const :tag "on: after stars/bullet and before tags first" t)
1512 (const :tag "reversed: true line boundary first" reversed)
1513 (cons :tag "Set C-a and C-e separately"
1514 (choice :tag "Special C-a"
1515 (const :tag "off" nil)
1516 (const :tag "on: after stars/bullet first" t)
1517 (const :tag "reversed: before stars/bullet first" reversed))
1518 (choice :tag "Special C-e"
1519 (const :tag "off" nil)
1520 (const :tag "on: before tags first" t)
1521 (const :tag "reversed: after tags first" reversed)))))
1522 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1524 (defcustom org-special-ctrl-k nil
1525 "Non-nil means `C-k' will behave specially in headlines.
1526 When nil, `C-k' will call the default `kill-line' command.
1527 When t, the following will happen while the cursor is in the headline:
1529 - When the cursor is at the beginning of a headline, kill the entire
1530 line and possible the folded subtree below the line.
1531 - When in the middle of the headline text, kill the headline up to the tags.
1532 - When after the headline text, kill the tags."
1533 :group 'org-edit-structure
1534 :type 'boolean)
1536 (defcustom org-ctrl-k-protect-subtree nil
1537 "Non-nil means, do not delete a hidden subtree with C-k.
1538 When set to the symbol `error', simply throw an error when C-k is
1539 used to kill (part-of) a headline that has hidden text behind it.
1540 Any other non-nil value will result in a query to the user, if it is
1541 OK to kill that hidden subtree. When nil, kill without remorse."
1542 :group 'org-edit-structure
1543 :version "24.1"
1544 :type '(choice
1545 (const :tag "Do not protect hidden subtrees" nil)
1546 (const :tag "Protect hidden subtrees with a security query" t)
1547 (const :tag "Never kill a hidden subtree with C-k" error)))
1549 (defcustom org-special-ctrl-o t
1550 "Non-nil means, make `C-o' insert a row in tables."
1551 :group 'org-edit-structure
1552 :type 'boolean)
1554 (defcustom org-catch-invisible-edits nil
1555 "Check if in invisible region before inserting or deleting a character.
1556 Valid values are:
1558 nil Do not check, so just do invisible edits.
1559 error Throw an error and do nothing.
1560 show Make point visible, and do the requested edit.
1561 show-and-error Make point visible, then throw an error and abort the edit.
1562 smart Make point visible, and do insertion/deletion if it is
1563 adjacent to visible text and the change feels predictable.
1564 Never delete a previously invisible character or add in the
1565 middle or right after an invisible region. Basically, this
1566 allows insertion and backward-delete right before ellipses.
1567 FIXME: maybe in this case we should not even show?"
1568 :group 'org-edit-structure
1569 :version "24.1"
1570 :type '(choice
1571 (const :tag "Do not check" nil)
1572 (const :tag "Throw error when trying to edit" error)
1573 (const :tag "Unhide, but do not do the edit" show-and-error)
1574 (const :tag "Show invisible part and do the edit" show)
1575 (const :tag "Be smart and do the right thing" smart)))
1577 (defcustom org-yank-folded-subtrees t
1578 "Non-nil means when yanking subtrees, fold them.
1579 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1580 it starts with a heading and all other headings in it are either children
1581 or siblings, then fold all the subtrees. However, do this only if no
1582 text after the yank would be swallowed into a folded tree by this action."
1583 :group 'org-edit-structure
1584 :type 'boolean)
1586 (defcustom org-yank-adjusted-subtrees nil
1587 "Non-nil means when yanking subtrees, adjust the level.
1588 With this setting, `org-paste-subtree' is used to insert the subtree, see
1589 this function for details."
1590 :group 'org-edit-structure
1591 :type 'boolean)
1593 (defcustom org-M-RET-may-split-line '((default . t))
1594 "Non-nil means M-RET will split the line at the cursor position.
1595 When nil, it will go to the end of the line before making a
1596 new line.
1597 You may also set this option in a different way for different
1598 contexts. Valid contexts are:
1600 headline when creating a new headline
1601 item when creating a new item
1602 table in a table field
1603 default the value to be used for all contexts not explicitly
1604 customized"
1605 :group 'org-structure
1606 :group 'org-table
1607 :type '(choice
1608 (const :tag "Always" t)
1609 (const :tag "Never" nil)
1610 (repeat :greedy t :tag "Individual contexts"
1611 (cons
1612 (choice :tag "Context"
1613 (const headline)
1614 (const item)
1615 (const table)
1616 (const default))
1617 (boolean)))))
1620 (defcustom org-insert-heading-respect-content nil
1621 "Non-nil means insert new headings after the current subtree.
1622 When nil, the new heading is created directly after the current line.
1623 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1624 this variable on for the duration of the command."
1625 :group 'org-structure
1626 :type 'boolean)
1628 (defcustom org-blank-before-new-entry '((heading . auto)
1629 (plain-list-item . auto))
1630 "Should `org-insert-heading' leave a blank line before new heading/item?
1631 The value is an alist, with `heading' and `plain-list-item' as CAR,
1632 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1633 which case Org will look at the surrounding headings/items and try to
1634 make an intelligent decision whether to insert a blank line or not.
1636 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1637 the setting here is ignored and no empty line is inserted to avoid breaking
1638 the list structure."
1639 :group 'org-edit-structure
1640 :type '(list
1641 (cons (const heading)
1642 (choice (const :tag "Never" nil)
1643 (const :tag "Always" t)
1644 (const :tag "Auto" auto)))
1645 (cons (const plain-list-item)
1646 (choice (const :tag "Never" nil)
1647 (const :tag "Always" t)
1648 (const :tag "Auto" auto)))))
1650 (defcustom org-insert-heading-hook nil
1651 "Hook being run after inserting a new heading."
1652 :group 'org-edit-structure
1653 :type 'hook)
1655 (defcustom org-enable-fixed-width-editor t
1656 "Non-nil means lines starting with \":\" are treated as fixed-width.
1657 This currently only means they are never auto-wrapped.
1658 When nil, such lines will be treated like ordinary lines."
1659 :group 'org-edit-structure
1660 :type 'boolean)
1662 (defcustom org-goto-auto-isearch t
1663 "Non-nil means typing characters in `org-goto' starts incremental search.
1664 When nil, you can use these keybindings to navigate the buffer:
1666 q Quit the org-goto interface
1667 n Go to the next visible heading
1668 p Go to the previous visible heading
1669 f Go one heading forward on same level
1670 b Go one heading backward on same level
1671 u Go one heading up"
1672 :group 'org-edit-structure
1673 :type 'boolean)
1675 (defgroup org-sparse-trees nil
1676 "Options concerning sparse trees in Org-mode."
1677 :tag "Org Sparse Trees"
1678 :group 'org-structure)
1680 (defcustom org-highlight-sparse-tree-matches t
1681 "Non-nil means highlight all matches that define a sparse tree.
1682 The highlights will automatically disappear the next time the buffer is
1683 changed by an edit command."
1684 :group 'org-sparse-trees
1685 :type 'boolean)
1687 (defcustom org-remove-highlights-with-change t
1688 "Non-nil means any change to the buffer will remove temporary highlights.
1689 Such highlights are created by `org-occur' and `org-clock-display'.
1690 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1691 The highlights created by `org-toggle-latex-fragment' always need
1692 `C-c C-x C-l' to be removed."
1693 :group 'org-sparse-trees
1694 :group 'org-time
1695 :type 'boolean)
1698 (defcustom org-occur-hook '(org-first-headline-recenter)
1699 "Hook that is run after `org-occur' has constructed a sparse tree.
1700 This can be used to recenter the window to show as much of the structure
1701 as possible."
1702 :group 'org-sparse-trees
1703 :type 'hook)
1705 (defgroup org-imenu-and-speedbar nil
1706 "Options concerning imenu and speedbar in Org-mode."
1707 :tag "Org Imenu and Speedbar"
1708 :group 'org-structure)
1710 (defcustom org-imenu-depth 2
1711 "The maximum level for Imenu access to Org-mode headlines.
1712 This also applied for speedbar access."
1713 :group 'org-imenu-and-speedbar
1714 :type 'integer)
1716 (defgroup org-table nil
1717 "Options concerning tables in Org-mode."
1718 :tag "Org Table"
1719 :group 'org)
1721 (defcustom org-enable-table-editor 'optimized
1722 "Non-nil means lines starting with \"|\" are handled by the table editor.
1723 When nil, such lines will be treated like ordinary lines.
1725 When equal to the symbol `optimized', the table editor will be optimized to
1726 do the following:
1727 - Automatic overwrite mode in front of whitespace in table fields.
1728 This makes the structure of the table stay in tact as long as the edited
1729 field does not exceed the column width.
1730 - Minimize the number of realigns. Normally, the table is aligned each time
1731 TAB or RET are pressed to move to another field. With optimization this
1732 happens only if changes to a field might have changed the column width.
1733 Optimization requires replacing the functions `self-insert-command',
1734 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1735 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1736 very good at guessing when a re-align will be necessary, but you can always
1737 force one with \\[org-ctrl-c-ctrl-c].
1739 If you would like to use the optimized version in Org-mode, but the
1740 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1742 This variable can be used to turn on and off the table editor during a session,
1743 but in order to toggle optimization, a restart is required.
1745 See also the variable `org-table-auto-blank-field'."
1746 :group 'org-table
1747 :type '(choice
1748 (const :tag "off" nil)
1749 (const :tag "on" t)
1750 (const :tag "on, optimized" optimized)))
1752 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1753 (version<= emacs-version "24.1"))
1754 "Non-nil means cluster self-insert commands for undo when possible.
1755 If this is set, then, like in the Emacs command loop, 20 consecutive
1756 characters will be undone together.
1757 This is configurable, because there is some impact on typing performance."
1758 :group 'org-table
1759 :type 'boolean)
1761 (defcustom org-table-tab-recognizes-table.el t
1762 "Non-nil means TAB will automatically notice a table.el table.
1763 When it sees such a table, it moves point into it and - if necessary -
1764 calls `table-recognize-table'."
1765 :group 'org-table-editing
1766 :type 'boolean)
1768 (defgroup org-link nil
1769 "Options concerning links in Org-mode."
1770 :tag "Org Link"
1771 :group 'org)
1773 (defvar org-link-abbrev-alist-local nil
1774 "Buffer-local version of `org-link-abbrev-alist', which see.
1775 The value of this is taken from the #+LINK lines.")
1776 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1778 (defcustom org-link-abbrev-alist nil
1779 "Alist of link abbreviations.
1780 The car of each element is a string, to be replaced at the start of a link.
1781 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1782 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1784 [[linkkey:tag][description]]
1786 The 'linkkey' must be a word word, starting with a letter, followed
1787 by letters, numbers, '-' or '_'.
1789 If REPLACE is a string, the tag will simply be appended to create the link.
1790 If the string contains \"%s\", the tag will be inserted there. If the string
1791 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1792 at that point (see the function `url-hexify-string'). If the string contains
1793 the specifier \"%(my-function)\", then the custom function `my-function' will
1794 be invoked: this function takes the tag as its only argument and must return
1795 a string.
1797 REPLACE may also be a function that will be called with the tag as the
1798 only argument to create the link, which should be returned as a string.
1800 See the manual for examples."
1801 :group 'org-link
1802 :type '(repeat
1803 (cons
1804 (string :tag "Protocol")
1805 (choice
1806 (string :tag "Format")
1807 (function)))))
1809 (defcustom org-descriptive-links t
1810 "Non-nil means Org will display descriptive links.
1811 E.g. [[http://orgmode.org][Org website]] will be displayed as
1812 \"Org Website\", hiding the link itself and just displaying its
1813 description. When set to `nil', Org will display the full links
1814 literally.
1816 You can interactively set the value of this variable by calling
1817 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1818 :group 'org-link
1819 :type 'boolean)
1821 (defcustom org-link-file-path-type 'adaptive
1822 "How the path name in file links should be stored.
1823 Valid values are:
1825 relative Relative to the current directory, i.e. the directory of the file
1826 into which the link is being inserted.
1827 absolute Absolute path, if possible with ~ for home directory.
1828 noabbrev Absolute path, no abbreviation of home directory.
1829 adaptive Use relative path for files in the current directory and sub-
1830 directories of it. For other files, use an absolute path."
1831 :group 'org-link
1832 :type '(choice
1833 (const relative)
1834 (const absolute)
1835 (const noabbrev)
1836 (const adaptive)))
1838 (defvaralias 'org-activate-links 'org-highlight-links)
1839 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1840 "Types of links that should be highlighted in Org-mode files.
1842 This is a list of symbols, each one of them leading to the
1843 highlighting of a certain link type.
1845 You can still open links that are not highlighted.
1847 In principle, it does not hurt to turn on highlighting for all
1848 link types. There may be a small gain when turning off unused
1849 link types. The types are:
1851 bracket The recommended [[link][description]] or [[link]] links with hiding.
1852 angle Links in angular brackets that may contain whitespace like
1853 <bbdb:Carsten Dominik>.
1854 plain Plain links in normal text, no whitespace, like http://google.com.
1855 radio Text that is matched by a radio target, see manual for details.
1856 tag Tag settings in a headline (link to tag search).
1857 date Time stamps (link to calendar).
1858 footnote Footnote labels.
1860 If you set this variable during an Emacs session, use `org-mode-restart'
1861 in the Org buffer so that the change takes effect."
1862 :group 'org-link
1863 :group 'org-appearance
1864 :type '(set :greedy t
1865 (const :tag "Double bracket links" bracket)
1866 (const :tag "Angular bracket links" angle)
1867 (const :tag "Plain text links" plain)
1868 (const :tag "Radio target matches" radio)
1869 (const :tag "Tags" tag)
1870 (const :tag "Timestamps" date)
1871 (const :tag "Footnotes" footnote)))
1873 (defcustom org-make-link-description-function nil
1874 "Function to use for generating link descriptions from links.
1875 When nil, the link location will be used. This function must take
1876 two parameters: the first one is the link, the second one is the
1877 description generated by `org-insert-link'. The function should
1878 return the description to use."
1879 :group 'org-link
1880 :type '(choice (const nil) (function)))
1882 (defgroup org-link-store nil
1883 "Options concerning storing links in Org-mode."
1884 :tag "Org Store Link"
1885 :group 'org-link)
1887 (defcustom org-url-hexify-p t
1888 "When non-nil, hexify URL when creating a link."
1889 :type 'boolean
1890 :version "24.3"
1891 :group 'org-link-store)
1893 (defcustom org-email-link-description-format "Email %c: %.30s"
1894 "Format of the description part of a link to an email or usenet message.
1895 The following %-escapes will be replaced by corresponding information:
1897 %F full \"From\" field
1898 %f name, taken from \"From\" field, address if no name
1899 %T full \"To\" field
1900 %t first name in \"To\" field, address if no name
1901 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1902 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1903 %s subject
1904 %d date
1905 %m message-id.
1907 You may use normal field width specification between the % and the letter.
1908 This is for example useful to limit the length of the subject.
1910 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1911 :group 'org-link-store
1912 :type 'string)
1914 (defcustom org-from-is-user-regexp
1915 (let (r1 r2)
1916 (when (and user-mail-address (not (string= user-mail-address "")))
1917 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1918 (when (and user-full-name (not (string= user-full-name "")))
1919 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1920 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1921 "Regexp matched against the \"From:\" header of an email or usenet message.
1922 It should match if the message is from the user him/herself."
1923 :group 'org-link-store
1924 :type 'regexp)
1926 (defcustom org-context-in-file-links t
1927 "Non-nil means file links from `org-store-link' contain context.
1928 A search string will be added to the file name with :: as separator and
1929 used to find the context when the link is activated by the command
1930 `org-open-at-point'. When this option is t, the entire active region
1931 will be placed in the search string of the file link. If set to a
1932 positive integer, only the first n lines of context will be stored.
1934 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1935 negates this setting for the duration of the command."
1936 :group 'org-link-store
1937 :type '(choice boolean integer))
1939 (defcustom org-keep-stored-link-after-insertion nil
1940 "Non-nil means keep link in list for entire session.
1942 The command `org-store-link' adds a link pointing to the current
1943 location to an internal list. These links accumulate during a session.
1944 The command `org-insert-link' can be used to insert links into any
1945 Org-mode file (offering completion for all stored links). When this
1946 option is nil, every link which has been inserted once using \\[org-insert-link]
1947 will be removed from the list, to make completing the unused links
1948 more efficient."
1949 :group 'org-link-store
1950 :type 'boolean)
1952 (defgroup org-link-follow nil
1953 "Options concerning following links in Org-mode."
1954 :tag "Org Follow Link"
1955 :group 'org-link)
1957 (defcustom org-link-translation-function nil
1958 "Function to translate links with different syntax to Org syntax.
1959 This can be used to translate links created for example by the Planner
1960 or emacs-wiki packages to Org syntax.
1961 The function must accept two parameters, a TYPE containing the link
1962 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1963 which is everything after the link protocol. It should return a cons
1964 with possibly modified values of type and path.
1965 Org contains a function for this, so if you set this variable to
1966 `org-translate-link-from-planner', you should be able follow many
1967 links created by planner."
1968 :group 'org-link-follow
1969 :type '(choice (const nil) (function)))
1971 (defcustom org-follow-link-hook nil
1972 "Hook that is run after a link has been followed."
1973 :group 'org-link-follow
1974 :type 'hook)
1976 (defcustom org-tab-follows-link nil
1977 "Non-nil means on links TAB will follow the link.
1978 Needs to be set before org.el is loaded.
1979 This really should not be used, it does not make sense, and the
1980 implementation is bad."
1981 :group 'org-link-follow
1982 :type 'boolean)
1984 (defcustom org-return-follows-link nil
1985 "Non-nil means on links RET will follow the link.
1986 In tables, the special behavior of RET has precedence."
1987 :group 'org-link-follow
1988 :type 'boolean)
1990 (defcustom org-mouse-1-follows-link
1991 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1992 "Non-nil means mouse-1 on a link will follow the link.
1993 A longer mouse click will still set point. Does not work on XEmacs.
1994 Needs to be set before org.el is loaded."
1995 :group 'org-link-follow
1996 :version "24.4"
1997 :package-version '(Org . "8.3")
1998 :type '(choice
1999 (const :tag "A double click follows the link" double)
2000 (const :tag "Unconditionally follow the link with mouse-1" t)
2001 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2003 (defcustom org-mark-ring-length 4
2004 "Number of different positions to be recorded in the ring.
2005 Changing this requires a restart of Emacs to work correctly."
2006 :group 'org-link-follow
2007 :type 'integer)
2009 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2010 "Non-nil means internal links in Org files must exactly match a headline.
2011 When nil, the link search tries to match a phrase with all words
2012 in the search text."
2013 :group 'org-link-follow
2014 :version "24.1"
2015 :type '(choice
2016 (const :tag "Use fuzzy text search" nil)
2017 (const :tag "Match only exact headline" t)
2018 (const :tag "Match exact headline or query to create it"
2019 query-to-create)))
2021 (defcustom org-link-frame-setup
2022 '((vm . vm-visit-folder-other-frame)
2023 (vm-imap . vm-visit-imap-folder-other-frame)
2024 (gnus . org-gnus-no-new-news)
2025 (file . find-file-other-window)
2026 (wl . wl-other-frame))
2027 "Setup the frame configuration for following links.
2028 When following a link with Emacs, it may often be useful to display
2029 this link in another window or frame. This variable can be used to
2030 set this up for the different types of links.
2031 For VM, use any of
2032 `vm-visit-folder'
2033 `vm-visit-folder-other-window'
2034 `vm-visit-folder-other-frame'
2035 For Gnus, use any of
2036 `gnus'
2037 `gnus-other-frame'
2038 `org-gnus-no-new-news'
2039 For FILE, use any of
2040 `find-file'
2041 `find-file-other-window'
2042 `find-file-other-frame'
2043 For Wanderlust use any of
2044 `wl'
2045 `wl-other-frame'
2046 For the calendar, use the variable `calendar-setup'.
2047 For BBDB, it is currently only possible to display the matches in
2048 another window."
2049 :group 'org-link-follow
2050 :type '(list
2051 (cons (const vm)
2052 (choice
2053 (const vm-visit-folder)
2054 (const vm-visit-folder-other-window)
2055 (const vm-visit-folder-other-frame)))
2056 (cons (const vm-imap)
2057 (choice
2058 (const vm-visit-imap-folder)
2059 (const vm-visit-imap-folder-other-window)
2060 (const vm-visit-imap-folder-other-frame)))
2061 (cons (const gnus)
2062 (choice
2063 (const gnus)
2064 (const gnus-other-frame)
2065 (const org-gnus-no-new-news)))
2066 (cons (const file)
2067 (choice
2068 (const find-file)
2069 (const find-file-other-window)
2070 (const find-file-other-frame)))
2071 (cons (const wl)
2072 (choice
2073 (const wl)
2074 (const wl-other-frame)))))
2076 (defcustom org-display-internal-link-with-indirect-buffer nil
2077 "Non-nil means use indirect buffer to display infile links.
2078 Activating internal links (from one location in a file to another location
2079 in the same file) normally just jumps to the location. When the link is
2080 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2081 is displayed in
2082 another window. When this option is set, the other window actually displays
2083 an indirect buffer clone of the current buffer, to avoid any visibility
2084 changes to the current buffer."
2085 :group 'org-link-follow
2086 :type 'boolean)
2088 (defcustom org-open-non-existing-files nil
2089 "Non-nil means `org-open-file' will open non-existing files.
2090 When nil, an error will be generated.
2091 This variable applies only to external applications because they
2092 might choke on non-existing files. If the link is to a file that
2093 will be opened in Emacs, the variable is ignored."
2094 :group 'org-link-follow
2095 :type 'boolean)
2097 (defcustom org-open-directory-means-index-dot-org nil
2098 "Non-nil means a link to a directory really means to index.org.
2099 When nil, following a directory link will run dired or open a finder/explorer
2100 window on that directory."
2101 :group 'org-link-follow
2102 :type 'boolean)
2104 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2105 "Non-nil means ask for confirmation before executing shell links.
2106 Shell links can be dangerous: just think about a link
2108 [[shell:rm -rf ~/*][Google Search]]
2110 This link would show up in your Org-mode document as \"Google Search\",
2111 but really it would remove your entire home directory.
2112 Therefore we advise against setting this variable to nil.
2113 Just change it to `y-or-n-p' if you want to confirm with a
2114 single keystroke rather than having to type \"yes\"."
2115 :group 'org-link-follow
2116 :type '(choice
2117 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2118 (const :tag "with y-or-n (faster)" y-or-n-p)
2119 (const :tag "no confirmation (dangerous)" nil)))
2120 (put 'org-confirm-shell-link-function
2121 'safe-local-variable
2122 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2124 (defcustom org-confirm-shell-link-not-regexp ""
2125 "A regexp to skip confirmation for shell links."
2126 :group 'org-link-follow
2127 :version "24.1"
2128 :type 'regexp)
2130 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2131 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2132 Elisp links can be dangerous: just think about a link
2134 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2136 This link would show up in your Org-mode document as \"Google Search\",
2137 but really it would remove your entire home directory.
2138 Therefore we advise against setting this variable to nil.
2139 Just change it to `y-or-n-p' if you want to confirm with a
2140 single keystroke rather than having to type \"yes\"."
2141 :group 'org-link-follow
2142 :type '(choice
2143 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2144 (const :tag "with y-or-n (faster)" y-or-n-p)
2145 (const :tag "no confirmation (dangerous)" nil)))
2146 (put 'org-confirm-shell-link-function
2147 'safe-local-variable
2148 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2150 (defcustom org-confirm-elisp-link-not-regexp ""
2151 "A regexp to skip confirmation for Elisp links."
2152 :group 'org-link-follow
2153 :version "24.1"
2154 :type 'regexp)
2156 (defconst org-file-apps-defaults-gnu
2157 '((remote . emacs)
2158 (system . mailcap)
2159 (t . mailcap))
2160 "Default file applications on a UNIX or GNU/Linux system.
2161 See `org-file-apps'.")
2163 (defconst org-file-apps-defaults-macosx
2164 '((remote . emacs)
2165 (t . "open %s")
2166 (system . "open %s")
2167 ("ps.gz" . "gv %s")
2168 ("eps.gz" . "gv %s")
2169 ("dvi" . "xdvi %s")
2170 ("fig" . "xfig %s"))
2171 "Default file applications on a MacOS X system.
2172 The system \"open\" is known as a default, but we use X11 applications
2173 for some files for which the OS does not have a good default.
2174 See `org-file-apps'.")
2176 (defconst org-file-apps-defaults-windowsnt
2177 (list
2178 '(remote . emacs)
2179 (cons t
2180 (list (if (featurep 'xemacs)
2181 'mswindows-shell-execute
2182 'w32-shell-execute)
2183 "open" 'file))
2184 (cons 'system
2185 (list (if (featurep 'xemacs)
2186 'mswindows-shell-execute
2187 'w32-shell-execute)
2188 "open" 'file)))
2189 "Default file applications on a Windows NT system.
2190 The system \"open\" is used for most files.
2191 See `org-file-apps'.")
2193 (defcustom org-file-apps
2194 '((auto-mode . emacs)
2195 ("\\.mm\\'" . default)
2196 ("\\.x?html?\\'" . default)
2197 ("\\.pdf\\'" . default))
2198 "External applications for opening `file:path' items in a document.
2199 Org-mode uses system defaults for different file types, but
2200 you can use this variable to set the application for a given file
2201 extension. The entries in this list are cons cells where the car identifies
2202 files and the cdr the corresponding command. Possible values for the
2203 file identifier are
2204 \"string\" A string as a file identifier can be interpreted in different
2205 ways, depending on its contents:
2207 - Alphanumeric characters only:
2208 Match links with this file extension.
2209 Example: (\"pdf\" . \"evince %s\")
2210 to open PDFs with evince.
2212 - Regular expression: Match links where the
2213 filename matches the regexp. If you want to
2214 use groups here, use shy groups.
2216 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2217 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2218 to open *.html and *.xhtml with firefox.
2220 - Regular expression which contains (non-shy) groups:
2221 Match links where the whole link, including \"::\", and
2222 anything after that, matches the regexp.
2223 In a custom command string, %1, %2, etc. are replaced with
2224 the parts of the link that were matched by the groups.
2225 For backwards compatibility, if a command string is given
2226 that does not use any of the group matches, this case is
2227 handled identically to the second one (i.e. match against
2228 file name only).
2229 In a custom lisp form, you can access the group matches with
2230 (match-string n link).
2232 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2233 to open [[file:document.pdf::5]] with evince at page 5.
2235 `directory' Matches a directory
2236 `remote' Matches a remote file, accessible through tramp or efs.
2237 Remote files most likely should be visited through Emacs
2238 because external applications cannot handle such paths.
2239 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2240 so all files Emacs knows how to handle. Using this with
2241 command `emacs' will open most files in Emacs. Beware that this
2242 will also open html files inside Emacs, unless you add
2243 (\"html\" . default) to the list as well.
2244 t Default for files not matched by any of the other options.
2245 `system' The system command to open files, like `open' on Windows
2246 and Mac OS X, and mailcap under GNU/Linux. This is the command
2247 that will be selected if you call `C-c C-o' with a double
2248 \\[universal-argument] \\[universal-argument] prefix.
2250 Possible values for the command are:
2251 `emacs' The file will be visited by the current Emacs process.
2252 `default' Use the default application for this file type, which is the
2253 association for t in the list, most likely in the system-specific
2254 part.
2255 This can be used to overrule an unwanted setting in the
2256 system-specific variable.
2257 `system' Use the system command for opening files, like \"open\".
2258 This command is specified by the entry whose car is `system'.
2259 Most likely, the system-specific version of this variable
2260 does define this command, but you can overrule/replace it
2261 here.
2262 string A command to be executed by a shell; %s will be replaced
2263 by the path to the file.
2264 sexp A Lisp form which will be evaluated. The file path will
2265 be available in the Lisp variable `file'.
2266 For more examples, see the system specific constants
2267 `org-file-apps-defaults-macosx'
2268 `org-file-apps-defaults-windowsnt'
2269 `org-file-apps-defaults-gnu'."
2270 :group 'org-link-follow
2271 :type '(repeat
2272 (cons (choice :value ""
2273 (string :tag "Extension")
2274 (const :tag "System command to open files" system)
2275 (const :tag "Default for unrecognized files" t)
2276 (const :tag "Remote file" remote)
2277 (const :tag "Links to a directory" directory)
2278 (const :tag "Any files that have Emacs modes"
2279 auto-mode))
2280 (choice :value ""
2281 (const :tag "Visit with Emacs" emacs)
2282 (const :tag "Use default" default)
2283 (const :tag "Use the system command" system)
2284 (string :tag "Command")
2285 (sexp :tag "Lisp form")))))
2287 (defcustom org-doi-server-url "http://dx.doi.org/"
2288 "The URL of the DOI server."
2289 :type 'string
2290 :version "24.3"
2291 :group 'org-link-follow)
2293 (defgroup org-refile nil
2294 "Options concerning refiling entries in Org-mode."
2295 :tag "Org Refile"
2296 :group 'org)
2298 (defcustom org-directory "~/org"
2299 "Directory with org files.
2300 This is just a default location to look for Org files. There is no need
2301 at all to put your files into this directory. It is only used in the
2302 following situations:
2304 1. When a capture template specifies a target file that is not an
2305 absolute path. The path will then be interpreted relative to
2306 `org-directory'
2307 2. When a capture note is filed away in an interactive way (when exiting the
2308 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2309 with `org-directory' as the default path."
2310 :group 'org-refile
2311 :group 'org-capture
2312 :type 'directory)
2314 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2315 "Default target for storing notes.
2316 Used as a fall back file for org-capture.el, for templates that
2317 do not specify a target file."
2318 :group 'org-refile
2319 :group 'org-capture
2320 :type '(choice
2321 (const :tag "Default from remember-data-file" nil)
2322 file))
2324 (defcustom org-goto-interface 'outline
2325 "The default interface to be used for `org-goto'.
2326 Allowed values are:
2327 outline The interface shows an outline of the relevant file
2328 and the correct heading is found by moving through
2329 the outline or by searching with incremental search.
2330 outline-path-completion Headlines in the current buffer are offered via
2331 completion. This is the interface also used by
2332 the refile command."
2333 :group 'org-refile
2334 :type '(choice
2335 (const :tag "Outline" outline)
2336 (const :tag "Outline-path-completion" outline-path-completion)))
2338 (defcustom org-goto-max-level 5
2339 "Maximum target level when running `org-goto' with refile interface."
2340 :group 'org-refile
2341 :type 'integer)
2343 (defcustom org-reverse-note-order nil
2344 "Non-nil means store new notes at the beginning of a file or entry.
2345 When nil, new notes will be filed to the end of a file or entry.
2346 This can also be a list with cons cells of regular expressions that
2347 are matched against file names, and values."
2348 :group 'org-capture
2349 :group 'org-refile
2350 :type '(choice
2351 (const :tag "Reverse always" t)
2352 (const :tag "Reverse never" nil)
2353 (repeat :tag "By file name regexp"
2354 (cons regexp boolean))))
2356 (defcustom org-log-refile nil
2357 "Information to record when a task is refiled.
2359 Possible values are:
2361 nil Don't add anything
2362 time Add a time stamp to the task
2363 note Prompt for a note and add it with template `org-log-note-headings'
2365 This option can also be set with on a per-file-basis with
2367 #+STARTUP: nologrefile
2368 #+STARTUP: logrefile
2369 #+STARTUP: lognoterefile
2371 You can have local logging settings for a subtree by setting the LOGGING
2372 property to one or more of these keywords.
2374 When bulk-refiling from the agenda, the value `note' is forbidden and
2375 will temporarily be changed to `time'."
2376 :group 'org-refile
2377 :group 'org-progress
2378 :version "24.1"
2379 :type '(choice
2380 (const :tag "No logging" nil)
2381 (const :tag "Record timestamp" time)
2382 (const :tag "Record timestamp with note." note)))
2384 (defcustom org-refile-targets nil
2385 "Targets for refiling entries with \\[org-refile].
2386 This is a list of cons cells. Each cell contains:
2387 - a specification of the files to be considered, either a list of files,
2388 or a symbol whose function or variable value will be used to retrieve
2389 a file name or a list of file names. If you use `org-agenda-files' for
2390 that, all agenda files will be scanned for targets. Nil means consider
2391 headings in the current buffer.
2392 - A specification of how to find candidate refile targets. This may be
2393 any of:
2394 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2395 This tag has to be present in all target headlines, inheritance will
2396 not be considered.
2397 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2398 todo keyword.
2399 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2400 headlines that are refiling targets.
2401 - a cons cell (:level . N). Any headline of level N is considered a target.
2402 Note that, when `org-odd-levels-only' is set, level corresponds to
2403 order in hierarchy, not to the number of stars.
2404 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2405 Note that, when `org-odd-levels-only' is set, level corresponds to
2406 order in hierarchy, not to the number of stars.
2408 Each element of this list generates a set of possible targets.
2409 The union of these sets is presented (with completion) to
2410 the user by `org-refile'.
2412 You can set the variable `org-refile-target-verify-function' to a function
2413 to verify each headline found by the simple criteria above.
2415 When this variable is nil, all top-level headlines in the current buffer
2416 are used, equivalent to the value `((nil . (:level . 1))'."
2417 :group 'org-refile
2418 :type '(repeat
2419 (cons
2420 (choice :value org-agenda-files
2421 (const :tag "All agenda files" org-agenda-files)
2422 (const :tag "Current buffer" nil)
2423 (function) (variable) (file))
2424 (choice :tag "Identify target headline by"
2425 (cons :tag "Specific tag" (const :value :tag) (string))
2426 (cons :tag "TODO keyword" (const :value :todo) (string))
2427 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2428 (cons :tag "Level number" (const :value :level) (integer))
2429 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2431 (defcustom org-refile-target-verify-function nil
2432 "Function to verify if the headline at point should be a refile target.
2433 The function will be called without arguments, with point at the
2434 beginning of the headline. It should return t and leave point
2435 where it is if the headline is a valid target for refiling.
2437 If the target should not be selected, the function must return nil.
2438 In addition to this, it may move point to a place from where the search
2439 should be continued. For example, the function may decide that the entire
2440 subtree of the current entry should be excluded and move point to the end
2441 of the subtree."
2442 :group 'org-refile
2443 :type '(choice
2444 (const nil)
2445 (function)))
2447 (defcustom org-refile-use-cache nil
2448 "Non-nil means cache refile targets to speed up the process.
2449 The cache for a particular file will be updated automatically when
2450 the buffer has been killed, or when any of the marker used for flagging
2451 refile targets no longer points at a live buffer.
2452 If you have added new entries to a buffer that might themselves be targets,
2453 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2454 find that easier, `C-u C-u C-u C-c C-w'."
2455 :group 'org-refile
2456 :version "24.1"
2457 :type 'boolean)
2459 (defcustom org-refile-use-outline-path nil
2460 "Non-nil means provide refile targets as paths.
2461 So a level 3 headline will be available as level1/level2/level3.
2463 When the value is `file', also include the file name (without directory)
2464 into the path. In this case, you can also stop the completion after
2465 the file name, to get entries inserted as top level in the file.
2467 When `full-file-path', include the full file path."
2468 :group 'org-refile
2469 :type '(choice
2470 (const :tag "Not" nil)
2471 (const :tag "Yes" t)
2472 (const :tag "Start with file name" file)
2473 (const :tag "Start with full file path" full-file-path)))
2475 (defcustom org-outline-path-complete-in-steps t
2476 "Non-nil means complete the outline path in hierarchical steps.
2477 When Org-mode uses the refile interface to select an outline path
2478 \(see variable `org-refile-use-outline-path'), the completion of
2479 the path can be done is a single go, or if can be done in steps down
2480 the headline hierarchy. Going in steps is probably the best if you
2481 do not use a special completion package like `ido' or `icicles'.
2482 However, when using these packages, going in one step can be very
2483 fast, while still showing the whole path to the entry."
2484 :group 'org-refile
2485 :type 'boolean)
2487 (defcustom org-refile-allow-creating-parent-nodes nil
2488 "Non-nil means allow to create new nodes as refile targets.
2489 New nodes are then created by adding \"/new node name\" to the completion
2490 of an existing node. When the value of this variable is `confirm',
2491 new node creation must be confirmed by the user (recommended).
2492 When nil, the completion must match an existing entry.
2494 Note that, if the new heading is not seen by the criteria
2495 listed in `org-refile-targets', multiple instances of the same
2496 heading would be created by trying again to file under the new
2497 heading."
2498 :group 'org-refile
2499 :type '(choice
2500 (const :tag "Never" nil)
2501 (const :tag "Always" t)
2502 (const :tag "Prompt for confirmation" confirm)))
2504 (defcustom org-refile-active-region-within-subtree nil
2505 "Non-nil means also refile active region within a subtree.
2507 By default `org-refile' doesn't allow refiling regions if they
2508 don't contain a set of subtrees, but it might be convenient to
2509 do so sometimes: in that case, the first line of the region is
2510 converted to a headline before refiling."
2511 :group 'org-refile
2512 :version "24.1"
2513 :type 'boolean)
2515 (defgroup org-todo nil
2516 "Options concerning TODO items in Org-mode."
2517 :tag "Org TODO"
2518 :group 'org)
2520 (defgroup org-progress nil
2521 "Options concerning Progress logging in Org-mode."
2522 :tag "Org Progress"
2523 :group 'org-time)
2525 (defvar org-todo-interpretation-widgets
2526 '((:tag "Sequence (cycling hits every state)" sequence)
2527 (:tag "Type (cycling directly to DONE)" type))
2528 "The available interpretation symbols for customizing `org-todo-keywords'.
2529 Interested libraries should add to this list.")
2531 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2532 "List of TODO entry keyword sequences and their interpretation.
2533 \\<org-mode-map>This is a list of sequences.
2535 Each sequence starts with a symbol, either `sequence' or `type',
2536 indicating if the keywords should be interpreted as a sequence of
2537 action steps, or as different types of TODO items. The first
2538 keywords are states requiring action - these states will select a headline
2539 for inclusion into the global TODO list Org-mode produces. If one of
2540 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2541 signify that no further action is necessary. If \"|\" is not found,
2542 the last keyword is treated as the only DONE state of the sequence.
2544 The command \\[org-todo] cycles an entry through these states, and one
2545 additional state where no keyword is present. For details about this
2546 cycling, see the manual.
2548 TODO keywords and interpretation can also be set on a per-file basis with
2549 the special #+SEQ_TODO and #+TYP_TODO lines.
2551 Each keyword can optionally specify a character for fast state selection
2552 \(in combination with the variable `org-use-fast-todo-selection')
2553 and specifiers for state change logging, using the same syntax that
2554 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2555 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2556 indicates to record a time stamp each time this state is selected.
2558 Each keyword may also specify if a timestamp or a note should be
2559 recorded when entering or leaving the state, by adding additional
2560 characters in the parenthesis after the keyword. This looks like this:
2561 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2562 record only the time of the state change. With X and Y being either
2563 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2564 Y when leaving the state if and only if the *target* state does not
2565 define X. You may omit any of the fast-selection key or X or /Y,
2566 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2568 For backward compatibility, this variable may also be just a list
2569 of keywords. In this case the interpretation (sequence or type) will be
2570 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2571 :group 'org-todo
2572 :group 'org-keywords
2573 :type '(choice
2574 (repeat :tag "Old syntax, just keywords"
2575 (string :tag "Keyword"))
2576 (repeat :tag "New syntax"
2577 (cons
2578 (choice
2579 :tag "Interpretation"
2580 ;;Quick and dirty way to see
2581 ;;`org-todo-interpretations'. This takes the
2582 ;;place of item arguments
2583 :convert-widget
2584 (lambda (widget)
2585 (widget-put widget
2586 :args (mapcar
2587 (lambda (x)
2588 (widget-convert
2589 (cons 'const x)))
2590 org-todo-interpretation-widgets))
2591 widget))
2592 (repeat
2593 (string :tag "Keyword"))))))
2595 (defvar org-todo-keywords-1 nil
2596 "All TODO and DONE keywords active in a buffer.")
2597 (make-variable-buffer-local 'org-todo-keywords-1)
2598 (defvar org-todo-keywords-for-agenda nil)
2599 (defvar org-done-keywords-for-agenda nil)
2600 (defvar org-todo-keyword-alist-for-agenda nil)
2601 (defvar org-tag-alist-for-agenda nil
2602 "Alist of all tags from all agenda files.")
2603 (defvar org-tag-groups-alist-for-agenda nil
2604 "Alist of all groups tags from all current agenda files.")
2605 (defvar org-tag-groups-alist nil)
2606 (make-variable-buffer-local 'org-tag-groups-alist)
2607 (defvar org-agenda-contributing-files nil)
2608 (defvar org-not-done-keywords nil)
2609 (make-variable-buffer-local 'org-not-done-keywords)
2610 (defvar org-done-keywords nil)
2611 (make-variable-buffer-local 'org-done-keywords)
2612 (defvar org-todo-heads nil)
2613 (make-variable-buffer-local 'org-todo-heads)
2614 (defvar org-todo-sets nil)
2615 (make-variable-buffer-local 'org-todo-sets)
2616 (defvar org-todo-log-states nil)
2617 (make-variable-buffer-local 'org-todo-log-states)
2618 (defvar org-todo-kwd-alist nil)
2619 (make-variable-buffer-local 'org-todo-kwd-alist)
2620 (defvar org-todo-key-alist nil)
2621 (make-variable-buffer-local 'org-todo-key-alist)
2622 (defvar org-todo-key-trigger nil)
2623 (make-variable-buffer-local 'org-todo-key-trigger)
2625 (defcustom org-todo-interpretation 'sequence
2626 "Controls how TODO keywords are interpreted.
2627 This variable is in principle obsolete and is only used for
2628 backward compatibility, if the interpretation of todo keywords is
2629 not given already in `org-todo-keywords'. See that variable for
2630 more information."
2631 :group 'org-todo
2632 :group 'org-keywords
2633 :type '(choice (const sequence)
2634 (const type)))
2636 (defcustom org-use-fast-todo-selection t
2637 "Non-nil means use the fast todo selection scheme with C-c C-t.
2638 This variable describes if and under what circumstances the cycling
2639 mechanism for TODO keywords will be replaced by a single-key, direct
2640 selection scheme.
2642 When nil, fast selection is never used.
2644 When the symbol `prefix', it will be used when `org-todo' is called
2645 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2646 `C-u t' in an agenda buffer.
2648 When t, fast selection is used by default. In this case, the prefix
2649 argument forces cycling instead.
2651 In all cases, the special interface is only used if access keys have
2652 actually been assigned by the user, i.e. if keywords in the configuration
2653 are followed by a letter in parenthesis, like TODO(t)."
2654 :group 'org-todo
2655 :type '(choice
2656 (const :tag "Never" nil)
2657 (const :tag "By default" t)
2658 (const :tag "Only with C-u C-c C-t" prefix)))
2660 (defcustom org-provide-todo-statistics t
2661 "Non-nil means update todo statistics after insert and toggle.
2662 ALL-HEADLINES means update todo statistics by including headlines
2663 with no TODO keyword as well, counting them as not done.
2664 A list of TODO keywords means the same, but skip keywords that are
2665 not in this list.
2666 When set to a list of two lists, the first list contains keywords
2667 to consider as TODO keywords, the second list contains keywords
2668 to consider as DONE keywords.
2670 When this is set, todo statistics is updated in the parent of the
2671 current entry each time a todo state is changed."
2672 :group 'org-todo
2673 :type '(choice
2674 (const :tag "Yes, only for TODO entries" t)
2675 (const :tag "Yes, including all entries" all-headlines)
2676 (repeat :tag "Yes, for TODOs in this list"
2677 (string :tag "TODO keyword"))
2678 (list :tag "Yes, for TODOs and DONEs in these lists"
2679 (repeat (string :tag "TODO keyword"))
2680 (repeat (string :tag "DONE keyword")))
2681 (other :tag "No TODO statistics" nil)))
2683 (defcustom org-hierarchical-todo-statistics t
2684 "Non-nil means TODO statistics covers just direct children.
2685 When nil, all entries in the subtree are considered.
2686 This has only an effect if `org-provide-todo-statistics' is set.
2687 To set this to nil for only a single subtree, use a COOKIE_DATA
2688 property and include the word \"recursive\" into the value."
2689 :group 'org-todo
2690 :type 'boolean)
2692 (defcustom org-after-todo-state-change-hook nil
2693 "Hook which is run after the state of a TODO item was changed.
2694 The new state (a string with a TODO keyword, or nil) is available in the
2695 Lisp variable `org-state'."
2696 :group 'org-todo
2697 :type 'hook)
2699 (defvar org-blocker-hook nil
2700 "Hook for functions that are allowed to block a state change.
2702 Functions in this hook should not modify the buffer.
2703 Each function gets as its single argument a property list,
2704 see `org-trigger-hook' for more information about this list.
2706 If any of the functions in this hook returns nil, the state change
2707 is blocked.")
2709 (defvar org-trigger-hook nil
2710 "Hook for functions that are triggered by a state change.
2712 Each function gets as its single argument a property list with at
2713 least the following elements:
2715 (:type type-of-change :position pos-at-entry-start
2716 :from old-state :to new-state)
2718 Depending on the type, more properties may be present.
2720 This mechanism is currently implemented for:
2722 TODO state changes
2723 ------------------
2724 :type todo-state-change
2725 :from previous state (keyword as a string), or nil, or a symbol
2726 'todo' or 'done', to indicate the general type of state.
2727 :to new state, like in :from")
2729 (defcustom org-enforce-todo-dependencies nil
2730 "Non-nil means undone TODO entries will block switching the parent to DONE.
2731 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2732 be blocked if any prior sibling is not yet done.
2733 Finally, if the parent is blocked because of ordered siblings of its own,
2734 the child will also be blocked."
2735 :set (lambda (var val)
2736 (set var val)
2737 (if val
2738 (add-hook 'org-blocker-hook
2739 'org-block-todo-from-children-or-siblings-or-parent)
2740 (remove-hook 'org-blocker-hook
2741 'org-block-todo-from-children-or-siblings-or-parent)))
2742 :group 'org-todo
2743 :type 'boolean)
2745 (defcustom org-enforce-todo-checkbox-dependencies nil
2746 "Non-nil means unchecked boxes will block switching the parent to DONE.
2747 When this is nil, checkboxes have no influence on switching TODO states.
2748 When non-nil, you first need to check off all check boxes before the TODO
2749 entry can be switched to DONE.
2750 This variable needs to be set before org.el is loaded, and you need to
2751 restart Emacs after a change to make the change effective. The only way
2752 to change is while Emacs is running is through the customize interface."
2753 :set (lambda (var val)
2754 (set var val)
2755 (if val
2756 (add-hook 'org-blocker-hook
2757 'org-block-todo-from-checkboxes)
2758 (remove-hook 'org-blocker-hook
2759 'org-block-todo-from-checkboxes)))
2760 :group 'org-todo
2761 :type 'boolean)
2763 (defcustom org-treat-insert-todo-heading-as-state-change nil
2764 "Non-nil means inserting a TODO heading is treated as state change.
2765 So when the command \\[org-insert-todo-heading] is used, state change
2766 logging will apply if appropriate. When nil, the new TODO item will
2767 be inserted directly, and no logging will take place."
2768 :group 'org-todo
2769 :type 'boolean)
2771 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2772 "Non-nil means switching TODO states with S-cursor counts as state change.
2773 This is the default behavior. However, setting this to nil allows a
2774 convenient way to select a TODO state and bypass any logging associated
2775 with that."
2776 :group 'org-todo
2777 :type 'boolean)
2779 (defcustom org-todo-state-tags-triggers nil
2780 "Tag changes that should be triggered by TODO state changes.
2781 This is a list. Each entry is
2783 (state-change (tag . flag) .......)
2785 State-change can be a string with a state, and empty string to indicate the
2786 state that has no TODO keyword, or it can be one of the symbols `todo'
2787 or `done', meaning any not-done or done state, respectively."
2788 :group 'org-todo
2789 :group 'org-tags
2790 :type '(repeat
2791 (cons (choice :tag "When changing to"
2792 (const :tag "Not-done state" todo)
2793 (const :tag "Done state" done)
2794 (string :tag "State"))
2795 (repeat
2796 (cons :tag "Tag action"
2797 (string :tag "Tag")
2798 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2800 (defcustom org-log-done nil
2801 "Information to record when a task moves to the DONE state.
2803 Possible values are:
2805 nil Don't add anything, just change the keyword
2806 time Add a time stamp to the task
2807 note Prompt for a note and add it with template `org-log-note-headings'
2809 This option can also be set with on a per-file-basis with
2811 #+STARTUP: nologdone
2812 #+STARTUP: logdone
2813 #+STARTUP: lognotedone
2815 You can have local logging settings for a subtree by setting the LOGGING
2816 property to one or more of these keywords."
2817 :group 'org-todo
2818 :group 'org-progress
2819 :type '(choice
2820 (const :tag "No logging" nil)
2821 (const :tag "Record CLOSED timestamp" time)
2822 (const :tag "Record CLOSED timestamp with note." note)))
2824 ;; Normalize old uses of org-log-done.
2825 (cond
2826 ((eq org-log-done t) (setq org-log-done 'time))
2827 ((and (listp org-log-done) (memq 'done org-log-done))
2828 (setq org-log-done 'note)))
2830 (defcustom org-log-reschedule nil
2831 "Information to record when the scheduling date of a tasks is modified.
2833 Possible values are:
2835 nil Don't add anything, just change the date
2836 time Add a time stamp to the task
2837 note Prompt for a note and add it with template `org-log-note-headings'
2839 This option can also be set with on a per-file-basis with
2841 #+STARTUP: nologreschedule
2842 #+STARTUP: logreschedule
2843 #+STARTUP: lognotereschedule"
2844 :group 'org-todo
2845 :group 'org-progress
2846 :type '(choice
2847 (const :tag "No logging" nil)
2848 (const :tag "Record timestamp" time)
2849 (const :tag "Record timestamp with note." note)))
2851 (defcustom org-log-redeadline nil
2852 "Information to record when the deadline date of a tasks is modified.
2854 Possible values are:
2856 nil Don't add anything, just change the date
2857 time Add a time stamp to the task
2858 note Prompt for a note and add it with template `org-log-note-headings'
2860 This option can also be set with on a per-file-basis with
2862 #+STARTUP: nologredeadline
2863 #+STARTUP: logredeadline
2864 #+STARTUP: lognoteredeadline
2866 You can have local logging settings for a subtree by setting the LOGGING
2867 property to one or more of these keywords."
2868 :group 'org-todo
2869 :group 'org-progress
2870 :type '(choice
2871 (const :tag "No logging" nil)
2872 (const :tag "Record timestamp" time)
2873 (const :tag "Record timestamp with note." note)))
2875 (defcustom org-log-note-clock-out nil
2876 "Non-nil means record a note when clocking out of an item.
2877 This can also be configured on a per-file basis by adding one of
2878 the following lines anywhere in the buffer:
2880 #+STARTUP: lognoteclock-out
2881 #+STARTUP: nolognoteclock-out"
2882 :group 'org-todo
2883 :group 'org-progress
2884 :type 'boolean)
2886 (defcustom org-log-done-with-time t
2887 "Non-nil means the CLOSED time stamp will contain date and time.
2888 When nil, only the date will be recorded."
2889 :group 'org-progress
2890 :type 'boolean)
2892 (defcustom org-log-note-headings
2893 '((done . "CLOSING NOTE %t")
2894 (state . "State %-12s from %-12S %t")
2895 (note . "Note taken on %t")
2896 (reschedule . "Rescheduled from %S on %t")
2897 (delschedule . "Not scheduled, was %S on %t")
2898 (redeadline . "New deadline from %S on %t")
2899 (deldeadline . "Removed deadline, was %S on %t")
2900 (refile . "Refiled on %t")
2901 (clock-out . ""))
2902 "Headings for notes added to entries.
2903 The value is an alist, with the car being a symbol indicating the note
2904 context, and the cdr is the heading to be used. The heading may also be the
2905 empty string.
2906 %t in the heading will be replaced by a time stamp.
2907 %T will be an active time stamp instead the default inactive one
2908 %d will be replaced by a short-format time stamp.
2909 %D will be replaced by an active short-format time stamp.
2910 %s will be replaced by the new TODO state, in double quotes.
2911 %S will be replaced by the old TODO state, in double quotes.
2912 %u will be replaced by the user name.
2913 %U will be replaced by the full user name.
2915 In fact, it is not a good idea to change the `state' entry, because
2916 agenda log mode depends on the format of these entries."
2917 :group 'org-todo
2918 :group 'org-progress
2919 :type '(list :greedy t
2920 (cons (const :tag "Heading when closing an item" done) string)
2921 (cons (const :tag
2922 "Heading when changing todo state (todo sequence only)"
2923 state) string)
2924 (cons (const :tag "Heading when just taking a note" note) string)
2925 (cons (const :tag "Heading when rescheduling" reschedule) string)
2926 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2927 (cons (const :tag "Heading when changing deadline" redeadline) string)
2928 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2929 (cons (const :tag "Heading when refiling" refile) string)
2930 (cons (const :tag "Heading when clocking out" clock-out) string)))
2932 (unless (assq 'note org-log-note-headings)
2933 (push '(note . "%t") org-log-note-headings))
2935 (defcustom org-log-into-drawer nil
2936 "Non-nil means insert state change notes and time stamps into a drawer.
2937 When nil, state changes notes will be inserted after the headline and
2938 any scheduling and clock lines, but not inside a drawer.
2940 The value of this variable should be the name of the drawer to use.
2941 LOGBOOK is proposed as the default drawer for this purpose, you can
2942 also set this to a string to define the drawer of your choice.
2944 A value of t is also allowed, representing \"LOGBOOK\".
2946 A value of t or nil can also be set with on a per-file-basis with
2948 #+STARTUP: logdrawer
2949 #+STARTUP: nologdrawer
2951 If this variable is set, `org-log-state-notes-insert-after-drawers'
2952 will be ignored.
2954 You can set the property LOG_INTO_DRAWER to overrule this setting for
2955 a subtree."
2956 :group 'org-todo
2957 :group 'org-progress
2958 :type '(choice
2959 (const :tag "Not into a drawer" nil)
2960 (const :tag "LOGBOOK" t)
2961 (string :tag "Other")))
2963 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2965 (defun org-log-into-drawer ()
2966 "Return the value of `org-log-into-drawer', but let properties overrule.
2967 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2968 used instead of the default value."
2969 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2970 (cond
2971 ((not p) org-log-into-drawer)
2972 ((equal p "nil") nil)
2973 ((equal p "t") "LOGBOOK")
2974 (t p))))
2976 (defcustom org-log-state-notes-insert-after-drawers nil
2977 "Non-nil means insert state change notes after any drawers in entry.
2978 Only the drawers that *immediately* follow the headline and the
2979 deadline/scheduled line are skipped.
2980 When nil, insert notes right after the heading and perhaps the line
2981 with deadline/scheduling if present.
2983 This variable will have no effect if `org-log-into-drawer' is
2984 set."
2985 :group 'org-todo
2986 :group 'org-progress
2987 :type 'boolean)
2989 (defcustom org-log-states-order-reversed t
2990 "Non-nil means the latest state note will be directly after heading.
2991 When nil, the state change notes will be ordered according to time.
2993 This option can also be set with on a per-file-basis with
2995 #+STARTUP: logstatesreversed
2996 #+STARTUP: nologstatesreversed"
2997 :group 'org-todo
2998 :group 'org-progress
2999 :type 'boolean)
3001 (defcustom org-todo-repeat-to-state nil
3002 "The TODO state to which a repeater should return the repeating task.
3003 By default this is the first task in a TODO sequence, or the previous state
3004 in a TODO_TYP set. But you can specify another task here.
3005 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3006 :group 'org-todo
3007 :version "24.1"
3008 :type '(choice (const :tag "Head of sequence" nil)
3009 (string :tag "Specific state")))
3011 (defcustom org-log-repeat 'time
3012 "Non-nil means record moving through the DONE state when triggering repeat.
3013 An auto-repeating task is immediately switched back to TODO when
3014 marked DONE. If you are not logging state changes (by adding \"@\"
3015 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3016 record a closing note, there will be no record of the task moving
3017 through DONE. This variable forces taking a note anyway.
3019 nil Don't force a record
3020 time Record a time stamp
3021 note Prompt for a note and add it with template `org-log-note-headings'
3023 This option can also be set with on a per-file-basis with
3025 #+STARTUP: nologrepeat
3026 #+STARTUP: logrepeat
3027 #+STARTUP: lognoterepeat
3029 You can have local logging settings for a subtree by setting the LOGGING
3030 property to one or more of these keywords."
3031 :group 'org-todo
3032 :group 'org-progress
3033 :type '(choice
3034 (const :tag "Don't force a record" nil)
3035 (const :tag "Force recording the DONE state" time)
3036 (const :tag "Force recording a note with the DONE state" note)))
3039 (defgroup org-priorities nil
3040 "Priorities in Org-mode."
3041 :tag "Org Priorities"
3042 :group 'org-todo)
3044 (defcustom org-enable-priority-commands t
3045 "Non-nil means priority commands are active.
3046 When nil, these commands will be disabled, so that you never accidentally
3047 set a priority."
3048 :group 'org-priorities
3049 :type 'boolean)
3051 (defcustom org-highest-priority ?A
3052 "The highest priority of TODO items. A character like ?A, ?B etc.
3053 Must have a smaller ASCII number than `org-lowest-priority'."
3054 :group 'org-priorities
3055 :type 'character)
3057 (defcustom org-lowest-priority ?C
3058 "The lowest priority of TODO items. A character like ?A, ?B etc.
3059 Must have a larger ASCII number than `org-highest-priority'."
3060 :group 'org-priorities
3061 :type 'character)
3063 (defcustom org-default-priority ?B
3064 "The default priority of TODO items.
3065 This is the priority an item gets if no explicit priority is given.
3066 When starting to cycle on an empty priority the first step in the cycle
3067 depends on `org-priority-start-cycle-with-default'. The resulting first
3068 step priority must not exceed the range from `org-highest-priority' to
3069 `org-lowest-priority' which means that `org-default-priority' has to be
3070 in this range exclusive or inclusive the range boundaries. Else the
3071 first step refuses to set the default and the second will fall back
3072 to (depending on the command used) the highest or lowest priority."
3073 :group 'org-priorities
3074 :type 'character)
3076 (defcustom org-priority-start-cycle-with-default t
3077 "Non-nil means start with default priority when starting to cycle.
3078 When this is nil, the first step in the cycle will be (depending on the
3079 command used) one higher or lower than the default priority.
3080 See also `org-default-priority'."
3081 :group 'org-priorities
3082 :type 'boolean)
3084 (defcustom org-get-priority-function nil
3085 "Function to extract the priority from a string.
3086 The string is normally the headline. If this is nil Org computes the
3087 priority from the priority cookie like [#A] in the headline. It returns
3088 an integer, increasing by 1000 for each priority level.
3089 The user can set a different function here, which should take a string
3090 as an argument and return the numeric priority."
3091 :group 'org-priorities
3092 :version "24.1"
3093 :type '(choice
3094 (const nil)
3095 (function)))
3097 (defgroup org-time nil
3098 "Options concerning time stamps and deadlines in Org-mode."
3099 :tag "Org Time"
3100 :group 'org)
3102 (defcustom org-insert-labeled-timestamps-at-point nil
3103 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3104 When nil, these labeled time stamps are forces into the second line of an
3105 entry, just after the headline. When scheduling from the global TODO list,
3106 the time stamp will always be forced into the second line."
3107 :group 'org-time
3108 :type 'boolean)
3110 (defcustom org-time-stamp-rounding-minutes '(0 5)
3111 "Number of minutes to round time stamps to.
3112 These are two values, the first applies when first creating a time stamp.
3113 The second applies when changing it with the commands `S-up' and `S-down'.
3114 When changing the time stamp, this means that it will change in steps
3115 of N minutes, as given by the second value.
3117 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3118 numbers should be factors of 60, so for example 5, 10, 15.
3120 When this is larger than 1, you can still force an exact time stamp by using
3121 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3122 and by using a prefix arg to `S-up/down' to specify the exact number
3123 of minutes to shift."
3124 :group 'org-time
3125 :get (lambda (var) ; Make sure both elements are there
3126 (if (integerp (default-value var))
3127 (list (default-value var) 5)
3128 (default-value var)))
3129 :type '(list
3130 (integer :tag "when inserting times")
3131 (integer :tag "when modifying times")))
3133 ;; Normalize old customizations of this variable.
3134 (when (integerp org-time-stamp-rounding-minutes)
3135 (setq org-time-stamp-rounding-minutes
3136 (list org-time-stamp-rounding-minutes
3137 org-time-stamp-rounding-minutes)))
3139 (defcustom org-display-custom-times nil
3140 "Non-nil means overlay custom formats over all time stamps.
3141 The formats are defined through the variable `org-time-stamp-custom-formats'.
3142 To turn this on on a per-file basis, insert anywhere in the file:
3143 #+STARTUP: customtime"
3144 :group 'org-time
3145 :set 'set-default
3146 :type 'sexp)
3147 (make-variable-buffer-local 'org-display-custom-times)
3149 (defcustom org-time-stamp-custom-formats
3150 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3151 "Custom formats for time stamps. See `format-time-string' for the syntax.
3152 These are overlaid over the default ISO format if the variable
3153 `org-display-custom-times' is set. Time like %H:%M should be at the
3154 end of the second format. The custom formats are also honored by export
3155 commands, if custom time display is turned on at the time of export."
3156 :group 'org-time
3157 :type 'sexp)
3159 (defun org-time-stamp-format (&optional long inactive)
3160 "Get the right format for a time string."
3161 (let ((f (if long (cdr org-time-stamp-formats)
3162 (car org-time-stamp-formats))))
3163 (if inactive
3164 (concat "[" (substring f 1 -1) "]")
3165 f)))
3167 (defcustom org-time-clocksum-format
3168 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3169 "The format string used when creating CLOCKSUM lines.
3170 This is also used when Org mode generates a time duration.
3172 The value can be a single format string containing two
3173 %-sequences, which will be filled with the number of hours and
3174 minutes in that order.
3176 Alternatively, the value can be a plist associating any of the
3177 keys :years, :months, :weeks, :days, :hours or :minutes with
3178 format strings. The time duration is formatted using only the
3179 time components that are needed and concatenating the results.
3180 If a time unit in absent, it falls back to the next smallest
3181 unit.
3183 The keys :require-years, :require-months, :require-days,
3184 :require-weeks, :require-hours, :require-minutes are also
3185 meaningful. A non-nil value for these keys indicates that the
3186 corresponding time component should always be included, even if
3187 its value is 0.
3190 For example,
3192 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3193 :require-minutes t)
3195 means durations longer than a day will be expressed in days,
3196 hours and minutes, and durations less than a day will always be
3197 expressed in hours and minutes (even for durations less than an
3198 hour).
3200 The value
3202 \(:days \"%dd\" :minutes \"%dm\")
3204 means durations longer than a day will be expressed in days and
3205 minutes, and durations less than a day will be expressed entirely
3206 in minutes (even for durations longer than an hour)."
3207 :group 'org-time
3208 :group 'org-clock
3209 :version "24.4"
3210 :package-version '(Org . "8.0")
3211 :type '(choice (string :tag "Format string")
3212 (set :tag "Plist"
3213 (group :inline t (const :tag "Years" :years)
3214 (string :tag "Format string"))
3215 (group :inline t
3216 (const :tag "Always show years" :require-years)
3217 (const t))
3218 (group :inline t (const :tag "Months" :months)
3219 (string :tag "Format string"))
3220 (group :inline t
3221 (const :tag "Always show months" :require-months)
3222 (const t))
3223 (group :inline t (const :tag "Weeks" :weeks)
3224 (string :tag "Format string"))
3225 (group :inline t
3226 (const :tag "Always show weeks" :require-weeks)
3227 (const t))
3228 (group :inline t (const :tag "Days" :days)
3229 (string :tag "Format string"))
3230 (group :inline t
3231 (const :tag "Always show days" :require-days)
3232 (const t))
3233 (group :inline t (const :tag "Hours" :hours)
3234 (string :tag "Format string"))
3235 (group :inline t
3236 (const :tag "Always show hours" :require-hours)
3237 (const t))
3238 (group :inline t (const :tag "Minutes" :minutes)
3239 (string :tag "Format string"))
3240 (group :inline t
3241 (const :tag "Always show minutes" :require-minutes)
3242 (const t)))))
3244 (defcustom org-time-clocksum-use-fractional nil
3245 "When non-nil, \\[org-clock-display] uses fractional times.
3246 See `org-time-clocksum-format' for more on time clock formats."
3247 :group 'org-time
3248 :group 'org-clock
3249 :version "24.3"
3250 :type 'boolean)
3252 (defcustom org-time-clocksum-use-effort-durations nil
3253 "When non-nil, \\[org-clock-display] uses effort durations.
3254 E.g. by default, one day is considered to be a 8 hours effort,
3255 so a task that has been clocked for 16 hours will be displayed
3256 as during 2 days in the clock display or in the clocktable.
3258 See `org-effort-durations' on how to set effort durations
3259 and `org-time-clocksum-format' for more on time clock formats."
3260 :group 'org-time
3261 :group 'org-clock
3262 :version "24.4"
3263 :package-version '(Org . "8.0")
3264 :type 'boolean)
3266 (defcustom org-time-clocksum-fractional-format "%.2f"
3267 "The format string used when creating CLOCKSUM lines,
3268 or when Org mode generates a time duration, if
3269 `org-time-clocksum-use-fractional' is enabled.
3271 The value can be a single format string containing one
3272 %-sequence, which will be filled with the number of hours as
3273 a float.
3275 Alternatively, the value can be a plist associating any of the
3276 keys :years, :months, :weeks, :days, :hours or :minutes with
3277 a format string. The time duration is formatted using the
3278 largest time unit which gives a non-zero integer part. If all
3279 specified formats have zero integer part, the smallest time unit
3280 is used."
3281 :group 'org-time
3282 :type '(choice (string :tag "Format string")
3283 (set (group :inline t (const :tag "Years" :years)
3284 (string :tag "Format string"))
3285 (group :inline t (const :tag "Months" :months)
3286 (string :tag "Format string"))
3287 (group :inline t (const :tag "Weeks" :weeks)
3288 (string :tag "Format string"))
3289 (group :inline t (const :tag "Days" :days)
3290 (string :tag "Format string"))
3291 (group :inline t (const :tag "Hours" :hours)
3292 (string :tag "Format string"))
3293 (group :inline t (const :tag "Minutes" :minutes)
3294 (string :tag "Format string")))))
3296 (defcustom org-deadline-warning-days 14
3297 "Number of days before expiration during which a deadline becomes active.
3298 This variable governs the display in sparse trees and in the agenda.
3299 When 0 or negative, it means use this number (the absolute value of it)
3300 even if a deadline has a different individual lead time specified.
3302 Custom commands can set this variable in the options section."
3303 :group 'org-time
3304 :group 'org-agenda-daily/weekly
3305 :type 'integer)
3307 (defcustom org-scheduled-delay-days 0
3308 "Number of days before a scheduled item becomes active.
3309 This variable governs the display in sparse trees and in the agenda.
3310 The default value (i.e. 0) means: don't delay scheduled item.
3311 When negative, it means use this number (the absolute value of it)
3312 even if a scheduled item has a different individual delay time
3313 specified.
3315 Custom commands can set this variable in the options section."
3316 :group 'org-time
3317 :group 'org-agenda-daily/weekly
3318 :version "24.4"
3319 :package-version '(Org . "8.0")
3320 :type 'integer)
3322 (defcustom org-read-date-prefer-future t
3323 "Non-nil means assume future for incomplete date input from user.
3324 This affects the following situations:
3325 1. The user gives a month but not a year.
3326 For example, if it is April and you enter \"feb 2\", this will be read
3327 as Feb 2, *next* year. \"May 5\", however, will be this year.
3328 2. The user gives a day, but no month.
3329 For example, if today is the 15th, and you enter \"3\", Org-mode will
3330 read this as the third of *next* month. However, if you enter \"17\",
3331 it will be considered as *this* month.
3333 If you set this variable to the symbol `time', then also the following
3334 will work:
3336 3. If the user gives a time.
3337 If the time is before now, it will be interpreted as tomorrow.
3339 Currently none of this works for ISO week specifications.
3341 When this option is nil, the current day, month and year will always be
3342 used as defaults.
3344 See also `org-agenda-jump-prefer-future'."
3345 :group 'org-time
3346 :type '(choice
3347 (const :tag "Never" nil)
3348 (const :tag "Check month and day" t)
3349 (const :tag "Check month, day, and time" time)))
3351 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3352 "Should the agenda jump command prefer the future for incomplete dates?
3353 The default is to do the same as configured in `org-read-date-prefer-future'.
3354 But you can also set a deviating value here.
3355 This may t or nil, or the symbol `org-read-date-prefer-future'."
3356 :group 'org-agenda
3357 :group 'org-time
3358 :version "24.1"
3359 :type '(choice
3360 (const :tag "Use org-read-date-prefer-future"
3361 org-read-date-prefer-future)
3362 (const :tag "Never" nil)
3363 (const :tag "Always" t)))
3365 (defcustom org-read-date-force-compatible-dates t
3366 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3368 Depending on the system Emacs is running on, certain dates cannot
3369 be represented with the type used internally to represent time.
3370 Dates between 1970-1-1 and 2038-1-1 can always be represented
3371 correctly. Some systems allow for earlier dates, some for later,
3372 some for both. One way to find out it to insert any date into an
3373 Org buffer, putting the cursor on the year and hitting S-up and
3374 S-down to test the range.
3376 When this variable is set to t, the date/time prompt will not let
3377 you specify dates outside the 1970-2037 range, so it is certain that
3378 these dates will work in whatever version of Emacs you are
3379 running, and also that you can move a file from one Emacs implementation
3380 to another. WHenever Org is forcing the year for you, it will display
3381 a message and beep.
3383 When this variable is nil, Org will check if the date is
3384 representable in the specific Emacs implementation you are using.
3385 If not, it will force a year, usually the current year, and beep
3386 to remind you. Currently this setting is not recommended because
3387 the likelihood that you will open your Org files in an Emacs that
3388 has limited date range is not negligible.
3390 A workaround for this problem is to use diary sexp dates for time
3391 stamps outside of this range."
3392 :group 'org-time
3393 :version "24.1"
3394 :type 'boolean)
3396 (defcustom org-read-date-display-live t
3397 "Non-nil means display current interpretation of date prompt live.
3398 This display will be in an overlay, in the minibuffer."
3399 :group 'org-time
3400 :type 'boolean)
3402 (defcustom org-read-date-popup-calendar t
3403 "Non-nil means pop up a calendar when prompting for a date.
3404 In the calendar, the date can be selected with mouse-1. However, the
3405 minibuffer will also be active, and you can simply enter the date as well.
3406 When nil, only the minibuffer will be available."
3407 :group 'org-time
3408 :type 'boolean)
3409 (org-defvaralias 'org-popup-calendar-for-date-prompt
3410 'org-read-date-popup-calendar)
3412 (make-obsolete-variable
3413 'org-read-date-minibuffer-setup-hook
3414 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3415 (defcustom org-read-date-minibuffer-setup-hook nil
3416 "Hook to be used to set up keys for the date/time interface.
3417 Add key definitions to `minibuffer-local-map', which will be a
3418 temporary copy.
3420 WARNING: This option is obsolete, you should use
3421 `org-read-date-minibuffer-local-map' to set up keys."
3422 :group 'org-time
3423 :type 'hook)
3425 (defcustom org-extend-today-until 0
3426 "The hour when your day really ends. Must be an integer.
3427 This has influence for the following applications:
3428 - When switching the agenda to \"today\". It it is still earlier than
3429 the time given here, the day recognized as TODAY is actually yesterday.
3430 - When a date is read from the user and it is still before the time given
3431 here, the current date and time will be assumed to be yesterday, 23:59.
3432 Also, timestamps inserted in capture templates follow this rule.
3434 IMPORTANT: This is a feature whose implementation is and likely will
3435 remain incomplete. Really, it is only here because past midnight seems to
3436 be the favorite working time of John Wiegley :-)"
3437 :group 'org-time
3438 :type 'integer)
3440 (defcustom org-use-effective-time nil
3441 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3442 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3443 \"effective time\" of any timestamps between midnight and 8am will be
3444 23:59 of the previous day."
3445 :group 'org-time
3446 :version "24.1"
3447 :type 'boolean)
3449 (defcustom org-use-last-clock-out-time-as-effective-time nil
3450 "When non-nil, use the last clock out time for `org-todo'.
3451 Note that this option has precedence over the combined use of
3452 `org-use-effective-time' and `org-extend-today-until'."
3453 :group 'org-time
3454 :version "24.4"
3455 :package-version '(Org . "8.0")
3456 :type 'boolean)
3458 (defcustom org-edit-timestamp-down-means-later nil
3459 "Non-nil means S-down will increase the time in a time stamp.
3460 When nil, S-up will increase."
3461 :group 'org-time
3462 :type 'boolean)
3464 (defcustom org-calendar-follow-timestamp-change t
3465 "Non-nil means make the calendar window follow timestamp changes.
3466 When a timestamp is modified and the calendar window is visible, it will be
3467 moved to the new date."
3468 :group 'org-time
3469 :type 'boolean)
3471 (defgroup org-tags nil
3472 "Options concerning tags in Org-mode."
3473 :tag "Org Tags"
3474 :group 'org)
3476 (defcustom org-tag-alist nil
3477 "List of tags allowed in Org-mode files.
3478 When this list is nil, Org-mode will base TAG input on what is already in the
3479 buffer.
3480 The value of this variable is an alist, the car of each entry must be a
3481 keyword as a string, the cdr may be a character that is used to select
3482 that tag through the fast-tag-selection interface.
3483 See the manual for details."
3484 :group 'org-tags
3485 :type '(repeat
3486 (choice
3487 (cons (string :tag "Tag name")
3488 (character :tag "Access char"))
3489 (list :tag "Start radio group"
3490 (const :startgroup)
3491 (option (string :tag "Group description")))
3492 (list :tag "Group tags delimiter"
3493 (const :grouptags))
3494 (list :tag "End radio group"
3495 (const :endgroup)
3496 (option (string :tag "Group description")))
3497 (const :tag "New line" (:newline)))))
3499 (defcustom org-tag-persistent-alist nil
3500 "List of tags that will always appear in all Org-mode files.
3501 This is in addition to any in buffer settings or customizations
3502 of `org-tag-alist'.
3503 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3504 The value of this variable is an alist, the car of each entry must be a
3505 keyword as a string, the cdr may be a character that is used to select
3506 that tag through the fast-tag-selection interface.
3507 See the manual for details.
3508 To disable these tags on a per-file basis, insert anywhere in the file:
3509 #+STARTUP: noptag"
3510 :group 'org-tags
3511 :type '(repeat
3512 (choice
3513 (cons (string :tag "Tag name")
3514 (character :tag "Access char"))
3515 (const :tag "Start radio group" (:startgroup))
3516 (const :tag "Group tags delimiter" (:grouptags))
3517 (const :tag "End radio group" (:endgroup))
3518 (const :tag "New line" (:newline)))))
3520 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3521 "If non-nil, always offer completion for all tags of all agenda files.
3522 Instead of customizing this variable directly, you might want to
3523 set it locally for capture buffers, because there no list of
3524 tags in that file can be created dynamically (there are none).
3526 (add-hook 'org-capture-mode-hook
3527 (lambda ()
3528 (set (make-local-variable
3529 'org-complete-tags-always-offer-all-agenda-tags)
3530 t)))"
3531 :group 'org-tags
3532 :version "24.1"
3533 :type 'boolean)
3535 (defvar org-file-tags nil
3536 "List of tags that can be inherited by all entries in the file.
3537 The tags will be inherited if the variable `org-use-tag-inheritance'
3538 says they should be.
3539 This variable is populated from #+FILETAGS lines.")
3541 (defcustom org-use-fast-tag-selection 'auto
3542 "Non-nil means use fast tag selection scheme.
3543 This is a special interface to select and deselect tags with single keys.
3544 When nil, fast selection is never used.
3545 When the symbol `auto', fast selection is used if and only if selection
3546 characters for tags have been configured, either through the variable
3547 `org-tag-alist' or through a #+TAGS line in the buffer.
3548 When t, fast selection is always used and selection keys are assigned
3549 automatically if necessary."
3550 :group 'org-tags
3551 :type '(choice
3552 (const :tag "Always" t)
3553 (const :tag "Never" nil)
3554 (const :tag "When selection characters are configured" auto)))
3556 (defcustom org-fast-tag-selection-single-key nil
3557 "Non-nil means fast tag selection exits after first change.
3558 When nil, you have to press RET to exit it.
3559 During fast tag selection, you can toggle this flag with `C-c'.
3560 This variable can also have the value `expert'. In this case, the window
3561 displaying the tags menu is not even shown, until you press C-c again."
3562 :group 'org-tags
3563 :type '(choice
3564 (const :tag "No" nil)
3565 (const :tag "Yes" t)
3566 (const :tag "Expert" expert)))
3568 (defvar org-fast-tag-selection-include-todo nil
3569 "Non-nil means fast tags selection interface will also offer TODO states.
3570 This is an undocumented feature, you should not rely on it.")
3572 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3573 "The column to which tags should be indented in a headline.
3574 If this number is positive, it specifies the column. If it is negative,
3575 it means that the tags should be flushright to that column. For example,
3576 -80 works well for a normal 80 character screen.
3577 When 0, place tags directly after headline text, with only one space in
3578 between."
3579 :group 'org-tags
3580 :type 'integer)
3582 (defcustom org-auto-align-tags t
3583 "Non-nil keeps tags aligned when modifying headlines.
3584 Some operations (i.e. demoting) change the length of a headline and
3585 therefore shift the tags around. With this option turned on, after
3586 each such operation the tags are again aligned to `org-tags-column'."
3587 :group 'org-tags
3588 :type 'boolean)
3590 (defcustom org-use-tag-inheritance t
3591 "Non-nil means tags in levels apply also for sublevels.
3592 When nil, only the tags directly given in a specific line apply there.
3593 This may also be a list of tags that should be inherited, or a regexp that
3594 matches tags that should be inherited. Additional control is possible
3595 with the variable `org-tags-exclude-from-inheritance' which gives an
3596 explicit list of tags to be excluded from inheritance, even if the value of
3597 `org-use-tag-inheritance' would select it for inheritance.
3599 If this option is t, a match early-on in a tree can lead to a large
3600 number of matches in the subtree when constructing the agenda or creating
3601 a sparse tree. If you only want to see the first match in a tree during
3602 a search, check out the variable `org-tags-match-list-sublevels'."
3603 :group 'org-tags
3604 :type '(choice
3605 (const :tag "Not" nil)
3606 (const :tag "Always" t)
3607 (repeat :tag "Specific tags" (string :tag "Tag"))
3608 (regexp :tag "Tags matched by regexp")))
3610 (defcustom org-tags-exclude-from-inheritance nil
3611 "List of tags that should never be inherited.
3612 This is a way to exclude a few tags from inheritance. For way to do
3613 the opposite, to actively allow inheritance for selected tags,
3614 see the variable `org-use-tag-inheritance'."
3615 :group 'org-tags
3616 :type '(repeat (string :tag "Tag")))
3618 (defun org-tag-inherit-p (tag)
3619 "Check if TAG is one that should be inherited."
3620 (cond
3621 ((member tag org-tags-exclude-from-inheritance) nil)
3622 ((eq org-use-tag-inheritance t) t)
3623 ((not org-use-tag-inheritance) nil)
3624 ((stringp org-use-tag-inheritance)
3625 (string-match org-use-tag-inheritance tag))
3626 ((listp org-use-tag-inheritance)
3627 (member tag org-use-tag-inheritance))
3628 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3630 (defcustom org-tags-match-list-sublevels t
3631 "Non-nil means list also sublevels of headlines matching a search.
3632 This variable applies to tags/property searches, and also to stuck
3633 projects because this search is based on a tags match as well.
3635 When set to the symbol `indented', sublevels are indented with
3636 leading dots.
3638 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3639 the sublevels of a headline matching a tag search often also match
3640 the same search. Listing all of them can create very long lists.
3641 Setting this variable to nil causes subtrees of a match to be skipped.
3643 This variable is semi-obsolete and probably should always be true. It
3644 is better to limit inheritance to certain tags using the variables
3645 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3646 :group 'org-tags
3647 :type '(choice
3648 (const :tag "No, don't list them" nil)
3649 (const :tag "Yes, do list them" t)
3650 (const :tag "List them, indented with leading dots" indented)))
3652 (defcustom org-tags-sort-function nil
3653 "When set, tags are sorted using this function as a comparator."
3654 :group 'org-tags
3655 :type '(choice
3656 (const :tag "No sorting" nil)
3657 (const :tag "Alphabetical" string<)
3658 (const :tag "Reverse alphabetical" string>)
3659 (function :tag "Custom function" nil)))
3661 (defvar org-tags-history nil
3662 "History of minibuffer reads for tags.")
3663 (defvar org-last-tags-completion-table nil
3664 "The last used completion table for tags.")
3665 (defvar org-after-tags-change-hook nil
3666 "Hook that is run after the tags in a line have changed.")
3668 (defgroup org-properties nil
3669 "Options concerning properties in Org-mode."
3670 :tag "Org Properties"
3671 :group 'org)
3673 (defcustom org-property-format "%-10s %s"
3674 "How property key/value pairs should be formatted by `indent-line'.
3675 When `indent-line' hits a property definition, it will format the line
3676 according to this format, mainly to make sure that the values are
3677 lined-up with respect to each other."
3678 :group 'org-properties
3679 :type 'string)
3681 (defcustom org-properties-postprocess-alist nil
3682 "Alist of properties and functions to adjust inserted values.
3683 Elements of this alist must be of the form
3685 ([string] [function])
3687 where [string] must be a property name and [function] must be a
3688 lambda expression: this lambda expression must take one argument,
3689 the value to adjust, and return the new value as a string.
3691 For example, this element will allow the property \"Remaining\"
3692 to be updated wrt the relation between the \"Effort\" property
3693 and the clock summary:
3695 ((\"Remaining\" (lambda(value)
3696 (let ((clocksum (org-clock-sum-current-item))
3697 (effort (org-duration-string-to-minutes
3698 (org-entry-get (point) \"Effort\"))))
3699 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3700 :group 'org-properties
3701 :version "24.1"
3702 :type '(alist :key-type (string :tag "Property")
3703 :value-type (function :tag "Function")))
3705 (defcustom org-use-property-inheritance nil
3706 "Non-nil means properties apply also for sublevels.
3708 This setting is chiefly used during property searches. Turning it on can
3709 cause significant overhead when doing a search, which is why it is not
3710 on by default.
3712 When nil, only the properties directly given in the current entry count.
3713 When t, every property is inherited. The value may also be a list of
3714 properties that should have inheritance, or a regular expression matching
3715 properties that should be inherited.
3717 However, note that some special properties use inheritance under special
3718 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3719 and the properties ending in \"_ALL\" when they are used as descriptor
3720 for valid values of a property.
3722 Note for programmers:
3723 When querying an entry with `org-entry-get', you can control if inheritance
3724 should be used. By default, `org-entry-get' looks only at the local
3725 properties. You can request inheritance by setting the inherit argument
3726 to t (to force inheritance) or to `selective' (to respect the setting
3727 in this variable)."
3728 :group 'org-properties
3729 :type '(choice
3730 (const :tag "Not" nil)
3731 (const :tag "Always" t)
3732 (repeat :tag "Specific properties" (string :tag "Property"))
3733 (regexp :tag "Properties matched by regexp")))
3735 (defun org-property-inherit-p (property)
3736 "Check if PROPERTY is one that should be inherited."
3737 (cond
3738 ((eq org-use-property-inheritance t) t)
3739 ((not org-use-property-inheritance) nil)
3740 ((stringp org-use-property-inheritance)
3741 (string-match org-use-property-inheritance property))
3742 ((listp org-use-property-inheritance)
3743 (member property org-use-property-inheritance))
3744 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3746 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3747 "The default column format, if no other format has been defined.
3748 This variable can be set on the per-file basis by inserting a line
3750 #+COLUMNS: %25ITEM ....."
3751 :group 'org-properties
3752 :type 'string)
3754 (defcustom org-columns-ellipses ".."
3755 "The ellipses to be used when a field in column view is truncated.
3756 When this is the empty string, as many characters as possible are shown,
3757 but then there will be no visual indication that the field has been truncated.
3758 When this is a string of length N, the last N characters of a truncated
3759 field are replaced by this string. If the column is narrower than the
3760 ellipses string, only part of the ellipses string will be shown."
3761 :group 'org-properties
3762 :type 'string)
3764 (defcustom org-columns-modify-value-for-display-function nil
3765 "Function that modifies values for display in column view.
3766 For example, it can be used to cut out a certain part from a time stamp.
3767 The function must take 2 arguments:
3769 column-title The title of the column (*not* the property name)
3770 value The value that should be modified.
3772 The function should return the value that should be displayed,
3773 or nil if the normal value should be used."
3774 :group 'org-properties
3775 :type '(choice (const nil) (function)))
3777 (defconst org-global-properties-fixed
3778 '(("VISIBILITY_ALL" . "folded children content all")
3779 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3780 "List of property/value pairs that can be inherited by any entry.
3782 These are fixed values, for the preset properties. The user variable
3783 that can be used to add to this list is `org-global-properties'.
3785 The entries in this list are cons cells where the car is a property
3786 name and cdr is a string with the value. If the value represents
3787 multiple items like an \"_ALL\" property, separate the items by
3788 spaces.")
3790 (defcustom org-global-properties nil
3791 "List of property/value pairs that can be inherited by any entry.
3793 This list will be combined with the constant `org-global-properties-fixed'.
3795 The entries in this list are cons cells where the car is a property
3796 name and cdr is a string with the value.
3798 You can set buffer-local values for the same purpose in the variable
3799 `org-file-properties' this by adding lines like
3801 #+PROPERTY: NAME VALUE"
3802 :group 'org-properties
3803 :type '(repeat
3804 (cons (string :tag "Property")
3805 (string :tag "Value"))))
3807 (defvar org-file-properties nil
3808 "List of property/value pairs that can be inherited by any entry.
3809 Valid for the current buffer.
3810 This variable is populated from #+PROPERTY lines.")
3811 (make-variable-buffer-local 'org-file-properties)
3813 (defgroup org-agenda nil
3814 "Options concerning agenda views in Org-mode."
3815 :tag "Org Agenda"
3816 :group 'org)
3818 (defvar org-category nil
3819 "Variable used by org files to set a category for agenda display.
3820 Such files should use a file variable to set it, for example
3822 # -*- mode: org; org-category: \"ELisp\"
3824 or contain a special line
3826 #+CATEGORY: ELisp
3828 If the file does not specify a category, then file's base name
3829 is used instead.")
3830 (make-variable-buffer-local 'org-category)
3831 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3833 (defcustom org-agenda-files nil
3834 "The files to be used for agenda display.
3835 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3836 \\[org-remove-file]. You can also use customize to edit the list.
3838 If an entry is a directory, all files in that directory that are matched by
3839 `org-agenda-file-regexp' will be part of the file list.
3841 If the value of the variable is not a list but a single file name, then
3842 the list of agenda files is actually stored and maintained in that file, one
3843 agenda file per line. In this file paths can be given relative to
3844 `org-directory'. Tilde expansion and environment variable substitution
3845 are also made."
3846 :group 'org-agenda
3847 :type '(choice
3848 (repeat :tag "List of files and directories" file)
3849 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3851 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3852 "Regular expression to match files for `org-agenda-files'.
3853 If any element in the list in that variable contains a directory instead
3854 of a normal file, all files in that directory that are matched by this
3855 regular expression will be included."
3856 :group 'org-agenda
3857 :type 'regexp)
3859 (defcustom org-agenda-text-search-extra-files nil
3860 "List of extra files to be searched by text search commands.
3861 These files will be searched in addition to the agenda files by the
3862 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3863 Note that these files will only be searched for text search commands,
3864 not for the other agenda views like todo lists, tag searches or the weekly
3865 agenda. This variable is intended to list notes and possibly archive files
3866 that should also be searched by these two commands.
3867 In fact, if the first element in the list is the symbol `agenda-archives',
3868 then all archive files of all agenda files will be added to the search
3869 scope."
3870 :group 'org-agenda
3871 :type '(set :greedy t
3872 (const :tag "Agenda Archives" agenda-archives)
3873 (repeat :inline t (file))))
3875 (org-defvaralias 'org-agenda-multi-occur-extra-files
3876 'org-agenda-text-search-extra-files)
3878 (defcustom org-agenda-skip-unavailable-files nil
3879 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3880 A nil value means to remove them, after a query, from the list."
3881 :group 'org-agenda
3882 :type 'boolean)
3884 (defcustom org-calendar-to-agenda-key [?c]
3885 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3886 The command `org-calendar-goto-agenda' will be bound to this key. The
3887 default is the character `c' because then `c' can be used to switch back and
3888 forth between agenda and calendar."
3889 :group 'org-agenda
3890 :type 'sexp)
3892 (defcustom org-calendar-insert-diary-entry-key [?i]
3893 "The key to be installed in `calendar-mode-map' for adding diary entries.
3894 This option is irrelevant until `org-agenda-diary-file' has been configured
3895 to point to an Org-mode file. When that is the case, the command
3896 `org-agenda-diary-entry' will be bound to the key given here, by default
3897 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3898 if you want to continue doing this, you need to change this to a different
3899 key."
3900 :group 'org-agenda
3901 :type 'sexp)
3903 (defcustom org-agenda-diary-file 'diary-file
3904 "File to which to add new entries with the `i' key in agenda and calendar.
3905 When this is the symbol `diary-file', the functionality in the Emacs
3906 calendar will be used to add entries to the `diary-file'. But when this
3907 points to a file, `org-agenda-diary-entry' will be used instead."
3908 :group 'org-agenda
3909 :type '(choice
3910 (const :tag "The standard Emacs diary file" diary-file)
3911 (file :tag "Special Org file diary entries")))
3913 (eval-after-load "calendar"
3914 '(progn
3915 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3916 'org-calendar-goto-agenda)
3917 (add-hook 'calendar-mode-hook
3918 (lambda ()
3919 (unless (eq org-agenda-diary-file 'diary-file)
3920 (define-key calendar-mode-map
3921 org-calendar-insert-diary-entry-key
3922 'org-agenda-diary-entry))))))
3924 (defgroup org-latex nil
3925 "Options for embedding LaTeX code into Org-mode."
3926 :tag "Org LaTeX"
3927 :group 'org)
3929 (defcustom org-format-latex-options
3930 '(:foreground default :background default :scale 1.0
3931 :html-foreground "Black" :html-background "Transparent"
3932 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3933 "Options for creating images from LaTeX fragments.
3934 This is a property list with the following properties:
3935 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3936 `default' means use the foreground of the default face.
3937 `auto' means use the foreground from the text face.
3938 :background the background color, or \"Transparent\".
3939 `default' means use the background of the default face.
3940 `auto' means use the background from the text face.
3941 :scale a scaling factor for the size of the images, to get more pixels
3942 :html-foreground, :html-background, :html-scale
3943 the same numbers for HTML export.
3944 :matchers a list indicating which matchers should be used to
3945 find LaTeX fragments. Valid members of this list are:
3946 \"begin\" find environments
3947 \"$1\" find single characters surrounded by $.$
3948 \"$\" find math expressions surrounded by $...$
3949 \"$$\" find math expressions surrounded by $$....$$
3950 \"\\(\" find math expressions surrounded by \\(...\\)
3951 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3952 :group 'org-latex
3953 :type 'plist)
3955 (defcustom org-format-latex-signal-error t
3956 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3957 When nil, just push out a message."
3958 :group 'org-latex
3959 :version "24.1"
3960 :type 'boolean)
3962 (defcustom org-latex-to-mathml-jar-file nil
3963 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3964 Use this to specify additional executable file say a jar file.
3966 When using MathToWeb as the converter, specify the full-path to
3967 your mathtoweb.jar file."
3968 :group 'org-latex
3969 :version "24.1"
3970 :type '(choice
3971 (const :tag "None" nil)
3972 (file :tag "JAR file" :must-match t)))
3974 (defcustom org-latex-to-mathml-convert-command nil
3975 "Command to convert LaTeX fragments to MathML.
3976 Replace format-specifiers in the command as noted below and use
3977 `shell-command' to convert LaTeX to MathML.
3978 %j: Executable file in fully expanded form as specified by
3979 `org-latex-to-mathml-jar-file'.
3980 %I: Input LaTeX file in fully expanded form
3981 %o: Output MathML file
3982 This command is used by `org-create-math-formula'.
3984 When using MathToWeb as the converter, set this to
3985 \"java -jar %j -unicode -force -df %o %I\"."
3986 :group 'org-latex
3987 :version "24.1"
3988 :type '(choice
3989 (const :tag "None" nil)
3990 (string :tag "\nShell command")))
3992 (defcustom org-latex-create-formula-image-program 'dvipng
3993 "Program to convert LaTeX fragments with.
3995 dvipng Process the LaTeX fragments to dvi file, then convert
3996 dvi files to png files using dvipng.
3997 This will also include processing of non-math environments.
3998 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3999 to convert pdf files to png files"
4000 :group 'org-latex
4001 :version "24.1"
4002 :type '(choice
4003 (const :tag "dvipng" dvipng)
4004 (const :tag "imagemagick" imagemagick)))
4006 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
4007 "Path to store latex preview images.
4008 A relative path here creates many directories relative to the
4009 processed org files paths. An absolute path puts all preview
4010 images at the same place."
4011 :group 'org-latex
4012 :version "24.3"
4013 :type 'string)
4015 (defun org-format-latex-mathml-available-p ()
4016 "Return t if `org-latex-to-mathml-convert-command' is usable."
4017 (save-match-data
4018 (when (and (boundp 'org-latex-to-mathml-convert-command)
4019 org-latex-to-mathml-convert-command)
4020 (let ((executable (car (split-string
4021 org-latex-to-mathml-convert-command))))
4022 (when (executable-find executable)
4023 (if (string-match
4024 "%j" org-latex-to-mathml-convert-command)
4025 (file-readable-p org-latex-to-mathml-jar-file)
4026 t))))))
4028 (defcustom org-format-latex-header "\\documentclass{article}
4029 \\usepackage[usenames]{color}
4030 \[PACKAGES]
4031 \[DEFAULT-PACKAGES]
4032 \\pagestyle{empty} % do not remove
4033 % The settings below are copied from fullpage.sty
4034 \\setlength{\\textwidth}{\\paperwidth}
4035 \\addtolength{\\textwidth}{-3cm}
4036 \\setlength{\\oddsidemargin}{1.5cm}
4037 \\addtolength{\\oddsidemargin}{-2.54cm}
4038 \\setlength{\\evensidemargin}{\\oddsidemargin}
4039 \\setlength{\\textheight}{\\paperheight}
4040 \\addtolength{\\textheight}{-\\headheight}
4041 \\addtolength{\\textheight}{-\\headsep}
4042 \\addtolength{\\textheight}{-\\footskip}
4043 \\addtolength{\\textheight}{-3cm}
4044 \\setlength{\\topmargin}{1.5cm}
4045 \\addtolength{\\topmargin}{-2.54cm}"
4046 "The document header used for processing LaTeX fragments.
4047 It is imperative that this header make sure that no page number
4048 appears on the page. The package defined in the variables
4049 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4050 will either replace the placeholder \"[PACKAGES]\" in this
4051 header, or they will be appended."
4052 :group 'org-latex
4053 :type 'string)
4055 (defun org-set-packages-alist (var val)
4056 "Set the packages alist and make sure it has 3 elements per entry."
4057 (set var (mapcar (lambda (x)
4058 (if (and (consp x) (= (length x) 2))
4059 (list (car x) (nth 1 x) t)
4061 val)))
4063 (defun org-get-packages-alist (var)
4064 "Get the packages alist and make sure it has 3 elements per entry."
4065 (mapcar (lambda (x)
4066 (if (and (consp x) (= (length x) 2))
4067 (list (car x) (nth 1 x) t)
4069 (default-value var)))
4071 (defcustom org-latex-default-packages-alist
4072 '(("AUTO" "inputenc" t)
4073 ("T1" "fontenc" t)
4074 ("" "fixltx2e" nil)
4075 ("" "graphicx" t)
4076 ("" "longtable" nil)
4077 ("" "float" nil)
4078 ("" "wrapfig" nil)
4079 ("" "rotating" nil)
4080 ("normalem" "ulem" t)
4081 ("" "amsmath" t)
4082 ("" "textcomp" t)
4083 ("" "marvosym" t)
4084 ("" "wasysym" t)
4085 ("" "amssymb" t)
4086 ("" "capt-of" nil)
4087 ("" "hyperref" nil)
4088 "\\tolerance=1000")
4089 "Alist of default packages to be inserted in the header.
4091 Change this only if one of the packages here causes an
4092 incompatibility with another package you are using.
4094 The packages in this list are needed by one part or another of
4095 Org mode to function properly:
4097 - inputenc, fontenc: for basic font and character selection
4098 - fixltx2e: Important patches of LaTeX itself
4099 - graphicx: for including images
4100 - longtable: For multipage tables
4101 - float, wrapfig: for figure placement
4102 - rotating: for sideways figures and tables
4103 - ulem: for underline and strike-through
4104 - amsmath: for subscript and superscript and math environments
4105 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4106 for interpreting the entities in `org-entities'. You can skip
4107 some of these packages if you don't use any of their symbols.
4108 - capt-of: for captions outside of floats
4109 - hyperref: for cross references
4111 Therefore you should not modify this variable unless you know
4112 what you are doing. The one reason to change it anyway is that
4113 you might be loading some other package that conflicts with one
4114 of the default packages. Each element is either a cell or
4115 a string.
4117 A cell is of the format:
4119 \( \"options\" \"package\" SNIPPET-FLAG).
4121 If SNIPPET-FLAG is non-nil, the package also needs to be included
4122 when compiling LaTeX snippets into images for inclusion into
4123 non-LaTeX output.
4125 A string will be inserted as-is in the header of the document."
4126 :group 'org-latex
4127 :group 'org-export-latex
4128 :set 'org-set-packages-alist
4129 :get 'org-get-packages-alist
4130 :version "24.1"
4131 :type '(repeat
4132 (choice
4133 (list :tag "options/package pair"
4134 (string :tag "options")
4135 (string :tag "package")
4136 (boolean :tag "Snippet"))
4137 (string :tag "A line of LaTeX"))))
4139 (defcustom org-latex-packages-alist nil
4140 "Alist of packages to be inserted in every LaTeX header.
4142 These will be inserted after `org-latex-default-packages-alist'.
4143 Each element is either a cell or a string.
4145 A cell is of the format:
4147 \(\"options\" \"package\" SNIPPET-FLAG)
4149 SNIPPET-FLAG, when non-nil, indicates that this package is also
4150 needed when turning LaTeX snippets into images for inclusion into
4151 non-LaTeX output.
4153 A string will be inserted as-is in the header of the document.
4155 Make sure that you only list packages here which:
4157 - you want in every file;
4158 - do not conflict with the setup in `org-format-latex-header';
4159 - do not conflict with the default packages in
4160 `org-latex-default-packages-alist'."
4161 :group 'org-latex
4162 :group 'org-export-latex
4163 :set 'org-set-packages-alist
4164 :get 'org-get-packages-alist
4165 :type '(repeat
4166 (choice
4167 (list :tag "options/package pair"
4168 (string :tag "options")
4169 (string :tag "package")
4170 (boolean :tag "Snippet"))
4171 (string :tag "A line of LaTeX"))))
4173 (defgroup org-appearance nil
4174 "Settings for Org-mode appearance."
4175 :tag "Org Appearance"
4176 :group 'org)
4178 (defcustom org-level-color-stars-only nil
4179 "Non-nil means fontify only the stars in each headline.
4180 When nil, the entire headline is fontified.
4181 Changing it requires restart of `font-lock-mode' to become effective
4182 also in regions already fontified."
4183 :group 'org-appearance
4184 :type 'boolean)
4186 (defcustom org-hide-leading-stars nil
4187 "Non-nil means hide the first N-1 stars in a headline.
4188 This works by using the face `org-hide' for these stars. This
4189 face is white for a light background, and black for a dark
4190 background. You may have to customize the face `org-hide' to
4191 make this work.
4192 Changing it requires restart of `font-lock-mode' to become effective
4193 also in regions already fontified.
4194 You may also set this on a per-file basis by adding one of the following
4195 lines to the buffer:
4197 #+STARTUP: hidestars
4198 #+STARTUP: showstars"
4199 :group 'org-appearance
4200 :type 'boolean)
4202 (defcustom org-hidden-keywords nil
4203 "List of symbols corresponding to keywords to be hidden the org buffer.
4204 For example, a value '(title) for this list will make the document's title
4205 appear in the buffer without the initial #+TITLE: keyword."
4206 :group 'org-appearance
4207 :version "24.1"
4208 :type '(set (const :tag "#+AUTHOR" author)
4209 (const :tag "#+DATE" date)
4210 (const :tag "#+EMAIL" email)
4211 (const :tag "#+TITLE" title)))
4213 (defcustom org-custom-properties nil
4214 "List of properties (as strings) with a special meaning.
4215 The default use of these custom properties is to let the user
4216 hide them with `org-toggle-custom-properties-visibility'."
4217 :group 'org-properties
4218 :group 'org-appearance
4219 :version "24.3"
4220 :type '(repeat (string :tag "Property Name")))
4222 (defcustom org-fontify-done-headline nil
4223 "Non-nil means change the face of a headline if it is marked DONE.
4224 Normally, only the TODO/DONE keyword indicates the state of a headline.
4225 When this is non-nil, the headline after the keyword is set to the
4226 `org-headline-done' as an additional indication."
4227 :group 'org-appearance
4228 :type 'boolean)
4230 (defcustom org-fontify-emphasized-text t
4231 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4232 Changing this variable requires a restart of Emacs to take effect."
4233 :group 'org-appearance
4234 :type 'boolean)
4236 (defcustom org-fontify-whole-heading-line nil
4237 "Non-nil means fontify the whole line for headings.
4238 This is useful when setting a background color for the
4239 org-level-* faces."
4240 :group 'org-appearance
4241 :type 'boolean)
4243 (defcustom org-highlight-latex-and-related nil
4244 "Non-nil means highlight LaTeX related syntax in the buffer.
4245 When non nil, the value should be a list containing any of the
4246 following symbols:
4247 `latex' Highlight LaTeX snippets and environments.
4248 `script' Highlight subscript and superscript.
4249 `entities' Highlight entities."
4250 :group 'org-appearance
4251 :version "24.4"
4252 :package-version '(Org . "8.0")
4253 :type '(choice
4254 (const :tag "No highlighting" nil)
4255 (set :greedy t :tag "Highlight"
4256 (const :tag "LaTeX snippets and environments" latex)
4257 (const :tag "Subscript and superscript" script)
4258 (const :tag "Entities" entities))))
4260 (defcustom org-hide-emphasis-markers nil
4261 "Non-nil mean font-lock should hide the emphasis marker characters."
4262 :group 'org-appearance
4263 :type 'boolean)
4265 (defcustom org-hide-macro-markers nil
4266 "Non-nil mean font-lock should hide the brackets marking macro calls."
4267 :group 'org-appearance
4268 :type 'boolean)
4270 (defcustom org-pretty-entities nil
4271 "Non-nil means show entities as UTF8 characters.
4272 When nil, the \\name form remains in the buffer."
4273 :group 'org-appearance
4274 :version "24.1"
4275 :type 'boolean)
4277 (defcustom org-pretty-entities-include-sub-superscripts t
4278 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4279 :group 'org-appearance
4280 :version "24.1"
4281 :type 'boolean)
4283 (defvar org-emph-re nil
4284 "Regular expression for matching emphasis.
4285 After a match, the match groups contain these elements:
4286 0 The match of the full regular expression, including the characters
4287 before and after the proper match
4288 1 The character before the proper match, or empty at beginning of line
4289 2 The proper match, including the leading and trailing markers
4290 3 The leading marker like * or /, indicating the type of highlighting
4291 4 The text between the emphasis markers, not including the markers
4292 5 The character after the match, empty at the end of a line")
4293 (defvar org-verbatim-re nil
4294 "Regular expression for matching verbatim text.")
4295 (defvar org-emphasis-regexp-components) ; defined just below
4296 (defvar org-emphasis-alist) ; defined just below
4297 (defun org-set-emph-re (var val)
4298 "Set variable and compute the emphasis regular expression."
4299 (set var val)
4300 (when (and (boundp 'org-emphasis-alist)
4301 (boundp 'org-emphasis-regexp-components)
4302 org-emphasis-alist org-emphasis-regexp-components)
4303 (let* ((e org-emphasis-regexp-components)
4304 (pre (car e))
4305 (post (nth 1 e))
4306 (border (nth 2 e))
4307 (body (nth 3 e))
4308 (nl (nth 4 e))
4309 (body1 (concat body "*?"))
4310 (markers (mapconcat 'car org-emphasis-alist ""))
4311 (vmarkers (mapconcat
4312 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4313 org-emphasis-alist "")))
4314 ;; make sure special characters appear at the right position in the class
4315 (if (string-match "\\^" markers)
4316 (setq markers (concat (replace-match "" t t markers) "^")))
4317 (if (string-match "-" markers)
4318 (setq markers (concat (replace-match "" t t markers) "-")))
4319 (if (string-match "\\^" vmarkers)
4320 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4321 (if (string-match "-" vmarkers)
4322 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4323 (if (> nl 0)
4324 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4325 (int-to-string nl) "\\}")))
4326 ;; Make the regexp
4327 (setq org-emph-re
4328 (concat "\\([" pre "]\\|^\\)"
4329 "\\("
4330 "\\([" markers "]\\)"
4331 "\\("
4332 "[^" border "]\\|"
4333 "[^" border "]"
4334 body1
4335 "[^" border "]"
4336 "\\)"
4337 "\\3\\)"
4338 "\\([" post "]\\|$\\)"))
4339 (setq org-verbatim-re
4340 (concat "\\([" pre "]\\|^\\)"
4341 "\\("
4342 "\\([" vmarkers "]\\)"
4343 "\\("
4344 "[^" border "]\\|"
4345 "[^" border "]"
4346 body1
4347 "[^" border "]"
4348 "\\)"
4349 "\\3\\)"
4350 "\\([" post "]\\|$\\)")))))
4352 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4353 ;; set this option proved cumbersome. See this message/thread:
4354 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4355 (defvar org-emphasis-regexp-components
4356 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4357 "Components used to build the regular expression for emphasis.
4358 This is a list with five entries. Terminology: In an emphasis string
4359 like \" *strong word* \", we call the initial space PREMATCH, the final
4360 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4361 and \"trong wor\" is the body. The different components in this variable
4362 specify what is allowed/forbidden in each part:
4364 pre Chars allowed as prematch. Beginning of line will be allowed too.
4365 post Chars allowed as postmatch. End of line will be allowed too.
4366 border The chars *forbidden* as border characters.
4367 body-regexp A regexp like \".\" to match a body character. Don't use
4368 non-shy groups here, and don't allow newline here.
4369 newline The maximum number of newlines allowed in an emphasis exp.
4371 You need to reload Org or to restart Emacs after customizing this.")
4373 (defcustom org-emphasis-alist
4374 `(("*" bold)
4375 ("/" italic)
4376 ("_" underline)
4377 ("=" org-verbatim verbatim)
4378 ("~" org-code verbatim)
4379 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4380 "Alist of characters and faces to emphasize text.
4381 Text starting and ending with a special character will be emphasized,
4382 for example *bold*, _underlined_ and /italic/. This variable sets the
4383 marker characters and the face to be used by font-lock for highlighting
4384 in Org-mode Emacs buffers.
4386 You need to reload Org or to restart Emacs after customizing this."
4387 :group 'org-appearance
4388 :set 'org-set-emph-re
4389 :version "24.4"
4390 :package-version '(Org . "8.0")
4391 :type '(repeat
4392 (list
4393 (string :tag "Marker character")
4394 (choice
4395 (face :tag "Font-lock-face")
4396 (plist :tag "Face property list"))
4397 (option (const verbatim)))))
4399 (defvar org-protecting-blocks
4400 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4401 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4402 This is needed for font-lock setup.")
4404 ;;; Miscellaneous options
4406 (defgroup org-completion nil
4407 "Completion in Org-mode."
4408 :tag "Org Completion"
4409 :group 'org)
4411 (defcustom org-completion-use-ido nil
4412 "Non-nil means use ido completion wherever possible.
4413 Note that `ido-mode' must be active for this variable to be relevant.
4414 If you decide to turn this variable on, you might well want to turn off
4415 `org-outline-path-complete-in-steps'.
4416 See also `org-completion-use-iswitchb'."
4417 :group 'org-completion
4418 :type 'boolean)
4420 (defcustom org-completion-use-iswitchb nil
4421 "Non-nil means use iswitchb completion wherever possible.
4422 Note that `iswitchb-mode' must be active for this variable to be relevant.
4423 If you decide to turn this variable on, you might well want to turn off
4424 `org-outline-path-complete-in-steps'.
4425 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4426 :group 'org-completion
4427 :type 'boolean)
4429 (defcustom org-completion-fallback-command 'hippie-expand
4430 "The expansion command called by \\[pcomplete] in normal context.
4431 Normal means, no org-mode-specific context."
4432 :group 'org-completion
4433 :type 'function)
4435 ;;; Functions and variables from their packages
4436 ;; Declared here to avoid compiler warnings
4438 ;; XEmacs only
4439 (defvar outline-mode-menu-heading)
4440 (defvar outline-mode-menu-show)
4441 (defvar outline-mode-menu-hide)
4442 (defvar zmacs-regions) ; XEmacs regions
4444 ;; Emacs only
4445 (defvar mark-active)
4447 ;; Various packages
4448 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4449 (declare-function calendar-forward-day "cal-move" (arg))
4450 (declare-function calendar-goto-date "cal-move" (date))
4451 (declare-function calendar-goto-today "cal-move" ())
4452 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4453 (defvar calc-embedded-close-formula)
4454 (defvar calc-embedded-open-formula)
4455 (declare-function cdlatex-tab "ext:cdlatex" ())
4456 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4457 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4458 (defvar font-lock-unfontify-region-function)
4459 (declare-function iswitchb-read-buffer "iswitchb"
4460 (prompt &optional default require-match start matches-set))
4461 (defvar iswitchb-temp-buflist)
4462 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4463 (defvar org-agenda-tags-todo-honor-ignore-options)
4464 (declare-function org-agenda-skip "org-agenda" ())
4465 (declare-function
4466 org-agenda-format-item "org-agenda"
4467 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4468 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4469 (declare-function org-agenda-change-all-lines "org-agenda"
4470 (newhead hdmarker &optional fixface just-this))
4471 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4472 (declare-function org-agenda-maybe-redo "org-agenda" ())
4473 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4474 (beg end))
4475 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4476 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4477 "org-agenda" (&optional end))
4478 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4479 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4480 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4481 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4482 (declare-function org-indent-mode "org-indent" (&optional arg))
4483 (declare-function parse-time-string "parse-time" (string))
4484 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4485 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4486 (defvar remember-data-file)
4487 (defvar texmathp-why)
4488 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4489 (declare-function table--at-cell-p "table" (position &optional object at-column))
4490 (declare-function calc-eval "calc" (str &optional separator &rest args))
4492 ;;;###autoload
4493 (defun turn-on-orgtbl ()
4494 "Unconditionally turn on `orgtbl-mode'."
4495 (require 'org-table)
4496 (orgtbl-mode 1))
4498 (defun org-at-table-p (&optional table-type)
4499 "Return t if the cursor is inside an org-type table.
4500 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4501 (if org-enable-table-editor
4502 (save-excursion
4503 (beginning-of-line 1)
4504 (looking-at (if table-type org-table-any-line-regexp
4505 org-table-line-regexp)))
4506 nil))
4507 (defsubst org-table-p () (org-at-table-p))
4509 (defun org-at-table.el-p ()
4510 "Return t if and only if we are at a table.el table."
4511 (and (org-at-table-p 'any)
4512 (save-excursion
4513 (goto-char (org-table-begin 'any))
4514 (looking-at org-table1-hline-regexp))))
4516 (defun org-table-recognize-table.el ()
4517 "If there is a table.el table nearby, recognize it and move into it."
4518 (if org-table-tab-recognizes-table.el
4519 (if (org-at-table.el-p)
4520 (progn
4521 (beginning-of-line 1)
4522 (if (looking-at org-table-dataline-regexp)
4524 (if (looking-at org-table1-hline-regexp)
4525 (progn
4526 (beginning-of-line 2)
4527 (if (looking-at org-table-any-border-regexp)
4528 (beginning-of-line -1)))))
4529 (if (re-search-forward "|" (org-table-end t) t)
4530 (progn
4531 (require 'table)
4532 (if (table--at-cell-p (point))
4534 (message "recognizing table.el table...")
4535 (table-recognize-table)
4536 (message "recognizing table.el table...done")))
4537 (error "This should not happen"))
4539 nil)
4540 nil))
4542 (defun org-at-table-hline-p ()
4543 "Return t if the cursor is inside a hline in a table."
4544 (if org-enable-table-editor
4545 (save-excursion
4546 (beginning-of-line 1)
4547 (looking-at org-table-hline-regexp))
4548 nil))
4550 (defun org-table-map-tables (function &optional quietly)
4551 "Apply FUNCTION to the start of all tables in the buffer."
4552 (save-excursion
4553 (save-restriction
4554 (widen)
4555 (goto-char (point-min))
4556 (while (re-search-forward org-table-any-line-regexp nil t)
4557 (unless quietly
4558 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4559 (beginning-of-line 1)
4560 (when (and (looking-at org-table-line-regexp)
4561 ;; Exclude tables in src/example/verbatim/clocktable blocks
4562 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4563 (save-excursion (funcall function))
4564 (or (looking-at org-table-line-regexp)
4565 (forward-char 1)))
4566 (re-search-forward org-table-any-border-regexp nil 1))))
4567 (unless quietly (message "Mapping tables: done")))
4569 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4570 (declare-function org-clock-update-mode-line "org-clock" ())
4571 (declare-function org-resolve-clocks "org-clock"
4572 (&optional also-non-dangling-p prompt last-valid))
4574 (defun org-at-TBLFM-p (&optional pos)
4575 "Return t when point (or POS) is in #+TBLFM line."
4576 (save-excursion
4577 (let ((pos pos)))
4578 (goto-char (or pos (point)))
4579 (beginning-of-line 1)
4580 (looking-at org-TBLFM-regexp)))
4582 (defvar org-clock-start-time)
4583 (defvar org-clock-marker (make-marker)
4584 "Marker recording the last clock-in.")
4585 (defvar org-clock-hd-marker (make-marker)
4586 "Marker recording the last clock-in, but the headline position.")
4587 (defvar org-clock-heading ""
4588 "The heading of the current clock entry.")
4589 (defun org-clock-is-active ()
4590 "Return the buffer where the clock is currently running.
4591 Return nil if no clock is running."
4592 (marker-buffer org-clock-marker))
4594 (defun org-check-running-clock ()
4595 "Check if the current buffer contains the running clock.
4596 If yes, offer to stop it and to save the buffer with the changes."
4597 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4598 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4599 (buffer-name))))
4600 (org-clock-out)
4601 (when (y-or-n-p "Save changed buffer?")
4602 (save-buffer))))
4604 (defun org-clocktable-try-shift (dir n)
4605 "Check if this line starts a clock table, if yes, shift the time block."
4606 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4607 (org-clocktable-shift dir n)))
4609 ;;;###autoload
4610 (defun org-clock-persistence-insinuate ()
4611 "Set up hooks for clock persistence."
4612 (require 'org-clock)
4613 (add-hook 'org-mode-hook 'org-clock-load)
4614 (add-hook 'kill-emacs-hook 'org-clock-save))
4616 (defgroup org-archive nil
4617 "Options concerning archiving in Org-mode."
4618 :tag "Org Archive"
4619 :group 'org-structure)
4621 (defcustom org-archive-location "%s_archive::"
4622 "The location where subtrees should be archived.
4624 The value of this variable is a string, consisting of two parts,
4625 separated by a double-colon. The first part is a filename and
4626 the second part is a headline.
4628 When the filename is omitted, archiving happens in the same file.
4629 %s in the filename will be replaced by the current file
4630 name (without the directory part). Archiving to a different file
4631 is useful to keep archived entries from contributing to the
4632 Org-mode Agenda.
4634 The archived entries will be filed as subtrees of the specified
4635 headline. When the headline is omitted, the subtrees are simply
4636 filed away at the end of the file, as top-level entries. Also in
4637 the heading you can use %s to represent the file name, this can be
4638 useful when using the same archive for a number of different files.
4640 Here are a few examples:
4641 \"%s_archive::\"
4642 If the current file is Projects.org, archive in file
4643 Projects.org_archive, as top-level trees. This is the default.
4645 \"::* Archived Tasks\"
4646 Archive in the current file, under the top-level headline
4647 \"* Archived Tasks\".
4649 \"~/org/archive.org::\"
4650 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4652 \"~/org/archive.org::* From %s\"
4653 Archive in file ~/org/archive.org (absolute path), under headlines
4654 \"From FILENAME\" where file name is the current file name.
4656 \"~/org/datetree.org::datetree/* Finished Tasks\"
4657 The \"datetree/\" string is special, signifying to archive
4658 items to the datetree. Items are placed in either the CLOSED
4659 date of the item, or the current date if there is no CLOSED date.
4660 The heading will be a subentry to the current date. There doesn't
4661 need to be a heading, but there always needs to be a slash after
4662 datetree. For example, to store archived items directly in the
4663 datetree, use \"~/org/datetree.org::datetree/\".
4665 \"basement::** Finished Tasks\"
4666 Archive in file ./basement (relative path), as level 3 trees
4667 below the level 2 heading \"** Finished Tasks\".
4669 You may set this option on a per-file basis by adding to the buffer a
4670 line like
4672 #+ARCHIVE: basement::** Finished Tasks
4674 You may also define it locally for a subtree by setting an ARCHIVE property
4675 in the entry. If such a property is found in an entry, or anywhere up
4676 the hierarchy, it will be used."
4677 :group 'org-archive
4678 :type 'string)
4680 (defcustom org-agenda-skip-archived-trees t
4681 "Non-nil means the agenda will skip any items located in archived trees.
4682 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4683 variable is no longer recommended, you should leave it at the value t.
4684 Instead, use the key `v' to cycle the archives-mode in the agenda."
4685 :group 'org-archive
4686 :group 'org-agenda-skip
4687 :type 'boolean)
4689 (defcustom org-columns-skip-archived-trees t
4690 "Non-nil means ignore archived trees when creating column view."
4691 :group 'org-archive
4692 :group 'org-properties
4693 :type 'boolean)
4695 (defcustom org-cycle-open-archived-trees nil
4696 "Non-nil means `org-cycle' will open archived trees.
4697 An archived tree is a tree marked with the tag ARCHIVE.
4698 When nil, archived trees will stay folded. You can still open them with
4699 normal outline commands like `show-all', but not with the cycling commands."
4700 :group 'org-archive
4701 :group 'org-cycle
4702 :type 'boolean)
4704 (defcustom org-sparse-tree-open-archived-trees nil
4705 "Non-nil means sparse tree construction shows matches in archived trees.
4706 When nil, matches in these trees are highlighted, but the trees are kept in
4707 collapsed state."
4708 :group 'org-archive
4709 :group 'org-sparse-trees
4710 :type 'boolean)
4712 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4713 "The default date type when building a sparse tree.
4714 When this is nil, a date is a scheduled or a deadline timestamp.
4715 Otherwise, these types are allowed:
4717 all: all timestamps
4718 active: only active timestamps (<...>)
4719 inactive: only inactive timestamps (<...)
4720 scheduled: only scheduled timestamps
4721 deadline: only deadline timestamps"
4722 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4723 (const :tag "All timestamps" all)
4724 (const :tag "Only active timestamps" active)
4725 (const :tag "Only inactive timestamps" inactive)
4726 (const :tag "Only scheduled timestamps" scheduled)
4727 (const :tag "Only deadline timestamps" deadline)
4728 (const :tag "Only closed timestamps" closed))
4729 :version "24.3"
4730 :group 'org-sparse-trees)
4732 (defun org-cycle-hide-archived-subtrees (state)
4733 "Re-hide all archived subtrees after a visibility state change."
4734 (when (and (not org-cycle-open-archived-trees)
4735 (not (memq state '(overview folded))))
4736 (save-excursion
4737 (let* ((globalp (memq state '(contents all)))
4738 (beg (if globalp (point-min) (point)))
4739 (end (if globalp (point-max) (org-end-of-subtree t))))
4740 (org-hide-archived-subtrees beg end)
4741 (goto-char beg)
4742 (if (looking-at (concat ".*:" org-archive-tag ":"))
4743 (message "%s" (substitute-command-keys
4744 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4746 (defun org-force-cycle-archived ()
4747 "Cycle subtree even if it is archived."
4748 (interactive)
4749 (setq this-command 'org-cycle)
4750 (let ((org-cycle-open-archived-trees t))
4751 (call-interactively 'org-cycle)))
4753 (defun org-hide-archived-subtrees (beg end)
4754 "Re-hide all archived subtrees after a visibility state change."
4755 (save-excursion
4756 (let* ((re (concat ":" org-archive-tag ":")))
4757 (goto-char beg)
4758 (while (re-search-forward re end t)
4759 (when (org-at-heading-p)
4760 (org-flag-subtree t)
4761 (org-end-of-subtree t))))))
4763 (declare-function outline-end-of-heading "outline" ())
4764 (declare-function outline-flag-region "outline" (from to flag))
4765 (defun org-flag-subtree (flag)
4766 (save-excursion
4767 (org-back-to-heading t)
4768 (outline-end-of-heading)
4769 (outline-flag-region (point)
4770 (progn (org-end-of-subtree t) (point))
4771 flag)))
4773 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4775 ;; Declare Column View Code
4777 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4778 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4779 (declare-function org-columns-compute "org-colview" (property))
4781 ;; Declare ID code
4783 (declare-function org-id-store-link "org-id")
4784 (declare-function org-id-locations-load "org-id")
4785 (declare-function org-id-locations-save "org-id")
4786 (defvar org-id-track-globally)
4788 ;;; Variables for pre-computed regular expressions, all buffer local
4790 (defvar org-todo-regexp nil
4791 "Matches any of the TODO state keywords.")
4792 (make-variable-buffer-local 'org-todo-regexp)
4793 (defvar org-not-done-regexp nil
4794 "Matches any of the TODO state keywords except the last one.")
4795 (make-variable-buffer-local 'org-not-done-regexp)
4796 (defvar org-not-done-heading-regexp nil
4797 "Matches a TODO headline that is not done.")
4798 (make-variable-buffer-local 'org-not-done-regexp)
4799 (defvar org-todo-line-regexp nil
4800 "Matches a headline and puts TODO state into group 2 if present.")
4801 (make-variable-buffer-local 'org-todo-line-regexp)
4802 (defvar org-complex-heading-regexp nil
4803 "Matches a headline and puts everything into groups:
4804 group 1: the stars
4805 group 2: The todo keyword, maybe
4806 group 3: Priority cookie
4807 group 4: True headline
4808 group 5: Tags")
4809 (make-variable-buffer-local 'org-complex-heading-regexp)
4810 (defvar org-complex-heading-regexp-format nil
4811 "Printf format to make regexp to match an exact headline.
4812 This regexp will match the headline of any node which has the
4813 exact headline text that is put into the format, but may have any
4814 TODO state, priority and tags.")
4815 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4816 (defvar org-todo-line-tags-regexp nil
4817 "Matches a headline and puts TODO state into group 2 if present.
4818 Also put tags into group 4 if tags are present.")
4819 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4821 (defconst org-plain-time-of-day-regexp
4822 (concat
4823 "\\(\\<[012]?[0-9]"
4824 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4825 "\\(--?"
4826 "\\(\\<[012]?[0-9]"
4827 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4828 "\\)?")
4829 "Regular expression to match a plain time or time range.
4830 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4831 groups carry important information:
4832 0 the full match
4833 1 the first time, range or not
4834 8 the second time, if it is a range.")
4836 (defconst org-plain-time-extension-regexp
4837 (concat
4838 "\\(\\<[012]?[0-9]"
4839 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4840 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4841 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4842 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4843 groups carry important information:
4844 0 the full match
4845 7 hours of duration
4846 9 minutes of duration")
4848 (defconst org-stamp-time-of-day-regexp
4849 (concat
4850 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4851 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4852 "\\(--?"
4853 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4854 "Regular expression to match a timestamp time or time range.
4855 After a match, the following groups carry important information:
4856 0 the full match
4857 1 date plus weekday, for back referencing to make sure both times are on the same day
4858 2 the first time, range or not
4859 4 the second time, if it is a range.")
4861 (defconst org-startup-options
4862 '(("fold" org-startup-folded t)
4863 ("overview" org-startup-folded t)
4864 ("nofold" org-startup-folded nil)
4865 ("showall" org-startup-folded nil)
4866 ("showeverything" org-startup-folded showeverything)
4867 ("content" org-startup-folded content)
4868 ("indent" org-startup-indented t)
4869 ("noindent" org-startup-indented nil)
4870 ("hidestars" org-hide-leading-stars t)
4871 ("showstars" org-hide-leading-stars nil)
4872 ("odd" org-odd-levels-only t)
4873 ("oddeven" org-odd-levels-only nil)
4874 ("align" org-startup-align-all-tables t)
4875 ("noalign" org-startup-align-all-tables nil)
4876 ("inlineimages" org-startup-with-inline-images t)
4877 ("noinlineimages" org-startup-with-inline-images nil)
4878 ("latexpreview" org-startup-with-latex-preview t)
4879 ("nolatexpreview" org-startup-with-latex-preview nil)
4880 ("customtime" org-display-custom-times t)
4881 ("logdone" org-log-done time)
4882 ("lognotedone" org-log-done note)
4883 ("nologdone" org-log-done nil)
4884 ("lognoteclock-out" org-log-note-clock-out t)
4885 ("nolognoteclock-out" org-log-note-clock-out nil)
4886 ("logrepeat" org-log-repeat state)
4887 ("lognoterepeat" org-log-repeat note)
4888 ("logdrawer" org-log-into-drawer t)
4889 ("nologdrawer" org-log-into-drawer nil)
4890 ("logstatesreversed" org-log-states-order-reversed t)
4891 ("nologstatesreversed" org-log-states-order-reversed nil)
4892 ("nologrepeat" org-log-repeat nil)
4893 ("logreschedule" org-log-reschedule time)
4894 ("lognotereschedule" org-log-reschedule note)
4895 ("nologreschedule" org-log-reschedule nil)
4896 ("logredeadline" org-log-redeadline time)
4897 ("lognoteredeadline" org-log-redeadline note)
4898 ("nologredeadline" org-log-redeadline nil)
4899 ("logrefile" org-log-refile time)
4900 ("lognoterefile" org-log-refile note)
4901 ("nologrefile" org-log-refile nil)
4902 ("fninline" org-footnote-define-inline t)
4903 ("nofninline" org-footnote-define-inline nil)
4904 ("fnlocal" org-footnote-section nil)
4905 ("fnauto" org-footnote-auto-label t)
4906 ("fnprompt" org-footnote-auto-label nil)
4907 ("fnconfirm" org-footnote-auto-label confirm)
4908 ("fnplain" org-footnote-auto-label plain)
4909 ("fnadjust" org-footnote-auto-adjust t)
4910 ("nofnadjust" org-footnote-auto-adjust nil)
4911 ("constcgs" constants-unit-system cgs)
4912 ("constSI" constants-unit-system SI)
4913 ("noptag" org-tag-persistent-alist nil)
4914 ("hideblocks" org-hide-block-startup t)
4915 ("nohideblocks" org-hide-block-startup nil)
4916 ("beamer" org-startup-with-beamer-mode t)
4917 ("entitiespretty" org-pretty-entities t)
4918 ("entitiesplain" org-pretty-entities nil))
4919 "Variable associated with STARTUP options for org-mode.
4920 Each element is a list of three items: the startup options (as written
4921 in the #+STARTUP line), the corresponding variable, and the value to set
4922 this variable to if the option is found. An optional forth element PUSH
4923 means to push this value onto the list in the variable.")
4925 (defcustom org-group-tags t
4926 "When non-nil (the default), use group tags.
4927 This can be turned on/off through `org-toggle-tags-groups'."
4928 :group 'org-tags
4929 :group 'org-startup
4930 :type 'boolean)
4932 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4934 (defun org-toggle-tags-groups ()
4935 "Toggle support for group tags.
4936 Support for group tags is controlled by the option
4937 `org-group-tags', which is non-nil by default."
4938 (interactive)
4939 (setq org-group-tags (not org-group-tags))
4940 (cond ((and (derived-mode-p 'org-agenda-mode)
4941 org-group-tags)
4942 (org-agenda-redo))
4943 ((derived-mode-p 'org-mode)
4944 (let ((org-inhibit-startup t)) (org-mode))))
4945 (message "Groups tags support has been turned %s"
4946 (if org-group-tags "on" "off")))
4948 (defun org-set-regexps-and-options (&optional tags-only)
4949 "Precompute regular expressions used in the current buffer.
4950 When optional argument TAGS-ONLY is non-nil, only compute tags
4951 related expressions."
4952 (when (derived-mode-p 'org-mode)
4953 (let ((alist (org--setup-collect-keywords
4954 (org-make-options-regexp
4955 (append '("FILETAGS" "TAGS" "SETUPFILE")
4956 (and (not tags-only)
4957 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4958 "LINK" "PRIORITIES" "PROPERTY" "SEQ_TODO"
4959 "STARTUP" "TODO" "TYP_TODO")))))))
4960 (org--setup-process-tags
4961 (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
4962 (unless tags-only
4963 ;; File properties.
4964 (org-set-local 'org-file-properties (cdr (assq 'property alist)))
4965 ;; Archive location.
4966 (let ((archive (cdr (assq 'archive alist))))
4967 (when archive (org-set-local 'org-archive-location archive)))
4968 ;; Category.
4969 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4970 (when cat
4971 (org-set-local 'org-category (intern cat))
4972 (org-set-local 'org-file-properties
4973 (org--update-property-plist
4974 "CATEGORY" cat org-file-properties))))
4975 ;; Columns.
4976 (let ((column (cdr (assq 'columns alist))))
4977 (when column (org-set-local 'org-columns-default-format column)))
4978 ;; Constants.
4979 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4980 ;; Link abbreviations.
4981 (let ((links (cdr (assq 'link alist))))
4982 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4983 ;; Priorities.
4984 (let ((priorities (cdr (assq 'priorities alist))))
4985 (when priorities
4986 (org-set-local 'org-highest-priority (nth 0 priorities))
4987 (org-set-local 'org-lowest-priority (nth 1 priorities))
4988 (org-set-local 'org-default-priority (nth 2 priorities))))
4989 ;; Startup options.
4990 (let ((startup (cdr (assq 'startup alist))))
4991 (dolist (option startup)
4992 (let ((entry (assoc-string option org-startup-options t)))
4993 (let ((var (nth 1 entry))
4994 (val (nth 2 entry)))
4995 (if (not (nth 3 entry)) (org-set-local var val)
4996 (unless (listp (symbol-value var))
4997 (org-set-local var nil))
4998 (add-to-list var val))))))
4999 ;; TODO keywords.
5000 (org-set-local 'org-todo-kwd-alist nil)
5001 (org-set-local 'org-todo-key-alist nil)
5002 (org-set-local 'org-todo-key-trigger nil)
5003 (org-set-local 'org-todo-keywords-1 nil)
5004 (org-set-local 'org-done-keywords nil)
5005 (org-set-local 'org-todo-heads nil)
5006 (org-set-local 'org-todo-sets nil)
5007 (org-set-local 'org-todo-log-states nil)
5008 (let ((todo-sequences
5009 (reverse
5010 (or (cdr (assq 'todo alist))
5011 (let ((d (default-value 'org-todo-keywords)))
5012 (if (not (stringp (car d))) d
5013 ;; XXX: Backward compatibility code.
5014 (list (cons org-todo-interpretation d))))))))
5015 (dolist (sequence todo-sequences)
5016 (let* ((sequence (or (run-hook-with-args-until-success
5017 'org-todo-setup-filter-hook sequence)
5018 sequence))
5019 (sequence-type (car sequence))
5020 (keywords (cdr sequence))
5021 (sep (member "|" keywords))
5022 names alist)
5023 (dolist (k (remove "|" keywords))
5024 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5026 (error "Invalid TODO keyword %s" k))
5027 (let ((name (match-string 1 k))
5028 (key (match-string 2 k))
5029 (log (org-extract-log-state-settings k)))
5030 (push name names)
5031 (push (cons name (and key (string-to-char key))) alist)
5032 (when log (push log org-todo-log-states))))
5033 (let* ((names (nreverse names))
5034 (done (if sep (org-remove-keyword-keys (cdr sep))
5035 (last names)))
5036 (head (car names))
5037 (tail (list sequence-type head (car done) (org-last done))))
5038 (add-to-list 'org-todo-heads head 'append)
5039 (push names org-todo-sets)
5040 (setq org-done-keywords (append org-done-keywords done nil))
5041 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5042 (setq org-todo-key-alist
5043 (append org-todo-key-alist
5044 (and alist
5045 (append '((:startgroup))
5046 (nreverse alist)
5047 '((:endgroup))))))
5048 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5049 (setq org-todo-sets (nreverse org-todo-sets)
5050 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5051 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5052 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5053 ;; Compute the regular expressions and other local variables.
5054 ;; Using `org-outline-regexp-bol' would complicate them much,
5055 ;; because of the fixed white space at the end of that string.
5056 (if (not org-done-keywords)
5057 (setq org-done-keywords
5058 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5059 (setq org-not-done-keywords
5060 (org-delete-all org-done-keywords
5061 (copy-sequence org-todo-keywords-1))
5062 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5063 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5064 org-not-done-heading-regexp
5065 (format org-heading-keyword-regexp-format org-not-done-regexp)
5066 org-todo-line-regexp
5067 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5068 org-complex-heading-regexp
5069 (concat "^\\(\\*+\\)"
5070 "\\(?: +" org-todo-regexp "\\)?"
5071 "\\(?: +\\(\\[#.\\]\\)\\)?"
5072 "\\(?: +\\(.*?\\)\\)??"
5073 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5074 "[ \t]*$")
5075 org-complex-heading-regexp-format
5076 (concat "^\\(\\*+\\)"
5077 "\\(?: +" org-todo-regexp "\\)?"
5078 "\\(?: +\\(\\[#.\\]\\)\\)?"
5079 "\\(?: +"
5080 ;; Stats cookies can be stuck to body.
5081 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5082 "\\(%s\\)"
5083 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5084 "\\)"
5085 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5086 "[ \t]*$")
5087 org-todo-line-tags-regexp
5088 (concat "^\\(\\*+\\)"
5089 "\\(?: +" org-todo-regexp "\\)?"
5090 "\\(?: +\\(.*?\\)\\)??"
5091 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5092 "[ \t]*$"))
5093 (org-compute-latex-and-related-regexp)))))
5095 (defun org--setup-collect-keywords (regexp &optional files alist)
5096 "Return setup keywords values as an alist.
5098 REGEXP matches a subset of setup keywords. FILES is a list of
5099 file names already visited. It is used to avoid circular setup
5100 files. ALIST, when non-nil, is the alist computed so far.
5102 Return value contains the following keys: `archive', `category',
5103 `columns', `constants', `filetags', `link', `priorities',
5104 `property', `startup', `tags' and `todo'."
5105 (org-with-wide-buffer
5106 (goto-char (point-min))
5107 (let ((case-fold-search t))
5108 (while (re-search-forward regexp nil t)
5109 (let ((element (org-element-at-point)))
5110 (when (eq (org-element-type element) 'keyword)
5111 (let ((key (org-element-property :key element))
5112 (value (org-element-property :value element)))
5113 (cond
5114 ((equal key "ARCHIVE")
5115 (when (org-string-nw-p value)
5116 (push (cons 'archive value) alist)))
5117 ((equal key "CATEGORY") (push (cons 'category value) alist))
5118 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5119 ((equal key "CONSTANTS")
5120 (let* ((constants (assq 'constants alist))
5121 (store (cdr constants)))
5122 (dolist (pair (org-split-string value))
5123 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5124 pair)
5125 (let* ((name (match-string 1 pair))
5126 (value (match-string 2 pair))
5127 (old (assoc name store)))
5128 (if old (setcdr old value)
5129 (push (cons name value) store)))))
5130 (if constants (setcdr constants store)
5131 (push (cons 'constants store) alist))))
5132 ((equal key "FILETAGS")
5133 (when (org-string-nw-p value)
5134 (let ((old (assq 'filetags alist))
5135 (new (apply #'nconc
5136 (mapcar (lambda (x) (org-split-string x ":"))
5137 (org-split-string value)))))
5138 (if old (setcdr old (nconc new (cdr old)))
5139 (push (cons 'filetags new) alist)))))
5140 ((equal key "LINK")
5141 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5142 (let ((links (assq 'link alist))
5143 (pair (cons (org-match-string-no-properties 1 value)
5144 (org-match-string-no-properties 2 value))))
5145 (if links (push pair (cdr links))
5146 (push (list 'link pair) alist)))))
5147 ((equal key "PRIORITIES")
5148 (push (cons 'priorities
5149 (let ((prio (org-split-string value)))
5150 (if (< (length prio) 3) '(?A ?C ?B)
5151 (mapcar #'string-to-char prio))))
5152 alist))
5153 ((equal key "PROPERTY")
5154 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5155 (let* ((property (assq 'property alist))
5156 (value (org--update-property-plist
5157 (org-match-string-no-properties 1 value)
5158 (org-match-string-no-properties 2 value)
5159 (cdr property))))
5160 (if property (setcdr property value)
5161 (push (cons 'property value) alist)))))
5162 ((equal key "STARTUP")
5163 (let ((startup (assq 'startup alist)))
5164 (if startup
5165 (setcdr startup
5166 (nconc (cdr startup) (org-split-string value)))
5167 (push (cons 'startup (org-split-string value)) alist))))
5168 ((equal key "TAGS")
5169 (let ((tag-cell (assq 'tags alist)))
5170 (if tag-cell
5171 (setcdr tag-cell
5172 (nconc (cdr tag-cell)
5173 '("\\n")
5174 (org-split-string value)))
5175 (push (cons 'tags (org-split-string value)) alist))))
5176 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5177 (let ((todo (assq 'todo alist))
5178 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5179 (org-split-string value))))
5180 (if todo (push value (cdr todo))
5181 (push (list 'todo value) alist))))
5182 ((equal key "SETUPFILE")
5183 (unless buffer-read-only ; Do not check in Gnus messages.
5184 (let ((f (expand-file-name (org-remove-double-quotes value))))
5185 (when (and (org-string-nw-p f)
5186 (file-readable-p f)
5187 (not (member f files)))
5188 (with-temp-buffer
5189 (let ((org-inhibit-startup t)) (org-mode))
5190 (insert-file-contents f)
5191 (setq alist
5192 (org--setup-collect-keywords
5193 regexp alist (cons f files)))))))))))))))
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 (org-set-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 (:grouptags ":")
5211 (:newline "\\n")
5212 (otherwise (concat (car tag)
5213 (and (characterp (cdr tag))
5214 (format "(%c)" (cdr tag)))))))
5215 org-tag-alist)))
5216 ;; Process the tags.
5217 (org-set-local 'org-tag-groups-alist nil)
5218 (org-set-local 'org-tag-alist nil)
5219 (let (group-flag)
5220 (dolist (e tags)
5221 (cond
5222 ((equal e "{")
5223 (push '(:startgroup) org-tag-alist)
5224 (setq group-flag t))
5225 ((equal e "}")
5226 (push '(:endgroup) org-tag-alist)
5227 (setq group-flag nil))
5228 ((equal e ":")
5229 (push '(:grouptags) org-tag-alist)
5230 (setq group-flag 'append))
5231 ((equal e "\\n") (push '(:newline) org-tag-alist))
5232 ((string-match (org-re "\\`\\([[:alnum:]_@#%]+\\)\\(?:(\\(.\\))\\)?\\'")
5234 (let ((tag (match-string 1 e))
5235 (key (and (match-beginning 2)
5236 (string-to-char (match-string 2 e)))))
5237 (cond ((eq group-flag 'append)
5238 (setcar org-tag-groups-alist
5239 (append (car org-tag-groups-alist) (list tag))))
5240 (group-flag (push (list tag) org-tag-groups-alist)))
5241 (unless (assoc tag org-tag-alist)
5242 (push (cons tag key) org-tag-alist)))))))
5243 (setq org-tag-alist (nreverse org-tag-alist)))
5245 (defun org-file-contents (file &optional noerror)
5246 "Return the contents of FILE, as a string."
5247 (if (and file (file-readable-p file))
5248 (with-temp-buffer
5249 (insert-file-contents file)
5250 (buffer-string))
5251 (funcall (if noerror 'message 'error)
5252 "Cannot read file \"%s\"%s"
5253 file
5254 (let ((from (buffer-file-name (buffer-base-buffer))))
5255 (if from (concat " (referenced in file \"" from "\")") "")))))
5257 (defun org-extract-log-state-settings (x)
5258 "Extract the log state setting from a TODO keyword string.
5259 This will extract info from a string like \"WAIT(w@/!)\"."
5260 (let (kw key log1 log2)
5261 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5262 (setq kw (match-string 1 x)
5263 key (and (match-end 2) (match-string 2 x))
5264 log1 (and (match-end 3) (match-string 3 x))
5265 log2 (and (match-end 4) (match-string 4 x)))
5266 (and (or log1 log2)
5267 (list kw
5268 (and log1 (if (equal log1 "!") 'time 'note))
5269 (and log2 (if (equal log2 "!") 'time 'note)))))))
5271 (defun org-remove-keyword-keys (list)
5272 "Remove a pair of parenthesis at the end of each string in LIST."
5273 (mapcar (lambda (x)
5274 (if (string-match "(.*)$" x)
5275 (substring x 0 (match-beginning 0))
5277 list))
5279 (defun org-assign-fast-keys (alist)
5280 "Assign fast keys to a keyword-key alist.
5281 Respect keys that are already there."
5282 (let (new e (alt ?0))
5283 (while (setq e (pop alist))
5284 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5285 (cdr e)) ;; Key already assigned.
5286 (push e new)
5287 (let ((clist (string-to-list (downcase (car e))))
5288 (used (append new alist)))
5289 (when (= (car clist) ?@)
5290 (pop clist))
5291 (while (and clist (rassoc (car clist) used))
5292 (pop clist))
5293 (unless clist
5294 (while (rassoc alt used)
5295 (incf alt)))
5296 (push (cons (car e) (or (car clist) alt)) new))))
5297 (nreverse new)))
5299 ;;; Some variables used in various places
5301 (defvar org-window-configuration nil
5302 "Used in various places to store a window configuration.")
5303 (defvar org-selected-window nil
5304 "Used in various places to store a window configuration.")
5305 (defvar org-finish-function nil
5306 "Function to be called when `C-c C-c' is used.
5307 This is for getting out of special buffers like capture.")
5310 ;; FIXME: Occasionally check by commenting these, to make sure
5311 ;; no other functions uses these, forgetting to let-bind them.
5312 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5313 (defvar org-last-state)
5314 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5316 ;; Defined somewhere in this file, but used before definition.
5317 (defvar org-entities) ;; defined in org-entities.el
5318 (defvar org-struct-menu)
5319 (defvar org-org-menu)
5320 (defvar org-tbl-menu)
5322 ;;;; Define the Org-mode
5324 ;; We use a before-change function to check if a table might need
5325 ;; an update.
5326 (defvar org-table-may-need-update t
5327 "Indicates that a table might need an update.
5328 This variable is set by `org-before-change-function'.
5329 `org-table-align' sets it back to nil.")
5330 (defun org-before-change-function (beg end)
5331 "Every change indicates that a table might need an update."
5332 (setq org-table-may-need-update t))
5333 (defvar org-mode-map)
5334 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5335 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5336 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5337 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5338 (defvar org-table-buffer-is-an nil)
5340 (defvar bidi-paragraph-direction)
5341 (defvar buffer-face-mode-face)
5343 (require 'outline)
5344 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5345 (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"))
5346 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5348 ;; Other stuff we need.
5349 (require 'time-date)
5350 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5351 (require 'easymenu)
5352 (require 'overlay)
5354 ;; (require 'org-macs) moved higher up in the file before it is first used
5355 (require 'org-entities)
5356 ;; (require 'org-compat) moved higher up in the file before it is first used
5357 (require 'org-faces)
5358 (require 'org-list)
5359 (require 'org-pcomplete)
5360 (require 'org-src)
5361 (require 'org-footnote)
5362 (require 'org-macro)
5364 ;; babel
5365 (require 'ob)
5367 ;;;###autoload
5368 (define-derived-mode org-mode outline-mode "Org"
5369 "Outline-based notes management and organizer, alias
5370 \"Carsten's outline-mode for keeping track of everything.\"
5372 Org-mode develops organizational tasks around a NOTES file which
5373 contains information about projects as plain text. Org-mode is
5374 implemented on top of outline-mode, which is ideal to keep the content
5375 of large files well structured. It supports ToDo items, deadlines and
5376 time stamps, which magically appear in the diary listing of the Emacs
5377 calendar. Tables are easily created with a built-in table editor.
5378 Plain text URL-like links connect to websites, emails (VM), Usenet
5379 messages (Gnus), BBDB entries, and any files related to the project.
5380 For printing and sharing of notes, an Org-mode file (or a part of it)
5381 can be exported as a structured ASCII or HTML file.
5383 The following commands are available:
5385 \\{org-mode-map}"
5387 ;; Get rid of Outline menus, they are not needed
5388 ;; Need to do this here because define-derived-mode sets up
5389 ;; the keymap so late. Still, it is a waste to call this each time
5390 ;; we switch another buffer into org-mode.
5391 (if (featurep 'xemacs)
5392 (when (boundp 'outline-mode-menu-heading)
5393 ;; Assume this is Greg's port, it uses easymenu
5394 (easy-menu-remove outline-mode-menu-heading)
5395 (easy-menu-remove outline-mode-menu-show)
5396 (easy-menu-remove outline-mode-menu-hide))
5397 (define-key org-mode-map [menu-bar headings] 'undefined)
5398 (define-key org-mode-map [menu-bar hide] 'undefined)
5399 (define-key org-mode-map [menu-bar show] 'undefined))
5401 (org-load-modules-maybe)
5402 (easy-menu-add org-org-menu)
5403 (easy-menu-add org-tbl-menu)
5404 (org-install-agenda-files-menu)
5405 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5406 (add-to-invisibility-spec '(org-cwidth))
5407 (add-to-invisibility-spec '(org-hide-block . t))
5408 (when (featurep 'xemacs)
5409 (org-set-local 'line-move-ignore-invisible t))
5410 (org-set-local 'outline-regexp org-outline-regexp)
5411 (org-set-local 'outline-level 'org-outline-level)
5412 (setq bidi-paragraph-direction 'left-to-right)
5413 (when (and org-ellipsis
5414 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5415 (fboundp 'make-glyph-code))
5416 (unless org-display-table
5417 (setq org-display-table (make-display-table)))
5418 (set-display-table-slot
5419 org-display-table 4
5420 (vconcat (mapcar
5421 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5422 org-ellipsis)))
5423 (if (stringp org-ellipsis) org-ellipsis "..."))))
5424 (setq buffer-display-table org-display-table))
5425 (org-set-regexps-and-options)
5426 (org-set-font-lock-defaults)
5427 (when (and org-tag-faces (not org-tags-special-faces-re))
5428 ;; tag faces set outside customize.... force initialization.
5429 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5430 ;; Calc embedded
5431 (org-set-local 'calc-embedded-open-mode "# ")
5432 ;; Modify a few syntax entries
5433 (modify-syntax-entry ?@ "w")
5434 (modify-syntax-entry ?\" "\"")
5435 (modify-syntax-entry ?\\ "_")
5436 (modify-syntax-entry ?~ "_")
5437 (if org-startup-truncated (setq truncate-lines t))
5438 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5439 (org-set-local 'font-lock-unfontify-region-function
5440 'org-unfontify-region)
5441 ;; Activate before-change-function
5442 (org-set-local 'org-table-may-need-update t)
5443 (org-add-hook 'before-change-functions 'org-before-change-function nil
5444 'local)
5445 ;; Check for running clock before killing a buffer
5446 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5447 ;; Initialize macros templates.
5448 (org-macro-initialize-templates)
5449 ;; Initialize radio targets.
5450 (org-update-radio-target-regexp)
5451 ;; Indentation.
5452 (org-set-local 'indent-line-function 'org-indent-line)
5453 (org-set-local 'indent-region-function 'org-indent-region)
5454 ;; Filling and auto-filling.
5455 (org-setup-filling)
5456 ;; Comments.
5457 (org-setup-comments-handling)
5458 ;; Initialize cache.
5459 (org-element-cache-reset)
5460 ;; Beginning/end of defun
5461 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5462 (org-set-local 'end-of-defun-function
5463 (lambda ()
5464 (if (not (org-at-heading-p))
5465 (org-forward-element)
5466 (org-forward-element)
5467 (forward-char -1))))
5468 ;; Next error for sparse trees
5469 (org-set-local 'next-error-function 'org-occur-next-match)
5470 ;; Make sure dependence stuff works reliably, even for users who set it
5471 ;; too late :-(
5472 (if org-enforce-todo-dependencies
5473 (add-hook 'org-blocker-hook
5474 'org-block-todo-from-children-or-siblings-or-parent)
5475 (remove-hook 'org-blocker-hook
5476 'org-block-todo-from-children-or-siblings-or-parent))
5477 (if org-enforce-todo-checkbox-dependencies
5478 (add-hook 'org-blocker-hook
5479 'org-block-todo-from-checkboxes)
5480 (remove-hook 'org-blocker-hook
5481 'org-block-todo-from-checkboxes))
5483 ;; Align options lines
5484 (org-set-local
5485 'align-mode-rules-list
5486 '((org-in-buffer-settings
5487 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5488 (modes . '(org-mode)))))
5490 ;; Imenu
5491 (org-set-local 'imenu-create-index-function
5492 'org-imenu-get-tree)
5494 ;; Make isearch reveal context
5495 (if (or (featurep 'xemacs)
5496 (not (boundp 'outline-isearch-open-invisible-function)))
5497 ;; Emacs 21 and XEmacs make use of the hook
5498 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5499 ;; Emacs 22 deals with this through a special variable
5500 (org-set-local 'outline-isearch-open-invisible-function
5501 (lambda (&rest ignore) (org-show-context 'isearch))))
5503 ;; Setup the pcomplete hooks
5504 (set (make-local-variable 'pcomplete-command-completion-function)
5505 'org-pcomplete-initial)
5506 (set (make-local-variable 'pcomplete-command-name-function)
5507 'org-command-at-point)
5508 (set (make-local-variable 'pcomplete-default-completion-function)
5509 'ignore)
5510 (set (make-local-variable 'pcomplete-parse-arguments-function)
5511 'org-parse-arguments)
5512 (set (make-local-variable 'pcomplete-termination-string) "")
5513 (when (>= emacs-major-version 23)
5514 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5516 ;; If empty file that did not turn on org-mode automatically, make it to.
5517 (if (and org-insert-mode-line-in-empty-file
5518 (org-called-interactively-p 'any)
5519 (= (point-min) (point-max)))
5520 (insert "# -*- mode: org -*-\n\n"))
5521 (unless org-inhibit-startup
5522 (org-unmodified
5523 (and org-startup-with-beamer-mode (org-beamer-mode))
5524 (when org-startup-align-all-tables
5525 (org-table-map-tables 'org-table-align 'quietly))
5526 (when org-startup-with-inline-images
5527 (org-display-inline-images))
5528 (when org-startup-with-latex-preview
5529 (org-toggle-latex-fragment))
5530 (unless org-inhibit-startup-visibility-stuff
5531 (org-set-startup-visibility))
5532 (org-refresh-effort-properties)))
5533 ;; Try to set org-hide correctly
5534 (let ((foreground (org-find-invisible-foreground)))
5535 (if foreground
5536 (set-face-foreground 'org-hide foreground))))
5538 ;; Update `customize-package-emacs-version-alist'
5539 (add-to-list 'customize-package-emacs-version-alist
5540 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5541 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5542 ("8.2.6" . "24.4")))
5544 (defvar org-mode-transpose-word-syntax-table
5545 (let ((st (make-syntax-table)))
5546 (mapc (lambda(c) (modify-syntax-entry
5547 (string-to-char (car c)) "w p" st))
5548 org-emphasis-alist)
5549 st))
5551 (when (fboundp 'abbrev-table-put)
5552 (abbrev-table-put org-mode-abbrev-table
5553 :parents (list text-mode-abbrev-table)))
5555 (defun org-find-invisible-foreground ()
5556 (let ((candidates (remove
5557 "unspecified-bg"
5558 (nconc
5559 (list (face-background 'default)
5560 (face-background 'org-default))
5561 (mapcar
5562 (lambda (alist)
5563 (when (boundp alist)
5564 (cdr (assoc 'background-color (symbol-value alist)))))
5565 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5566 (list (face-foreground 'org-hide))))))
5567 (car (remove nil candidates))))
5569 (defun org-current-time (&optional rounding-minutes past)
5570 "Current time, possibly rounded to ROUNDING-MINUTES.
5571 When ROUNDING-MINUTES is not an integer, fall back on the car of
5572 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5573 the rounding returns a past time."
5574 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5575 (car org-time-stamp-rounding-minutes)))
5576 (time (decode-time)) res)
5577 (if (< r 1)
5578 (current-time)
5579 (setq res
5580 (apply 'encode-time
5581 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5582 (nthcdr 2 time))))
5583 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5584 (seconds-to-time (- (org-float-time res) (* r 60)))
5585 res))))
5587 (defun org-today ()
5588 "Return today date, considering `org-extend-today-until'."
5589 (time-to-days
5590 (time-subtract (current-time)
5591 (list 0 (* 3600 org-extend-today-until) 0))))
5593 ;;;; Font-Lock stuff, including the activators
5595 (defvar org-mouse-map (make-sparse-keymap))
5596 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5597 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5598 (when org-mouse-1-follows-link
5599 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5600 (when org-tab-follows-link
5601 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5602 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5604 (require 'font-lock)
5606 (defconst org-non-link-chars "]\t\n\r<>")
5607 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5608 "file+sys" "news" "shell" "elisp" "doi" "message"
5609 "help"))
5610 (defvar org-link-types-re nil
5611 "Matches a link that has a url-like prefix like \"http:\"")
5612 (defvar org-link-re-with-space nil
5613 "Matches a link with spaces, optional angular brackets around it.")
5614 (defvar org-link-re-with-space2 nil
5615 "Matches a link with spaces, optional angular brackets around it.")
5616 (defvar org-link-re-with-space3 nil
5617 "Matches a link with spaces, only for internal part in bracket links.")
5618 (defvar org-angle-link-re nil
5619 "Matches link with angular brackets, spaces are allowed.")
5620 (defvar org-plain-link-re nil
5621 "Matches plain link, without spaces.")
5622 (defvar org-bracket-link-regexp nil
5623 "Matches a link in double brackets.")
5624 (defvar org-bracket-link-analytic-regexp nil
5625 "Regular expression used to analyze links.
5626 Here is what the match groups contain after a match:
5627 1: http:
5628 2: http
5629 3: path
5630 4: [desc]
5631 5: desc")
5632 (defvar org-bracket-link-analytic-regexp++ nil
5633 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5634 (defvar org-any-link-re nil
5635 "Regular expression matching any link.")
5637 (defconst org-match-sexp-depth 3
5638 "Number of stacked braces for sub/superscript matching.")
5640 (defun org-create-multibrace-regexp (left right n)
5641 "Create a regular expression which will match a balanced sexp.
5642 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5643 as single character strings.
5644 The regexp returned will match the entire expression including the
5645 delimiters. It will also define a single group which contains the
5646 match except for the outermost delimiters. The maximum depth of
5647 stacked delimiters is N. Escaping delimiters is not possible."
5648 (let* ((nothing (concat "[^" left right "]*?"))
5649 (or "\\|")
5650 (re nothing)
5651 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5652 (while (> n 1)
5653 (setq n (1- n)
5654 re (concat re or next)
5655 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5656 (concat left "\\(" re "\\)" right)))
5658 (defconst org-match-substring-regexp
5659 (concat
5660 "\\(\\S-\\)\\([_^]\\)\\("
5661 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5662 "\\|"
5663 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5664 "\\|"
5665 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5666 "The regular expression matching a sub- or superscript.")
5668 (defconst org-match-substring-with-braces-regexp
5669 (concat
5670 "\\(\\S-\\)\\([_^]\\)"
5671 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5672 "The regular expression matching a sub- or superscript, forcing braces.")
5674 (defun org-make-link-regexps ()
5675 "Update the link regular expressions.
5676 This should be called after the variable `org-link-types' has changed."
5677 (let ((types-re (regexp-opt org-link-types t)))
5678 (setq org-link-types-re
5679 (concat "\\`" types-re ":")
5680 org-link-re-with-space
5681 (concat "<?" types-re ":"
5682 "\\([^" org-non-link-chars " ]"
5683 "[^" org-non-link-chars "]*"
5684 "[^" org-non-link-chars " ]\\)>?")
5685 org-link-re-with-space2
5686 (concat "<?" types-re ":"
5687 "\\([^" org-non-link-chars " ]"
5688 "[^\t\n\r]*"
5689 "[^" org-non-link-chars " ]\\)>?")
5690 org-link-re-with-space3
5691 (concat "<?" types-re ":"
5692 "\\([^" org-non-link-chars " ]"
5693 "[^\t\n\r]*\\)")
5694 org-angle-link-re
5695 (concat "<" types-re ":"
5696 "\\([^" org-non-link-chars " ]"
5697 "[^" org-non-link-chars "]*"
5698 "\\)>")
5699 org-plain-link-re
5700 (concat
5701 "\\<" types-re ":"
5702 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5703 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5704 org-bracket-link-regexp
5705 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5706 org-bracket-link-analytic-regexp
5707 (concat
5708 "\\[\\["
5709 "\\(" types-re ":\\)?"
5710 "\\([^]]+\\)"
5711 "\\]"
5712 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5713 "\\]")
5714 org-bracket-link-analytic-regexp++
5715 (concat
5716 "\\[\\["
5717 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5718 "\\([^]]+\\)"
5719 "\\]"
5720 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5721 "\\]")
5722 org-any-link-re
5723 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5724 org-angle-link-re "\\)\\|\\("
5725 org-plain-link-re "\\)"))))
5727 (org-make-link-regexps)
5729 (defvar org-emph-face nil)
5731 (defun org-do-emphasis-faces (limit)
5732 "Run through the buffer and emphasize strings."
5733 (let (rtn a)
5734 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5735 (let* ((border (char-after (match-beginning 3)))
5736 (bre (regexp-quote (char-to-string border))))
5737 (if (and (not (= border (char-after (match-beginning 4))))
5738 (not (save-match-data
5739 (string-match (concat bre ".*" bre)
5740 (replace-regexp-in-string
5741 "\n" " "
5742 (substring (match-string 2) 1 -1))))))
5743 (progn
5744 (setq rtn t)
5745 (setq a (assoc (match-string 3) org-emphasis-alist))
5746 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5747 'face
5748 (nth 1 a))
5749 (and (nth 2 a)
5750 (org-remove-flyspell-overlays-in
5751 (match-beginning 0) (match-end 0)))
5752 (add-text-properties (match-beginning 2) (match-end 2)
5753 '(font-lock-multiline t org-emphasis t))
5754 (when org-hide-emphasis-markers
5755 (add-text-properties (match-end 4) (match-beginning 5)
5756 '(invisible org-link))
5757 (add-text-properties (match-beginning 3) (match-end 3)
5758 '(invisible org-link))))))
5759 (goto-char (1+ (match-beginning 0))))
5760 rtn))
5762 (defun org-emphasize (&optional char)
5763 "Insert or change an emphasis, i.e. a font like bold or italic.
5764 If there is an active region, change that region to a new emphasis.
5765 If there is no region, just insert the marker characters and position
5766 the cursor between them.
5767 CHAR should be the marker character. If it is a space, it means to
5768 remove the emphasis of the selected region.
5769 If CHAR is not given (for example in an interactive call) it will be
5770 prompted for."
5771 (interactive)
5772 (let ((erc org-emphasis-regexp-components)
5773 (prompt "")
5774 (string "") beg end move c s)
5775 (if (org-region-active-p)
5776 (setq beg (region-beginning) end (region-end)
5777 string (buffer-substring beg end))
5778 (setq move t))
5780 (unless char
5781 (message "Emphasis marker or tag: [%s]"
5782 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5783 (setq char (read-char-exclusive)))
5784 (if (equal char ?\ )
5785 (setq s "" move nil)
5786 (unless (assoc (char-to-string char) org-emphasis-alist)
5787 (user-error "No such emphasis marker: \"%c\"" char))
5788 (setq s (char-to-string char)))
5789 (while (and (> (length string) 1)
5790 (equal (substring string 0 1) (substring string -1))
5791 (assoc (substring string 0 1) org-emphasis-alist))
5792 (setq string (substring string 1 -1)))
5793 (setq string (concat s string s))
5794 (if beg (delete-region beg end))
5795 (unless (or (bolp)
5796 (string-match (concat "[" (nth 0 erc) "\n]")
5797 (char-to-string (char-before (point)))))
5798 (insert " "))
5799 (unless (or (eobp)
5800 (string-match (concat "[" (nth 1 erc) "\n]")
5801 (char-to-string (char-after (point)))))
5802 (insert " ") (backward-char 1))
5803 (insert string)
5804 (and move (backward-char 1))))
5806 (defconst org-nonsticky-props
5807 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5809 (defsubst org-rear-nonsticky-at (pos)
5810 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5812 (defun org-activate-plain-links (limit)
5813 "Add link properties for plain links."
5814 (let (f hl)
5815 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5816 (not (member 'org-tag
5817 (get-text-property (1- (match-beginning 0)) 'face)))
5818 (not (org-in-src-block-p)))
5819 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5820 (setq f (get-text-property (match-beginning 0) 'face))
5821 (setq hl (org-match-string-no-properties 0))
5822 (if (or (eq f 'org-tag)
5823 (and (listp f) (memq 'org-tag f)))
5825 (add-text-properties (match-beginning 0) (match-end 0)
5826 (list 'mouse-face 'highlight
5827 'face 'org-link
5828 'htmlize-link `(:uri ,hl)
5829 'keymap org-mouse-map))
5830 (org-rear-nonsticky-at (match-end 0)))
5831 t)))
5833 (defun org-activate-code (limit)
5834 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5835 (progn
5836 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5837 (remove-text-properties (match-beginning 0) (match-end 0)
5838 '(display t invisible t intangible t))
5839 t)))
5841 (defcustom org-src-fontify-natively t
5842 "When non-nil, fontify code in code blocks."
5843 :type 'boolean
5844 :version "24.4"
5845 :package-version '(Org . "8.3")
5846 :group 'org-appearance
5847 :group 'org-babel)
5849 (defcustom org-allow-promoting-top-level-subtree nil
5850 "When non-nil, allow promoting a top level subtree.
5851 The leading star of the top level headline will be replaced
5852 by a #."
5853 :type 'boolean
5854 :version "24.1"
5855 :group 'org-appearance)
5857 (defun org-fontify-meta-lines-and-blocks (limit)
5858 (condition-case nil
5859 (org-fontify-meta-lines-and-blocks-1 limit)
5860 (error (message "org-mode fontification error"))))
5862 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5863 "Fontify #+ lines and blocks."
5864 (let ((case-fold-search t))
5865 (if (re-search-forward
5866 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5867 limit t)
5868 (let ((beg (match-beginning 0))
5869 (block-start (match-end 0))
5870 (block-end nil)
5871 (lang (match-string 7))
5872 (beg1 (line-beginning-position 2))
5873 (dc1 (downcase (match-string 2)))
5874 (dc3 (downcase (match-string 3)))
5875 end end1 quoting block-type ovl)
5876 (cond
5877 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5878 ;; a single line of backend-specific content
5879 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5880 (remove-text-properties (match-beginning 0) (match-end 0)
5881 '(display t invisible t intangible t))
5882 (add-text-properties (match-beginning 1) (match-end 3)
5883 '(font-lock-fontified t face org-meta-line))
5884 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5885 '(font-lock-fontified t face org-block))
5886 ; for backend-specific code
5888 ((and (match-end 4) (equal dc3 "+begin"))
5889 ;; Truly a block
5890 (setq block-type (downcase (match-string 5))
5891 quoting (member block-type org-protecting-blocks))
5892 (when (re-search-forward
5893 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5894 nil t) ;; on purpose, we look further than LIMIT
5895 (setq end (min (point-max) (match-end 0))
5896 end1 (min (point-max) (1- (match-beginning 0))))
5897 (setq block-end (match-beginning 0))
5898 (when quoting
5899 (org-remove-flyspell-overlays-in beg1 end1)
5900 (remove-text-properties beg end
5901 '(display t invisible t intangible t)))
5902 (add-text-properties
5903 beg end '(font-lock-fontified t font-lock-multiline t))
5904 (add-text-properties beg beg1 '(face org-meta-line))
5905 (org-remove-flyspell-overlays-in beg beg1)
5906 (add-text-properties ; For end_src
5907 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5908 (org-remove-flyspell-overlays-in end1 end)
5909 (cond
5910 ((and lang (not (string= lang "")) org-src-fontify-natively)
5911 (org-src-font-lock-fontify-block lang block-start block-end)
5912 (add-text-properties beg1 block-end '(src-block t)))
5913 (quoting
5914 (add-text-properties beg1 (min (point-max) (1+ end1))
5915 '(face org-block))) ; end of source block
5916 ((not org-fontify-quote-and-verse-blocks))
5917 ((string= block-type "quote")
5918 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5919 ((string= block-type "verse")
5920 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5921 (add-text-properties beg beg1 '(face org-block-begin-line))
5922 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5923 '(face org-block-end-line))
5925 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5926 (org-remove-flyspell-overlays-in
5927 (match-beginning 0)
5928 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5929 (add-text-properties
5930 beg (match-end 3)
5931 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5932 '(font-lock-fontified t invisible t)
5933 '(font-lock-fontified t face org-document-info-keyword)))
5934 (add-text-properties
5935 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5936 (if (string-equal dc1 "+title:")
5937 '(font-lock-fontified t face org-document-title)
5938 '(font-lock-fontified t face org-document-info))))
5939 ((or (equal dc1 "+results")
5940 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5941 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5942 "+call:" "+header:" "+headers:" "+name:"))
5943 (and (match-end 4) (equal dc3 "+attr")))
5944 (org-remove-flyspell-overlays-in
5945 (match-beginning 0)
5946 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5947 (add-text-properties
5948 beg (match-end 0)
5949 '(font-lock-fontified t face org-meta-line))
5951 ((member dc3 '(" " ""))
5952 (org-remove-flyspell-overlays-in beg (match-end 0))
5953 (add-text-properties
5954 beg (match-end 0)
5955 '(font-lock-fontified t face font-lock-comment-face)))
5956 (t ;; just any other in-buffer setting, but not indented
5957 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5958 (add-text-properties
5959 beg (match-end 0)
5960 '(font-lock-fontified t face org-meta-line))
5961 t))))))
5963 (defun org-fontify-drawers (limit)
5964 "Fontify drawers."
5965 (when (re-search-forward org-drawer-regexp limit t)
5966 (add-text-properties
5967 (match-beginning 0) (match-end 0)
5968 '(font-lock-fontified t face org-special-keyword))
5969 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5972 (defun org-fontify-macros (limit)
5973 "Fontify macros."
5974 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5975 (add-text-properties
5976 (match-beginning 0) (match-end 0)
5977 '(font-lock-fontified t face org-macro))
5978 (when org-hide-macro-markers
5979 (add-text-properties (match-end 2) (match-beginning 2)
5980 '(invisible t))
5981 (add-text-properties (match-beginning 1) (match-end 1)
5982 '(invisible t)))
5983 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5986 (defun org-activate-angle-links (limit)
5987 "Add text properties for angle links."
5988 (if (and (re-search-forward org-angle-link-re limit t)
5989 (not (org-in-src-block-p)))
5990 (progn
5991 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5992 (add-text-properties (match-beginning 0) (match-end 0)
5993 (list 'mouse-face 'highlight
5994 'keymap org-mouse-map))
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 org-target-link-regexp nil
6073 "Regular expression matching radio targets in plain text.")
6074 (make-variable-buffer-local 'org-target-link-regexp)
6076 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6077 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6078 border border border))
6079 "Regular expression matching a link target.")
6081 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6082 "Regular expression matching a radio target.")
6084 (defconst org-any-target-regexp
6085 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6086 "Regular expression matching any target.")
6088 (defun org-activate-target-links (limit)
6089 "Add text properties for target matches."
6090 (when org-target-link-regexp
6091 (let ((case-fold-search t))
6092 (if (re-search-forward org-target-link-regexp limit t)
6093 (progn
6094 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6095 (add-text-properties (match-beginning 1) (match-end 1)
6096 (list 'mouse-face 'highlight
6097 'keymap org-mouse-map
6098 'help-echo "Radio target link"
6099 'org-linked-text t))
6100 (org-rear-nonsticky-at (match-end 1))
6101 t)))))
6103 (defun org-update-radio-target-regexp ()
6104 "Find all radio targets in this file and update the regular expression.
6105 Also refresh fontification if needed."
6106 (interactive)
6107 (let ((old-regexp org-target-link-regexp)
6108 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6109 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6110 (targets
6111 (org-with-wide-buffer
6112 (goto-char (point-min))
6113 (let (rtn)
6114 (while (re-search-forward org-radio-target-regexp nil t)
6115 ;; Make sure point is really within the object.
6116 (backward-char)
6117 (let ((obj (org-element-context)))
6118 (when (eq (org-element-type obj) 'radio-target)
6119 (add-to-list 'rtn (org-element-property :value obj)))))
6120 rtn))))
6121 (setq org-target-link-regexp
6122 (and targets
6123 (concat before-re
6124 (mapconcat
6125 (lambda (x)
6126 (replace-regexp-in-string
6127 " +" "\\s-+" (regexp-quote x) t t))
6128 targets
6129 "\\|")
6130 after-re)))
6131 (unless (equal old-regexp org-target-link-regexp)
6132 ;; Clean-up cache.
6133 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6134 ((not org-target-link-regexp) old-regexp)
6136 (concat before-re
6137 (mapconcat
6138 (lambda (re)
6139 (substring re (length before-re)
6140 (- (length after-re))))
6141 (list old-regexp org-target-link-regexp)
6142 "\\|")
6143 after-re)))))
6144 (org-with-wide-buffer
6145 (goto-char (point-min))
6146 (while (re-search-forward regexp nil t)
6147 (org-element-cache-refresh (match-beginning 1)))))
6148 ;; Re fontify buffer.
6149 (when (memq 'radio org-highlight-links)
6150 (org-restart-font-lock)))))
6152 (defun org-hide-wide-columns (limit)
6153 (let (s e)
6154 (setq s (text-property-any (point) (or limit (point-max))
6155 'org-cwidth t))
6156 (when s
6157 (setq e (next-single-property-change s 'org-cwidth))
6158 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6159 (goto-char e)
6160 t)))
6162 (defvar org-latex-and-related-regexp nil
6163 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6165 (defun org-compute-latex-and-related-regexp ()
6166 "Compute regular expression for LaTeX, entities and sub/superscript.
6167 Result depends on variable `org-highlight-latex-and-related'."
6168 (org-set-local
6169 'org-latex-and-related-regexp
6170 (let* ((re-sub
6171 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6172 ((eq org-use-sub-superscripts '{})
6173 (list org-match-substring-with-braces-regexp))
6174 (org-use-sub-superscripts (list org-match-substring-regexp))))
6175 (re-latex
6176 (when (memq 'latex org-highlight-latex-and-related)
6177 (let ((matchers (plist-get org-format-latex-options :matchers)))
6178 (delq nil
6179 (mapcar (lambda (x)
6180 (and (member (car x) matchers) (nth 1 x)))
6181 org-latex-regexps)))))
6182 (re-entities
6183 (when (memq 'entities org-highlight-latex-and-related)
6184 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6185 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6187 (defun org-do-latex-and-related (limit)
6188 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6189 LIMIT bounds the search for syntax to highlight. Stop at first
6190 highlighted object, if any. Return t if some highlighting was
6191 done, nil otherwise."
6192 (when (org-string-nw-p org-latex-and-related-regexp)
6193 (catch 'found
6194 (while (re-search-forward org-latex-and-related-regexp limit t)
6195 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6196 'face))
6197 '(org-code org-verbatim underline))
6198 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6199 '(?_ ?^))
6201 0)))
6202 (font-lock-prepend-text-property
6203 (+ offset (match-beginning 0)) (match-end 0)
6204 'face 'org-latex-and-related)
6205 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6206 '(font-lock-multiline t)))
6207 (throw 'found t)))
6208 nil)))
6210 (defun org-restart-font-lock ()
6211 "Restart `font-lock-mode', to force refontification."
6212 (when (and (boundp 'font-lock-mode) font-lock-mode)
6213 (font-lock-mode -1)
6214 (font-lock-mode 1)))
6216 (defun org-activate-tags (limit)
6217 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6218 (progn
6219 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6220 (add-text-properties (match-beginning 1) (match-end 1)
6221 (list 'mouse-face 'highlight
6222 'keymap org-mouse-map))
6223 (org-rear-nonsticky-at (match-end 1))
6224 t)))
6226 (defun org-outline-level ()
6227 "Compute the outline level of the heading at point.
6228 If this is called at a normal headline, the level is the number of stars.
6229 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6230 (save-excursion
6231 (if (not (ignore-errors (org-back-to-heading t)))
6233 (looking-at org-outline-regexp)
6234 (1- (- (match-end 0) (match-beginning 0))))))
6236 (defvar org-font-lock-keywords nil)
6238 (defsubst org-re-property (property &optional literal allow-null)
6239 "Return a regexp matching a PROPERTY line.
6241 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6242 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6243 non-nil, match properties even without a value.
6245 Match group 3 is set to the value when it exists. If there is no
6246 value and ALLOW-NULL is non-nil, it is set to the empty string."
6247 (concat
6248 "^\\(?4:[ \t]*\\)"
6249 (format "\\(?1::\\(?2:%s\\):\\)"
6250 (if literal property (regexp-quote property)))
6251 (if allow-null
6252 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$"
6253 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))
6255 (defconst org-property-re
6256 (org-re-property "\\S-+" 'literal t)
6257 "Regular expression matching a property line.
6258 There are four matching groups:
6259 1: :PROPKEY: including the leading and trailing colon,
6260 2: PROPKEY without the leading and trailing colon,
6261 3: PROPVAL without leading or trailing spaces,
6262 4: the indentation of the current line,
6263 5: trailing whitespace.")
6265 (defvar org-font-lock-hook nil
6266 "Functions to be called for special font lock stuff.")
6268 (defvar org-font-lock-set-keywords-hook nil
6269 "Functions that can manipulate `org-font-lock-extra-keywords'.
6270 This is called after `org-font-lock-extra-keywords' is defined, but before
6271 it is installed to be used by font lock. This can be useful if something
6272 needs to be inserted at a specific position in the font-lock sequence.")
6274 (defun org-font-lock-hook (limit)
6275 "Run `org-font-lock-hook' within LIMIT."
6276 (run-hook-with-args 'org-font-lock-hook limit))
6278 (defun org-set-font-lock-defaults ()
6279 "Set font lock defaults for the current buffer."
6280 (let* ((em org-fontify-emphasized-text)
6281 (lk org-highlight-links)
6282 (org-font-lock-extra-keywords
6283 (list
6284 ;; Call the hook
6285 '(org-font-lock-hook)
6286 ;; Headlines
6287 `(,(if org-fontify-whole-heading-line
6288 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6289 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6290 (1 (org-get-level-face 1))
6291 (2 (org-get-level-face 2))
6292 (3 (org-get-level-face 3)))
6293 ;; Table lines
6294 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6295 (1 'org-table t))
6296 ;; Table internals
6297 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6298 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6299 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6300 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6301 ;; Drawers
6302 '(org-fontify-drawers)
6303 ;; Properties
6304 (list org-property-re
6305 '(1 'org-special-keyword t)
6306 '(3 'org-property-value t))
6307 ;; Links
6308 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6309 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6310 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6311 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6312 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6313 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6314 (if (memq 'footnote lk) '(org-activate-footnote-links))
6315 ;; Targets.
6316 (list org-any-target-regexp '(0 'org-target t))
6317 ;; Diary sexps.
6318 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6319 ;; Macro
6320 '(org-fontify-macros)
6321 '(org-hide-wide-columns (0 nil append))
6322 ;; TODO keyword
6323 (list (format org-heading-keyword-regexp-format
6324 org-todo-regexp)
6325 '(2 (org-get-todo-face 2) t))
6326 ;; DONE
6327 (if org-fontify-done-headline
6328 (list (format org-heading-keyword-regexp-format
6329 (concat
6330 "\\(?:"
6331 (mapconcat 'regexp-quote org-done-keywords "\\|")
6332 "\\)"))
6333 '(2 'org-headline-done t))
6334 nil)
6335 ;; Priorities
6336 '(org-font-lock-add-priority-faces)
6337 ;; Tags
6338 '(org-font-lock-add-tag-faces)
6339 ;; Tags groups
6340 (if (and org-group-tags org-tag-groups-alist)
6341 (list (concat org-outline-regexp-bol ".+\\(:"
6342 (regexp-opt (mapcar 'car org-tag-groups-alist))
6343 ":\\).*$")
6344 '(1 'org-tag-group prepend)))
6345 ;; Special keywords
6346 (list (concat "\\<" org-comment-string) '(0 'org-special-keyword t))
6347 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6348 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6349 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6350 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6351 ;; Emphasis
6352 (if em
6353 (if (featurep 'xemacs)
6354 '(org-do-emphasis-faces (0 nil append))
6355 '(org-do-emphasis-faces)))
6356 ;; Checkboxes
6357 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6358 1 'org-checkbox prepend)
6359 (if (cdr (assq 'checkbox org-list-automatic-rules))
6360 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6361 (0 (org-get-checkbox-statistics-face) t)))
6362 ;; Description list items
6363 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6364 1 'org-list-dt prepend)
6365 ;; ARCHIVEd headings
6366 (list (concat
6367 org-outline-regexp-bol
6368 "\\(.*:" org-archive-tag ":.*\\)")
6369 '(1 'org-archived prepend))
6370 ;; Specials
6371 '(org-do-latex-and-related)
6372 '(org-fontify-entities)
6373 '(org-raise-scripts)
6374 ;; Code
6375 '(org-activate-code (1 'org-code t))
6376 ;; COMMENT
6377 (list (format
6378 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6379 org-todo-regexp
6380 org-comment-string)
6381 '(9 'org-special-keyword t))
6382 ;; Blocks and meta lines
6383 '(org-fontify-meta-lines-and-blocks))))
6384 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6385 (run-hooks 'org-font-lock-set-keywords-hook)
6386 ;; Now set the full font-lock-keywords
6387 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6388 (org-set-local 'font-lock-defaults
6389 '(org-font-lock-keywords t nil nil backward-paragraph))
6390 (kill-local-variable 'font-lock-keywords) nil))
6392 (defun org-toggle-pretty-entities ()
6393 "Toggle the composition display of entities as UTF8 characters."
6394 (interactive)
6395 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6396 (org-restart-font-lock)
6397 (if org-pretty-entities
6398 (message "Entities are now displayed as UTF8 characters")
6399 (save-restriction
6400 (widen)
6401 (org-decompose-region (point-min) (point-max))
6402 (message "Entities are now displayed as plain text"))))
6404 (defvar org-custom-properties-overlays nil
6405 "List of overlays used for custom properties.")
6406 (make-variable-buffer-local 'org-custom-properties-overlays)
6408 (defun org-toggle-custom-properties-visibility ()
6409 "Display or hide properties in `org-custom-properties'."
6410 (interactive)
6411 (if org-custom-properties-overlays
6412 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6413 (setq org-custom-properties-overlays nil))
6414 (when org-custom-properties
6415 (org-with-wide-buffer
6416 (goto-char (point-min))
6417 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6418 (while (re-search-forward regexp nil t)
6419 (let ((end (cdr (save-match-data (org-get-property-block)))))
6420 (when (and end (< (point) end))
6421 ;; Hide first custom property in current drawer.
6422 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6423 (overlay-put o 'invisible t)
6424 (overlay-put o 'org-custom-property t)
6425 (push o org-custom-properties-overlays))
6426 ;; Hide additional custom properties in the same drawer.
6427 (while (re-search-forward regexp end t)
6428 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6429 (overlay-put o 'invisible t)
6430 (overlay-put o 'org-custom-property t)
6431 (push o org-custom-properties-overlays)))))
6432 ;; Each entry is limited to a single property drawer.
6433 (outline-next-heading)))))))
6435 (defun org-fontify-entities (limit)
6436 "Find an entity to fontify."
6437 (let (ee)
6438 (when org-pretty-entities
6439 (catch 'match
6440 (while (re-search-forward
6441 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6442 limit t)
6443 (if (and (not (org-at-comment-p))
6444 (setq ee (org-entity-get (match-string 1)))
6445 (= (length (nth 6 ee)) 1))
6446 (let*
6447 ((end (if (equal (match-string 2) "{}")
6448 (match-end 2)
6449 (match-end 1))))
6450 (add-text-properties
6451 (match-beginning 0) end
6452 (list 'font-lock-fontified t))
6453 (compose-region (match-beginning 0) end
6454 (nth 6 ee) nil)
6455 (backward-char 1)
6456 (throw 'match t))))
6457 nil))))
6459 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6460 "Fontify string S like in Org-mode."
6461 (with-temp-buffer
6462 (insert s)
6463 (let ((org-odd-levels-only odd-levels))
6464 (org-mode)
6465 (font-lock-ensure)
6466 (buffer-string))))
6468 (defvar org-m nil)
6469 (defvar org-l nil)
6470 (defvar org-f nil)
6471 (defun org-get-level-face (n)
6472 "Get the right face for match N in font-lock matching of headlines."
6473 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6474 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6475 (if org-cycle-level-faces
6476 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6477 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6478 (cond
6479 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6480 ((eq n 2) org-f)
6481 (t (if org-level-color-stars-only nil org-f))))
6484 (defun org-get-todo-face (kwd)
6485 "Get the right face for a TODO keyword KWD.
6486 If KWD is a number, get the corresponding match group."
6487 (if (numberp kwd) (setq kwd (match-string kwd)))
6488 (or (org-face-from-face-or-color
6489 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6490 (and (member kwd org-done-keywords) 'org-done)
6491 'org-todo))
6493 (defun org-face-from-face-or-color (context inherit face-or-color)
6494 "Create a face list that inherits INHERIT, but sets the foreground color.
6495 When FACE-OR-COLOR is not a string, just return it."
6496 (if (stringp face-or-color)
6497 (list :inherit inherit
6498 (cdr (assoc context org-faces-easy-properties))
6499 face-or-color)
6500 face-or-color))
6502 (defun org-font-lock-add-tag-faces (limit)
6503 "Add the special tag faces."
6504 (when (and org-tag-faces org-tags-special-faces-re)
6505 (while (re-search-forward org-tags-special-faces-re limit t)
6506 (add-text-properties (match-beginning 1) (match-end 1)
6507 (list 'face (org-get-tag-face 1)
6508 'font-lock-fontified t))
6509 (backward-char 1))))
6511 (defun org-font-lock-add-priority-faces (limit)
6512 "Add the special priority faces."
6513 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6514 (when (save-match-data (org-at-heading-p))
6515 (add-text-properties
6516 (match-beginning 0) (match-end 0)
6517 (list 'face (or (org-face-from-face-or-color
6518 'priority 'org-priority
6519 (cdr (assoc (char-after (match-beginning 1))
6520 org-priority-faces)))
6521 'org-priority)
6522 'font-lock-fontified t)))))
6524 (defun org-get-tag-face (kwd)
6525 "Get the right face for a TODO keyword KWD.
6526 If KWD is a number, get the corresponding match group."
6527 (if (numberp kwd) (setq kwd (match-string kwd)))
6528 (or (org-face-from-face-or-color
6529 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6530 'org-tag))
6532 (defun org-unfontify-region (beg end &optional maybe_loudly)
6533 "Remove fontification and activation overlays from links."
6534 (font-lock-default-unfontify-region beg end)
6535 (let* ((buffer-undo-list t)
6536 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6537 (inhibit-modification-hooks t)
6538 deactivate-mark buffer-file-name buffer-file-truename)
6539 (org-decompose-region beg end)
6540 (remove-text-properties beg end
6541 '(mouse-face t keymap t org-linked-text t
6542 invisible t intangible t
6543 org-emphasis t))
6544 (org-remove-font-lock-display-properties beg end)))
6546 (defconst org-script-display '(((raise -0.3) (height 0.7))
6547 ((raise 0.3) (height 0.7))
6548 ((raise -0.5))
6549 ((raise 0.5)))
6550 "Display properties for showing superscripts and subscripts.")
6552 (defun org-remove-font-lock-display-properties (beg end)
6553 "Remove specific display properties that have been added by font lock.
6554 The will remove the raise properties that are used to show superscripts
6555 and subscripts."
6556 (let (next prop)
6557 (while (< beg end)
6558 (setq next (next-single-property-change beg 'display nil end)
6559 prop (get-text-property beg 'display))
6560 (if (member prop org-script-display)
6561 (put-text-property beg next 'display nil))
6562 (setq beg next))))
6564 (defun org-raise-scripts (limit)
6565 "Add raise properties to sub/superscripts."
6566 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6567 (if (re-search-forward
6568 (if (eq org-use-sub-superscripts t)
6569 org-match-substring-regexp
6570 org-match-substring-with-braces-regexp)
6571 limit t)
6572 (let* ((pos (point)) table-p comment-p
6573 (mpos (match-beginning 3))
6574 (emph-p (get-text-property mpos 'org-emphasis))
6575 (link-p (get-text-property mpos 'mouse-face))
6576 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6577 (goto-char (point-at-bol))
6578 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6579 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6580 (goto-char pos)
6581 ;; Handle a_b^c
6582 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6583 (if (or comment-p emph-p link-p keyw-p)
6585 (put-text-property (match-beginning 3) (match-end 0)
6586 'display
6587 (if (equal (char-after (match-beginning 2)) ?^)
6588 (nth (if table-p 3 1) org-script-display)
6589 (nth (if table-p 2 0) org-script-display)))
6590 (add-text-properties (match-beginning 2) (match-end 2)
6591 (list 'invisible t
6592 'org-dwidth t 'org-dwidth-n 1))
6593 (if (and (eq (char-after (match-beginning 3)) ?{)
6594 (eq (char-before (match-end 3)) ?}))
6595 (progn
6596 (add-text-properties
6597 (match-beginning 3) (1+ (match-beginning 3))
6598 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6599 (add-text-properties
6600 (1- (match-end 3)) (match-end 3)
6601 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6602 t)))))
6604 ;;;; Visibility cycling, including org-goto and indirect buffer
6606 ;;; Cycling
6608 (defvar org-cycle-global-status nil)
6609 (make-variable-buffer-local 'org-cycle-global-status)
6610 (put 'org-cycle-global-status 'org-state t)
6611 (defvar org-cycle-subtree-status nil)
6612 (make-variable-buffer-local 'org-cycle-subtree-status)
6613 (put 'org-cycle-subtree-status 'org-state t)
6615 (defvar org-inlinetask-min-level)
6617 (defun org-unlogged-message (&rest args)
6618 "Display a message, but avoid logging it in the *Messages* buffer."
6619 (let ((message-log-max nil))
6620 (apply 'message args)))
6622 ;;;###autoload
6623 (defun org-cycle (&optional arg)
6624 "TAB-action and visibility cycling for Org-mode.
6626 This is the command invoked in Org-mode by the TAB key. Its main purpose
6627 is outline visibility cycling, but it also invokes other actions
6628 in special contexts.
6630 - When this function is called with a prefix argument, rotate the entire
6631 buffer through 3 states (global cycling)
6632 1. OVERVIEW: Show only top-level headlines.
6633 2. CONTENTS: Show all headlines of all levels, but no body text.
6634 3. SHOW ALL: Show everything.
6635 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6636 determined by the variable `org-startup-folded', and by any VISIBILITY
6637 properties in the buffer.
6638 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6639 including any drawers.
6641 - When inside a table, re-align the table and move to the next field.
6643 - When point is at the beginning of a headline, rotate the subtree started
6644 by this line through 3 different states (local cycling)
6645 1. FOLDED: Only the main headline is shown.
6646 2. CHILDREN: The main headline and the direct children are shown.
6647 From this state, you can move to one of the children
6648 and zoom in further.
6649 3. SUBTREE: Show the entire subtree, including body text.
6650 If there is no subtree, switch directly from CHILDREN to FOLDED.
6652 - When point is at the beginning of an empty headline and the variable
6653 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6654 of the headline by demoting and promoting it to likely levels. This
6655 speeds up creation document structure by pressing TAB once or several
6656 times right after creating a new headline.
6658 - When there is a numeric prefix, go up to a heading with level ARG, do
6659 a `show-subtree' and return to the previous cursor position. If ARG
6660 is negative, go up that many levels.
6662 - When point is not at the beginning of a headline, execute the global
6663 binding for TAB, which is re-indenting the line. See the option
6664 `org-cycle-emulate-tab' for details.
6666 - Special case: if point is at the beginning of the buffer and there is
6667 no headline in line 1, this function will act as if called with prefix arg
6668 (C-u TAB, same as S-TAB) also when called without prefix arg.
6669 But only if also the variable `org-cycle-global-at-bob' is t."
6670 (interactive "P")
6671 (org-load-modules-maybe)
6672 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6673 (and org-cycle-level-after-item/entry-creation
6674 (or (org-cycle-level)
6675 (org-cycle-item-indentation))))
6676 (let* ((limit-level
6677 (or org-cycle-max-level
6678 (and (boundp 'org-inlinetask-min-level)
6679 org-inlinetask-min-level
6680 (1- org-inlinetask-min-level))))
6681 (nstars (and limit-level
6682 (if org-odd-levels-only
6683 (and limit-level (1- (* limit-level 2)))
6684 limit-level)))
6685 (org-outline-regexp
6686 (if (not (derived-mode-p 'org-mode))
6687 outline-regexp
6688 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6689 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6690 (not (looking-at org-outline-regexp))))
6691 (org-cycle-hook
6692 (if bob-special
6693 (delq 'org-optimize-window-after-visibility-change
6694 (copy-sequence org-cycle-hook))
6695 org-cycle-hook))
6696 (pos (point)))
6698 (if (or bob-special (equal arg '(4)))
6699 ;; special case: use global cycling
6700 (setq arg t))
6702 (cond
6704 ((equal arg '(16))
6705 (setq last-command 'dummy)
6706 (org-set-startup-visibility)
6707 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6709 ((equal arg '(64))
6710 (show-all)
6711 (org-unlogged-message "Entire buffer visible, including drawers"))
6713 ;; Try cdlatex TAB completion
6714 ((org-try-cdlatex-tab))
6716 ;; Table: enter it or move to the next field.
6717 ((org-at-table-p 'any)
6718 (if (org-at-table.el-p)
6719 (message "Use C-c ' to edit table.el tables")
6720 (if arg (org-table-edit-field t)
6721 (org-table-justify-field-maybe)
6722 (call-interactively 'org-table-next-field))))
6724 ((run-hook-with-args-until-success
6725 'org-tab-after-check-for-table-hook))
6727 ;; Global cycling: delegate to `org-cycle-internal-global'.
6728 ((eq arg t) (org-cycle-internal-global))
6730 ;; Drawers: delegate to `org-flag-drawer'.
6731 ((save-excursion
6732 (beginning-of-line 1)
6733 (looking-at org-drawer-regexp))
6734 (org-flag-drawer ; toggle block visibility
6735 (not (get-char-property (match-end 0) 'invisible))))
6737 ;; Show-subtree, ARG levels up from here.
6738 ((integerp arg)
6739 (save-excursion
6740 (org-back-to-heading)
6741 (outline-up-heading (if (< arg 0) (- arg)
6742 (- (funcall outline-level) arg)))
6743 (org-show-subtree)))
6745 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6746 ((and (featurep 'org-inlinetask)
6747 (org-inlinetask-at-task-p)
6748 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6749 (org-inlinetask-toggle-visibility))
6751 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6752 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6753 (save-excursion (beginning-of-line 1)
6754 (looking-at org-outline-regexp)))
6755 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6756 (org-cycle-internal-local))
6758 ;; From there: TAB emulation and template completion.
6759 (buffer-read-only (org-back-to-heading))
6761 ((run-hook-with-args-until-success
6762 'org-tab-after-check-for-cycling-hook))
6764 ((org-try-structure-completion))
6766 ((run-hook-with-args-until-success
6767 'org-tab-before-tab-emulation-hook))
6769 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6770 (or (not (bolp))
6771 (not (looking-at org-outline-regexp))))
6772 (call-interactively (global-key-binding "\t")))
6774 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6775 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6776 (or (and (eq org-cycle-emulate-tab 'white)
6777 (= (match-end 0) (point-at-eol)))
6778 (and (eq org-cycle-emulate-tab 'whitestart)
6779 (>= (match-end 0) pos))))
6781 (eq org-cycle-emulate-tab t))
6782 (call-interactively (global-key-binding "\t")))
6784 (t (save-excursion
6785 (org-back-to-heading)
6786 (org-cycle)))))))
6788 (defun org-cycle-internal-global ()
6789 "Do the global cycling action."
6790 ;; Hack to avoid display of messages for .org attachments in Gnus
6791 (let ((ga (string-match "\\*fontification" (buffer-name))))
6792 (cond
6793 ((and (eq last-command this-command)
6794 (eq org-cycle-global-status 'overview))
6795 ;; We just created the overview - now do table of contents
6796 ;; This can be slow in very large buffers, so indicate action
6797 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6798 (unless ga (org-unlogged-message "CONTENTS..."))
6799 (org-content)
6800 (unless ga (org-unlogged-message "CONTENTS...done"))
6801 (setq org-cycle-global-status 'contents)
6802 (run-hook-with-args 'org-cycle-hook 'contents))
6804 ((and (eq last-command this-command)
6805 (eq org-cycle-global-status 'contents))
6806 ;; We just showed the table of contents - now show everything
6807 (run-hook-with-args 'org-pre-cycle-hook 'all)
6808 (show-all)
6809 (unless ga (org-unlogged-message "SHOW ALL"))
6810 (setq org-cycle-global-status 'all)
6811 (run-hook-with-args 'org-cycle-hook 'all))
6814 ;; Default action: go to overview
6815 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6816 (org-overview)
6817 (unless ga (org-unlogged-message "OVERVIEW"))
6818 (setq org-cycle-global-status 'overview)
6819 (run-hook-with-args 'org-cycle-hook 'overview)))))
6821 (defvar org-called-with-limited-levels nil
6822 "Non-nil when `org-with-limited-levels' is currently active.")
6824 (defun org-cycle-internal-local ()
6825 "Do the local cycling action."
6826 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6827 ;; First, determine end of headline (EOH), end of subtree or item
6828 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6829 (save-excursion
6830 (if (org-at-item-p)
6831 (progn
6832 (beginning-of-line)
6833 (setq struct (org-list-struct))
6834 (setq eoh (point-at-eol))
6835 (setq eos (org-list-get-item-end-before-blank (point) struct))
6836 (setq has-children (org-list-has-child-p (point) struct)))
6837 (org-back-to-heading)
6838 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6839 (setq eos (save-excursion (org-end-of-subtree t t)
6840 (when (bolp) (backward-char)) (point)))
6841 (setq has-children
6842 (or (save-excursion
6843 (let ((level (funcall outline-level)))
6844 (outline-next-heading)
6845 (and (org-at-heading-p t)
6846 (> (funcall outline-level) level))))
6847 (save-excursion
6848 (org-list-search-forward (org-item-beginning-re) eos t)))))
6849 ;; Determine end invisible part of buffer (EOL)
6850 (beginning-of-line 2)
6851 ;; XEmacs doesn't have `next-single-char-property-change'
6852 (if (featurep 'xemacs)
6853 (while (and (not (eobp)) ;; this is like `next-line'
6854 (get-char-property (1- (point)) 'invisible))
6855 (beginning-of-line 2))
6856 (while (and (not (eobp)) ;; this is like `next-line'
6857 (get-char-property (1- (point)) 'invisible))
6858 (goto-char (next-single-char-property-change (point) 'invisible))
6859 (and (eolp) (beginning-of-line 2))))
6860 (setq eol (point)))
6861 ;; Find out what to do next and set `this-command'
6862 (cond
6863 ((= eos eoh)
6864 ;; Nothing is hidden behind this heading
6865 (unless (org-before-first-heading-p)
6866 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6867 (org-unlogged-message "EMPTY ENTRY")
6868 (setq org-cycle-subtree-status nil)
6869 (save-excursion
6870 (goto-char eos)
6871 (outline-next-heading)
6872 (if (outline-invisible-p) (org-flag-heading nil))))
6873 ((and (or (>= eol eos)
6874 (not (string-match "\\S-" (buffer-substring eol eos))))
6875 (or has-children
6876 (not (setq children-skipped
6877 org-cycle-skip-children-state-if-no-children))))
6878 ;; Entire subtree is hidden in one line: children view
6879 (unless (org-before-first-heading-p)
6880 (run-hook-with-args 'org-pre-cycle-hook 'children))
6881 (if (org-at-item-p)
6882 (org-list-set-item-visibility (point-at-bol) struct 'children)
6883 (org-show-entry)
6884 (org-with-limited-levels (show-children))
6885 ;; FIXME: This slows down the func way too much.
6886 ;; How keep drawers hidden in subtree anyway?
6887 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6888 ;; (org-cycle-hide-drawers 'subtree))
6890 ;; Fold every list in subtree to top-level items.
6891 (when (eq org-cycle-include-plain-lists 'integrate)
6892 (save-excursion
6893 (org-back-to-heading)
6894 (while (org-list-search-forward (org-item-beginning-re) eos t)
6895 (beginning-of-line 1)
6896 (let* ((struct (org-list-struct))
6897 (prevs (org-list-prevs-alist struct))
6898 (end (org-list-get-bottom-point struct)))
6899 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6900 (org-list-get-all-items (point) struct prevs))
6901 (goto-char (if (< end eos) end eos)))))))
6902 (org-unlogged-message "CHILDREN")
6903 (save-excursion
6904 (goto-char eos)
6905 (outline-next-heading)
6906 (if (outline-invisible-p) (org-flag-heading nil)))
6907 (setq org-cycle-subtree-status 'children)
6908 (unless (org-before-first-heading-p)
6909 (run-hook-with-args 'org-cycle-hook 'children)))
6910 ((or children-skipped
6911 (and (eq last-command this-command)
6912 (eq org-cycle-subtree-status 'children)))
6913 ;; We just showed the children, or no children are there,
6914 ;; now show everything.
6915 (unless (org-before-first-heading-p)
6916 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6917 (outline-flag-region eoh eos nil)
6918 (org-unlogged-message
6919 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6920 (setq org-cycle-subtree-status 'subtree)
6921 (unless (org-before-first-heading-p)
6922 (run-hook-with-args 'org-cycle-hook 'subtree)))
6924 ;; Default action: hide the subtree.
6925 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6926 (outline-flag-region eoh eos t)
6927 (org-unlogged-message "FOLDED")
6928 (setq org-cycle-subtree-status 'folded)
6929 (unless (org-before-first-heading-p)
6930 (run-hook-with-args 'org-cycle-hook 'folded))))))
6932 ;;;###autoload
6933 (defun org-global-cycle (&optional arg)
6934 "Cycle the global visibility. For details see `org-cycle'.
6935 With \\[universal-argument] prefix arg, switch to startup visibility.
6936 With a numeric prefix, show all headlines up to that level."
6937 (interactive "P")
6938 (let ((org-cycle-include-plain-lists
6939 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6940 (cond
6941 ((integerp arg)
6942 (show-all)
6943 (hide-sublevels arg)
6944 (setq org-cycle-global-status 'contents))
6945 ((equal arg '(4))
6946 (org-set-startup-visibility)
6947 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6949 (org-cycle '(4))))))
6951 (defun org-set-startup-visibility ()
6952 "Set the visibility required by startup options and properties."
6953 (cond
6954 ((eq org-startup-folded t)
6955 (org-overview))
6956 ((eq org-startup-folded 'content)
6957 (org-content))
6958 ((or (eq org-startup-folded 'showeverything)
6959 (eq org-startup-folded nil))
6960 (show-all)))
6961 (unless (eq org-startup-folded 'showeverything)
6962 (if org-hide-block-startup (org-hide-block-all))
6963 (org-set-visibility-according-to-property 'no-cleanup)
6964 (org-cycle-hide-archived-subtrees 'all)
6965 (org-cycle-hide-drawers 'all)
6966 (org-cycle-show-empty-lines t)))
6968 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6969 "Switch subtree visibilities according to :VISIBILITY: property."
6970 (interactive)
6971 (let (org-show-entry-below state)
6972 (save-excursion
6973 (goto-char (point-min))
6974 (while (re-search-forward
6975 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6976 nil t)
6977 (setq state (match-string 1))
6978 (save-excursion
6979 (org-back-to-heading t)
6980 (hide-subtree)
6981 (org-reveal)
6982 (cond
6983 ((equal state '("fold" "folded"))
6984 (hide-subtree))
6985 ((equal state "children")
6986 (org-show-hidden-entry)
6987 (show-children))
6988 ((equal state "content")
6989 (save-excursion
6990 (save-restriction
6991 (org-narrow-to-subtree)
6992 (org-content))))
6993 ((member state '("all" "showall"))
6994 (show-subtree)))))
6995 (unless no-cleanup
6996 (org-cycle-hide-archived-subtrees 'all)
6997 (org-cycle-hide-drawers 'all)
6998 (org-cycle-show-empty-lines 'all)))))
7000 ;; This function uses outline-regexp instead of the more fundamental
7001 ;; org-outline-regexp so that org-cycle-global works outside of Org
7002 ;; buffers, where outline-regexp is needed.
7003 (defun org-overview ()
7004 "Switch to overview mode, showing only top-level headlines.
7005 This shows all headlines with a level equal or greater than the level
7006 of the first headline in the buffer. This is important, because if the
7007 first headline is not level one, then (hide-sublevels 1) gives confusing
7008 results."
7009 (interactive)
7010 (save-excursion
7011 (let ((level
7012 (save-excursion
7013 (goto-char (point-min))
7014 (if (re-search-forward (concat "^" outline-regexp) nil t)
7015 (progn
7016 (goto-char (match-beginning 0))
7017 (funcall outline-level))))))
7018 (and level (hide-sublevels level)))))
7020 (defun org-content (&optional arg)
7021 "Show all headlines in the buffer, like a table of contents.
7022 With numerical argument N, show content up to level N."
7023 (interactive "P")
7024 (org-overview)
7025 (save-excursion
7026 ;; Visit all headings and show their offspring
7027 (and (integerp arg) (org-overview))
7028 (goto-char (point-max))
7029 (catch 'exit
7030 (while (and (progn (condition-case nil
7031 (outline-previous-visible-heading 1)
7032 (error (goto-char (point-min))))
7034 (looking-at org-outline-regexp))
7035 (if (integerp arg)
7036 (show-children (1- arg))
7037 (show-branches))
7038 (if (bobp) (throw 'exit nil))))))
7040 (defun org-optimize-window-after-visibility-change (state)
7041 "Adjust the window after a change in outline visibility.
7042 This function is the default value of the hook `org-cycle-hook'."
7043 (when (get-buffer-window (current-buffer))
7044 (cond
7045 ((eq state 'content) nil)
7046 ((eq state 'all) nil)
7047 ((eq state 'folded) nil)
7048 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7049 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7051 (defun org-remove-empty-overlays-at (pos)
7052 "Remove outline overlays that do not contain non-white stuff."
7053 (mapc
7054 (lambda (o)
7055 (and (eq 'outline (overlay-get o 'invisible))
7056 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7057 (overlay-end o))))
7058 (delete-overlay o)))
7059 (overlays-at pos)))
7061 (defun org-clean-visibility-after-subtree-move ()
7062 "Fix visibility issues after moving a subtree."
7063 ;; First, find a reasonable region to look at:
7064 ;; Start two siblings above, end three below
7065 (let* ((beg (save-excursion
7066 (and (org-get-last-sibling)
7067 (org-get-last-sibling))
7068 (point)))
7069 (end (save-excursion
7070 (and (org-get-next-sibling)
7071 (org-get-next-sibling)
7072 (org-get-next-sibling))
7073 (if (org-at-heading-p)
7074 (point-at-eol)
7075 (point))))
7076 (level (looking-at "\\*+"))
7077 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7078 (save-excursion
7079 (save-restriction
7080 (narrow-to-region beg end)
7081 (when re
7082 ;; Properly fold already folded siblings
7083 (goto-char (point-min))
7084 (while (re-search-forward re nil t)
7085 (if (and (not (outline-invisible-p))
7086 (save-excursion
7087 (goto-char (point-at-eol)) (outline-invisible-p)))
7088 (hide-entry))))
7089 (org-cycle-show-empty-lines 'overview)
7090 (org-cycle-hide-drawers 'overview)))))
7092 (defun org-cycle-show-empty-lines (state)
7093 "Show empty lines above all visible headlines.
7094 The region to be covered depends on STATE when called through
7095 `org-cycle-hook'. Lisp program can use t for STATE to get the
7096 entire buffer covered. Note that an empty line is only shown if there
7097 are at least `org-cycle-separator-lines' empty lines before the headline."
7098 (when (not (= org-cycle-separator-lines 0))
7099 (save-excursion
7100 (let* ((n (abs org-cycle-separator-lines))
7101 (re (cond
7102 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7103 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7104 (t (let ((ns (number-to-string (- n 2))))
7105 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7106 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7107 beg end b e)
7108 (cond
7109 ((memq state '(overview contents t))
7110 (setq beg (point-min) end (point-max)))
7111 ((memq state '(children folded))
7112 (setq beg (point) end (progn (org-end-of-subtree t t)
7113 (beginning-of-line 2)
7114 (point)))))
7115 (when beg
7116 (goto-char beg)
7117 (while (re-search-forward re end t)
7118 (unless (get-char-property (match-end 1) 'invisible)
7119 (setq e (match-end 1))
7120 (if (< org-cycle-separator-lines 0)
7121 (setq b (save-excursion
7122 (goto-char (match-beginning 0))
7123 (org-back-over-empty-lines)
7124 (if (save-excursion
7125 (goto-char (max (point-min) (1- (point))))
7126 (org-at-heading-p))
7127 (1- (point))
7128 (point))))
7129 (setq b (match-beginning 1)))
7130 (outline-flag-region b e nil)))))))
7131 ;; Never hide empty lines at the end of the file.
7132 (save-excursion
7133 (goto-char (point-max))
7134 (outline-previous-heading)
7135 (outline-end-of-heading)
7136 (if (and (looking-at "[ \t\n]+")
7137 (= (match-end 0) (point-max)))
7138 (outline-flag-region (point) (match-end 0) nil))))
7140 (defun org-show-empty-lines-in-parent ()
7141 "Move to the parent and re-show empty lines before visible headlines."
7142 (save-excursion
7143 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7144 (org-cycle-show-empty-lines context))))
7146 (defun org-files-list ()
7147 "Return `org-agenda-files' list, plus all open org-mode files.
7148 This is useful for operations that need to scan all of a user's
7149 open and agenda-wise Org files."
7150 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7151 (dolist (buf (buffer-list))
7152 (with-current-buffer buf
7153 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7154 (let ((file (expand-file-name (buffer-file-name))))
7155 (unless (member file files)
7156 (push file files))))))
7157 files))
7159 (defsubst org-entry-beginning-position ()
7160 "Return the beginning position of the current entry."
7161 (save-excursion (outline-back-to-heading t) (point)))
7163 (defsubst org-entry-end-position ()
7164 "Return the end position of the current entry."
7165 (save-excursion (outline-next-heading) (point)))
7167 (defun org-cycle-hide-drawers (state &optional exceptions)
7168 "Re-hide all drawers after a visibility state change.
7169 When non-nil, optional argument EXCEPTIONS is a list of strings
7170 specifying which drawers should not be hidden."
7171 (when (and (derived-mode-p 'org-mode)
7172 (not (memq state '(overview folded contents))))
7173 (save-excursion
7174 (let* ((globalp (memq state '(contents all)))
7175 (beg (if globalp (point-min) (point)))
7176 (end (if globalp (point-max)
7177 (if (eq state 'children)
7178 (save-excursion (outline-next-heading) (point))
7179 (org-end-of-subtree t)))))
7180 (goto-char beg)
7181 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7182 (unless (member-ignore-case (match-string 1) exceptions)
7183 (let ((drawer (org-element-at-point)))
7184 (when (memq (org-element-type drawer) '(drawer property-drawer))
7185 (org-flag-drawer t drawer)
7186 ;; Make sure to skip drawer entirely or we might flag
7187 ;; it another time when matching its ending line with
7188 ;; `org-drawer-regexp'.
7189 (goto-char (org-element-property :end drawer))))))))))
7191 (defun org-cycle-hide-inline-tasks (state)
7192 "Re-hide inline tasks when switching to 'contents or 'children
7193 visibility state."
7194 (case state
7195 (contents
7196 (when (org-bound-and-true-p org-inlinetask-min-level)
7197 (hide-sublevels (1- org-inlinetask-min-level))))
7198 (children
7199 (when (featurep 'org-inlinetask)
7200 (save-excursion
7201 (while (and (outline-next-heading)
7202 (org-inlinetask-at-task-p))
7203 (org-inlinetask-toggle-visibility)
7204 (org-inlinetask-goto-end)))))))
7206 (defun org-flag-drawer (flag &optional element)
7207 "When FLAG is non-nil, hide the drawer we are at.
7208 Otherwise make it visible. When optional argument ELEMENT is
7209 a parsed drawer, as returned by `org-element-at-point', hide or
7210 show that drawer instead."
7211 (when (save-excursion
7212 (beginning-of-line)
7213 (org-looking-at-p org-drawer-regexp))
7214 (let ((drawer (or element (org-element-at-point))))
7215 (when (memq (org-element-type drawer) '(drawer property-drawer))
7216 (let ((post (org-element-property :post-affiliated drawer)))
7217 (save-excursion
7218 (outline-flag-region
7219 (progn (goto-char post) (line-end-position))
7220 (progn (goto-char (org-element-property :end drawer))
7221 (skip-chars-backward " \r\t\n")
7222 (line-end-position))
7223 flag))
7224 ;; When the drawer is hidden away, make sure point lies in
7225 ;; a visible part of the buffer.
7226 (when (and flag (> (line-beginning-position) post))
7227 (goto-char post)))))))
7229 (defun org-subtree-end-visible-p ()
7230 "Is the end of the current subtree visible?"
7231 (pos-visible-in-window-p
7232 (save-excursion (org-end-of-subtree t) (point))))
7234 (defun org-first-headline-recenter ()
7235 "Move cursor to the first headline and recenter the headline."
7236 (goto-char (point-min))
7237 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7238 (set-window-start (selected-window) (point-at-bol))))
7240 ;;; Saving and restoring visibility
7242 (defun org-outline-overlay-data (&optional use-markers)
7243 "Return a list of the locations of all outline overlays.
7244 These are overlays with the `invisible' property value `outline'.
7245 The return value is a list of cons cells, with start and stop
7246 positions for each overlay.
7247 If USE-MARKERS is set, return the positions as markers."
7248 (let (beg end)
7249 (save-excursion
7250 (save-restriction
7251 (widen)
7252 (delq nil
7253 (mapcar (lambda (o)
7254 (when (eq (overlay-get o 'invisible) 'outline)
7255 (setq beg (overlay-start o)
7256 end (overlay-end o))
7257 (and beg end (> end beg)
7258 (if use-markers
7259 (cons (copy-marker beg)
7260 (copy-marker end t))
7261 (cons beg end)))))
7262 (overlays-in (point-min) (point-max))))))))
7264 (defun org-set-outline-overlay-data (data)
7265 "Create visibility overlays for all positions in DATA.
7266 DATA should have been made by `org-outline-overlay-data'."
7267 (let (o)
7268 (save-excursion
7269 (save-restriction
7270 (widen)
7271 (show-all)
7272 (mapc (lambda (c)
7273 (outline-flag-region (car c) (cdr c) t))
7274 data)))))
7276 ;;; Folding of blocks
7278 (defvar org-hide-block-overlays nil
7279 "Overlays hiding blocks.")
7280 (make-variable-buffer-local 'org-hide-block-overlays)
7282 (defun org-block-map (function &optional start end)
7283 "Call FUNCTION at the head of all source blocks in the current buffer.
7284 Optional arguments START and END can be used to limit the range."
7285 (let ((start (or start (point-min)))
7286 (end (or end (point-max))))
7287 (save-excursion
7288 (goto-char start)
7289 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7290 (save-excursion
7291 (save-match-data
7292 (goto-char (match-beginning 0))
7293 (funcall function)))))))
7295 (defun org-hide-block-toggle-all ()
7296 "Toggle the visibility of all blocks in the current buffer."
7297 (org-block-map 'org-hide-block-toggle))
7299 (defun org-hide-block-all ()
7300 "Fold all blocks in the current buffer."
7301 (interactive)
7302 (org-show-block-all)
7303 (org-block-map 'org-hide-block-toggle-maybe))
7305 (defun org-show-block-all ()
7306 "Unfold all blocks in the current buffer."
7307 (interactive)
7308 (mapc 'delete-overlay org-hide-block-overlays)
7309 (setq org-hide-block-overlays nil))
7311 (defun org-hide-block-toggle-maybe ()
7312 "Toggle visibility of block at point.
7313 Unlike to `org-hide-block-toggle', this function does not throw
7314 an error. Return a non-nil value when toggling is successful."
7315 (interactive)
7316 (ignore-errors (org-hide-block-toggle)))
7318 (defun org-hide-block-toggle (&optional force)
7319 "Toggle the visibility of the current block.
7320 When optional argument FORCE is `off', make block visible. If it
7321 is non-nil, hide it unconditionally. Throw an error when not at
7322 a block. Return a non-nil value when toggling is successful."
7323 (interactive)
7324 (let ((element (org-element-at-point)))
7325 (unless (memq (org-element-type element)
7326 '(center-block comment-block dynamic-block example-block
7327 export-block quote-block special-block
7328 src-block verse-block))
7329 (user-error "Not at a block"))
7330 (let* ((start (save-excursion
7331 (goto-char (org-element-property :post-affiliated element))
7332 (line-end-position)))
7333 (end (save-excursion
7334 (goto-char (org-element-property :end element))
7335 (skip-chars-backward " \r\t\n")
7336 (line-end-position)))
7337 (overlays (overlays-at start)))
7338 (cond
7339 ;; Do nothing when not before or at the block opening line or
7340 ;; at the block closing line.
7341 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7342 ((and (not (eq force 'off))
7343 (not (memq t (mapcar
7344 (lambda (o)
7345 (eq (overlay-get o 'invisible) 'org-hide-block))
7346 overlays))))
7347 (let ((ov (make-overlay start end)))
7348 (overlay-put ov 'invisible 'org-hide-block)
7349 ;; Make the block accessible to `isearch'.
7350 (overlay-put
7351 ov 'isearch-open-invisible
7352 (lambda (ov)
7353 (when (memq ov org-hide-block-overlays)
7354 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7355 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7356 (delete-overlay ov))))
7357 (push ov org-hide-block-overlays)
7358 ;; When the block is hidden away, make sure point is left in
7359 ;; a visible part of the buffer.
7360 (when (> (line-beginning-position) start)
7361 (goto-char start)
7362 (beginning-of-line))
7363 ;; Signal successful toggling.
7365 ((or (not force) (eq force 'off))
7366 (dolist (ov overlays t)
7367 (when (memq ov org-hide-block-overlays)
7368 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7369 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7370 (delete-overlay ov))))))))
7372 ;; org-tab-after-check-for-cycling-hook
7373 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7374 ;; Remove overlays when changing major mode
7375 (add-hook 'org-mode-hook
7376 (lambda () (org-add-hook 'change-major-mode-hook
7377 'org-show-block-all 'append 'local)))
7379 ;;; Org-goto
7381 (defvar org-goto-window-configuration nil)
7382 (defvar org-goto-marker nil)
7383 (defvar org-goto-map)
7384 (defun org-goto-map ()
7385 "Set the keymap `org-goto'."
7386 (setq org-goto-map
7387 (let ((map (make-sparse-keymap)))
7388 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7389 mouse-drag-region universal-argument org-occur))
7390 cmd)
7391 (while (setq cmd (pop cmds))
7392 (substitute-key-definition cmd cmd map global-map)))
7393 (suppress-keymap map)
7394 (org-defkey map "\C-m" 'org-goto-ret)
7395 (org-defkey map [(return)] 'org-goto-ret)
7396 (org-defkey map [(left)] 'org-goto-left)
7397 (org-defkey map [(right)] 'org-goto-right)
7398 (org-defkey map [(control ?g)] 'org-goto-quit)
7399 (org-defkey map "\C-i" 'org-cycle)
7400 (org-defkey map [(tab)] 'org-cycle)
7401 (org-defkey map [(down)] 'outline-next-visible-heading)
7402 (org-defkey map [(up)] 'outline-previous-visible-heading)
7403 (if org-goto-auto-isearch
7404 (if (fboundp 'define-key-after)
7405 (define-key-after map [t] 'org-goto-local-auto-isearch)
7406 nil)
7407 (org-defkey map "q" 'org-goto-quit)
7408 (org-defkey map "n" 'outline-next-visible-heading)
7409 (org-defkey map "p" 'outline-previous-visible-heading)
7410 (org-defkey map "f" 'outline-forward-same-level)
7411 (org-defkey map "b" 'outline-backward-same-level)
7412 (org-defkey map "u" 'outline-up-heading))
7413 (org-defkey map "/" 'org-occur)
7414 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7415 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7416 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7417 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7418 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7419 map)))
7421 (defconst org-goto-help
7422 "Browse buffer copy, to find location or copy text.%s
7423 RET=jump to location C-g=quit and return to previous location
7424 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7426 (defvar org-goto-start-pos) ; dynamically scoped parameter
7428 (defun org-goto (&optional alternative-interface)
7429 "Look up a different location in the current file, keeping current visibility.
7431 When you want look-up or go to a different location in a
7432 document, the fastest way is often to fold the entire buffer and
7433 then dive into the tree. This method has the disadvantage, that
7434 the previous location will be folded, which may not be what you
7435 want.
7437 This command works around this by showing a copy of the current
7438 buffer in an indirect buffer, in overview mode. You can dive
7439 into the tree in that copy, use org-occur and incremental search
7440 to find a location. When pressing RET or `Q', the command
7441 returns to the original buffer in which the visibility is still
7442 unchanged. After RET it will also jump to the location selected
7443 in the indirect buffer and expose the headline hierarchy above.
7445 With a prefix argument, use the alternative interface: e.g. if
7446 `org-goto-interface' is 'outline use 'outline-path-completion."
7447 (interactive "P")
7448 (org-goto-map)
7449 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7450 (org-refile-use-outline-path t)
7451 (org-refile-target-verify-function nil)
7452 (interface
7453 (if (not alternative-interface)
7454 org-goto-interface
7455 (if (eq org-goto-interface 'outline)
7456 'outline-path-completion
7457 'outline)))
7458 (org-goto-start-pos (point))
7459 (selected-point
7460 (if (eq interface 'outline)
7461 (car (org-get-location (current-buffer) org-goto-help))
7462 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7463 (org-refile-check-position pa)
7464 (nth 3 pa)))))
7465 (if selected-point
7466 (progn
7467 (org-mark-ring-push org-goto-start-pos)
7468 (goto-char selected-point)
7469 (if (or (outline-invisible-p) (org-invisible-p2))
7470 (org-show-context 'org-goto)))
7471 (message "Quit"))))
7473 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7474 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7475 (defvar org-goto-local-auto-isearch-map) ; defined below
7477 (defun org-get-location (buf help)
7478 "Let the user select a location in the Org-mode buffer BUF.
7479 This function uses a recursive edit. It returns the selected position
7480 or nil."
7481 (org-no-popups
7482 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7483 (isearch-hide-immediately nil)
7484 (isearch-search-fun-function
7485 (lambda () 'org-goto-local-search-headings))
7486 (org-goto-selected-point org-goto-exit-command))
7487 (save-excursion
7488 (save-window-excursion
7489 (delete-other-windows)
7490 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7491 (org-pop-to-buffer-same-window
7492 (condition-case nil
7493 (make-indirect-buffer (current-buffer) "*org-goto*")
7494 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7495 (with-output-to-temp-buffer "*Org Help*"
7496 (princ (format help (if org-goto-auto-isearch
7497 " Just type for auto-isearch."
7498 " n/p/f/b/u to navigate, q to quit."))))
7499 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7500 (setq buffer-read-only nil)
7501 (let ((org-startup-truncated t)
7502 (org-startup-folded nil)
7503 (org-startup-align-all-tables nil))
7504 (org-mode)
7505 (org-overview))
7506 (setq buffer-read-only t)
7507 (if (and (boundp 'org-goto-start-pos)
7508 (integer-or-marker-p org-goto-start-pos))
7509 (let ((org-show-hierarchy-above t)
7510 (org-show-siblings t)
7511 (org-show-following-heading t))
7512 (goto-char org-goto-start-pos)
7513 (and (outline-invisible-p) (org-show-context)))
7514 (goto-char (point-min)))
7515 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7516 (message "Select location and press RET")
7517 (use-local-map org-goto-map)
7518 (recursive-edit)))
7519 (kill-buffer "*org-goto*")
7520 (cons org-goto-selected-point org-goto-exit-command))))
7522 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7523 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7524 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7525 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7527 (defun org-goto-local-search-headings (string bound noerror)
7528 "Search and make sure that any matches are in headlines."
7529 (catch 'return
7530 (while (if isearch-forward
7531 (search-forward string bound noerror)
7532 (search-backward string bound noerror))
7533 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7534 (and (member :headline context)
7535 (not (member :tags context))))
7536 (throw 'return (point))))))
7538 (defun org-goto-local-auto-isearch ()
7539 "Start isearch."
7540 (interactive)
7541 (goto-char (point-min))
7542 (let ((keys (this-command-keys)))
7543 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7544 (isearch-mode t)
7545 (isearch-process-search-char (string-to-char keys)))))
7547 (defun org-goto-ret (&optional arg)
7548 "Finish `org-goto' by going to the new location."
7549 (interactive "P")
7550 (setq org-goto-selected-point (point)
7551 org-goto-exit-command 'return)
7552 (throw 'exit nil))
7554 (defun org-goto-left ()
7555 "Finish `org-goto' by going to the new location."
7556 (interactive)
7557 (if (org-at-heading-p)
7558 (progn
7559 (beginning-of-line 1)
7560 (setq org-goto-selected-point (point)
7561 org-goto-exit-command 'left)
7562 (throw 'exit nil))
7563 (user-error "Not on a heading")))
7565 (defun org-goto-right ()
7566 "Finish `org-goto' by going to the new location."
7567 (interactive)
7568 (if (org-at-heading-p)
7569 (progn
7570 (setq org-goto-selected-point (point)
7571 org-goto-exit-command 'right)
7572 (throw 'exit nil))
7573 (user-error "Not on a heading")))
7575 (defun org-goto-quit ()
7576 "Finish `org-goto' without cursor motion."
7577 (interactive)
7578 (setq org-goto-selected-point nil)
7579 (setq org-goto-exit-command 'quit)
7580 (throw 'exit nil))
7582 ;;; Indirect buffer display of subtrees
7584 (defvar org-indirect-dedicated-frame nil
7585 "This is the frame being used for indirect tree display.")
7586 (defvar org-last-indirect-buffer nil)
7588 (defun org-tree-to-indirect-buffer (&optional arg)
7589 "Create indirect buffer and narrow it to current subtree.
7590 With a numerical prefix ARG, go up to this level and then take that tree.
7591 If ARG is negative, go up that many levels.
7593 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7594 indirect buffer previously made with this command, to avoid proliferation of
7595 indirect buffers. However, when you call the command with a \
7596 \\[universal-argument] prefix, or
7597 when `org-indirect-buffer-display' is `new-frame', the last buffer
7598 is kept so that you can work with several indirect buffers at the same time.
7599 If `org-indirect-buffer-display' is `dedicated-frame', the \
7600 \\[universal-argument] prefix also
7601 requests that a new frame be made for the new buffer, so that the dedicated
7602 frame is not changed."
7603 (interactive "P")
7604 (let ((cbuf (current-buffer))
7605 (cwin (selected-window))
7606 (pos (point))
7607 beg end level heading ibuf)
7608 (save-excursion
7609 (org-back-to-heading t)
7610 (when (numberp arg)
7611 (setq level (org-outline-level))
7612 (if (< arg 0) (setq arg (+ level arg)))
7613 (while (> (setq level (org-outline-level)) arg)
7614 (org-up-heading-safe)))
7615 (setq beg (point)
7616 heading (org-get-heading))
7617 (org-end-of-subtree t t)
7618 (if (org-at-heading-p) (backward-char 1))
7619 (setq end (point)))
7620 (if (and (buffer-live-p org-last-indirect-buffer)
7621 (not (eq org-indirect-buffer-display 'new-frame))
7622 (not arg))
7623 (kill-buffer org-last-indirect-buffer))
7624 (setq ibuf (org-get-indirect-buffer cbuf heading)
7625 org-last-indirect-buffer ibuf)
7626 (cond
7627 ((or (eq org-indirect-buffer-display 'new-frame)
7628 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7629 (select-frame (make-frame))
7630 (delete-other-windows)
7631 (org-pop-to-buffer-same-window ibuf)
7632 (org-set-frame-title heading))
7633 ((eq org-indirect-buffer-display 'dedicated-frame)
7634 (raise-frame
7635 (select-frame (or (and org-indirect-dedicated-frame
7636 (frame-live-p org-indirect-dedicated-frame)
7637 org-indirect-dedicated-frame)
7638 (setq org-indirect-dedicated-frame (make-frame)))))
7639 (delete-other-windows)
7640 (org-pop-to-buffer-same-window ibuf)
7641 (org-set-frame-title (concat "Indirect: " heading)))
7642 ((eq org-indirect-buffer-display 'current-window)
7643 (org-pop-to-buffer-same-window ibuf))
7644 ((eq org-indirect-buffer-display 'other-window)
7645 (pop-to-buffer ibuf))
7646 (t (error "Invalid value")))
7647 (if (featurep 'xemacs)
7648 (save-excursion (org-mode) (turn-on-font-lock)))
7649 (narrow-to-region beg end)
7650 (show-all)
7651 (goto-char pos)
7652 (run-hook-with-args 'org-cycle-hook 'all)
7653 (and (window-live-p cwin) (select-window cwin))))
7655 (defun org-get-indirect-buffer (&optional buffer heading)
7656 (setq buffer (or buffer (current-buffer)))
7657 (let ((n 1) (base (buffer-name buffer)) bname)
7658 (while (buffer-live-p
7659 (get-buffer
7660 (setq bname
7661 (concat base "-"
7662 (if heading (concat heading "-" (number-to-string n))
7663 (number-to-string n))))))
7664 (setq n (1+ n)))
7665 (condition-case nil
7666 (make-indirect-buffer buffer bname 'clone)
7667 (error (make-indirect-buffer buffer bname)))))
7669 (defun org-set-frame-title (title)
7670 "Set the title of the current frame to the string TITLE."
7671 ;; FIXME: how to name a single frame in XEmacs???
7672 (unless (featurep 'xemacs)
7673 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7675 ;;;; Structure editing
7677 ;;; Inserting headlines
7679 (defun org-previous-line-empty-p (&optional next)
7680 "Is the previous line a blank line?
7681 When NEXT is non-nil, check the next line instead."
7682 (save-excursion
7683 (and (not (bobp))
7684 (or (beginning-of-line (if next 2 0)) t)
7685 (save-match-data
7686 (looking-at "[ \t]*$")))))
7688 (defun org-insert-heading (&optional arg invisible-ok)
7689 "Insert a new heading or an item with the same depth at point.
7691 If point is at the beginning of a heading or a list item, insert
7692 a new heading or a new item above the current one. If point is
7693 at the beginning of a normal line, turn the line into a heading.
7695 If point is in the middle of a headline or a list item, split the
7696 headline or the item and create a new headline/item with the text
7697 in the current line after point \(see `org-M-RET-may-split-line'
7698 on how to modify this behavior).
7700 With one universal prefix argument, set the user option
7701 `org-insert-heading-respect-content' to t for the duration of
7702 the command. This modifies the behavior described above in this
7703 ways: on list items and at the beginning of normal lines, force
7704 the insertion of a heading after the current subtree.
7706 With two universal prefix arguments, insert the heading at the
7707 end of the grandparent subtree. For example, if point is within
7708 a 2nd-level heading, then it will insert a 2nd-level heading at
7709 the end of the 1st-level parent heading.
7711 If point is at the beginning of a headline, insert a sibling
7712 before the current headline. If point is not at the beginning,
7713 split the line and create a new headline with the text in the
7714 current line after point \(see `org-M-RET-may-split-line' on how
7715 to modify this behavior).
7717 If point is at the beginning of a normal line, turn this line
7718 into a heading.
7720 When INVISIBLE-OK is set, stop at invisible headlines when going
7721 back. This is important for non-interactive uses of the
7722 command."
7723 (interactive "P")
7724 (if (org-called-interactively-p 'any) (org-reveal))
7725 (let ((itemp (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 "")
7730 (adjust-empty-lines t))
7732 (cond
7734 ((or (= (buffer-size) 0)
7735 (and (not (save-excursion
7736 (and (ignore-errors (org-back-to-heading invisible-ok))
7737 (org-at-heading-p))))
7738 (or arg (not itemp))))
7739 ;; At beginning of buffer or so high up that only a heading
7740 ;; makes sense.
7741 (cond ((and (bolp) (not respect-content)) (insert "* "))
7742 ((not respect-content)
7743 (unless may-split (end-of-line))
7744 (insert "\n* "))
7745 ((re-search-forward org-outline-regexp-bol nil t)
7746 (beginning-of-line)
7747 (insert "* \n")
7748 (backward-char))
7749 (t (goto-char (point-max))
7750 (insert "\n* ")))
7751 (run-hooks 'org-insert-heading-hook))
7753 ((and itemp (not (member arg '((4) (16)))))
7754 ;; Insert an item
7755 (org-insert-item))
7758 ;; Maybe move at the end of the subtree
7759 (when (equal arg '(16))
7760 (org-up-heading-safe)
7761 (org-end-of-subtree t))
7762 ;; Insert a heading
7763 (save-restriction
7764 (widen)
7765 (let* ((level nil)
7766 (on-heading (org-at-heading-p))
7767 (empty-line-p (if on-heading
7768 (org-previous-line-empty-p)
7769 ;; We will decide later
7770 nil))
7771 ;; Get a level string to fall back on
7772 (fix-level
7773 (if (org-before-first-heading-p) "*"
7774 (save-excursion
7775 (org-back-to-heading t)
7776 (if (org-previous-line-empty-p) (setq empty-line-p t))
7777 (looking-at org-outline-regexp)
7778 (make-string (1- (length (match-string 0))) ?*))))
7779 (stars
7780 (save-excursion
7781 (condition-case nil
7782 (progn
7783 (org-back-to-heading invisible-ok)
7784 (when (and (not on-heading)
7785 (featurep 'org-inlinetask)
7786 (integerp org-inlinetask-min-level)
7787 (>= (length (match-string 0))
7788 org-inlinetask-min-level))
7789 ;; Find a heading level before the inline task
7790 (while (and (setq level (org-up-heading-safe))
7791 (>= level org-inlinetask-min-level)))
7792 (if (org-at-heading-p)
7793 (org-back-to-heading invisible-ok)
7794 (error "This should not happen")))
7795 (unless (and (save-excursion
7796 (save-match-data
7797 (org-backward-heading-same-level
7798 1 invisible-ok))
7799 (= (point) (match-beginning 0)))
7800 (not (org-previous-line-empty-p t)))
7801 (setq empty-line-p (or empty-line-p
7802 (org-previous-line-empty-p))))
7803 (match-string 0))
7804 (error (or fix-level "* ")))))
7805 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7806 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7807 pos hide-previous previous-pos)
7809 ;; If we insert after content, move there and clean up whitespace
7810 (when (and respect-content
7811 (not (org-looking-at-p org-outline-regexp-bol)))
7812 (if (not (org-before-first-heading-p))
7813 (org-end-of-subtree nil t)
7814 (re-search-forward org-outline-regexp-bol)
7815 (beginning-of-line 0))
7816 (skip-chars-backward " \r\n")
7817 (and (not (looking-back "^\\*+"))
7818 (looking-at "[ \t]+") (replace-match ""))
7819 (unless (eobp) (forward-char 1))
7820 (when (looking-at "^\\*")
7821 (unless (bobp) (backward-char 1))
7822 (insert "\n")))
7824 ;; If we are splitting, grab the text that should be moved to the new headline
7825 (when may-split
7826 (if (org-on-heading-p)
7827 ;; This is a heading, we split intelligently (keeping tags)
7828 (let ((pos (point)))
7829 (goto-char (point-at-bol))
7830 (unless (looking-at org-complex-heading-regexp)
7831 (error "This should not happen"))
7832 (when (and (match-beginning 4)
7833 (> pos (match-beginning 4))
7834 (< pos (match-end 4)))
7835 (setq initial-content (buffer-substring pos (match-end 4)))
7836 (goto-char pos)
7837 (delete-region (point) (match-end 4))
7838 (if (looking-at "[ \t]*$")
7839 (replace-match "")
7840 (insert (make-string (length initial-content) ?\ )))
7841 (setq initial-content (org-trim initial-content)))
7842 (goto-char pos))
7843 ;; a normal line
7844 (setq initial-content
7845 (org-trim (buffer-substring (point) (point-at-eol))))
7846 (delete-region (point) (point-at-eol))))
7848 ;; If we are at the beginning of the line, insert before it. Else after
7849 (cond
7850 ((and (bolp) (looking-at "[ \t]*$")))
7851 ((and (bolp) (not (looking-at "[ \t]*$")))
7852 (open-line 1))
7854 (goto-char (point-at-eol))
7855 (insert "\n")))
7857 ;; Insert the new heading
7858 (insert stars)
7859 (just-one-space)
7860 (insert initial-content)
7861 (when adjust-empty-lines
7862 (if (or (not blank)
7863 (and blank (not (org-previous-line-empty-p))))
7864 (org-N-empty-lines-before-current (if blank 1 0))))
7865 (run-hooks 'org-insert-heading-hook)))))))
7867 (defun org-N-empty-lines-before-current (N)
7868 "Make the number of empty lines before current exactly N.
7869 So this will delete or add empty lines."
7870 (save-excursion
7871 (beginning-of-line)
7872 (let ((p (point)))
7873 (skip-chars-backward " \r\t\n")
7874 (unless (bolp) (forward-line))
7875 (delete-region (point) p))
7876 (when (> N 0) (insert (make-string N ?\n)))))
7878 (defun org-get-heading (&optional no-tags no-todo)
7879 "Return the heading of the current entry, without the stars.
7880 When NO-TAGS is non-nil, don't include tags.
7881 When NO-TODO is non-nil, don't include TODO keywords."
7882 (save-excursion
7883 (org-back-to-heading t)
7884 (cond
7885 ((and no-tags no-todo)
7886 (looking-at org-complex-heading-regexp)
7887 (match-string 4))
7888 (no-tags
7889 (looking-at (concat org-outline-regexp
7890 "\\(.*?\\)"
7891 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7892 (match-string 1))
7893 (no-todo
7894 (looking-at org-todo-line-regexp)
7895 (match-string 3))
7896 (t (looking-at org-heading-regexp)
7897 (match-string 2)))))
7899 (defvar orgstruct-mode) ; defined below
7901 (defun org-heading-components ()
7902 "Return the components of the current heading.
7903 This is a list with the following elements:
7904 - the level as an integer
7905 - the reduced level, different if `org-odd-levels-only' is set.
7906 - the TODO keyword, or nil
7907 - the priority character, like ?A, or nil if no priority is given
7908 - the headline text itself, or the tags string if no headline text
7909 - the tags string, or nil."
7910 (save-excursion
7911 (org-back-to-heading t)
7912 (if (let (case-fold-search)
7913 (looking-at
7914 (if orgstruct-mode
7915 org-heading-regexp
7916 org-complex-heading-regexp)))
7917 (if orgstruct-mode
7918 (list (length (match-string 1))
7919 (org-reduced-level (length (match-string 1)))
7922 (match-string 2)
7923 nil)
7924 (list (length (match-string 1))
7925 (org-reduced-level (length (match-string 1)))
7926 (org-match-string-no-properties 2)
7927 (and (match-end 3) (aref (match-string 3) 2))
7928 (org-match-string-no-properties 4)
7929 (org-match-string-no-properties 5))))))
7931 (defun org-get-entry ()
7932 "Get the entry text, after heading, entire subtree."
7933 (save-excursion
7934 (org-back-to-heading t)
7935 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7937 (defun org-insert-heading-after-current ()
7938 "Insert a new heading with same level as current, after current subtree."
7939 (interactive)
7940 (org-back-to-heading)
7941 (org-insert-heading)
7942 (org-move-subtree-down)
7943 (end-of-line 1))
7945 (defun org-insert-heading-respect-content (&optional invisible-ok)
7946 "Insert heading with `org-insert-heading-respect-content' set to t."
7947 (interactive)
7948 (org-insert-heading '(4) invisible-ok))
7950 (defun org-insert-todo-heading-respect-content (&optional force-state)
7951 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7952 (interactive)
7953 (org-insert-todo-heading force-state '(4)))
7955 (defun org-insert-todo-heading (arg &optional force-heading)
7956 "Insert a new heading with the same level and TODO state as current heading.
7957 If the heading has no TODO state, or if the state is DONE, use the first
7958 state (TODO by default). Also with one prefix arg, force first state. With
7959 two prefix args, force inserting at the end of the parent subtree."
7960 (interactive "P")
7961 (when (or force-heading (not (org-insert-item 'checkbox)))
7962 (org-insert-heading (or (and (equal arg '(16)) '(16))
7963 force-heading))
7964 (save-excursion
7965 (org-back-to-heading)
7966 (outline-previous-heading)
7967 (looking-at org-todo-line-regexp))
7968 (let*
7969 ((new-mark-x
7970 (if (or (equal arg '(4))
7971 (not (match-beginning 2))
7972 (member (match-string 2) org-done-keywords))
7973 (car org-todo-keywords-1)
7974 (match-string 2)))
7975 (new-mark
7977 (run-hook-with-args-until-success
7978 'org-todo-get-default-hook new-mark-x nil)
7979 new-mark-x)))
7980 (beginning-of-line 1)
7981 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7982 (if org-treat-insert-todo-heading-as-state-change
7983 (org-todo new-mark)
7984 (insert new-mark " "))))
7985 (when org-provide-todo-statistics
7986 (org-update-parent-todo-statistics))))
7988 (defun org-insert-subheading (arg)
7989 "Insert a new subheading and demote it.
7990 Works for outline headings and for plain lists alike."
7991 (interactive "P")
7992 (org-insert-heading arg)
7993 (cond
7994 ((org-at-heading-p) (org-do-demote))
7995 ((org-at-item-p) (org-indent-item))))
7997 (defun org-insert-todo-subheading (arg)
7998 "Insert a new subheading with TODO keyword or checkbox and demote it.
7999 Works for outline headings and for plain lists alike."
8000 (interactive "P")
8001 (org-insert-todo-heading arg)
8002 (cond
8003 ((org-at-heading-p) (org-do-demote))
8004 ((org-at-item-p) (org-indent-item))))
8006 ;;; Promotion and Demotion
8008 (defvar org-after-demote-entry-hook nil
8009 "Hook run after an entry has been demoted.
8010 The cursor will be at the beginning of the entry.
8011 When a subtree is being demoted, the hook will be called for each node.")
8013 (defvar org-after-promote-entry-hook nil
8014 "Hook run after an entry has been promoted.
8015 The cursor will be at the beginning of the entry.
8016 When a subtree is being promoted, the hook will be called for each node.")
8018 (defun org-promote-subtree ()
8019 "Promote the entire subtree.
8020 See also `org-promote'."
8021 (interactive)
8022 (save-excursion
8023 (org-with-limited-levels (org-map-tree 'org-promote)))
8024 (org-fix-position-after-promote))
8026 (defun org-demote-subtree ()
8027 "Demote the entire subtree. See `org-demote'.
8028 See also `org-promote'."
8029 (interactive)
8030 (save-excursion
8031 (org-with-limited-levels (org-map-tree 'org-demote)))
8032 (org-fix-position-after-promote))
8035 (defun org-do-promote ()
8036 "Promote the current heading higher up the tree.
8037 If the region is active in `transient-mark-mode', promote all headings
8038 in the region."
8039 (interactive)
8040 (save-excursion
8041 (if (org-region-active-p)
8042 (org-map-region 'org-promote (region-beginning) (region-end))
8043 (org-promote)))
8044 (org-fix-position-after-promote))
8046 (defun org-do-demote ()
8047 "Demote the current heading lower down the tree.
8048 If the region is active in `transient-mark-mode', demote all headings
8049 in the region."
8050 (interactive)
8051 (save-excursion
8052 (if (org-region-active-p)
8053 (org-map-region 'org-demote (region-beginning) (region-end))
8054 (org-demote)))
8055 (org-fix-position-after-promote))
8057 (defun org-fix-position-after-promote ()
8058 "Make sure that after pro/demotion cursor position is right."
8059 (let ((pos (point)))
8060 (when (save-excursion
8061 (beginning-of-line 1)
8062 (looking-at org-todo-line-regexp)
8063 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8064 (cond ((eobp) (insert " "))
8065 ((eolp) (insert " "))
8066 ((equal (char-after) ?\ ) (forward-char 1))))))
8068 (defun org-current-level ()
8069 "Return the level of the current entry, or nil if before the first headline.
8070 The level is the number of stars at the beginning of the headline."
8071 (save-excursion
8072 (org-with-limited-levels
8073 (if (ignore-errors (org-back-to-heading t))
8074 (funcall outline-level)))))
8076 (defun org-get-previous-line-level ()
8077 "Return the outline depth of the last headline before the current line.
8078 Returns 0 for the first headline in the buffer, and nil if before the
8079 first headline."
8080 (and (org-current-level)
8081 (or (and (/= (line-beginning-position) (point-min))
8082 (save-excursion (beginning-of-line 0) (org-current-level)))
8083 0)))
8085 (defun org-reduced-level (l)
8086 "Compute the effective level of a heading.
8087 This takes into account the setting of `org-odd-levels-only'."
8088 (cond
8089 ((zerop l) 0)
8090 (org-odd-levels-only (1+ (floor (/ l 2))))
8091 (t l)))
8093 (defun org-level-increment ()
8094 "Return the number of stars that will be added or removed at a
8095 time to headlines when structure editing, based on the value of
8096 `org-odd-levels-only'."
8097 (if org-odd-levels-only 2 1))
8099 (defun org-get-valid-level (level &optional change)
8100 "Rectify a level change under the influence of `org-odd-levels-only'
8101 LEVEL is a current level, CHANGE is by how much the level should be
8102 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8103 even level numbers will become the next higher odd number."
8104 (if org-odd-levels-only
8105 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8106 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8107 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8108 (max 1 (+ level (or change 0)))))
8110 (if (boundp 'define-obsolete-function-alias)
8111 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8112 (define-obsolete-function-alias 'org-get-legal-level
8113 'org-get-valid-level)
8114 (define-obsolete-function-alias 'org-get-legal-level
8115 'org-get-valid-level "23.1")))
8117 (defun org-promote ()
8118 "Promote the current heading higher up the tree.
8119 If the region is active in `transient-mark-mode', promote all headings
8120 in the region."
8121 (org-back-to-heading t)
8122 (let* ((level (save-match-data (funcall outline-level)))
8123 (after-change-functions (remove 'flyspell-after-change-function
8124 after-change-functions))
8125 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8126 (diff (abs (- level (length up-head) -1))))
8127 (cond ((and (= level 1) org-called-with-limited-levels
8128 org-allow-promoting-top-level-subtree)
8129 (replace-match "# " nil t))
8130 ((= level 1)
8131 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8132 (t (replace-match up-head nil t)))
8133 ;; Fixup tag positioning
8134 (unless (= level 1)
8135 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8136 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8137 (run-hooks 'org-after-promote-entry-hook)))
8139 (defun org-demote ()
8140 "Demote the current heading lower down the tree.
8141 If the region is active in `transient-mark-mode', demote all headings
8142 in the region."
8143 (org-back-to-heading t)
8144 (let* ((level (save-match-data (funcall outline-level)))
8145 (after-change-functions (remove 'flyspell-after-change-function
8146 after-change-functions))
8147 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8148 (diff (abs (- level (length down-head) -1))))
8149 (replace-match down-head nil t)
8150 ;; Fixup tag positioning
8151 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8152 (if org-adapt-indentation (org-fixup-indentation diff))
8153 (run-hooks 'org-after-demote-entry-hook)))
8155 (defun org-cycle-level ()
8156 "Cycle the level of an empty headline through possible states.
8157 This goes first to child, then to parent, level, then up the hierarchy.
8158 After top level, it switches back to sibling level."
8159 (interactive)
8160 (let ((org-adapt-indentation nil))
8161 (when (org-point-at-end-of-empty-headline)
8162 (setq this-command 'org-cycle-level) ; Only needed for caching
8163 (let ((cur-level (org-current-level))
8164 (prev-level (org-get-previous-line-level)))
8165 (cond
8166 ;; If first headline in file, promote to top-level.
8167 ((= prev-level 0)
8168 (loop repeat (/ (- cur-level 1) (org-level-increment))
8169 do (org-do-promote)))
8170 ;; If same level as prev, demote one.
8171 ((= prev-level cur-level)
8172 (org-do-demote))
8173 ;; If parent is top-level, promote to top level if not already.
8174 ((= prev-level 1)
8175 (loop repeat (/ (- cur-level 1) (org-level-increment))
8176 do (org-do-promote)))
8177 ;; If top-level, return to prev-level.
8178 ((= cur-level 1)
8179 (loop repeat (/ (- prev-level 1) (org-level-increment))
8180 do (org-do-demote)))
8181 ;; If less than prev-level, promote one.
8182 ((< cur-level prev-level)
8183 (org-do-promote))
8184 ;; If deeper than prev-level, promote until higher than
8185 ;; prev-level.
8186 ((> cur-level prev-level)
8187 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8188 do (org-do-promote))))
8189 t))))
8191 (defun org-map-tree (fun)
8192 "Call FUN for every heading underneath the current one."
8193 (org-back-to-heading)
8194 (let ((level (funcall outline-level)))
8195 (save-excursion
8196 (funcall fun)
8197 (while (and (progn
8198 (outline-next-heading)
8199 (> (funcall outline-level) level))
8200 (not (eobp)))
8201 (funcall fun)))))
8203 (defun org-map-region (fun beg end)
8204 "Call FUN for every heading between BEG and END."
8205 (let ((org-ignore-region t))
8206 (save-excursion
8207 (setq end (copy-marker end))
8208 (goto-char beg)
8209 (if (and (re-search-forward org-outline-regexp-bol nil t)
8210 (< (point) end))
8211 (funcall fun))
8212 (while (and (progn
8213 (outline-next-heading)
8214 (< (point) end))
8215 (not (eobp)))
8216 (funcall fun)))))
8218 (defvar org-property-end-re) ; silence byte-compiler
8219 (defun org-fixup-indentation (diff)
8220 "Change the indentation in the current entry by DIFF.
8221 However, if any line in the current entry has no indentation, or if it
8222 would end up with no indentation after the change, nothing at all is done."
8223 (save-excursion
8224 (let ((end (save-excursion (outline-next-heading)
8225 (point-marker)))
8226 (prohibit (if (> diff 0)
8227 "^\\S-"
8228 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8229 col)
8230 (unless (save-excursion (end-of-line 1)
8231 (re-search-forward prohibit end t))
8232 (while (and (< (point) end)
8233 (re-search-forward "^[ \t]+" end t))
8234 (goto-char (match-end 0))
8235 (setq col (current-column))
8236 (if (< diff 0) (replace-match ""))
8237 (org-indent-to-column (+ diff col))))
8238 (move-marker end nil))))
8240 (defun org-convert-to-odd-levels ()
8241 "Convert an org-mode file with all levels allowed to one with odd levels.
8242 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8243 level 5 etc."
8244 (interactive)
8245 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8246 (let ((outline-level 'org-outline-level)
8247 (org-odd-levels-only nil) n)
8248 (save-excursion
8249 (goto-char (point-min))
8250 (while (re-search-forward "^\\*\\*+ " nil t)
8251 (setq n (- (length (match-string 0)) 2))
8252 (while (>= (setq n (1- n)) 0)
8253 (org-demote))
8254 (end-of-line 1))))))
8256 (defun org-convert-to-oddeven-levels ()
8257 "Convert an org-mode file with only odd levels to one with odd/even levels.
8258 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8259 file contains a section with an even level, conversion would
8260 destroy the structure of the file. An error is signaled in this
8261 case."
8262 (interactive)
8263 (goto-char (point-min))
8264 ;; First check if there are no even levels
8265 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8266 (org-show-context t)
8267 (error "Not all levels are odd in this file. Conversion not possible"))
8268 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8269 (let ((outline-regexp org-outline-regexp)
8270 (outline-level 'org-outline-level)
8271 (org-odd-levels-only nil) n)
8272 (save-excursion
8273 (goto-char (point-min))
8274 (while (re-search-forward "^\\*\\*+ " nil t)
8275 (setq n (/ (1- (length (match-string 0))) 2))
8276 (while (>= (setq n (1- n)) 0)
8277 (org-promote))
8278 (end-of-line 1))))))
8280 (defun org-tr-level (n)
8281 "Make N odd if required."
8282 (if org-odd-levels-only (1+ (/ n 2)) n))
8284 ;;; Vertical tree motion, cutting and pasting of subtrees
8286 (defun org-move-subtree-up (&optional arg)
8287 "Move the current subtree up past ARG headlines of the same level."
8288 (interactive "p")
8289 (org-move-subtree-down (- (prefix-numeric-value arg))))
8291 (defun org-move-subtree-down (&optional arg)
8292 "Move the current subtree down past ARG headlines of the same level."
8293 (interactive "p")
8294 (setq arg (prefix-numeric-value arg))
8295 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8296 'org-get-last-sibling))
8297 (ins-point (make-marker))
8298 (cnt (abs arg))
8299 (col (current-column))
8300 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8301 ;; Select the tree
8302 (org-back-to-heading)
8303 (setq beg0 (point))
8304 (save-excursion
8305 (setq ne-beg (org-back-over-empty-lines))
8306 (setq beg (point)))
8307 (save-match-data
8308 (save-excursion (outline-end-of-heading)
8309 (setq folded (outline-invisible-p)))
8310 (progn (org-end-of-subtree nil t)
8311 (unless (eobp) (backward-char))))
8312 (outline-next-heading)
8313 (setq ne-end (org-back-over-empty-lines))
8314 (setq end (point))
8315 (goto-char beg0)
8316 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8317 ;; include less whitespace
8318 (save-excursion
8319 (goto-char beg)
8320 (forward-line (- ne-beg ne-end))
8321 (setq beg (point))))
8322 ;; Find insertion point, with error handling
8323 (while (> cnt 0)
8324 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8325 (progn (goto-char beg0)
8326 (user-error "Cannot move past superior level or buffer limit")))
8327 (setq cnt (1- cnt)))
8328 (if (> arg 0)
8329 ;; Moving forward - still need to move over subtree
8330 (progn (org-end-of-subtree t t)
8331 (save-excursion
8332 (org-back-over-empty-lines)
8333 (or (bolp) (newline)))))
8334 (setq ne-ins (org-back-over-empty-lines))
8335 (move-marker ins-point (point))
8336 (setq txt (buffer-substring beg end))
8337 (org-save-markers-in-region beg end)
8338 (delete-region beg end)
8339 (org-remove-empty-overlays-at beg)
8340 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8341 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8342 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8343 (let ((bbb (point)))
8344 (insert-before-markers txt)
8345 (org-reinstall-markers-in-region bbb)
8346 (move-marker ins-point bbb))
8347 (or (bolp) (insert "\n"))
8348 (setq ins-end (point))
8349 (goto-char ins-point)
8350 (org-skip-whitespace)
8351 (when (and (< arg 0)
8352 (org-first-sibling-p)
8353 (> ne-ins ne-beg))
8354 ;; Move whitespace back to beginning
8355 (save-excursion
8356 (goto-char ins-end)
8357 (let ((kill-whole-line t))
8358 (kill-line (- ne-ins ne-beg)) (point)))
8359 (insert (make-string (- ne-ins ne-beg) ?\n)))
8360 (move-marker ins-point nil)
8361 (if folded
8362 (hide-subtree)
8363 (org-show-entry)
8364 (show-children)
8365 (org-cycle-hide-drawers 'children))
8366 (org-clean-visibility-after-subtree-move)
8367 ;; move back to the initial column we were at
8368 (move-to-column col)))
8370 (defvar org-subtree-clip ""
8371 "Clipboard for cut and paste of subtrees.
8372 This is actually only a copy of the kill, because we use the normal kill
8373 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8375 (defvar org-subtree-clip-folded nil
8376 "Was the last copied subtree folded?
8377 This is used to fold the tree back after pasting.")
8379 (defun org-cut-subtree (&optional n)
8380 "Cut the current subtree into the clipboard.
8381 With prefix arg N, cut this many sequential subtrees.
8382 This is a short-hand for marking the subtree and then cutting it."
8383 (interactive "p")
8384 (org-copy-subtree n 'cut))
8386 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8387 "Copy the current subtree it in the clipboard.
8388 With prefix arg N, copy this many sequential subtrees.
8389 This is a short-hand for marking the subtree and then copying it.
8390 If CUT is non-nil, actually cut the subtree.
8391 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8392 of some markers in the region, even if CUT is non-nil. This is
8393 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8394 (interactive "p")
8395 (let (beg end folded (beg0 (point)))
8396 (if (org-called-interactively-p 'any)
8397 (org-back-to-heading nil) ; take what looks like a subtree
8398 (org-back-to-heading t)) ; take what is really there
8399 (setq beg (point))
8400 (skip-chars-forward " \t\r\n")
8401 (save-match-data
8402 (if nosubtrees
8403 (outline-next-heading)
8404 (save-excursion (outline-end-of-heading)
8405 (setq folded (outline-invisible-p)))
8406 (ignore-errors (org-forward-heading-same-level (1- n) t))
8407 (org-end-of-subtree t t)))
8408 (setq end (point))
8409 (goto-char beg0)
8410 (when (> end beg)
8411 (setq org-subtree-clip-folded folded)
8412 (when (or cut force-store-markers)
8413 (org-save-markers-in-region beg end))
8414 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8415 (setq org-subtree-clip (current-kill 0))
8416 (message "%s: Subtree(s) with %d characters"
8417 (if cut "Cut" "Copied")
8418 (length org-subtree-clip)))))
8420 (defun org-paste-subtree (&optional level tree for-yank remove)
8421 "Paste the clipboard as a subtree, with modification of headline level.
8422 The entire subtree is promoted or demoted in order to match a new headline
8423 level.
8425 If the cursor is at the beginning of a headline, the same level as
8426 that headline is used to paste the tree.
8428 If not, the new level is derived from the *visible* headings
8429 before and after the insertion point, and taken to be the inferior headline
8430 level of the two. So if the previous visible heading is level 3 and the
8431 next is level 4 (or vice versa), level 4 will be used for insertion.
8432 This makes sure that the subtree remains an independent subtree and does
8433 not swallow low level entries.
8435 You can also force a different level, either by using a numeric prefix
8436 argument, or by inserting the heading marker by hand. For example, if the
8437 cursor is after \"*****\", then the tree will be shifted to level 5.
8439 If optional TREE is given, use this text instead of the kill ring.
8441 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8442 move back over whitespace before inserting, and move point to the end of
8443 the inserted text when done.
8445 When REMOVE is non-nil, remove the subtree from the clipboard."
8446 (interactive "P")
8447 (setq tree (or tree (and kill-ring (current-kill 0))))
8448 (unless (org-kill-is-subtree-p tree)
8449 (user-error "%s"
8450 (substitute-command-keys
8451 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8452 (org-with-limited-levels
8453 (let* ((visp (not (outline-invisible-p)))
8454 (txt tree)
8455 (^re_ "\\(\\*+\\)[ \t]*")
8456 (old-level (if (string-match org-outline-regexp-bol txt)
8457 (- (match-end 0) (match-beginning 0) 1)
8458 -1))
8459 (force-level (cond (level (prefix-numeric-value level))
8460 ((and (looking-at "[ \t]*$")
8461 (string-match
8462 "^\\*+$" (buffer-substring
8463 (point-at-bol) (point))))
8464 (- (match-end 0) (match-beginning 0)))
8465 ((and (bolp)
8466 (looking-at org-outline-regexp))
8467 (- (match-end 0) (point) 1))))
8468 (previous-level (save-excursion
8469 (condition-case nil
8470 (progn
8471 (outline-previous-visible-heading 1)
8472 (if (looking-at ^re_)
8473 (- (match-end 0) (match-beginning 0) 1)
8475 (error 1))))
8476 (next-level (save-excursion
8477 (condition-case nil
8478 (progn
8479 (or (looking-at org-outline-regexp)
8480 (outline-next-visible-heading 1))
8481 (if (looking-at ^re_)
8482 (- (match-end 0) (match-beginning 0) 1)
8484 (error 1))))
8485 (new-level (or force-level (max previous-level next-level)))
8486 (shift (if (or (= old-level -1)
8487 (= new-level -1)
8488 (= old-level new-level))
8490 (- new-level old-level)))
8491 (delta (if (> shift 0) -1 1))
8492 (func (if (> shift 0) 'org-demote 'org-promote))
8493 (org-odd-levels-only nil)
8494 beg end newend)
8495 ;; Remove the forced level indicator
8496 (if force-level
8497 (delete-region (point-at-bol) (point)))
8498 ;; Paste
8499 (beginning-of-line (if (bolp) 1 2))
8500 (setq beg (point))
8501 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8502 (insert-before-markers txt)
8503 (unless (string-match "\n\\'" txt) (insert "\n"))
8504 (setq newend (point))
8505 (org-reinstall-markers-in-region beg)
8506 (setq end (point))
8507 (goto-char beg)
8508 (skip-chars-forward " \t\n\r")
8509 (setq beg (point))
8510 (if (and (outline-invisible-p) visp)
8511 (save-excursion (outline-show-heading)))
8512 ;; Shift if necessary
8513 (unless (= shift 0)
8514 (save-restriction
8515 (narrow-to-region beg end)
8516 (while (not (= shift 0))
8517 (org-map-region func (point-min) (point-max))
8518 (setq shift (+ delta shift)))
8519 (goto-char (point-min))
8520 (setq newend (point-max))))
8521 (when (or (org-called-interactively-p 'interactive) for-yank)
8522 (message "Clipboard pasted as level %d subtree" new-level))
8523 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8524 kill-ring
8525 (eq org-subtree-clip (current-kill 0))
8526 org-subtree-clip-folded)
8527 ;; The tree was folded before it was killed/copied
8528 (hide-subtree))
8529 (and for-yank (goto-char newend))
8530 (and remove (setq kill-ring (cdr kill-ring))))))
8532 (defun org-kill-is-subtree-p (&optional txt)
8533 "Check if the current kill is an outline subtree, or a set of trees.
8534 Returns nil if kill does not start with a headline, or if the first
8535 headline level is not the largest headline level in the tree.
8536 So this will actually accept several entries of equal levels as well,
8537 which is OK for `org-paste-subtree'.
8538 If optional TXT is given, check this string instead of the current kill."
8539 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8540 (re (org-get-limited-outline-regexp))
8541 (^re (concat "^" re))
8542 (start-level (and kill
8543 (string-match
8544 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8545 kill)
8546 (- (match-end 2) (match-beginning 2) 1)))
8547 (start (1+ (or (match-beginning 2) -1))))
8548 (if (not start-level)
8549 (progn
8550 nil) ;; does not even start with a heading
8551 (catch 'exit
8552 (while (setq start (string-match ^re kill (1+ start)))
8553 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8554 (throw 'exit nil)))
8555 t))))
8557 (defvar org-markers-to-move nil
8558 "Markers that should be moved with a cut-and-paste operation.
8559 Those markers are stored together with their positions relative to
8560 the start of the region.")
8562 (defun org-save-markers-in-region (beg end)
8563 "Check markers in region.
8564 If these markers are between BEG and END, record their position relative
8565 to BEG, so that after moving the block of text, we can put the markers back
8566 into place.
8567 This function gets called just before an entry or tree gets cut from the
8568 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8569 called immediately, to move the markers with the entries."
8570 (setq org-markers-to-move nil)
8571 (when (featurep 'org-clock)
8572 (org-clock-save-markers-for-cut-and-paste beg end))
8573 (when (featurep 'org-agenda)
8574 (org-agenda-save-markers-for-cut-and-paste beg end)))
8576 (defun org-check-and-save-marker (marker beg end)
8577 "Check if MARKER is between BEG and END.
8578 If yes, remember the marker and the distance to BEG."
8579 (when (and (marker-buffer marker)
8580 (equal (marker-buffer marker) (current-buffer)))
8581 (if (and (>= marker beg) (< marker end))
8582 (push (cons marker (- marker beg)) org-markers-to-move))))
8584 (defun org-reinstall-markers-in-region (beg)
8585 "Move all remembered markers to their position relative to BEG."
8586 (mapc (lambda (x)
8587 (move-marker (car x) (+ beg (cdr x))))
8588 org-markers-to-move)
8589 (setq org-markers-to-move nil))
8591 (defun org-narrow-to-subtree ()
8592 "Narrow buffer to the current subtree."
8593 (interactive)
8594 (save-excursion
8595 (save-match-data
8596 (org-with-limited-levels
8597 (narrow-to-region
8598 (progn (org-back-to-heading t) (point))
8599 (progn (org-end-of-subtree t t)
8600 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8601 (point)))))))
8603 (defun org-narrow-to-block ()
8604 "Narrow buffer to the current block."
8605 (interactive)
8606 (let* ((case-fold-search t)
8607 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8608 "^[ \t]*#\\+end_.*")))
8609 (if blockp
8610 (narrow-to-region (car blockp) (cdr blockp))
8611 (user-error "Not in a block"))))
8613 (defun org-clone-subtree-with-time-shift (n &optional shift)
8614 "Clone the task (subtree) at point N times.
8615 The clones will be inserted as siblings.
8617 In interactive use, the user will be prompted for the number of
8618 clones to be produced. If the entry has a timestamp, the user
8619 will also be prompted for a time shift, which may be a repeater
8620 as used in time stamps, for example `+3d'. To disable this,
8621 you can call the function with a universal prefix argument.
8623 When a valid repeater is given and the entry contains any time
8624 stamps, the clones will become a sequence in time, with time
8625 stamps in the subtree shifted for each clone produced. If SHIFT
8626 is nil or the empty string, time stamps will be left alone. The
8627 ID property of the original subtree is removed.
8629 If the original subtree did contain time stamps with a repeater,
8630 the following will happen:
8631 - the repeater will be removed in each clone
8632 - an additional clone will be produced, with the current, unshifted
8633 date(s) in the entry.
8634 - the original entry will be placed *after* all the clones, with
8635 repeater intact.
8636 - the start days in the repeater in the original entry will be shifted
8637 to past the last clone.
8638 In this way you can spell out a number of instances of a repeating task,
8639 and still retain the repeater to cover future instances of the task."
8640 (interactive "nNumber of clones to produce: ")
8641 (let ((shift
8642 (or shift
8643 (if (and (not (equal current-prefix-arg '(4)))
8644 (save-excursion
8645 (re-search-forward org-ts-regexp-both
8646 (save-excursion
8647 (org-end-of-subtree t)
8648 (point)) t)))
8649 (read-from-minibuffer
8650 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8651 ""))) ;; No time shift
8652 (n-no-remove -1)
8653 (drawer-re org-drawer-regexp)
8654 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8655 beg end template task idprop
8656 shift-n shift-what doshift nmin nmax)
8657 (if (not (and (integerp n) (> n 0)))
8658 (user-error "Invalid number of replications %s" n))
8659 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8660 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8661 shift)))
8662 (user-error "Invalid shift specification %s" shift))
8663 (when doshift
8664 (setq shift-n (string-to-number (match-string 1 shift))
8665 shift-what (cdr (assoc (match-string 2 shift)
8666 '(("d" . day) ("w" . week)
8667 ("m" . month) ("y" . year))))))
8668 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8669 (setq nmin 1 nmax n)
8670 (org-back-to-heading t)
8671 (setq beg (point))
8672 (setq idprop (org-entry-get nil "ID"))
8673 (org-end-of-subtree t t)
8674 (or (bolp) (insert "\n"))
8675 (setq end (point))
8676 (setq template (buffer-substring beg end))
8677 (when (and doshift
8678 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8679 (delete-region beg end)
8680 (setq end beg)
8681 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8682 (goto-char end)
8683 (loop for n from nmin to nmax do
8684 ;; prepare clone
8685 (with-temp-buffer
8686 (insert template)
8687 (org-mode)
8688 (goto-char (point-min))
8689 (org-show-subtree)
8690 (and idprop (if org-clone-delete-id
8691 (org-entry-delete nil "ID")
8692 (org-id-get-create t)))
8693 (unless (= n 0)
8694 (while (re-search-forward org-clock-re nil t)
8695 (kill-whole-line))
8696 (goto-char (point-min))
8697 (while (re-search-forward drawer-re nil t)
8698 (org-remove-empty-drawer-at (point))))
8699 (goto-char (point-min))
8700 (when doshift
8701 (while (re-search-forward org-ts-regexp-both nil t)
8702 (org-timestamp-change (* n shift-n) shift-what))
8703 (unless (= n n-no-remove)
8704 (goto-char (point-min))
8705 (while (re-search-forward org-ts-regexp nil t)
8706 (save-excursion
8707 (goto-char (match-beginning 0))
8708 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8709 (delete-region (match-beginning 1) (match-end 1)))))))
8710 (setq task (buffer-string)))
8711 (insert task))
8712 (goto-char beg)))
8714 ;;; Outline Sorting
8716 (defun org-sort (with-case)
8717 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8718 Optional argument WITH-CASE means sort case-sensitively."
8719 (interactive "P")
8720 (cond
8721 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8722 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8724 (org-call-with-arg 'org-sort-entries with-case))))
8726 (defun org-sort-remove-invisible (s)
8727 "Remove invisible links from string S."
8728 (remove-text-properties 0 (length s) org-rm-props s)
8729 (while (string-match org-bracket-link-regexp s)
8730 (setq s (replace-match (if (match-end 2)
8731 (match-string 3 s)
8732 (match-string 1 s)) t t s)))
8733 (let ((st (format " %s " s)))
8734 (while (string-match org-emph-re st)
8735 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8736 (setq s (substring st 1 -1)))
8739 (defvar org-priority-regexp) ; defined later in the file
8741 (defvar org-after-sorting-entries-or-items-hook nil
8742 "Hook that is run after a bunch of entries or items have been sorted.
8743 When children are sorted, the cursor is in the parent line when this
8744 hook gets called. When a region or a plain list is sorted, the cursor
8745 will be in the first entry of the sorted region/list.")
8747 (defun org-sort-entries
8748 (&optional with-case sorting-type getkey-func compare-func property)
8749 "Sort entries on a certain level of an outline tree.
8750 If there is an active region, the entries in the region are sorted.
8751 Else, if the cursor is before the first entry, sort the top-level items.
8752 Else, the children of the entry at point are sorted.
8754 Sorting can be alphabetically, numerically, by date/time as given by
8755 a time stamp, by a property, by priority order, or by a custom function.
8757 The command prompts for the sorting type unless it has been given to the
8758 function through the SORTING-TYPE argument, which needs to be a character,
8759 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8760 the precise meaning of each character:
8762 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8763 c By creation time, which is assumed to be the first inactive time stamp
8764 at the beginning of a line.
8765 d By deadline date/time.
8766 k By clocking time.
8767 n Numerically, by converting the beginning of the entry/item to a number.
8768 o By order of TODO keywords.
8769 p By priority according to the cookie.
8770 r By the value of a property.
8771 s By scheduled date/time.
8772 t By date/time, either the first active time stamp in the entry, or, if
8773 none exist, by the first inactive one.
8775 Capital letters will reverse the sort order.
8777 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8778 called with point at the beginning of the record. It must return either
8779 a string or a number that should serve as the sorting key for that record.
8781 Comparing entries ignores case by default. However, with an optional argument
8782 WITH-CASE, the sorting considers case as well.
8784 Sorting is done against the visible part of the headlines, it ignores hidden
8785 links.
8787 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8788 (interactive "P")
8789 (let ((case-func (if with-case 'identity 'downcase))
8790 (cmstr
8791 ;; The clock marker is lost when using `sort-subr', let's
8792 ;; store the clocking string.
8793 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8794 (save-excursion
8795 (goto-char org-clock-marker)
8796 (looking-back "^.*") (match-string-no-properties 0))))
8797 start beg end stars re re2
8798 txt what tmp)
8799 ;; Find beginning and end of region to sort
8800 (cond
8801 ((org-region-active-p)
8802 ;; we will sort the region
8803 (setq end (region-end)
8804 what "region")
8805 (goto-char (region-beginning))
8806 (if (not (org-at-heading-p)) (outline-next-heading))
8807 (setq start (point)))
8808 ((or (org-at-heading-p)
8809 (ignore-errors (progn (org-back-to-heading) t)))
8810 ;; we will sort the children of the current headline
8811 (org-back-to-heading)
8812 (setq start (point)
8813 end (progn (org-end-of-subtree t t)
8814 (or (bolp) (insert "\n"))
8815 (when (>= (org-back-over-empty-lines) 1)
8816 (forward-line 1))
8817 (point))
8818 what "children")
8819 (goto-char start)
8820 (show-subtree)
8821 (outline-next-heading))
8823 ;; we will sort the top-level entries in this file
8824 (goto-char (point-min))
8825 (or (org-at-heading-p) (outline-next-heading))
8826 (setq start (point))
8827 (goto-char (point-max))
8828 (beginning-of-line 1)
8829 (when (looking-at ".*?\\S-")
8830 ;; File ends in a non-white line
8831 (end-of-line 1)
8832 (insert "\n"))
8833 (setq end (point-max))
8834 (setq what "top-level")
8835 (goto-char start)
8836 (show-all)))
8838 (setq beg (point))
8839 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8841 (looking-at "\\(\\*+\\)")
8842 (setq stars (match-string 1)
8843 re (concat "^" (regexp-quote stars) " +")
8844 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8845 txt (buffer-substring beg end))
8846 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8847 (if (and (not (equal stars "*")) (string-match re2 txt))
8848 (user-error "Region to sort contains a level above the first entry"))
8850 (unless sorting-type
8851 (message
8852 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8853 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8854 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8855 what)
8856 (setq sorting-type (read-char-exclusive))
8858 (unless getkey-func
8859 (and (= (downcase sorting-type) ?f)
8860 (setq getkey-func
8861 (org-icompleting-read "Sort using function: "
8862 obarray 'fboundp t nil nil))
8863 (setq getkey-func (intern getkey-func))))
8865 (and (= (downcase sorting-type) ?r)
8866 (not property)
8867 (setq property
8868 (org-icompleting-read "Property: "
8869 (mapcar 'list (org-buffer-property-keys t))
8870 nil t))))
8872 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8873 (message "Sorting entries...")
8875 (save-restriction
8876 (narrow-to-region start end)
8877 (let ((dcst (downcase sorting-type))
8878 (case-fold-search nil)
8879 (now (current-time)))
8880 (sort-subr
8881 (/= dcst sorting-type)
8882 ;; This function moves to the beginning character of the "record" to
8883 ;; be sorted.
8884 (lambda nil
8885 (if (re-search-forward re nil t)
8886 (goto-char (match-beginning 0))
8887 (goto-char (point-max))))
8888 ;; This function moves to the last character of the "record" being
8889 ;; sorted.
8890 (lambda nil
8891 (save-match-data
8892 (condition-case nil
8893 (outline-forward-same-level 1)
8894 (error
8895 (goto-char (point-max))))))
8896 ;; This function returns the value that gets sorted against.
8897 (lambda nil
8898 (cond
8899 ((= dcst ?n)
8900 (if (looking-at org-complex-heading-regexp)
8901 (string-to-number (org-sort-remove-invisible (match-string 4)))
8902 nil))
8903 ((= dcst ?a)
8904 (if (looking-at org-complex-heading-regexp)
8905 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8906 nil))
8907 ((= dcst ?k)
8908 (or (get-text-property (point) :org-clock-minutes) 0))
8909 ((= dcst ?t)
8910 (let ((end (save-excursion (outline-next-heading) (point))))
8911 (if (or (re-search-forward org-ts-regexp end t)
8912 (re-search-forward org-ts-regexp-both end t))
8913 (org-time-string-to-seconds (match-string 0))
8914 (org-float-time now))))
8915 ((= dcst ?c)
8916 (let ((end (save-excursion (outline-next-heading) (point))))
8917 (if (re-search-forward
8918 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8919 end t)
8920 (org-time-string-to-seconds (match-string 0))
8921 (org-float-time now))))
8922 ((= dcst ?s)
8923 (let ((end (save-excursion (outline-next-heading) (point))))
8924 (if (re-search-forward org-scheduled-time-regexp end t)
8925 (org-time-string-to-seconds (match-string 1))
8926 (org-float-time now))))
8927 ((= dcst ?d)
8928 (let ((end (save-excursion (outline-next-heading) (point))))
8929 (if (re-search-forward org-deadline-time-regexp end t)
8930 (org-time-string-to-seconds (match-string 1))
8931 (org-float-time now))))
8932 ((= dcst ?p)
8933 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8934 (string-to-char (match-string 2))
8935 org-default-priority))
8936 ((= dcst ?r)
8937 (or (org-entry-get nil property) ""))
8938 ((= dcst ?o)
8939 (if (looking-at org-complex-heading-regexp)
8940 (let* ((m (match-string 2))
8941 (s (if (member m org-done-keywords) '- '+)))
8942 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8943 ((= dcst ?f)
8944 (if getkey-func
8945 (progn
8946 (setq tmp (funcall getkey-func))
8947 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8948 tmp)
8949 (error "Invalid key function `%s'" getkey-func)))
8950 (t (error "Invalid sorting type `%c'" sorting-type))))
8952 (cond
8953 ((= dcst ?a) 'string<)
8954 ((= dcst ?f) compare-func)
8955 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8956 (run-hooks 'org-after-sorting-entries-or-items-hook)
8957 ;; Reset the clock marker if needed
8958 (when cmstr
8959 (save-excursion
8960 (goto-char start)
8961 (search-forward cmstr nil t)
8962 (move-marker org-clock-marker (point))))
8963 (message "Sorting entries...done")))
8965 (defun org-do-sort (table what &optional with-case sorting-type)
8966 "Sort TABLE of WHAT according to SORTING-TYPE.
8967 The user will be prompted for the SORTING-TYPE if the call to this
8968 function does not specify it.
8969 WHAT is only for the prompt, to indicate what is being sorted.
8970 The sorting key will be extracted from the car of the elements of
8971 the table.
8972 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8973 (unless sorting-type
8974 (message
8975 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8976 what)
8977 (setq sorting-type (read-char-exclusive)))
8978 (let ((dcst (downcase sorting-type))
8979 extractfun comparefun)
8980 ;; Define the appropriate functions
8981 (cond
8982 ((= dcst ?n)
8983 (setq extractfun 'string-to-number
8984 comparefun (if (= dcst sorting-type) '< '>)))
8985 ((= dcst ?a)
8986 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8987 (lambda(x) (downcase (org-sort-remove-invisible x))))
8988 comparefun (if (= dcst sorting-type)
8989 'string<
8990 (lambda (a b) (and (not (string< a b))
8991 (not (string= a b)))))))
8992 ((= dcst ?t)
8993 (setq extractfun
8994 (lambda (x)
8995 (cond ((or (string-match org-ts-regexp x)
8996 (string-match org-ts-regexp-both x))
8997 (org-float-time
8998 (org-time-string-to-time (match-string 0 x))))
8999 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
9000 (org-hh:mm-string-to-minutes x))
9001 (t 0)))
9002 comparefun (if (= dcst sorting-type) '< '>)))
9003 (t (error "Invalid sorting type `%c'" sorting-type)))
9005 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
9006 table)
9007 (lambda (a b) (funcall comparefun (car a) (car b))))))
9010 ;;; The orgstruct minor mode
9012 ;; Define a minor mode which can be used in other modes in order to
9013 ;; integrate the org-mode structure editing commands.
9015 ;; This is really a hack, because the org-mode structure commands use
9016 ;; keys which normally belong to the major mode. Here is how it
9017 ;; works: The minor mode defines all the keys necessary to operate the
9018 ;; structure commands, but wraps the commands into a function which
9019 ;; tests if the cursor is currently at a headline or a plain list
9020 ;; item. If that is the case, the structure command is used,
9021 ;; temporarily setting many Org-mode variables like regular
9022 ;; expressions for filling etc. However, when any of those keys is
9023 ;; used at a different location, function uses `key-binding' to look
9024 ;; up if the key has an associated command in another currently active
9025 ;; keymap (minor modes, major mode, global), and executes that
9026 ;; command. There might be problems if any of the keys is otherwise
9027 ;; used as a prefix key.
9029 (defcustom orgstruct-heading-prefix-regexp ""
9030 "Regexp that matches the custom prefix of Org headlines in
9031 orgstruct(++)-mode."
9032 :group 'org
9033 :version "24.4"
9034 :package-version '(Org . "8.3")
9035 :type 'regexp)
9036 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9038 (defcustom orgstruct-setup-hook nil
9039 "Hook run after orgstruct-mode-map is filled."
9040 :group 'org
9041 :version "24.4"
9042 :package-version '(Org . "8.0")
9043 :type 'hook)
9045 (defvar orgstruct-initialized nil)
9047 (defvar org-local-vars nil
9048 "List of local variables, for use by `orgstruct-mode'.")
9050 ;;;###autoload
9051 (define-minor-mode orgstruct-mode
9052 "Toggle the minor mode `orgstruct-mode'.
9053 This mode is for using Org-mode structure commands in other
9054 modes. The following keys behave as if Org-mode were active, if
9055 the cursor is on a headline, or on a plain list item (both as
9056 defined by Org-mode)."
9057 nil " OrgStruct" (make-sparse-keymap)
9058 (funcall (if orgstruct-mode
9059 'add-to-invisibility-spec
9060 'remove-from-invisibility-spec)
9061 '(outline . t))
9062 (when orgstruct-mode
9063 (org-load-modules-maybe)
9064 (unless orgstruct-initialized
9065 (orgstruct-setup)
9066 (setq orgstruct-initialized t))))
9068 ;;;###autoload
9069 (defun turn-on-orgstruct ()
9070 "Unconditionally turn on `orgstruct-mode'."
9071 (orgstruct-mode 1))
9073 (defvar org-fb-vars nil)
9074 (make-variable-buffer-local 'org-fb-vars)
9075 (defun orgstruct++-mode (&optional arg)
9076 "Toggle `orgstruct-mode', the enhanced version of it.
9077 In addition to setting orgstruct-mode, this also exports all
9078 indentation and autofilling variables from org-mode into the
9079 buffer. It will also recognize item context in multiline items."
9080 (interactive "P")
9081 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9082 (if (< arg 1)
9083 (progn (orgstruct-mode -1)
9084 (mapc (lambda(v)
9085 (org-set-local (car v)
9086 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9087 org-fb-vars))
9088 (orgstruct-mode 1)
9089 (setq org-fb-vars nil)
9090 (unless org-local-vars
9091 (setq org-local-vars (org-get-local-variables)))
9092 (let (var val)
9093 (mapc
9094 (lambda (x)
9095 (when (string-match
9096 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9097 (symbol-name (car x)))
9098 (setq var (car x) val (nth 1 x))
9099 (push (list var `(quote ,(eval var))) org-fb-vars)
9100 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9101 org-local-vars)
9102 (org-set-local 'orgstruct-is-++ t))))
9104 (defvar orgstruct-is-++ nil
9105 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9106 (make-variable-buffer-local 'orgstruct-is-++)
9108 ;;;###autoload
9109 (defun turn-on-orgstruct++ ()
9110 "Unconditionally turn on `orgstruct++-mode'."
9111 (orgstruct++-mode 1))
9113 (defun orgstruct-error ()
9114 "Error when there is no default binding for a structure key."
9115 (interactive)
9116 (funcall (if (fboundp 'user-error)
9117 'user-error
9118 'error)
9119 "This key has no function outside structure elements"))
9121 (defun orgstruct-setup ()
9122 "Setup orgstruct keymap."
9123 (dolist (cell '((org-demote . t)
9124 (org-metaleft . t)
9125 (org-metaright . t)
9126 (org-promote . t)
9127 (org-shiftmetaleft . t)
9128 (org-shiftmetaright . t)
9129 org-backward-element
9130 org-backward-heading-same-level
9131 org-ctrl-c-ret
9132 org-ctrl-c-minus
9133 org-ctrl-c-star
9134 org-cycle
9135 org-forward-heading-same-level
9136 org-insert-heading
9137 org-insert-heading-respect-content
9138 org-kill-note-or-show-branches
9139 org-mark-subtree
9140 org-meta-return
9141 org-metadown
9142 org-metaup
9143 org-narrow-to-subtree
9144 org-promote-subtree
9145 org-reveal
9146 org-shiftdown
9147 org-shiftleft
9148 org-shiftmetadown
9149 org-shiftmetaup
9150 org-shiftright
9151 org-shifttab
9152 org-shifttab
9153 org-shiftup
9154 org-show-subtree
9155 org-sort
9156 org-up-element
9157 outline-demote
9158 outline-next-visible-heading
9159 outline-previous-visible-heading
9160 outline-promote
9161 outline-up-heading
9162 show-children))
9163 (let ((f (or (car-safe cell) cell))
9164 (disable-when-heading-prefix (cdr-safe cell)))
9165 (when (fboundp f)
9166 (let ((new-bindings))
9167 (dolist (binding (nconc (where-is-internal f org-mode-map)
9168 (where-is-internal f outline-mode-map)))
9169 (push binding new-bindings)
9170 ;; TODO use local-function-key-map
9171 (dolist (rep '(("<tab>" . "TAB")
9172 ("<return>" . "RET")
9173 ("<escape>" . "ESC")
9174 ("<delete>" . "DEL")))
9175 (setq binding (read-kbd-macro
9176 (let ((case-fold-search))
9177 (replace-regexp-in-string
9178 (regexp-quote (cdr rep))
9179 (car rep)
9180 (key-description binding)))))
9181 (pushnew binding new-bindings :test 'equal)))
9182 (dolist (binding new-bindings)
9183 (let ((key (lookup-key orgstruct-mode-map binding)))
9184 (when (or (not key) (numberp key))
9185 (ignore-errors
9186 (org-defkey orgstruct-mode-map
9187 binding
9188 (orgstruct-make-binding
9189 f binding disable-when-heading-prefix))))))))))
9190 (run-hooks 'orgstruct-setup-hook))
9192 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9193 "Create a function for binding in the structure minor mode.
9194 FUN is the command to call inside a table. KEY is the key that
9195 should be checked in for a command to execute outside of tables.
9196 Non-nil `disable-when-heading-prefix' means to disable the command
9197 if `orgstruct-heading-prefix-regexp' is not empty."
9198 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9199 (let ((nname name)
9200 (i 0))
9201 (while (fboundp (intern nname))
9202 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9203 (setq name (intern nname)))
9204 (eval
9205 (let ((bindings '((org-heading-regexp
9206 (concat "^"
9207 orgstruct-heading-prefix-regexp
9208 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9209 (org-outline-regexp
9210 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9211 (org-outline-regexp-bol
9212 (concat "^" org-outline-regexp))
9213 (outline-regexp org-outline-regexp)
9214 (outline-heading-end-regexp "\n")
9215 (outline-level 'org-outline-level)
9216 (outline-heading-alist))))
9217 `(defun ,name (arg)
9218 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9219 "Outside of structure, run the binding of `"
9220 (key-description key) "'."
9221 (when disable-when-heading-prefix
9222 (concat
9223 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9224 "back to the default binding due to limitations of Org's implementation of\n"
9225 "`" (symbol-name fun) "'.")))
9226 (interactive "p")
9227 (let* ((disable
9228 ,(and disable-when-heading-prefix
9229 '(not (string= orgstruct-heading-prefix-regexp ""))))
9230 (fallback
9231 (or disable
9232 (not
9233 (let* ,bindings
9234 (org-context-p 'headline 'item
9235 ,(when (memq fun
9236 '(org-insert-heading
9237 org-insert-heading-respect-content
9238 org-meta-return))
9239 '(when orgstruct-is-++
9240 'item-body))))))))
9241 (if fallback
9242 (let* ((orgstruct-mode)
9243 (binding
9244 (let ((key ,key))
9245 (catch 'exit
9246 (dolist
9247 (rep
9248 '(nil
9249 ("<\\([^>]*\\)tab>" . "\\1TAB")
9250 ("<\\([^>]*\\)return>" . "\\1RET")
9251 ("<\\([^>]*\\)escape>" . "\\1ESC")
9252 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9253 nil)
9254 (when rep
9255 (setq key (read-kbd-macro
9256 (let ((case-fold-search))
9257 (replace-regexp-in-string
9258 (car rep)
9259 (cdr rep)
9260 (key-description key))))))
9261 (when (key-binding key)
9262 (throw 'exit (key-binding key))))))))
9263 (if (keymapp binding)
9264 (org-set-transient-map binding)
9265 (let ((func (or binding
9266 (unless disable
9267 'orgstruct-error))))
9268 (when func
9269 (call-interactively func)))))
9270 (org-run-like-in-org-mode
9271 (lambda ()
9272 (interactive)
9273 (let* ,bindings
9274 (call-interactively ',fun)))))))))
9275 name))
9277 (defun org-contextualize-keys (alist contexts)
9278 "Return valid elements in ALIST depending on CONTEXTS.
9280 `org-agenda-custom-commands' or `org-capture-templates' are the
9281 values used for ALIST, and `org-agenda-custom-commands-contexts'
9282 or `org-capture-templates-contexts' are the associated contexts
9283 definitions."
9284 (let ((contexts
9285 ;; normalize contexts
9286 (mapcar
9287 (lambda(c) (cond ((listp (cadr c))
9288 (list (car c) (car c) (cadr c)))
9289 ((string= "" (cadr c))
9290 (list (car c) (car c) (caddr c)))
9291 (t c))) contexts))
9292 (a alist) c r s)
9293 ;; loop over all commands or templates
9294 (while (setq c (pop a))
9295 (let (vrules repl)
9296 (cond
9297 ((not (assoc (car c) contexts))
9298 (push c r))
9299 ((and (assoc (car c) contexts)
9300 (setq vrules (org-contextualize-validate-key
9301 (car c) contexts)))
9302 (mapc (lambda (vr)
9303 (when (not (equal (car vr) (cadr vr)))
9304 (setq repl vr))) vrules)
9305 (if (not repl) (push c r)
9306 (push (cadr repl) s)
9307 (push
9308 (cons (car c)
9309 (cdr (or (assoc (cadr repl) alist)
9310 (error "Undefined key `%s' as contextual replacement for `%s'"
9311 (cadr repl) (car c)))))
9312 r))))))
9313 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9314 (delq
9316 (delete-dups
9317 (mapcar (lambda (x)
9318 (let ((tpl (car x)))
9319 (when (not (delq
9321 (mapcar (lambda(y)
9322 (equal y tpl)) s))) x)))
9323 (reverse r))))))
9325 (defun org-contextualize-validate-key (key contexts)
9326 "Check CONTEXTS for agenda or capture KEY."
9327 (let (r rr res)
9328 (while (setq r (pop contexts))
9329 (mapc
9330 (lambda (rr)
9331 (when
9332 (and (equal key (car r))
9333 (if (functionp rr) (funcall rr)
9334 (or (and (eq (car rr) 'in-file)
9335 (buffer-file-name)
9336 (string-match (cdr rr) (buffer-file-name)))
9337 (and (eq (car rr) 'in-mode)
9338 (string-match (cdr rr) (symbol-name major-mode)))
9339 (and (eq (car rr) 'in-buffer)
9340 (string-match (cdr rr) (buffer-name)))
9341 (when (and (eq (car rr) 'not-in-file)
9342 (buffer-file-name))
9343 (not (string-match (cdr rr) (buffer-file-name))))
9344 (when (eq (car rr) 'not-in-mode)
9345 (not (string-match (cdr rr) (symbol-name major-mode))))
9346 (when (eq (car rr) 'not-in-buffer)
9347 (not (string-match (cdr rr) (buffer-name)))))))
9348 (push r res)))
9349 (car (last r))))
9350 (delete-dups (delq nil res))))
9352 (defun org-context-p (&rest contexts)
9353 "Check if local context is any of CONTEXTS.
9354 Possible values in the list of contexts are `table', `headline', and `item'."
9355 (let ((pos (point)))
9356 (goto-char (point-at-bol))
9357 (prog1 (or (and (memq 'table contexts)
9358 (looking-at "[ \t]*|"))
9359 (and (memq 'headline contexts)
9360 (looking-at org-outline-regexp))
9361 (and (memq 'item contexts)
9362 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9363 (and (memq 'item-body contexts)
9364 (org-in-item-p)))
9365 (goto-char pos))))
9367 (defun org-get-local-variables ()
9368 "Return a list of all local variables in an Org mode buffer."
9369 (let (varlist)
9370 (with-current-buffer (get-buffer-create "*Org tmp*")
9371 (erase-buffer)
9372 (org-mode)
9373 (setq varlist (buffer-local-variables)))
9374 (kill-buffer "*Org tmp*")
9375 (delq nil
9376 (mapcar
9377 (lambda (x)
9378 (setq x
9379 (if (symbolp x)
9380 (list x)
9381 (list (car x) (cdr x))))
9382 (if (and (not (get (car x) 'org-state))
9383 (string-match
9384 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9385 (symbol-name (car x))))
9386 x nil))
9387 varlist))))
9389 (defun org-clone-local-variables (from-buffer &optional regexp)
9390 "Clone local variables from FROM-BUFFER.
9391 Optional argument REGEXP selects variables to clone."
9392 (mapc
9393 (lambda (pair)
9394 (and (symbolp (car pair))
9395 (or (null regexp)
9396 (string-match regexp (symbol-name (car pair))))
9397 (set (make-local-variable (car pair))
9398 (cdr pair))))
9399 (buffer-local-variables from-buffer)))
9401 ;;;###autoload
9402 (defun org-run-like-in-org-mode (cmd)
9403 "Run a command, pretending that the current buffer is in Org-mode.
9404 This will temporarily bind local variables that are typically bound in
9405 Org-mode to the values they have in Org-mode, and then interactively
9406 call CMD."
9407 (org-load-modules-maybe)
9408 (unless org-local-vars
9409 (setq org-local-vars (org-get-local-variables)))
9410 (let (binds)
9411 (dolist (var org-local-vars)
9412 (when (or (not (boundp (car var)))
9413 (eq (symbol-value (car var))
9414 (default-value (car var))))
9415 (push (list (car var) `(quote ,(cadr var))) binds)))
9416 (eval `(let ,binds
9417 (call-interactively (quote ,cmd))))))
9419 (defun org-get-category (&optional pos force-refresh)
9420 "Get the category applying to position POS."
9421 (save-match-data
9422 (if force-refresh (org-refresh-category-properties))
9423 (let ((pos (or pos (point))))
9424 (or (get-text-property pos 'org-category)
9425 (progn (org-refresh-category-properties)
9426 (get-text-property pos 'org-category))))))
9428 ;;; Refresh properties
9430 (defun org-refresh-properties (dprop tprop)
9431 "Refresh buffer text properties.
9432 DPROP is the drawer property and TPROP is either the
9433 corresponding text property to set, or an alist with each element
9434 being a text property (as a symbol) and a function to apply to
9435 the value of the drawer property."
9436 (let ((case-fold-search t)
9437 (inhibit-read-only t))
9438 (org-with-silent-modifications
9439 (save-excursion
9440 (save-restriction
9441 (widen)
9442 (goto-char (point-min))
9443 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9444 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9446 (defun org-refresh-property (tprop p)
9447 "Refresh the buffer text property TPROP from the drawer property P.
9448 The refresh happens only for the current tree (not subtree)."
9449 (save-excursion
9450 (org-back-to-heading t)
9451 ;; tprop is a text property symbol
9452 (if (symbolp tprop)
9453 (put-text-property
9454 (point) (or (outline-next-heading) (point-max)) tprop p)
9455 ;; tprop is an alist with (properties . function) elements
9456 (mapc (lambda(al)
9457 (save-excursion
9458 (put-text-property
9459 (point-at-bol) (or (outline-next-heading) (point-max))
9460 (car al)
9461 (funcall (cdr al) p))))
9462 tprop))))
9464 (defun org-refresh-category-properties ()
9465 "Refresh category text properties in the buffer."
9466 (let ((case-fold-search t)
9467 (inhibit-read-only t)
9468 (def-cat (cond
9469 ((null org-category)
9470 (if buffer-file-name
9471 (file-name-sans-extension
9472 (file-name-nondirectory buffer-file-name))
9473 "???"))
9474 ((symbolp org-category) (symbol-name org-category))
9475 (t org-category)))
9476 beg end cat pos optionp)
9477 (org-with-silent-modifications
9478 (save-excursion
9479 (save-restriction
9480 (widen)
9481 (goto-char (point-min))
9482 (put-text-property (point) (point-max) 'org-category def-cat)
9483 (while (re-search-forward
9484 "^[ \t]*\\(\\(?:#\\+\\|:\\)CATEGORY:\\)\\(.*\\)" nil t)
9485 (setq pos (match-end 0)
9486 optionp (equal (char-after (match-beginning 0)) ?#)
9487 cat (org-trim (match-string 2)))
9488 (if optionp
9489 (setq beg (point-at-bol) end (point-max))
9490 (org-back-to-heading t)
9491 (setq beg (point) end (org-end-of-subtree t t)))
9492 (put-text-property beg end 'org-category cat)
9493 (goto-char pos)))))))
9495 (defun org-refresh-stats-properties ()
9496 "Refresh stats text properties in the buffer."
9497 (let (stats)
9498 (org-with-silent-modifications
9499 (save-excursion
9500 (save-restriction
9501 (widen)
9502 (goto-char (point-min))
9503 (while (re-search-forward
9504 (concat org-outline-regexp-bol ".*"
9505 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9506 nil t)
9507 (setq stats (cond ((equal (match-string 3) "0") 0)
9508 ((match-string 2)
9509 (/ (* (string-to-number (match-string 2)) 100)
9510 (string-to-number (match-string 3))))
9511 (t (string-to-number (match-string 1)))))
9512 (org-back-to-heading t)
9513 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9514 'org-stats stats)))))))
9516 (defun org-refresh-effort-properties ()
9517 "Refresh effort properties"
9518 (org-refresh-properties
9519 org-effort-property
9520 '((effort . identity)
9521 (effort-minutes . org-duration-string-to-minutes))))
9523 ;;;; Link Stuff
9525 ;;; Link abbreviations
9527 (defun org-link-expand-abbrev (link)
9528 "Apply replacements as defined in `org-link-abbrev-alist'."
9529 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9530 (let* ((key (match-string 1 link))
9531 (as (or (assoc key org-link-abbrev-alist-local)
9532 (assoc key org-link-abbrev-alist)))
9533 (tag (and (match-end 2) (match-string 3 link)))
9534 rpl)
9535 (if (not as)
9536 link
9537 (setq rpl (cdr as))
9538 (cond
9539 ((symbolp rpl) (funcall rpl tag))
9540 ((string-match "%(\\([^)]+\\))" rpl)
9541 (replace-match
9542 (save-match-data
9543 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9544 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9545 ((string-match "%h" rpl)
9546 (replace-match (url-hexify-string (or tag "")) t t rpl))
9547 (t (concat rpl tag)))))
9548 link))
9550 ;;; Storing and inserting links
9552 (defvar org-insert-link-history nil
9553 "Minibuffer history for links inserted with `org-insert-link'.")
9555 (defvar org-stored-links nil
9556 "Contains the links stored with `org-store-link'.")
9558 (defvar org-store-link-plist nil
9559 "Plist with info about the most recently link created with `org-store-link'.")
9561 (defvar org-link-protocols nil
9562 "Link protocols added to Org-mode using `org-add-link-type'.")
9564 (defvar org-store-link-functions nil
9565 "List of functions that are called to create and store a link.
9566 Each function will be called in turn until one returns a non-nil
9567 value. Each function should check if it is responsible for creating
9568 this link (for example by looking at the major mode).
9569 If not, it must exit and return nil.
9570 If yes, it should return a non-nil value after a calling
9571 `org-store-link-props' with a list of properties and values.
9572 Special properties are:
9574 :type The link prefix, like \"http\". This must be given.
9575 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9576 This is obligatory as well.
9577 :description Optional default description for the second pair
9578 of brackets in an Org-mode link. The user can still change
9579 this when inserting this link into an Org-mode buffer.
9581 In addition to these, any additional properties can be specified
9582 and then used in capture templates.")
9584 (defun org-add-link-type (type &optional follow export)
9585 "Add TYPE to the list of `org-link-types'.
9586 Re-compute all regular expressions depending on `org-link-types'
9588 FOLLOW and EXPORT are two functions.
9590 FOLLOW should take the link path as the single argument and do whatever
9591 is necessary to follow the link, for example find a file or display
9592 a mail message.
9594 EXPORT should format the link path for export to one of the export formats.
9595 It should be a function accepting three arguments:
9597 path the path of the link, the text after the prefix (like \"http:\")
9598 desc the description of the link, if any, or a description added by
9599 org-export-normalize-links if there is none
9600 format the export format, a symbol like `html' or `latex' or `ascii'..
9602 The function may use the FORMAT information to return different values
9603 depending on the format. The return value will be put literally into
9604 the exported file. If the return value is nil, this means Org should
9605 do what it normally does with links which do not have EXPORT defined.
9607 Org-mode has a built-in default for exporting links. If you are happy with
9608 this default, there is no need to define an export function for the link
9609 type. For a simple example of an export function, see `org-bbdb.el'."
9610 (add-to-list 'org-link-types type t)
9611 (org-make-link-regexps)
9612 (if (assoc type org-link-protocols)
9613 (setcdr (assoc type org-link-protocols) (list follow export))
9614 (push (list type follow export) org-link-protocols)))
9616 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9617 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9619 ;;;###autoload
9620 (defun org-store-link (arg)
9621 "\\<org-mode-map>Store an org-link to the current location.
9622 This link is added to `org-stored-links' and can later be inserted
9623 into an org-buffer with \\[org-insert-link].
9625 For some link types, a prefix arg is interpreted.
9626 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9627 For file links, arg negates `org-context-in-file-links'.
9629 A double prefix arg force skipping storing functions that are not
9630 part of Org's core.
9632 A triple prefix arg force storing a link for each line in the
9633 active region."
9634 (interactive "P")
9635 (org-load-modules-maybe)
9636 (if (and (equal arg '(64)) (org-region-active-p))
9637 (save-excursion
9638 (let ((end (region-end)))
9639 (goto-char (region-beginning))
9640 (set-mark (point))
9641 (while (< (point-at-eol) end)
9642 (move-end-of-line 1) (activate-mark)
9643 (let (current-prefix-arg)
9644 (call-interactively 'org-store-link))
9645 (move-beginning-of-line 2)
9646 (set-mark (point)))))
9647 (org-with-limited-levels
9648 (setq org-store-link-plist nil)
9649 (let (link cpltxt desc description search
9650 txt custom-id agenda-link sfuns sfunsn)
9651 (cond
9653 ;; Store a link using an external link type
9654 ((and (not (equal arg '(16)))
9655 (setq sfuns
9656 (delq
9657 nil (mapcar (lambda (f)
9658 (let (fs) (if (funcall f) (push f fs))))
9659 org-store-link-functions))
9660 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9661 (or (and (cdr sfuns)
9662 (funcall (intern
9663 (completing-read
9664 "Which function for creating the link? "
9665 sfunsn nil t (car sfunsn)))))
9666 (funcall (caar sfuns)))
9667 (setq link (plist-get org-store-link-plist :link)
9668 desc (or (plist-get org-store-link-plist
9669 :description) link))))
9671 ;; Store a link from a source code buffer
9672 ((org-src-edit-buffer-p)
9673 (let (label gc)
9674 (while (or (not label)
9675 (save-excursion
9676 (save-restriction
9677 (widen)
9678 (goto-char (point-min))
9679 (re-search-forward
9680 (regexp-quote (format org-coderef-label-format label))
9681 nil t))))
9682 (when label (message "Label exists already") (sit-for 2))
9683 (setq label (read-string "Code line label: " label)))
9684 (end-of-line 1)
9685 (setq link (format org-coderef-label-format label))
9686 (setq gc (- 79 (length link)))
9687 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9688 (insert link)
9689 (setq link (concat "(" label ")") desc nil)))
9691 ;; We are in the agenda, link to referenced location
9692 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9693 (let ((m (or (get-text-property (point) 'org-hd-marker)
9694 (get-text-property (point) 'org-marker))))
9695 (when m
9696 (org-with-point-at m
9697 (setq agenda-link
9698 (if (org-called-interactively-p 'any)
9699 (call-interactively 'org-store-link)
9700 (org-store-link nil)))))))
9702 ((eq major-mode 'calendar-mode)
9703 (let ((cd (calendar-cursor-to-date)))
9704 (setq link
9705 (format-time-string
9706 (car org-time-stamp-formats)
9707 (apply 'encode-time
9708 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9709 nil nil nil))))
9710 (org-store-link-props :type "calendar" :date cd)))
9712 ((eq major-mode 'help-mode)
9713 (setq link (concat "help:" (save-excursion
9714 (goto-char (point-min))
9715 (looking-at "^[^ ]+")
9716 (match-string 0))))
9717 (org-store-link-props :type "help"))
9719 ((eq major-mode 'w3-mode)
9720 (setq cpltxt (if (and (buffer-name)
9721 (not (string-match "Untitled" (buffer-name))))
9722 (buffer-name)
9723 (url-view-url t))
9724 link (url-view-url t))
9725 (org-store-link-props :type "w3" :url (url-view-url t)))
9727 ((eq major-mode 'image-mode)
9728 (setq cpltxt (concat "file:"
9729 (abbreviate-file-name buffer-file-name))
9730 link cpltxt)
9731 (org-store-link-props :type "image" :file buffer-file-name))
9733 ;; In dired, store a link to the file of the current line
9734 ((derived-mode-p 'dired-mode)
9735 (let ((file (dired-get-filename nil t)))
9736 (setq file (if file
9737 (abbreviate-file-name
9738 (expand-file-name (dired-get-filename nil t)))
9739 ;; otherwise, no file so use current directory.
9740 default-directory))
9741 (setq cpltxt (concat "file:" file)
9742 link cpltxt)))
9744 ((setq search (run-hook-with-args-until-success
9745 'org-create-file-search-functions))
9746 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9747 "::" search))
9748 (setq cpltxt (or description link)))
9750 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9751 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9752 (cond
9753 ;; Store a link using the target at point
9754 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9755 (setq cpltxt
9756 (concat "file:"
9757 (abbreviate-file-name
9758 (buffer-file-name (buffer-base-buffer)))
9759 "::" (match-string 1))
9760 link cpltxt))
9761 ((and (featurep 'org-id)
9762 (or (eq org-id-link-to-org-use-id t)
9763 (and (org-called-interactively-p 'any)
9764 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9765 (and (eq org-id-link-to-org-use-id
9766 'create-if-interactive-and-no-custom-id)
9767 (not custom-id))))
9768 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9769 ;; Store a link using the ID at point
9770 (setq link (condition-case nil
9771 (prog1 (org-id-store-link)
9772 (setq desc (or (plist-get org-store-link-plist
9773 :description)
9774 "")))
9775 (error
9776 ;; Probably before first headline, link only to file
9777 (concat "file:"
9778 (abbreviate-file-name
9779 (buffer-file-name (buffer-base-buffer))))))))
9781 ;; Just link to current headline
9782 (setq cpltxt (concat "file:"
9783 (abbreviate-file-name
9784 (buffer-file-name (buffer-base-buffer)))))
9785 ;; Add a context search string
9786 (when (org-xor org-context-in-file-links arg)
9787 (let* ((ee (org-element-at-point))
9788 (et (org-element-type ee))
9789 (ev (plist-get (cadr ee) :value))
9790 (ek (plist-get (cadr ee) :key))
9791 (eok (and (stringp ek) (string-match "name" ek))))
9792 (setq txt (cond
9793 ((org-at-heading-p) nil)
9794 ((and (eq et 'keyword) eok) ev)
9795 ((org-region-active-p)
9796 (buffer-substring (region-beginning) (region-end)))))
9797 (when (or (null txt) (string-match "\\S-" txt))
9798 (setq cpltxt
9799 (concat cpltxt "::"
9800 (condition-case nil
9801 (org-make-org-heading-search-string txt)
9802 (error "")))
9803 desc (or (and (eq et 'keyword) eok ev)
9804 (nth 4 (ignore-errors (org-heading-components)))
9805 "NONE")))))
9806 (if (string-match "::\\'" cpltxt)
9807 (setq cpltxt (substring cpltxt 0 -2)))
9808 (setq link cpltxt))))
9810 ((buffer-file-name (buffer-base-buffer))
9811 ;; Just link to this file here.
9812 (setq cpltxt (concat "file:"
9813 (abbreviate-file-name
9814 (buffer-file-name (buffer-base-buffer)))))
9815 ;; Add a context string.
9816 (when (org-xor org-context-in-file-links arg)
9817 (setq txt (if (org-region-active-p)
9818 (buffer-substring (region-beginning) (region-end))
9819 (buffer-substring (point-at-bol) (point-at-eol))))
9820 ;; Only use search option if there is some text.
9821 (when (string-match "\\S-" txt)
9822 (setq cpltxt
9823 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9824 desc "NONE")))
9825 (setq link cpltxt))
9827 ((org-called-interactively-p 'interactive)
9828 (user-error "No method for storing a link from this buffer"))
9830 (t (setq link nil)))
9832 ;; We're done setting link and desc, clean up
9833 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9834 (setq link (or link cpltxt)
9835 desc (or desc cpltxt))
9836 (cond ((equal desc "NONE") (setq desc nil))
9837 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9838 (let ((d0 (match-string 3 desc))
9839 (p0 (match-string 5 desc)))
9840 (setq desc
9841 (replace-regexp-in-string
9842 org-bracket-link-regexp
9843 (concat (or p0 d0)
9844 (if (equal (length (match-string 0 desc))
9845 (length desc)) "*" "")) desc)))))
9847 ;; Return the link
9848 (if (not (and (or (org-called-interactively-p 'any)
9849 executing-kbd-macro) link))
9850 (or agenda-link (and link (org-make-link-string link desc)))
9851 (push (list link desc) org-stored-links)
9852 (message "Stored: %s" (or desc link))
9853 (when custom-id
9854 (setq link (concat "file:" (abbreviate-file-name
9855 (buffer-file-name)) "::#" custom-id))
9856 (push (list link desc) org-stored-links))
9857 (car org-stored-links))))))
9859 (defun org-store-link-props (&rest plist)
9860 "Store link properties, extract names and addresses."
9861 (let (x adr)
9862 (when (setq x (plist-get plist :from))
9863 (setq adr (mail-extract-address-components x))
9864 (setq plist (plist-put plist :fromname (car adr)))
9865 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9866 (when (setq x (plist-get plist :to))
9867 (setq adr (mail-extract-address-components x))
9868 (setq plist (plist-put plist :toname (car adr)))
9869 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9870 (let ((from (plist-get plist :from))
9871 (to (plist-get plist :to)))
9872 (when (and from to org-from-is-user-regexp)
9873 (setq plist
9874 (plist-put plist :fromto
9875 (if (string-match org-from-is-user-regexp from)
9876 (concat "to %t")
9877 (concat "from %f"))))))
9878 (setq org-store-link-plist plist))
9880 (defun org-add-link-props (&rest plist)
9881 "Add these properties to the link property list."
9882 (let (key value)
9883 (while plist
9884 (setq key (pop plist) value (pop plist))
9885 (setq org-store-link-plist
9886 (plist-put org-store-link-plist key value)))))
9888 (defun org-email-link-description (&optional fmt)
9889 "Return the description part of an email link.
9890 This takes information from `org-store-link-plist' and formats it
9891 according to FMT (default from `org-email-link-description-format')."
9892 (setq fmt (or fmt org-email-link-description-format))
9893 (let* ((p org-store-link-plist)
9894 (to (plist-get p :toaddress))
9895 (from (plist-get p :fromaddress))
9896 (table
9897 (list
9898 (cons "%c" (plist-get p :fromto))
9899 (cons "%F" (plist-get p :from))
9900 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9901 (cons "%T" (plist-get p :to))
9902 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9903 (cons "%s" (plist-get p :subject))
9904 (cons "%d" (plist-get p :date))
9905 (cons "%m" (plist-get p :message-id)))))
9906 (when (string-match "%c" fmt)
9907 ;; Check if the user wrote this message
9908 (if (and org-from-is-user-regexp from to
9909 (save-match-data (string-match org-from-is-user-regexp from)))
9910 (setq fmt (replace-match "to %t" t t fmt))
9911 (setq fmt (replace-match "from %f" t t fmt))))
9912 (org-replace-escapes fmt table)))
9914 (defun org-make-org-heading-search-string (&optional string)
9915 "Make search string for the current headline or STRING."
9916 (let ((s (or string
9917 (and (derived-mode-p 'org-mode)
9918 (save-excursion
9919 (org-back-to-heading t)
9920 (org-element-property :raw-value (org-element-at-point))))))
9921 (lines org-context-in-file-links))
9922 (or string (setq s (concat "*" s))) ; Add * for headlines
9923 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9924 (when (and string (integerp lines) (> lines 0))
9925 (let ((slines (org-split-string s "\n")))
9926 (when (< lines (length slines))
9927 (setq s (mapconcat
9928 'identity
9929 (reverse (nthcdr (- (length slines) lines)
9930 (reverse slines))) "\n")))))
9931 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9933 (defun org-make-link-string (link &optional description)
9934 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9935 (unless (string-match "\\S-" link)
9936 (error "Empty link"))
9937 (when (and description
9938 (stringp description)
9939 (not (string-match "\\S-" description)))
9940 (setq description nil))
9941 (when (stringp description)
9942 ;; Remove brackets from the description, they are fatal.
9943 (while (string-match "\\[" description)
9944 (setq description (replace-match "{" t t description)))
9945 (while (string-match "\\]" description)
9946 (setq description (replace-match "}" t t description))))
9947 (when (equal link description)
9948 ;; No description needed, it is identical
9949 (setq description nil))
9950 (when (and (not description)
9951 (not (string-match (org-image-file-name-regexp) link))
9952 (not (equal link (org-link-escape link))))
9953 (setq description (org-extract-attributes link)))
9954 (setq link
9955 (cond ((string-match (org-image-file-name-regexp) link) link)
9956 ((string-match org-link-types-re link)
9957 (concat (match-string 1 link)
9958 (org-link-escape (substring link (match-end 1)))))
9959 (t (org-link-escape link))))
9960 (concat "[[" link "]"
9961 (if description (concat "[" description "]") "")
9962 "]"))
9964 (defconst org-link-escape-chars
9965 ;;%20 %5B %5D
9966 '(?\ ?\[ ?\])
9967 "List of characters that should be escaped in a link when stored to Org.
9968 This is the list that is used for internal purposes.")
9970 (defconst org-link-escape-chars-browser
9971 ;;%20 %22
9972 '(?\ ?\")
9973 "List of characters to be escaped before handing over to the browser.
9974 If you consider using this constant then you probably want to use
9975 the function `org-link-escape-browser' instead. See there why
9976 this constant is a candidate to be removed once Org drops support
9977 for Emacs 24.1 and 24.2.")
9979 (defun org-link-escape (text &optional table merge)
9980 "Return percent escaped representation of TEXT.
9981 TEXT is a string with the text to escape.
9982 Optional argument TABLE is a list with characters that should be
9983 escaped. When nil, `org-link-escape-chars' is used.
9984 If optional argument MERGE is set, merge TABLE into
9985 `org-link-escape-chars'."
9986 ;; Don't escape chars in internal links
9987 (if (string-match "^\\*[[:alnum:]]+" text)
9988 text
9989 (cond
9990 ((and table merge)
9991 (mapc (lambda (defchr)
9992 (unless (member defchr table)
9993 (setq table (cons defchr table))))
9994 org-link-escape-chars))
9995 ((null table)
9996 (setq table org-link-escape-chars)))
9997 (mapconcat
9998 (lambda (char)
9999 (if (or (member char table)
10000 (and (or (< char 32) (= char ?\%) (> char 126))
10001 org-url-hexify-p))
10002 (mapconcat (lambda (sequence-element)
10003 (format "%%%.2X" sequence-element))
10004 (or (encode-coding-char char 'utf-8)
10005 (error "Unable to percent escape character: %s"
10006 (char-to-string char))) "")
10007 (char-to-string char))) text "")))
10009 (defun org-link-escape-browser (text)
10010 "Escape some characters before handing over to the browser.
10011 This function is a candidate to be removed together with the
10012 constant `org-link-escape-chars-browser' once Org drops support
10013 for Emacs 24.1 and 24.2. All calls to this function will have to
10014 be replaced with `url-encode-url' which is available since Emacs
10015 24.3.1."
10016 ;; Example with the Org link
10017 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10018 ;; to open the browser with +subject:"Release 8.2" filled into the
10019 ;; query field: In this case the variable TEXT contains the
10020 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10021 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10022 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10023 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10024 (if (fboundp 'url-encode-url)
10025 (url-encode-url text)
10026 (if (org-string-match-p
10027 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10028 text)
10029 (org-link-escape text org-link-escape-chars-browser)
10030 text)))
10032 (defun org-link-unescape (str)
10033 "Unhex hexified Unicode strings as returned from the JavaScript function
10034 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10035 (unless (and (null str) (string= "" str))
10036 (let ((pos 0) (case-fold-search t) unhexed)
10037 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10038 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10039 (setq str (replace-match unhexed t t str))
10040 (setq pos (+ pos (length unhexed))))))
10041 str)
10043 (defun org-link-unescape-compound (hex)
10044 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10045 Note: this function also decodes single byte encodings like
10046 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10047 (save-match-data
10048 (let* ((bytes (cdr (split-string hex "%")))
10049 (ret "")
10050 (eat 0)
10051 (sum 0))
10052 (while bytes
10053 (let* ((val (string-to-number (pop bytes) 16))
10054 (shift-xor
10055 (if (= 0 eat)
10056 (cond
10057 ((>= val 252) (cons 6 252))
10058 ((>= val 248) (cons 5 248))
10059 ((>= val 240) (cons 4 240))
10060 ((>= val 224) (cons 3 224))
10061 ((>= val 192) (cons 2 192))
10062 (t (cons 0 0)))
10063 (cons 6 128))))
10064 (if (>= val 192) (setq eat (car shift-xor)))
10065 (setq val (logxor val (cdr shift-xor)))
10066 (setq sum (+ (lsh sum (car shift-xor)) val))
10067 (if (> eat 0) (setq eat (- eat 1)))
10068 (cond
10069 ((= 0 eat) ;multi byte
10070 (setq ret (concat ret (org-char-to-string sum)))
10071 (setq sum 0))
10072 ((not bytes) ; single byte(s)
10073 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10074 ret)))
10076 (defun org-link-unescape-single-byte-sequence (hex)
10077 "Unhexify hex-encoded single byte character sequences."
10078 (mapconcat (lambda (byte)
10079 (char-to-string (string-to-number byte 16)))
10080 (cdr (split-string hex "%")) ""))
10082 (defun org-xor (a b)
10083 "Exclusive or."
10084 (if a (not b) b))
10086 (defun org-fixup-message-id-for-http (s)
10087 "Replace special characters in a message id, so it can be used in an http query."
10088 (when (string-match "%" s)
10089 (setq s (mapconcat (lambda (c)
10090 (if (eq c ?%)
10091 "%25"
10092 (char-to-string c)))
10093 s "")))
10094 (while (string-match "<" s)
10095 (setq s (replace-match "%3C" t t s)))
10096 (while (string-match ">" s)
10097 (setq s (replace-match "%3E" t t s)))
10098 (while (string-match "@" s)
10099 (setq s (replace-match "%40" t t s)))
10102 (defun org-link-prettify (link)
10103 "Return a human-readable representation of LINK.
10104 The car of LINK must be a raw link.
10105 The cdr of LINK must be either a link description or nil."
10106 (let ((desc (or (cadr link) "<no description>")))
10107 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10108 "<" (car link) ">")))
10110 ;;;###autoload
10111 (defun org-insert-link-global ()
10112 "Insert a link like Org-mode does.
10113 This command can be called in any mode to insert a link in Org-mode syntax."
10114 (interactive)
10115 (org-load-modules-maybe)
10116 (org-run-like-in-org-mode 'org-insert-link))
10118 (defun org-insert-all-links (arg &optional pre post)
10119 "Insert all links in `org-stored-links'.
10120 When a universal prefix, do not delete the links from `org-stored-links'.
10121 When `ARG' is a number, insert the last N link(s).
10122 `PRE' and `POST' are optional arguments to define a string to
10123 prepend or to append."
10124 (interactive "P")
10125 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10126 (links (copy-seq org-stored-links))
10127 (pr (or pre "- "))
10128 (po (or post "\n"))
10129 (cnt 1) l)
10130 (if (null org-stored-links)
10131 (message "No link to insert")
10132 (while (and (or (listp arg) (>= arg cnt))
10133 (setq l (if (listp arg)
10134 (pop links)
10135 (pop org-stored-links))))
10136 (setq cnt (1+ cnt))
10137 (insert pr)
10138 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10139 (insert po)))))
10141 (defun org-insert-last-stored-link (arg)
10142 "Insert the last link stored in `org-stored-links'."
10143 (interactive "p")
10144 (org-insert-all-links arg "" "\n"))
10146 (defun org-link-fontify-links-to-this-file ()
10147 "Fontify links to the current file in `org-stored-links'."
10148 (let ((f (buffer-file-name)) a b)
10149 (setq a (mapcar (lambda(l)
10150 (let ((ll (car l)))
10151 (when (and (string-match "^file:\\(.+\\)::" ll)
10152 (equal f (expand-file-name (match-string 1 ll))))
10153 ll)))
10154 org-stored-links))
10155 (when (featurep 'org-id)
10156 (setq b (mapcar (lambda(l)
10157 (let ((ll (car l)))
10158 (when (and (string-match "^id:\\(.+\\)$" ll)
10159 (equal f (expand-file-name
10160 (or (org-id-find-id-file
10161 (match-string 1 ll)) ""))))
10162 ll)))
10163 org-stored-links)))
10164 (mapcar (lambda(l)
10165 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10166 (delq nil (append a b)))))
10168 (defvar org-link-links-in-this-file nil)
10169 (defun org-insert-link (&optional complete-file link-location default-description)
10170 "Insert a link. At the prompt, enter the link.
10172 Completion can be used to insert any of the link protocol prefixes like
10173 http or ftp in use.
10175 The history can be used to select a link previously stored with
10176 `org-store-link'. When the empty string is entered (i.e. if you just
10177 press RET at the prompt), the link defaults to the most recently
10178 stored link. As SPC triggers completion in the minibuffer, you need to
10179 use M-SPC or C-q SPC to force the insertion of a space character.
10181 You will also be prompted for a description, and if one is given, it will
10182 be displayed in the buffer instead of the link.
10184 If there is already a link at point, this command will allow you to edit link
10185 and description parts.
10187 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10188 be selected using completion. The path to the file will be relative to the
10189 current directory if the file is in the current directory or a subdirectory.
10190 Otherwise, the link will be the absolute path as completed in the minibuffer
10191 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10192 option `org-link-file-path-type'.
10194 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10195 the current directory or below.
10197 With three \\[universal-argument] prefixes, negate the meaning of
10198 `org-keep-stored-link-after-insertion'.
10200 If `org-make-link-description-function' is non-nil, this function will be
10201 called with the link target, and the result will be the default
10202 link description.
10204 If the LINK-LOCATION parameter is non-nil, this value will be
10205 used as the link location instead of reading one interactively.
10207 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10208 be used as the default description."
10209 (interactive "P")
10210 (let* ((wcf (current-window-configuration))
10211 (origbuf (current-buffer))
10212 (region (if (org-region-active-p)
10213 (buffer-substring (region-beginning) (region-end))))
10214 (remove (and region (list (region-beginning) (region-end))))
10215 (desc region)
10216 tmphist ; byte-compile incorrectly complains about this
10217 (link link-location)
10218 (abbrevs org-link-abbrev-alist-local)
10219 entry file all-prefixes auto-desc)
10220 (cond
10221 (link-location) ; specified by arg, just use it.
10222 ((org-in-regexp org-bracket-link-regexp 1)
10223 ;; We do have a link at point, and we are going to edit it.
10224 (setq remove (list (match-beginning 0) (match-end 0)))
10225 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10226 (setq link (read-string "Link: "
10227 (org-link-unescape
10228 (org-match-string-no-properties 1)))))
10229 ((or (org-in-regexp org-angle-link-re)
10230 (org-in-regexp org-plain-link-re))
10231 ;; Convert to bracket link
10232 (setq remove (list (match-beginning 0) (match-end 0))
10233 link (read-string "Link: "
10234 (org-remove-angle-brackets (match-string 0)))))
10235 ((member complete-file '((4) (16)))
10236 ;; Completing read for file names.
10237 (setq link (org-file-complete-link complete-file)))
10239 ;; Read link, with completion for stored links.
10240 (org-link-fontify-links-to-this-file)
10241 (org-switch-to-buffer-other-window "*Org Links*")
10242 (with-current-buffer "*Org Links*"
10243 (erase-buffer)
10244 (insert "Insert a link.
10245 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10246 (when org-stored-links
10247 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10248 (insert (mapconcat 'org-link-prettify
10249 (reverse org-stored-links) "\n")))
10250 (goto-char (point-min)))
10251 (let ((cw (selected-window)))
10252 (select-window (get-buffer-window "*Org Links*" 'visible))
10253 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10254 (unless (pos-visible-in-window-p (point-max))
10255 (org-fit-window-to-buffer))
10256 (and (window-live-p cw) (select-window cw)))
10257 ;; Fake a link history, containing the stored links.
10258 (setq tmphist (append (mapcar 'car org-stored-links)
10259 org-insert-link-history))
10260 (setq all-prefixes (append (mapcar 'car abbrevs)
10261 (mapcar 'car org-link-abbrev-alist)
10262 org-link-types))
10263 (unwind-protect
10264 (progn
10265 (setq link
10266 (org-completing-read
10267 "Link: "
10268 (append
10269 (mapcar (lambda (x) (concat x ":"))
10270 all-prefixes)
10271 (mapcar 'car org-stored-links))
10272 nil nil nil
10273 'tmphist
10274 (caar org-stored-links)))
10275 (if (not (string-match "\\S-" link))
10276 (user-error "No link selected"))
10277 (mapc (lambda(l)
10278 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10279 org-stored-links)
10280 (if (or (member link all-prefixes)
10281 (and (equal ":" (substring link -1))
10282 (member (substring link 0 -1) all-prefixes)
10283 (setq link (substring link 0 -1))))
10284 (setq link (with-current-buffer origbuf
10285 (org-link-try-special-completion link)))))
10286 (set-window-configuration wcf)
10287 (kill-buffer "*Org Links*"))
10288 (setq entry (assoc link org-stored-links))
10289 (or entry (push link org-insert-link-history))
10290 (setq desc (or desc (nth 1 entry)))))
10292 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10293 (not org-keep-stored-link-after-insertion))
10294 (setq org-stored-links (delq (assoc link org-stored-links)
10295 org-stored-links)))
10297 (if (and (string-match org-plain-link-re link)
10298 (not (string-match org-ts-regexp link)))
10299 ;; URL-like link, normalize the use of angular brackets.
10300 (setq link (org-remove-angle-brackets link)))
10302 ;; Check if we are linking to the current file with a search
10303 ;; option If yes, simplify the link by using only the search
10304 ;; option.
10305 (when (and buffer-file-name
10306 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10307 (let* ((path (match-string 1 link))
10308 (case-fold-search nil)
10309 (search (match-string 2 link)))
10310 (save-match-data
10311 (if (equal (file-truename buffer-file-name) (file-truename path))
10312 ;; We are linking to this same file, with a search option
10313 (setq link search)))))
10315 ;; Check if we can/should use a relative path. If yes, simplify the link
10316 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10317 (let* ((type (match-string 1 link))
10318 (path (match-string 2 link))
10319 (origpath path)
10320 (case-fold-search nil))
10321 (cond
10322 ((or (eq org-link-file-path-type 'absolute)
10323 (equal complete-file '(16)))
10324 (setq path (abbreviate-file-name (expand-file-name path))))
10325 ((eq org-link-file-path-type 'noabbrev)
10326 (setq path (expand-file-name path)))
10327 ((eq org-link-file-path-type 'relative)
10328 (setq path (file-relative-name path)))
10330 (save-match-data
10331 (if (string-match (concat "^" (regexp-quote
10332 (expand-file-name
10333 (file-name-as-directory
10334 default-directory))))
10335 (expand-file-name path))
10336 ;; We are linking a file with relative path name.
10337 (setq path (substring (expand-file-name path)
10338 (match-end 0)))
10339 (setq path (abbreviate-file-name (expand-file-name path)))))))
10340 (setq link (concat type path))
10341 (if (equal desc origpath)
10342 (setq desc path))))
10344 (if org-make-link-description-function
10345 (setq desc
10346 (or (condition-case nil
10347 (funcall org-make-link-description-function link desc)
10348 (error (progn (message "Can't get link description from `%s'"
10349 (symbol-name org-make-link-description-function))
10350 (sit-for 2) nil)))
10351 (read-string "Description: " default-description)))
10352 (if default-description (setq desc default-description)
10353 (setq desc (or (and auto-desc desc)
10354 (read-string "Description: " desc)))))
10356 (unless (string-match "\\S-" desc) (setq desc nil))
10357 (if remove (apply 'delete-region remove))
10358 (insert (org-make-link-string link desc))))
10360 (defun org-link-try-special-completion (type)
10361 "If there is completion support for link type TYPE, offer it."
10362 (let ((fun (intern (concat "org-" type "-complete-link"))))
10363 (if (functionp fun)
10364 (funcall fun)
10365 (read-string "Link (no completion support): " (concat type ":")))))
10367 (defun org-file-complete-link (&optional arg)
10368 "Create a file link using completion."
10369 (let (file link)
10370 (setq file (org-iread-file-name "File: "))
10371 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10372 (pwd1 (file-name-as-directory (abbreviate-file-name
10373 (expand-file-name ".")))))
10374 (cond
10375 ((equal arg '(16))
10376 (setq link (concat
10377 "file:"
10378 (abbreviate-file-name (expand-file-name file)))))
10379 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10380 (setq link (concat "file:" (match-string 1 file))))
10381 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10382 (expand-file-name file))
10383 (setq link (concat
10384 "file:" (match-string 1 (expand-file-name file)))))
10385 (t (setq link (concat "file:" file)))))
10386 link))
10388 (defun org-iread-file-name (&rest args)
10389 "Read-file-name using `ido-mode' speedup if available.
10390 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10391 See `read-file-name' for a description of parameters."
10392 (org-without-partial-completion
10393 (if (and org-completion-use-ido
10394 (fboundp 'ido-read-file-name)
10395 (boundp 'ido-mode) ido-mode
10396 (listp (second args)))
10397 (let ((ido-enter-matching-directory nil))
10398 (apply 'ido-read-file-name args))
10399 (apply 'read-file-name args))))
10401 (defun org-completing-read (&rest args)
10402 "Completing-read with SPACE being a normal character."
10403 (let ((enable-recursive-minibuffers t)
10404 (minibuffer-local-completion-map
10405 (copy-keymap minibuffer-local-completion-map)))
10406 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10407 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10408 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10409 (apply 'org-icompleting-read args)))
10411 (defun org-completing-read-no-i (&rest args)
10412 (let (org-completion-use-ido org-completion-use-iswitchb)
10413 (apply 'org-completing-read args)))
10415 (defun org-iswitchb-completing-read (prompt choices &rest args)
10416 "Use iswitch as a completing-read replacement to choose from choices.
10417 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10418 from."
10419 (let* ((iswitchb-use-virtual-buffers nil)
10420 (iswitchb-make-buflist-hook
10421 (lambda ()
10422 (setq iswitchb-temp-buflist choices))))
10423 (iswitchb-read-buffer prompt)))
10425 (defun org-icompleting-read (&rest args)
10426 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10427 (org-without-partial-completion
10428 (if (and org-completion-use-ido
10429 (fboundp 'ido-completing-read)
10430 (boundp 'ido-mode) ido-mode
10431 (listp (second args)))
10432 (let ((ido-enter-matching-directory nil))
10433 (apply 'ido-completing-read (concat (car args))
10434 (if (consp (car (nth 1 args)))
10435 (mapcar 'car (nth 1 args))
10436 (nth 1 args))
10437 (cddr args)))
10438 (if (and org-completion-use-iswitchb
10439 (boundp 'iswitchb-mode) iswitchb-mode
10440 (listp (second args)))
10441 (apply 'org-iswitchb-completing-read (concat (car args))
10442 (if (consp (car (nth 1 args)))
10443 (mapcar 'car (nth 1 args))
10444 (nth 1 args))
10445 (cddr args))
10446 (apply 'completing-read args)))))
10448 (defun org-extract-attributes (s)
10449 "Extract the attributes cookie from a string and set as text property."
10450 (let (a attr (start 0) key value)
10451 (save-match-data
10452 (when (string-match "{{\\([^}]+\\)}}$" s)
10453 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10454 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10455 (setq key (match-string 1 a) value (match-string 2 a)
10456 start (match-end 0)
10457 attr (plist-put attr (intern key) value))))
10458 (org-add-props s nil 'org-attr attr))
10461 ;;; Opening/following a link
10463 (defvar org-link-search-failed nil)
10465 (defvar org-open-link-functions nil
10466 "Hook for functions finding a plain text link.
10467 These functions must take a single argument, the link content.
10468 They will be called for links that look like [[link text][description]]
10469 when LINK TEXT does not have a protocol like \"http:\" and does not look
10470 like a filename (e.g. \"./blue.png\").
10472 These functions will be called *before* Org attempts to resolve the
10473 link by doing text searches in the current buffer - so if you want a
10474 link \"[[target]]\" to still find \"<<target>>\", your function should
10475 handle this as a special case.
10477 When the function does handle the link, it must return a non-nil value.
10478 If it decides that it is not responsible for this link, it must return
10479 nil to indicate that that Org-mode can continue with other options
10480 like exact and fuzzy text search.")
10482 (defun org-next-link (&optional search-backward)
10483 "Move forward to the next link.
10484 If the link is in hidden text, expose it."
10485 (interactive "P")
10486 (when (and org-link-search-failed (eq this-command last-command))
10487 (goto-char (point-min))
10488 (message "Link search wrapped back to beginning of buffer"))
10489 (setq org-link-search-failed nil)
10490 (let* ((pos (point))
10491 (ct (org-context))
10492 (a (assoc :link ct))
10493 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10494 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10495 ((looking-at org-any-link-re)
10496 ;; Don't stay stuck at link without an org-link face
10497 (forward-char (if search-backward -1 1))))
10498 (if (funcall srch-fun org-any-link-re nil t)
10499 (progn
10500 (goto-char (match-beginning 0))
10501 (if (outline-invisible-p) (org-show-context)))
10502 (goto-char pos)
10503 (setq org-link-search-failed t)
10504 (message "No further link found"))))
10506 (defun org-previous-link ()
10507 "Move backward to the previous link.
10508 If the link is in hidden text, expose it."
10509 (interactive)
10510 (funcall 'org-next-link t))
10512 (defun org-translate-link (s)
10513 "Translate a link string if a translation function has been defined."
10514 (if (and org-link-translation-function
10515 (fboundp org-link-translation-function)
10516 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10517 (progn
10518 (setq s (funcall org-link-translation-function
10519 (match-string 1 s) (match-string 2 s)))
10520 (concat (car s) ":" (cdr s)))
10523 (defun org-translate-link-from-planner (type path)
10524 "Translate a link from Emacs Planner syntax so that Org can follow it.
10525 This is still an experimental function, your mileage may vary."
10526 (cond
10527 ((member type '("http" "https" "news" "ftp"))
10528 ;; standard Internet links are the same.
10529 nil)
10530 ((and (equal type "irc") (string-match "^//" path))
10531 ;; Planner has two / at the beginning of an irc link, we have 1.
10532 ;; We should have zero, actually....
10533 (setq path (substring path 1)))
10534 ((and (equal type "lisp") (string-match "^/" path))
10535 ;; Planner has a slash, we do not.
10536 (setq type "elisp" path (substring path 1)))
10537 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10538 ;; A typical message link. Planner has the id after the final slash,
10539 ;; we separate it with a hash mark
10540 (setq path (concat (match-string 1 path) "#"
10541 (org-remove-angle-brackets (match-string 2 path))))))
10542 (cons type path))
10544 (defun org-find-file-at-mouse (ev)
10545 "Open file link or URL at mouse."
10546 (interactive "e")
10547 (mouse-set-point ev)
10548 (org-open-at-point 'in-emacs))
10550 (defun org-open-at-mouse (ev)
10551 "Open file link or URL at mouse.
10552 See the docstring of `org-open-file' for details."
10553 (interactive "e")
10554 (mouse-set-point ev)
10555 (if (eq major-mode 'org-agenda-mode)
10556 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10557 (org-open-at-point))
10559 (defvar org-window-config-before-follow-link nil
10560 "The window configuration before following a link.
10561 This is saved in case the need arises to restore it.")
10563 (defvar org-open-link-marker (make-marker)
10564 "Marker pointing to the location where `org-open-at-point' was called.")
10566 ;;;###autoload
10567 (defun org-open-at-point-global ()
10568 "Follow a link like Org-mode does.
10569 This command can be called in any mode to follow a link that has
10570 Org-mode syntax."
10571 (interactive)
10572 (org-run-like-in-org-mode 'org-open-at-point))
10574 ;;;###autoload
10575 (defun org-open-link-from-string (s &optional arg reference-buffer)
10576 "Open a link in the string S, as if it was in Org-mode."
10577 (interactive "sLink: \nP")
10578 (let ((reference-buffer (or reference-buffer (current-buffer))))
10579 (with-temp-buffer
10580 (let ((org-inhibit-startup (not reference-buffer)))
10581 (org-mode)
10582 (insert s)
10583 (goto-char (point-min))
10584 (when reference-buffer
10585 (setq org-link-abbrev-alist-local
10586 (with-current-buffer reference-buffer
10587 org-link-abbrev-alist-local)))
10588 (org-open-at-point arg reference-buffer)))))
10590 (defvar org-open-at-point-functions nil
10591 "Hook that is run when following a link at point.
10593 Functions in this hook must return t if they identify and follow
10594 a link at point. If they don't find anything interesting at point,
10595 they must return nil.")
10597 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10598 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10599 (defun org-open-at-point (&optional arg reference-buffer)
10600 "Open link, timestamp, footnote or tags at point.
10602 When point is on a link, follow it. Normally, files will be
10603 opened by an appropriate application. If the optional prefix
10604 argument ARG is non-nil, Emacs will visit the file. With
10605 a double prefix argument, try to open outside of Emacs, in the
10606 application the system uses for this file type.
10608 When point is on a timestamp, open the agenda at the day
10609 specified.
10611 When point is a footnote definition, move to the first reference
10612 found. If it is on a reference, move to the associated
10613 definition.
10615 When point is on a headline, display a list of every link in the
10616 entry, so it is possible to pick one, or all, of them. If point
10617 is on a tag, call `org-tags-view' instead.
10619 When optional argument REFERENCE-BUFFER is non-nil, it should
10620 specify a buffer from where the link search should happen. This
10621 is used internally by `org-open-link-from-string'.
10623 On top of syntactically correct links, this function will open
10624 the link at point in comments or comment blocks and the first
10625 link in a property drawer line."
10626 (interactive "P")
10627 ;; On a code block, open block's results.
10628 (unless (call-interactively 'org-babel-open-src-block-result)
10629 (org-load-modules-maybe)
10630 (move-marker org-open-link-marker (point))
10631 (setq org-window-config-before-follow-link (current-window-configuration))
10632 (org-remove-occur-highlights nil nil t)
10633 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10634 (let* ((context (org-element-context)) type value)
10635 ;; On an unsupported type, check if point is contained within
10636 ;; a support one.
10637 (while (and (not (memq (setq type (org-element-type context))
10638 '(comment comment-block
10639 headline inlinetask link
10640 footnote-definition footnote-reference
10641 node-property timestamp)))
10642 (setq context (org-element-property :parent context))))
10643 (setq value (org-element-property :value context))
10644 (cond
10645 ;; Blank lines at the beginning of buffer: bail out.
10646 ((not context) (user-error "No link found"))
10647 ;; Exception n°1: links in property drawers
10648 ((eq type 'node-property)
10649 (org-open-link-from-string
10650 (and (string-match org-any-link-re value)
10651 (match-string-no-properties 0 value))))
10652 ;; Exception n°2: links in comments.
10653 ((memq type '(comment comment-block))
10654 (save-excursion
10655 (skip-chars-forward "\\S-" (point-at-eol))
10656 (let ((string-rear (replace-regexp-in-string
10657 "^[ \t]*# [ \t]*" ""
10658 (buffer-substring (point) (line-beginning-position))))
10659 (string-front (buffer-substring (point) (line-end-position))))
10660 (with-temp-buffer
10661 (let ((org-inhibit-startup t)) (org-mode))
10662 (insert value)
10663 (goto-char (point-min))
10664 (when (and (search-forward string-rear nil t)
10665 (search-forward string-front (line-end-position) t))
10666 (goto-char (match-beginning 0))
10667 (org-open-at-point)
10668 (when (string= string-rear "") (forward-char)))))))
10669 ;; On a headline or an inlinetask, but not on a timestamp,
10670 ;; a link, a footnote reference or on tags.
10671 ((and (memq type '(headline inlinetask))
10672 ;; Not on tags.
10673 (progn (save-excursion (beginning-of-line)
10674 (looking-at org-complex-heading-regexp))
10675 (or (not (match-beginning 5))
10676 (< (point) (match-beginning 5)))))
10677 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10678 (links (car data))
10679 (links-end (cdr data)))
10680 (if links
10681 (dolist (link (if (stringp links) (list links) links))
10682 (search-forward link nil links-end)
10683 (goto-char (match-beginning 0))
10684 (org-open-at-point))
10685 (require 'org-attach)
10686 (org-attach-reveal 'if-exists))))
10687 ;; Do nothing on white spaces after an object, unless point
10688 ;; is right after it.
10689 ((> (point)
10690 (save-excursion
10691 (goto-char (org-element-property :end context))
10692 (skip-chars-backward " \t")
10693 (point)))
10694 (user-error "No link found"))
10695 ((eq type 'timestamp) (org-follow-timestamp-link))
10696 ;; On tags within a headline or an inlinetask.
10697 ((and (memq type '(headline inlinetask))
10698 (progn (save-excursion (beginning-of-line)
10699 (looking-at org-complex-heading-regexp))
10700 (and (match-beginning 5)
10701 (>= (point) (match-beginning 5)))))
10702 (org-tags-view arg (substring (match-string 5) 0 -1)))
10703 ((eq type 'link)
10704 (let ((type (org-element-property :type context))
10705 (path (org-link-unescape (org-element-property :path context))))
10706 ;; Switch back to REFERENCE-BUFFER needed when called in
10707 ;; a temporary buffer through `org-open-link-from-string'.
10708 (with-current-buffer (or reference-buffer (current-buffer))
10709 (cond
10710 ((equal type "file")
10711 (if (string-match "[*?{]" (file-name-nondirectory path))
10712 (dired path)
10713 ;; Look into `org-link-protocols' in order to find
10714 ;; a DEDICATED-FUNCTION to open file. The function
10715 ;; will be applied on raw link instead of parsed
10716 ;; link due to the limitation in `org-add-link-type'
10717 ;; ("open" function called with a single argument).
10718 ;; If no such function is found, fallback to
10719 ;; `org-open-file'.
10721 ;; Note : "file+emacs" and "file+sys" types are
10722 ;; hard-coded in order to escape the previous
10723 ;; limitation.
10724 (let* ((option (org-element-property :search-option context))
10725 (app (org-element-property :application context))
10726 (dedicated-function
10727 (nth 1 (assoc app org-link-protocols))))
10728 (if dedicated-function
10729 (funcall dedicated-function
10730 (concat path
10731 (and option (concat "::" option))))
10732 (apply 'org-open-file
10733 path
10734 (cond (arg)
10735 ((equal app "emacs") 'emacs)
10736 ((equal app "sys") 'system))
10737 (cond ((not option) nil)
10738 ((org-string-match-p "\\`[0-9]+\\'" option)
10739 (list (string-to-number option)))
10740 (t (list nil
10741 (org-link-unescape option)))))))))
10742 ((assoc type org-link-protocols)
10743 (funcall (nth 1 (assoc type org-link-protocols)) path))
10744 ((equal type "help")
10745 (let ((f-or-v (intern path)))
10746 (cond ((fboundp f-or-v) (describe-function f-or-v))
10747 ((boundp f-or-v) (describe-variable f-or-v))
10748 (t (error "Not a known function or variable")))))
10749 ((member type '("http" "https" "ftp" "mailto" "news"))
10750 (browse-url (org-link-escape-browser (concat type ":" path))))
10751 ((equal type "doi")
10752 (browse-url
10753 (org-link-escape-browser (concat org-doi-server-url path))))
10754 ((equal type "message") (browse-url (concat type ":" path)))
10755 ((equal type "shell")
10756 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10757 (cmd path))
10758 (if (or (and (org-string-nw-p
10759 org-confirm-shell-link-not-regexp)
10760 (string-match
10761 org-confirm-shell-link-not-regexp cmd))
10762 (not org-confirm-shell-link-function)
10763 (funcall org-confirm-shell-link-function
10764 (format "Execute \"%s\" in shell? "
10765 (org-add-props cmd nil
10766 'face 'org-warning))))
10767 (progn
10768 (message "Executing %s" cmd)
10769 (shell-command cmd buf)
10770 (when (featurep 'midnight)
10771 (setq clean-buffer-list-kill-buffer-names
10772 (cons buf
10773 clean-buffer-list-kill-buffer-names))))
10774 (user-error "Abort"))))
10775 ((equal type "elisp")
10776 (let ((cmd path))
10777 (if (or (and (org-string-nw-p
10778 org-confirm-elisp-link-not-regexp)
10779 (org-string-match-p
10780 org-confirm-elisp-link-not-regexp cmd))
10781 (not org-confirm-elisp-link-function)
10782 (funcall org-confirm-elisp-link-function
10783 (format "Execute \"%s\" as elisp? "
10784 (org-add-props cmd nil
10785 'face 'org-warning))))
10786 (message "%s => %s" cmd
10787 (if (eq (string-to-char cmd) ?\()
10788 (eval (read cmd))
10789 (call-interactively (read cmd))))
10790 (user-error "Abort"))))
10791 ((equal type "id")
10792 (require 'ord-id)
10793 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10794 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10795 (unless (run-hook-with-args-until-success
10796 'org-open-link-functions path)
10797 (if (not arg) (org-mark-ring-push)
10798 (switch-to-buffer-other-window
10799 (org-get-buffer-for-internal-link (current-buffer))))
10800 (let ((cmd `(org-link-search
10801 ,(if (member type '("custom-id" "coderef"))
10802 (org-element-property :raw-link context)
10803 path)
10804 ,(cond ((equal arg '(4)) 'occur)
10805 ((equal arg '(16)) 'org-occur))
10806 ,(org-element-property :begin context))))
10807 (condition-case nil
10808 (let ((org-link-search-inhibit-query t))
10809 (eval cmd))
10810 (error (progn (widen) (eval cmd)))))))
10811 (t (browse-url-at-point))))))
10812 ;; On a footnote reference or at a footnote definition's label.
10813 ((or (eq type 'footnote-reference)
10814 (and (eq type 'footnote-definition)
10815 (save-excursion
10816 ;; Do not validate action when point is on the
10817 ;; spaces right after the footnote label, in
10818 ;; order to be on par with behaviour on links.
10819 (skip-chars-forward " \t")
10820 (let ((begin
10821 (org-element-property :contents-begin context)))
10822 (if begin (< (point) begin)
10823 (= (org-element-property :post-affiliated context)
10824 (line-beginning-position)))))))
10825 (org-footnote-action))
10826 (t (user-error "No link found")))))
10827 (move-marker org-open-link-marker nil)
10828 (run-hook-with-args 'org-follow-link-hook)))
10830 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10831 "Offer links in the current entry and return the selected link.
10832 If there is only one link, return it.
10833 If NTH is an integer, return the NTH link found.
10834 If ZERO is a string, check also this string for a link, and if
10835 there is one, return it."
10836 (with-current-buffer buffer
10837 (save-excursion
10838 (save-restriction
10839 (widen)
10840 (goto-char marker)
10841 (let ((cnt ?0)
10842 (in-emacs (if (integerp nth) nil nth))
10843 have-zero end links link c)
10844 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10845 (push (match-string 0 zero) links)
10846 (setq cnt (1- cnt) have-zero t))
10847 (save-excursion
10848 (org-back-to-heading t)
10849 (setq end (save-excursion (outline-next-heading) (point)))
10850 (while (re-search-forward org-any-link-re end t)
10851 (push (match-string 0) links))
10852 (setq links (org-uniquify (reverse links))))
10853 (cond
10854 ((null links)
10855 (message "No links"))
10856 ((equal (length links) 1)
10857 (setq link (car links)))
10858 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10859 (setq link (nth (if have-zero nth (1- nth)) links)))
10860 (t ; we have to select a link
10861 (save-excursion
10862 (save-window-excursion
10863 (delete-other-windows)
10864 (with-output-to-temp-buffer "*Select Link*"
10865 (mapc (lambda (l)
10866 (if (not (string-match org-bracket-link-regexp l))
10867 (princ (format "[%c] %s\n" (incf cnt)
10868 (org-remove-angle-brackets l)))
10869 (if (match-end 3)
10870 (princ (format "[%c] %s (%s)\n" (incf cnt)
10871 (match-string 3 l) (match-string 1 l)))
10872 (princ (format "[%c] %s\n" (incf cnt)
10873 (match-string 1 l))))))
10874 links))
10875 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10876 (message "Select link to open, RET to open all:")
10877 (setq c (read-char-exclusive))
10878 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10879 (when (equal c ?q) (user-error "Abort"))
10880 (if (equal c ?\C-m)
10881 (setq link links)
10882 (setq nth (- c ?0))
10883 (if have-zero (setq nth (1+ nth)))
10884 (unless (and (integerp nth) (>= (length links) nth))
10885 (user-error "Invalid link selection"))
10886 (setq link (nth (1- nth) links)))))
10887 (cons link end))))))
10889 ;; TODO: These functions are deprecated since `org-open-at-point'
10890 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10891 (defun org-open-file-with-system (path)
10892 "Open file at PATH using the system way of opening it."
10893 (org-open-file path 'system))
10894 (defun org-open-file-with-emacs (path)
10895 "Open file at PATH in Emacs."
10896 (org-open-file path 'emacs))
10899 ;;; File search
10901 (defvar org-create-file-search-functions nil
10902 "List of functions to construct the right search string for a file link.
10903 These functions are called in turn with point at the location to
10904 which the link should point.
10906 A function in the hook should first test if it would like to
10907 handle this file type, for example by checking the `major-mode'
10908 or the file extension. If it decides not to handle this file, it
10909 should just return nil to give other functions a chance. If it
10910 does handle the file, it must return the search string to be used
10911 when following the link. The search string will be part of the
10912 file link, given after a double colon, and `org-open-at-point'
10913 will automatically search for it. If special measures must be
10914 taken to make the search successful, another function should be
10915 added to the companion hook `org-execute-file-search-functions',
10916 which see.
10918 A function in this hook may also use `setq' to set the variable
10919 `description' to provide a suggestion for the descriptive text to
10920 be used for this link when it gets inserted into an Org-mode
10921 buffer with \\[org-insert-link].")
10923 (defvar org-execute-file-search-functions nil
10924 "List of functions to execute a file search triggered by a link.
10926 Functions added to this hook must accept a single argument, the
10927 search string that was part of the file link, the part after the
10928 double colon. The function must first check if it would like to
10929 handle this search, for example by checking the `major-mode' or
10930 the file extension. If it decides not to handle this search, it
10931 should just return nil to give other functions a chance. If it
10932 does handle the search, it must return a non-nil value to keep
10933 other functions from trying.
10935 Each function can access the current prefix argument through the
10936 variable `current-prefix-arg'. Note that a single prefix is used
10937 to force opening a link in Emacs, so it may be good to only use a
10938 numeric or double prefix to guide the search function.
10940 In case this is needed, a function in this hook can also restore
10941 the window configuration before `org-open-at-point' was called using:
10943 (set-window-configuration org-window-config-before-follow-link)")
10945 (defun org-link-search (s &optional type avoid-pos stealth)
10946 "Search for a link search option.
10947 If S is surrounded by forward slashes, it is interpreted as a
10948 regular expression. In org-mode files, this will create an `org-occur'
10949 sparse tree. In ordinary files, `occur' will be used to list matches.
10950 If the current buffer is in `dired-mode', grep will be used to search
10951 in all files. If AVOID-POS is given, ignore matches near that position.
10953 When optional argument STEALTH is non-nil, do not modify
10954 visibility around point, thus ignoring
10955 `org-show-hierarchy-above', `org-show-following-heading' and
10956 `org-show-siblings' variables."
10957 (let ((case-fold-search t)
10958 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10959 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10960 (append '(("") (" ") ("\t") ("\n"))
10961 org-emphasis-alist)
10962 "\\|") "\\)"))
10963 (pos (point))
10964 (pre nil) (post nil)
10965 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10966 (cond
10967 ;; First check if there are any special search functions
10968 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10969 ;; Now try the builtin stuff
10970 ((and (equal (string-to-char s0) ?#)
10971 (> (length s0) 1)
10972 (save-excursion
10973 (goto-char (point-min))
10974 (and
10975 (re-search-forward
10976 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10977 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10978 (setq type 'dedicated
10979 pos (match-beginning 0))))
10980 ;; There is an exact target for this
10981 (goto-char pos)
10982 (org-back-to-heading t)))
10983 ((save-excursion
10984 (goto-char (point-min))
10985 (and
10986 (re-search-forward
10987 (concat "<<" (regexp-quote s0) ">>") nil t)
10988 (setq type 'dedicated
10989 pos (match-beginning 0))))
10990 ;; There is an exact target for this
10991 (goto-char pos))
10992 ((save-excursion
10993 (goto-char (point-min))
10994 (and
10995 (re-search-forward
10996 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10997 (setq type 'dedicated pos (match-beginning 0))))
10998 ;; Found an element with a matching #+name affiliated keyword.
10999 (goto-char pos))
11000 ((and (string-match "^(\\(.*\\))$" s0)
11001 (save-excursion
11002 (goto-char (point-min))
11003 (and
11004 (re-search-forward
11005 (concat "[^[]" (regexp-quote
11006 (format org-coderef-label-format
11007 (match-string 1 s0))))
11008 nil t)
11009 (setq type 'dedicated
11010 pos (1+ (match-beginning 0))))))
11011 ;; There is a coderef target for this
11012 (goto-char pos))
11013 ((string-match "^/\\(.*\\)/$" s)
11014 ;; A regular expression
11015 (cond
11016 ((derived-mode-p 'org-mode)
11017 (org-occur (match-string 1 s)))
11018 (t (org-do-occur (match-string 1 s)))))
11019 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11020 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11021 (goto-char (point-min))
11022 (cond
11023 ((let (case-fold-search)
11024 (re-search-forward (format org-complex-heading-regexp-format
11025 (regexp-quote s))
11026 nil t))
11027 ;; OK, found a match
11028 (setq type 'dedicated)
11029 (goto-char (match-beginning 0)))
11030 ((and (not org-link-search-inhibit-query)
11031 (eq org-link-search-must-match-exact-headline 'query-to-create)
11032 (y-or-n-p "No match - create this as a new heading? "))
11033 (goto-char (point-max))
11034 (or (bolp) (newline))
11035 (insert "* " s "\n")
11036 (beginning-of-line 0))
11038 (goto-char pos)
11039 (error "No match"))))
11041 ;; A normal search string
11042 (when (equal (string-to-char s) ?*)
11043 ;; Anchor on headlines, post may include tags.
11044 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11045 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11046 s (substring s 1)))
11047 (remove-text-properties
11048 0 (length s)
11049 '(face nil mouse-face nil keymap nil fontified nil) s)
11050 ;; Make a series of regular expressions to find a match
11051 (setq words (org-split-string s "[ \n\r\t]+")
11053 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11054 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11055 "\\)" markers)
11056 re2a_ (concat "\\(" (mapconcat 'downcase words
11057 "[ \t\r\n]+") "\\)[ \t\r\n]")
11058 re2a (concat "[ \t\r\n]" re2a_)
11059 re4_ (concat "\\(" (mapconcat 'downcase words
11060 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11061 re4 (concat "[^a-zA-Z_]" re4_)
11063 re1 (concat pre re2 post)
11064 re3 (concat pre (if pre re4_ re4) post)
11065 re5 (concat pre ".*" re4)
11066 re2 (concat pre re2)
11067 re2a (concat pre (if pre re2a_ re2a))
11068 re4 (concat pre (if pre re4_ re4))
11069 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11070 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11071 re5 "\\)"))
11072 (cond
11073 ((eq type 'org-occur) (org-occur reall))
11074 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11075 (t (goto-char (point-min))
11076 (setq type 'fuzzy)
11077 (if (or (and (org-search-not-self 1 re0 nil t)
11078 (setq type 'dedicated))
11079 (org-search-not-self 1 re1 nil t)
11080 (org-search-not-self 1 re2 nil t)
11081 (org-search-not-self 1 re2a nil t)
11082 (org-search-not-self 1 re3 nil t)
11083 (org-search-not-self 1 re4 nil t)
11084 (org-search-not-self 1 re5 nil t))
11085 (goto-char (match-beginning 1))
11086 (goto-char pos)
11087 (error "No match"))))))
11088 (and (derived-mode-p 'org-mode)
11089 (not stealth)
11090 (org-show-context 'link-search))
11091 type))
11093 (defun org-search-not-self (group &rest args)
11094 "Execute `re-search-forward', but only accept matches that do not
11095 enclose the position of `org-open-link-marker'."
11096 (let ((m org-open-link-marker))
11097 (catch 'exit
11098 (while (apply 're-search-forward args)
11099 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11100 (goto-char (match-end group))
11101 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11102 (> (match-beginning 0) (marker-position m))
11103 (< (match-end 0) (marker-position m)))
11104 (save-match-data
11105 (or (not (org-in-regexp
11106 org-bracket-link-analytic-regexp 1))
11107 (not (match-end 4)) ; no description
11108 (and (<= (match-beginning 4) (point))
11109 (>= (match-end 4) (point))))))
11110 (throw 'exit (point))))))))
11112 (defun org-get-buffer-for-internal-link (buffer)
11113 "Return a buffer to be used for displaying the link target of internal links."
11114 (cond
11115 ((not org-display-internal-link-with-indirect-buffer)
11116 buffer)
11117 ((string-match "(Clone)$" (buffer-name buffer))
11118 (message "Buffer is already a clone, not making another one")
11119 ;; we also do not modify visibility in this case
11120 buffer)
11121 (t ; make a new indirect buffer for displaying the link
11122 (let* ((bn (buffer-name buffer))
11123 (ibn (concat bn "(Clone)"))
11124 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11125 (with-current-buffer ib (org-overview))
11126 ib))))
11128 (defun org-do-occur (regexp &optional cleanup)
11129 "Call the Emacs command `occur'.
11130 If CLEANUP is non-nil, remove the printout of the regular expression
11131 in the *Occur* buffer. This is useful if the regex is long and not useful
11132 to read."
11133 (occur regexp)
11134 (when cleanup
11135 (let ((cwin (selected-window)) win beg end)
11136 (when (setq win (get-buffer-window "*Occur*"))
11137 (select-window win))
11138 (goto-char (point-min))
11139 (when (re-search-forward "match[a-z]+" nil t)
11140 (setq beg (match-end 0))
11141 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11142 (setq end (1- (match-beginning 0)))))
11143 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11144 (goto-char (point-min))
11145 (select-window cwin))))
11147 ;;; The mark ring for links jumps
11149 (defvar org-mark-ring nil
11150 "Mark ring for positions before jumps in Org-mode.")
11151 (defvar org-mark-ring-last-goto nil
11152 "Last position in the mark ring used to go back.")
11153 ;; Fill and close the ring
11154 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11155 (loop for i from 1 to org-mark-ring-length do
11156 (push (make-marker) org-mark-ring))
11157 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11158 org-mark-ring)
11160 (defun org-mark-ring-push (&optional pos buffer)
11161 "Put the current position or POS into the mark ring and rotate it."
11162 (interactive)
11163 (setq pos (or pos (point)))
11164 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11165 (move-marker (car org-mark-ring)
11166 (or pos (point))
11167 (or buffer (current-buffer)))
11168 (message "%s"
11169 (substitute-command-keys
11170 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11172 (defun org-mark-ring-goto (&optional n)
11173 "Jump to the previous position in the mark ring.
11174 With prefix arg N, jump back that many stored positions. When
11175 called several times in succession, walk through the entire ring.
11176 Org-mode commands jumping to a different position in the current file,
11177 or to another Org-mode file, automatically push the old position
11178 onto the ring."
11179 (interactive "p")
11180 (let (p m)
11181 (if (eq last-command this-command)
11182 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11183 (setq p org-mark-ring))
11184 (setq org-mark-ring-last-goto p)
11185 (setq m (car p))
11186 (org-pop-to-buffer-same-window (marker-buffer m))
11187 (goto-char m)
11188 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11190 (defun org-remove-angle-brackets (s)
11191 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11192 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11194 (defun org-add-angle-brackets (s)
11195 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11196 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11198 (defun org-remove-double-quotes (s)
11199 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11200 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11203 ;;; Following specific links
11205 (defun org-follow-timestamp-link ()
11206 "Open an agenda view for the time-stamp date/range at point."
11207 (cond
11208 ((org-at-date-range-p t)
11209 (let ((org-agenda-start-on-weekday)
11210 (t1 (match-string 1))
11211 (t2 (match-string 2)) tt1 tt2)
11212 (setq tt1 (time-to-days (org-time-string-to-time t1))
11213 tt2 (time-to-days (org-time-string-to-time t2)))
11214 (let ((org-agenda-buffer-tmp-name
11215 (format "*Org Agenda(a:%s)"
11216 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11217 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11218 ((org-at-timestamp-p t)
11219 (let ((org-agenda-buffer-tmp-name
11220 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11221 (org-agenda-list nil (time-to-days (org-time-string-to-time
11222 (substring (match-string 1) 0 10)))
11223 1)))
11224 (t (error "This should not happen"))))
11227 ;;; Following file links
11228 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11229 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11230 (declare-function mailcap-mime-info
11231 "mailcap" (string &optional request no-decode))
11232 (defvar org-wait nil)
11233 (defun org-open-file (path &optional in-emacs line search)
11234 "Open the file at PATH.
11235 First, this expands any special file name abbreviations. Then the
11236 configuration variable `org-file-apps' is checked if it contains an
11237 entry for this file type, and if yes, the corresponding command is launched.
11239 If no application is found, Emacs simply visits the file.
11241 With optional prefix argument IN-EMACS, Emacs will visit the file.
11242 With a double \\[universal-argument] \\[universal-argument] \
11243 prefix arg, Org tries to avoid opening in Emacs
11244 and to use an external application to visit the file.
11246 Optional LINE specifies a line to go to, optional SEARCH a string
11247 to search for. If LINE or SEARCH is given, the file will be
11248 opened in Emacs, unless an entry from org-file-apps that makes
11249 use of groups in a regexp matches.
11251 If you want to change the way frames are used when following a
11252 link, please customize `org-link-frame-setup'.
11254 If the file does not exist, an error is thrown."
11255 (let* ((file (if (equal path "")
11256 buffer-file-name
11257 (substitute-in-file-name (expand-file-name path))))
11258 (file-apps (append org-file-apps (org-default-apps)))
11259 (apps (org-remove-if
11260 'org-file-apps-entry-match-against-dlink-p file-apps))
11261 (apps-dlink (org-remove-if-not
11262 'org-file-apps-entry-match-against-dlink-p file-apps))
11263 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11264 (dirp (if remp nil (file-directory-p file)))
11265 (file (if (and dirp org-open-directory-means-index-dot-org)
11266 (concat (file-name-as-directory file) "index.org")
11267 file))
11268 (a-m-a-p (assq 'auto-mode apps))
11269 (dfile (downcase file))
11270 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11271 (link (cond ((and (eq line nil)
11272 (eq search nil))
11273 file)
11274 (line
11275 (concat file "::" (number-to-string line)))
11276 (search
11277 (concat file "::" search))))
11278 (dlink (downcase link))
11279 (old-buffer (current-buffer))
11280 (old-pos (point))
11281 (old-mode major-mode)
11282 ext cmd link-match-data)
11283 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11284 (setq ext (match-string 1 dfile))
11285 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11286 (setq ext (match-string 1 dfile))))
11287 (cond
11288 ((member in-emacs '((16) system))
11289 (setq cmd (cdr (assoc 'system apps))))
11290 (in-emacs (setq cmd 'emacs))
11292 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11293 (and dirp (cdr (assoc 'directory apps)))
11294 ; first, try matching against apps-dlink
11295 ; if we get a match here, store the match data for later
11296 (let ((match (assoc-default dlink apps-dlink
11297 'string-match)))
11298 (if match
11299 (progn (setq link-match-data (match-data))
11300 match)
11301 (progn (setq in-emacs (or in-emacs line search))
11302 nil))) ; if we have no match in apps-dlink,
11303 ; always open the file in emacs if line or search
11304 ; is given (for backwards compatibility)
11305 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11306 'string-match)
11307 (cdr (assoc ext apps))
11308 (cdr (assoc t apps))))))
11309 (when (eq cmd 'system)
11310 (setq cmd (cdr (assoc 'system apps))))
11311 (when (eq cmd 'default)
11312 (setq cmd (cdr (assoc t apps))))
11313 (when (eq cmd 'mailcap)
11314 (require 'mailcap)
11315 (mailcap-parse-mailcaps)
11316 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11317 (command (mailcap-mime-info mime-type)))
11318 (if (stringp command)
11319 (setq cmd command)
11320 (setq cmd 'emacs))))
11321 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11322 (not (file-exists-p file))
11323 (not org-open-non-existing-files))
11324 (user-error "No such file: %s" file))
11325 (cond
11326 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11327 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11328 (while (string-match "['\"]%s['\"]" cmd)
11329 (setq cmd (replace-match "%s" t t cmd)))
11330 (while (string-match "%s" cmd)
11331 (setq cmd (replace-match
11332 (save-match-data
11333 (shell-quote-argument
11334 (convert-standard-filename file)))
11335 t t cmd)))
11337 ;; Replace "%1", "%2" etc. in command with group matches from regex
11338 (save-match-data
11339 (let ((match-index 1)
11340 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11341 (set-match-data link-match-data)
11342 (while (<= match-index number-of-groups)
11343 (let ((regex (concat "%" (number-to-string match-index)))
11344 (replace-with (match-string match-index dlink)))
11345 (while (string-match regex cmd)
11346 (setq cmd (replace-match replace-with t t cmd))))
11347 (setq match-index (+ match-index 1)))))
11349 (save-window-excursion
11350 (message "Running %s...done" cmd)
11351 (start-process-shell-command cmd nil cmd)
11352 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11353 ((or (stringp cmd)
11354 (eq cmd 'emacs))
11355 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11356 (widen)
11357 (if line (progn (org-goto-line line)
11358 (if (derived-mode-p 'org-mode)
11359 (org-reveal)))
11360 (if search (org-link-search search))))
11361 ((consp cmd)
11362 (let ((file (convert-standard-filename file)))
11363 (save-match-data
11364 (set-match-data link-match-data)
11365 (eval cmd))))
11366 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11367 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11368 (or (not (equal old-buffer (current-buffer)))
11369 (not (equal old-pos (point))))
11370 (org-mark-ring-push old-pos old-buffer))))
11372 (defun org-file-apps-entry-match-against-dlink-p (entry)
11373 "This function returns non-nil if `entry' uses a regular
11374 expression which should be matched against the whole link by
11375 org-open-file.
11377 It assumes that is the case when the entry uses a regular
11378 expression which has at least one grouping construct and the
11379 action is either a lisp form or a command string containing
11380 '%1', i.e. using at least one subexpression match as a
11381 parameter."
11382 (let ((selector (car entry))
11383 (action (cdr entry)))
11384 (if (stringp selector)
11385 (and (> (regexp-opt-depth selector) 0)
11386 (or (and (stringp action)
11387 (string-match "%[0-9]" action))
11388 (consp action)))
11389 nil)))
11391 (defun org-default-apps ()
11392 "Return the default applications for this operating system."
11393 (cond
11394 ((eq system-type 'darwin)
11395 org-file-apps-defaults-macosx)
11396 ((eq system-type 'windows-nt)
11397 org-file-apps-defaults-windowsnt)
11398 (t org-file-apps-defaults-gnu)))
11400 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11401 "Convert extensions to regular expressions in the cars of LIST.
11402 Also, weed out any non-string entries, because the return value is used
11403 only for regexp matching.
11404 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11405 point to the symbol `emacs', indicating that the file should
11406 be opened in Emacs."
11407 (append
11408 (delq nil
11409 (mapcar (lambda (x)
11410 (if (not (stringp (car x)))
11412 (if (string-match "\\W" (car x))
11414 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11415 list))
11416 (if add-auto-mode
11417 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11419 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11420 (defun org-file-remote-p (file)
11421 "Test whether FILE specifies a location on a remote system.
11422 Return non-nil if the location is indeed remote.
11424 For example, the filename \"/user@host:/foo\" specifies a location
11425 on the system \"/user@host:\"."
11426 (cond ((fboundp 'file-remote-p)
11427 (file-remote-p file))
11428 ((fboundp 'tramp-handle-file-remote-p)
11429 (tramp-handle-file-remote-p file))
11430 ((and (boundp 'ange-ftp-name-format)
11431 (string-match (car ange-ftp-name-format) file))
11432 t)))
11435 ;;;; Refiling
11437 (defun org-get-org-file ()
11438 "Read a filename, with default directory `org-directory'."
11439 (let ((default (or org-default-notes-file remember-data-file)))
11440 (read-file-name (format "File name [%s]: " default)
11441 (file-name-as-directory org-directory)
11442 default)))
11444 (defun org-notes-order-reversed-p ()
11445 "Check if the current file should receive notes in reversed order."
11446 (cond
11447 ((not org-reverse-note-order) nil)
11448 ((eq t org-reverse-note-order) t)
11449 ((not (listp org-reverse-note-order)) nil)
11450 (t (catch 'exit
11451 (let ((all org-reverse-note-order)
11452 entry)
11453 (while (setq entry (pop all))
11454 (if (string-match (car entry) buffer-file-name)
11455 (throw 'exit (cdr entry))))
11456 nil)))))
11458 (defvar org-refile-target-table nil
11459 "The list of refile targets, created by `org-refile'.")
11461 (defvar org-agenda-new-buffers nil
11462 "Buffers created to visit agenda files.")
11464 (defvar org-refile-cache nil
11465 "Cache for refile targets.")
11467 (defvar org-refile-markers nil
11468 "All the markers used for caching refile locations.")
11470 (defun org-refile-marker (pos)
11471 "Get a new refile marker, but only if caching is in use."
11472 (if (not org-refile-use-cache)
11474 (let ((m (make-marker)))
11475 (move-marker m pos)
11476 (push m org-refile-markers)
11477 m)))
11479 (defun org-refile-cache-clear ()
11480 "Clear the refile cache and disable all the markers."
11481 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11482 (setq org-refile-markers nil)
11483 (setq org-refile-cache nil)
11484 (message "Refile cache has been cleared"))
11486 (defun org-refile-cache-check-set (set)
11487 "Check if all the markers in the cache still have live buffers."
11488 (let (marker)
11489 (catch 'exit
11490 (while (and set (setq marker (nth 3 (pop set))))
11491 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11492 (when (and marker (null (marker-buffer marker)))
11493 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11494 (sit-for 3)
11495 (throw 'exit nil)))
11496 t)))
11498 (defun org-refile-cache-put (set &rest identifiers)
11499 "Push the refile targets SET into the cache, under IDENTIFIERS."
11500 (let* ((key (sha1 (prin1-to-string identifiers)))
11501 (entry (assoc key org-refile-cache)))
11502 (if entry
11503 (setcdr entry set)
11504 (push (cons key set) org-refile-cache))))
11506 (defun org-refile-cache-get (&rest identifiers)
11507 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11508 (cond
11509 ((not org-refile-cache) nil)
11510 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11512 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11513 org-refile-cache))))
11514 (and set (org-refile-cache-check-set set) set)))))
11516 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11517 "Produce a table with refile targets."
11518 (let ((case-fold-search nil)
11519 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11520 (entries (or org-refile-targets '((nil . (:level . 1)))))
11521 targets tgs txt re files f desc descre fast-path-p level pos0)
11522 (message "Getting targets...")
11523 (with-current-buffer (or default-buffer (current-buffer))
11524 (while (setq entry (pop entries))
11525 (setq files (car entry) desc (cdr entry))
11526 (setq fast-path-p nil)
11527 (cond
11528 ((null files) (setq files (list (current-buffer))))
11529 ((eq files 'org-agenda-files)
11530 (setq files (org-agenda-files 'unrestricted)))
11531 ((and (symbolp files) (fboundp files))
11532 (setq files (funcall files)))
11533 ((and (symbolp files) (boundp files))
11534 (setq files (symbol-value files))))
11535 (if (stringp files) (setq files (list files)))
11536 (cond
11537 ((eq (car desc) :tag)
11538 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11539 ((eq (car desc) :todo)
11540 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11541 ((eq (car desc) :regexp)
11542 (setq descre (cdr desc)))
11543 ((eq (car desc) :level)
11544 (setq descre (concat "^\\*\\{" (number-to-string
11545 (if org-odd-levels-only
11546 (1- (* 2 (cdr desc)))
11547 (cdr desc)))
11548 "\\}[ \t]")))
11549 ((eq (car desc) :maxlevel)
11550 (setq fast-path-p t)
11551 (setq descre (concat "^\\*\\{1," (number-to-string
11552 (if org-odd-levels-only
11553 (1- (* 2 (cdr desc)))
11554 (cdr desc)))
11555 "\\}[ \t]")))
11556 (t (error "Bad refiling target description %s" desc)))
11557 (while (setq f (pop files))
11558 (with-current-buffer
11559 (if (bufferp f) f (org-get-agenda-file-buffer f))
11561 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11562 (progn
11563 (if (bufferp f) (setq f (buffer-file-name
11564 (buffer-base-buffer f))))
11565 (setq f (and f (expand-file-name f)))
11566 (if (eq org-refile-use-outline-path 'file)
11567 (push (list (file-name-nondirectory f) f nil nil) tgs))
11568 (save-excursion
11569 (save-restriction
11570 (widen)
11571 (goto-char (point-min))
11572 (while (re-search-forward descre nil t)
11573 (goto-char (setq pos0 (point-at-bol)))
11574 (catch 'next
11575 (when org-refile-target-verify-function
11576 (save-match-data
11577 (or (funcall org-refile-target-verify-function)
11578 (throw 'next t))))
11579 (when (and (looking-at org-complex-heading-regexp)
11580 (not (member (match-string 4) excluded-entries))
11581 (match-string 4))
11582 (setq level (org-reduced-level
11583 (- (match-end 1) (match-beginning 1)))
11584 txt (org-link-display-format (match-string 4))
11585 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11586 re (format org-complex-heading-regexp-format
11587 (regexp-quote (match-string 4))))
11588 (when org-refile-use-outline-path
11589 (setq txt (mapconcat
11590 'org-protect-slash
11591 (append
11592 (if (eq org-refile-use-outline-path
11593 'file)
11594 (list (file-name-nondirectory
11595 (buffer-file-name
11596 (buffer-base-buffer))))
11597 (if (eq org-refile-use-outline-path
11598 'full-file-path)
11599 (list (buffer-file-name
11600 (buffer-base-buffer)))))
11601 (org-get-outline-path fast-path-p
11602 level txt)
11603 (list txt))
11604 "/")))
11605 (push (list txt f re (org-refile-marker (point)))
11606 tgs)))
11607 (when (= (point) pos0)
11608 ;; verification function has not moved point
11609 (goto-char (point-at-eol))))))))
11610 (when org-refile-use-cache
11611 (org-refile-cache-put tgs (buffer-file-name) descre))
11612 (setq targets (append tgs targets))))))
11613 (message "Getting targets...done")
11614 (nreverse targets)))
11616 (defun org-protect-slash (s)
11617 (while (string-match "/" s)
11618 (setq s (replace-match "\\" t t s)))
11621 (defvar org-olpa (make-vector 20 nil))
11623 (defun org-get-outline-path (&optional fastp level heading)
11624 "Return the outline path to the current entry, as a list.
11626 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11627 routine which makes outline path derivations for an entire file,
11628 avoiding backtracing. Refile target collection makes use of that."
11629 (if fastp
11630 (progn
11631 (if (> level 19)
11632 (error "Outline path failure, more than 19 levels"))
11633 (loop for i from level upto 19 do
11634 (aset org-olpa i nil))
11635 (prog1
11636 (delq nil (append org-olpa nil))
11637 (aset org-olpa level heading)))
11638 (let (rtn case-fold-search)
11639 (save-excursion
11640 (save-restriction
11641 (widen)
11642 (while (org-up-heading-safe)
11643 (when (looking-at org-complex-heading-regexp)
11644 (push (org-trim
11645 (replace-regexp-in-string
11646 ;; Remove statistical/checkboxes cookies
11647 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11648 (org-match-string-no-properties 4)))
11649 rtn)))
11650 rtn)))))
11652 (defun org-format-outline-path (path &optional width prefix separator)
11653 "Format the outline path PATH for display.
11654 WIDTH is the maximum number of characters that is available.
11655 PREFIX is a prefix to be included in the returned string,
11656 such as the file name.
11657 SEPARATOR is inserted between the different parts of the path,
11658 the default is \"/\"."
11659 (setq width (or width 79))
11660 (if prefix (setq width (- width (length prefix))))
11661 (if (not path)
11662 (or prefix "")
11663 (let* ((nsteps (length path))
11664 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11665 (maxwidth (if (<= total-width width)
11666 10000 ;; everything fits
11667 ;; we need to shorten the level headings
11668 (/ (- width nsteps) nsteps)))
11669 (org-odd-levels-only nil)
11670 (n 0)
11671 (total (1+ (length prefix))))
11672 (setq maxwidth (max maxwidth 10))
11673 (concat prefix
11674 (if prefix (or separator "/"))
11675 (mapconcat
11676 (lambda (h)
11677 (setq n (1+ n))
11678 (if (and (= n nsteps) (< maxwidth 10000))
11679 (setq maxwidth (- total-width total)))
11680 (if (< (length h) maxwidth)
11681 (progn (setq total (+ total (length h) 1)) h)
11682 (setq h (substring h 0 (- maxwidth 2))
11683 total (+ total maxwidth 1))
11684 (if (string-match "[ \t]+\\'" h)
11685 (setq h (substring h 0 (match-beginning 0))))
11686 (setq h (concat h "..")))
11687 (org-add-props h nil 'face
11688 (nth (% (1- n) org-n-level-faces)
11689 org-level-faces))
11691 path (or separator "/"))))))
11693 (defun org-display-outline-path (&optional file current separator just-return-string)
11694 "Display the current outline path in the echo area.
11696 If FILE is non-nil, prepend the output with the file name.
11697 If CURRENT is non-nil, append the current heading to the output.
11698 SEPARATOR is passed through to `org-format-outline-path'. It separates
11699 the different parts of the path and defaults to \"/\".
11700 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11701 (interactive "P")
11702 (let* (case-fold-search
11703 (bfn (buffer-file-name (buffer-base-buffer)))
11704 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11705 res)
11706 (if current (setq path (append path
11707 (save-excursion
11708 (org-back-to-heading t)
11709 (if (looking-at org-complex-heading-regexp)
11710 (list (match-string 4)))))))
11711 (setq res
11712 (org-format-outline-path
11713 path
11714 (1- (frame-width))
11715 (and file bfn (concat (file-name-nondirectory bfn) separator))
11716 separator))
11717 (if just-return-string
11718 (org-no-properties res)
11719 (org-unlogged-message "%s" res))))
11721 (defvar org-refile-history nil
11722 "History for refiling operations.")
11724 (defvar org-after-refile-insert-hook nil
11725 "Hook run after `org-refile' has inserted its stuff at the new location.
11726 Note that this is still *before* the stuff will be removed from
11727 the *old* location.")
11729 (defvar org-capture-last-stored-marker)
11730 (defvar org-refile-keep nil
11731 "Non-nil means `org-refile' will copy instead of refile.")
11733 (defun org-copy ()
11734 "Like `org-refile', but copy."
11735 (interactive)
11736 (let ((org-refile-keep t))
11737 (funcall 'org-refile nil nil nil "Copy")))
11739 (defun org-refile (&optional arg default-buffer rfloc msg)
11740 "Move the entry or entries at point to another heading.
11741 The list of target headings is compiled using the information in
11742 `org-refile-targets', which see.
11744 At the target location, the entry is filed as a subitem of the
11745 target heading. Depending on `org-reverse-note-order', the new
11746 subitem will either be the first or the last subitem.
11748 If there is an active region, all entries in that region will be
11749 refiled. However, the region must fulfill the requirement that
11750 the first heading sets the top-level of the moved text.
11752 With prefix arg ARG, the command will only visit the target
11753 location and not actually move anything.
11755 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11756 refiling operation has put the subtree.
11758 With a numeric prefix argument of `2', refile to the running clock.
11760 With a numeric prefix argument of `3', emulate `org-refile-keep'
11761 being set to `t' and copy to the target location, don't move it.
11762 Beware that keeping refiled entries may result in duplicated ID
11763 properties.
11765 RFLOC can be a refile location obtained in a different way.
11767 MSG is a string to replace \"Refile\" in the default prompt with
11768 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11770 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11772 If you are using target caching (see `org-refile-use-cache'), you
11773 have to clear the target cache in order to find new targets.
11774 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11775 prefix argument (`C-u C-u C-u C-c C-w')."
11776 (interactive "P")
11777 (if (member arg '(0 (64)))
11778 (org-refile-cache-clear)
11779 (let* ((actionmsg (cond (msg msg)
11780 ((equal arg 3) "Refile (and keep)")
11781 (t "Refile")))
11782 (cbuf (current-buffer))
11783 (regionp (org-region-active-p))
11784 (region-start (and regionp (region-beginning)))
11785 (region-end (and regionp (region-end)))
11786 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11787 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11788 pos it nbuf file re level reversed)
11789 (setq last-command nil)
11790 (when regionp
11791 (goto-char region-start)
11792 (or (bolp) (goto-char (point-at-bol)))
11793 (setq region-start (point))
11794 (unless (or (org-kill-is-subtree-p
11795 (buffer-substring region-start region-end))
11796 (prog1 org-refile-active-region-within-subtree
11797 (let ((s (point-at-eol)))
11798 (org-toggle-heading)
11799 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11800 (user-error "The region is not a (sequence of) subtree(s)")))
11801 (if (equal arg '(16))
11802 (org-refile-goto-last-stored)
11803 (when (or
11804 (and (equal arg 2)
11805 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11806 (prog1
11807 (setq it (list (or org-clock-heading "running clock")
11808 (buffer-file-name
11809 (marker-buffer org-clock-hd-marker))
11811 (marker-position org-clock-hd-marker)))
11812 (setq arg nil)))
11813 (setq it (or rfloc
11814 (let (heading-text)
11815 (save-excursion
11816 (unless (and arg (listp arg))
11817 (org-back-to-heading t)
11818 (setq heading-text
11819 (replace-regexp-in-string
11820 org-bracket-link-regexp
11821 "\\3"
11822 (nth 4 (org-heading-components)))))
11823 (org-refile-get-location
11824 (cond ((and arg (listp arg)) "Goto")
11825 (regionp (concat actionmsg " region to"))
11826 (t (concat actionmsg " subtree \""
11827 heading-text "\" to")))
11828 default-buffer
11829 (and (not (equal '(4) arg))
11830 org-refile-allow-creating-parent-nodes)
11831 arg))))))
11832 (setq file (nth 1 it)
11833 re (nth 2 it)
11834 pos (nth 3 it))
11835 (if (and (not arg)
11837 (equal (buffer-file-name) file)
11838 (if regionp
11839 (and (>= pos region-start)
11840 (<= pos region-end))
11841 (and (>= pos (point))
11842 (< pos (save-excursion
11843 (org-end-of-subtree t t))))))
11844 (error "Cannot refile to position inside the tree or region"))
11845 (setq nbuf (or (find-buffer-visiting file)
11846 (find-file-noselect file)))
11847 (if (and arg (not (equal arg 3)))
11848 (progn
11849 (org-pop-to-buffer-same-window nbuf)
11850 (goto-char pos)
11851 (org-show-context 'org-goto))
11852 (if regionp
11853 (progn
11854 (org-kill-new (buffer-substring region-start region-end))
11855 (org-save-markers-in-region region-start region-end))
11856 (org-copy-subtree 1 nil t))
11857 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11858 (find-file-noselect file)))
11859 (setq reversed (org-notes-order-reversed-p))
11860 (save-excursion
11861 (save-restriction
11862 (widen)
11863 (if pos
11864 (progn
11865 (goto-char pos)
11866 (looking-at org-outline-regexp)
11867 (setq level (org-get-valid-level (funcall outline-level) 1))
11868 (goto-char
11869 (if reversed
11870 (or (outline-next-heading) (point-max))
11871 (or (save-excursion (org-get-next-sibling))
11872 (org-end-of-subtree t t)
11873 (point-max)))))
11874 (setq level 1)
11875 (if (not reversed)
11876 (goto-char (point-max))
11877 (goto-char (point-min))
11878 (or (outline-next-heading) (goto-char (point-max)))))
11879 (if (not (bolp)) (newline))
11880 (org-paste-subtree level nil nil t)
11881 (when org-log-refile
11882 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11883 (unless (eq org-log-refile 'note)
11884 (save-excursion (org-add-log-note))))
11885 (and org-auto-align-tags
11886 (let ((org-loop-over-headlines-in-active-region nil))
11887 (org-set-tags nil t)))
11888 (let ((bookmark-name (plist-get org-bookmark-names-plist
11889 :last-refile)))
11890 (when bookmark-name
11891 (with-demoted-errors
11892 (bookmark-set bookmark-name))))
11893 ;; If we are refiling for capture, make sure that the
11894 ;; last-capture pointers point here
11895 (when (org-bound-and-true-p org-refile-for-capture)
11896 (let ((bookmark-name (plist-get org-bookmark-names-plist
11897 :last-capture-marker)))
11898 (when bookmark-name
11899 (with-demoted-errors
11900 (bookmark-set bookmark-name))))
11901 (move-marker org-capture-last-stored-marker (point)))
11902 (if (fboundp 'deactivate-mark) (deactivate-mark))
11903 (run-hooks 'org-after-refile-insert-hook))))
11904 (unless org-refile-keep
11905 (if regionp
11906 (delete-region (point) (+ (point) (- region-end region-start)))
11907 (delete-region
11908 (and (org-back-to-heading t) (point))
11909 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11910 (when (featurep 'org-inlinetask)
11911 (org-inlinetask-remove-END-maybe))
11912 (setq org-markers-to-move nil)
11913 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11915 (defun org-refile-goto-last-stored ()
11916 "Go to the location where the last refile was stored."
11917 (interactive)
11918 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11919 (message "This is the location of the last refile"))
11921 (defun org-refile--get-location (refloc tbl)
11922 "When user refile to REFLOC, find the associated target in TBL.
11923 Also check `org-refile-target-table'."
11924 (car (delq
11926 (mapcar
11927 (lambda (r) (or (assoc r tbl)
11928 (assoc r org-refile-target-table)))
11929 (list (replace-regexp-in-string "/$" "" refloc)
11930 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11932 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11933 no-exclude)
11934 "Prompt the user for a refile location, using PROMPT.
11935 PROMPT should not be suffixed with a colon and a space, because
11936 this function appends the default value from
11937 `org-refile-history' automatically, if that is not empty.
11938 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11939 this is used for the GOTO interface."
11940 (let ((org-refile-targets org-refile-targets)
11941 (org-refile-use-outline-path org-refile-use-outline-path)
11942 excluded-entries)
11943 (when (and (derived-mode-p 'org-mode)
11944 (not org-refile-use-cache)
11945 (not no-exclude))
11946 (org-map-tree
11947 (lambda()
11948 (setq excluded-entries
11949 (append excluded-entries (list (org-get-heading t t)))))))
11950 (setq org-refile-target-table
11951 (org-refile-get-targets default-buffer excluded-entries)))
11952 (unless org-refile-target-table
11953 (user-error "No refile targets"))
11954 (let* ((cbuf (current-buffer))
11955 (partial-completion-mode nil)
11956 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11957 (cfunc (if (and org-refile-use-outline-path
11958 org-outline-path-complete-in-steps)
11959 'org-olpath-completing-read
11960 'org-icompleting-read))
11961 (extra (if org-refile-use-outline-path "/" ""))
11962 (cbnex (concat (buffer-name) extra))
11963 (filename (and cfn (expand-file-name cfn)))
11964 (tbl (mapcar
11965 (lambda (x)
11966 (if (and (not (member org-refile-use-outline-path
11967 '(file full-file-path)))
11968 (not (equal filename (nth 1 x))))
11969 (cons (concat (car x) extra " ("
11970 (file-name-nondirectory (nth 1 x)) ")")
11971 (cdr x))
11972 (cons (concat (car x) extra) (cdr x))))
11973 org-refile-target-table))
11974 (completion-ignore-case t)
11975 cdef
11976 (prompt (concat prompt
11977 (or (and (car org-refile-history)
11978 (concat " (default " (car org-refile-history) ")"))
11979 (and (assoc cbnex tbl) (setq cdef cbnex)
11980 (concat " (default " cbnex ")"))) ": "))
11981 pa answ parent-target child parent old-hist)
11982 (setq old-hist org-refile-history)
11983 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11984 nil 'org-refile-history (or cdef (car org-refile-history))))
11985 (if (setq pa (org-refile--get-location answ tbl))
11986 (progn
11987 (org-refile-check-position pa)
11988 (when (or (not org-refile-history)
11989 (not (eq old-hist org-refile-history))
11990 (not (equal (car pa) (car org-refile-history))))
11991 (setq org-refile-history
11992 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11993 org-refile-history
11994 (cdr org-refile-history))))
11995 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11996 (pop org-refile-history)))
11998 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11999 (progn
12000 (setq parent (match-string 1 answ)
12001 child (match-string 2 answ))
12002 (setq parent-target (org-refile--get-location parent tbl))
12003 (when (and parent-target
12004 (or (eq new-nodes t)
12005 (and (eq new-nodes 'confirm)
12006 (y-or-n-p (format "Create new node \"%s\"? "
12007 child)))))
12008 (org-refile-new-child parent-target child)))
12009 (user-error "Invalid target location")))))
12011 (declare-function org-string-nw-p "org-macs" (s))
12012 (defun org-refile-check-position (refile-pointer)
12013 "Check if the refile pointer matches the headline to which it points."
12014 (let* ((file (nth 1 refile-pointer))
12015 (re (nth 2 refile-pointer))
12016 (pos (nth 3 refile-pointer))
12017 buffer)
12018 (if (and (not (markerp pos)) (not file))
12019 (user-error "Please indicate a target file in the refile path")
12020 (when (org-string-nw-p re)
12021 (setq buffer (if (markerp pos)
12022 (marker-buffer pos)
12023 (or (find-buffer-visiting file)
12024 (find-file-noselect file))))
12025 (with-current-buffer buffer
12026 (save-excursion
12027 (save-restriction
12028 (widen)
12029 (goto-char pos)
12030 (beginning-of-line 1)
12031 (unless (org-looking-at-p re)
12032 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12034 (defun org-refile-new-child (parent-target child)
12035 "Use refile target PARENT-TARGET to add new CHILD below it."
12036 (unless parent-target
12037 (error "Cannot find parent for new node"))
12038 (let ((file (nth 1 parent-target))
12039 (pos (nth 3 parent-target))
12040 level)
12041 (with-current-buffer (or (find-buffer-visiting file)
12042 (find-file-noselect file))
12043 (save-excursion
12044 (save-restriction
12045 (widen)
12046 (if pos
12047 (goto-char pos)
12048 (goto-char (point-max))
12049 (if (not (bolp)) (newline)))
12050 (when (looking-at org-outline-regexp)
12051 (setq level (funcall outline-level))
12052 (org-end-of-subtree t t))
12053 (org-back-over-empty-lines)
12054 (insert "\n" (make-string
12055 (if pos (org-get-valid-level level 1) 1) ?*)
12056 " " child "\n")
12057 (beginning-of-line 0)
12058 (list (concat (car parent-target) "/" child) file "" (point)))))))
12060 (defun org-olpath-completing-read (prompt collection &rest args)
12061 "Read an outline path like a file name."
12062 (let ((thetable collection)
12063 (org-completion-use-ido nil) ; does not work with ido.
12064 (org-completion-use-iswitchb nil)) ; or iswitchb
12065 (apply
12066 'org-icompleting-read prompt
12067 (lambda (string predicate &optional flag)
12068 (let (rtn r f (l (length string)))
12069 (cond
12070 ((eq flag nil)
12071 ;; try completion
12072 (try-completion string thetable))
12073 ((eq flag t)
12074 ;; all-completions
12075 (setq rtn (all-completions string thetable predicate))
12076 (mapcar
12077 (lambda (x)
12078 (setq r (substring x l))
12079 (if (string-match " ([^)]*)$" x)
12080 (setq f (match-string 0 x))
12081 (setq f ""))
12082 (if (string-match "/" r)
12083 (concat string (substring r 0 (match-end 0)) f)
12085 rtn))
12086 ((eq flag 'lambda)
12087 ;; exact match?
12088 (assoc string thetable)))))
12089 args)))
12091 ;;;; Dynamic blocks
12093 (defun org-find-dblock (name)
12094 "Find the first dynamic block with name NAME in the buffer.
12095 If not found, stay at current position and return nil."
12096 (let ((case-fold-search t) pos)
12097 (save-excursion
12098 (goto-char (point-min))
12099 (setq pos (and (re-search-forward
12100 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12101 (match-beginning 0))))
12102 (if pos (goto-char pos))
12103 pos))
12105 (defun org-create-dblock (plist)
12106 "Create a dynamic block section, with parameters taken from PLIST.
12107 PLIST must contain a :name entry which is used as the name of the block."
12108 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12109 (end-of-line 1)
12110 (newline))
12111 (let ((col (current-column))
12112 (name (plist-get plist :name)))
12113 (insert "#+BEGIN: " name)
12114 (while plist
12115 (if (eq (car plist) :name)
12116 (setq plist (cddr plist))
12117 (insert " " (prin1-to-string (pop plist)))))
12118 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12119 (beginning-of-line -2)))
12121 (defun org-prepare-dblock ()
12122 "Prepare dynamic block for refresh.
12123 This empties the block, puts the cursor at the insert position and returns
12124 the property list including an extra property :name with the block name."
12125 (unless (looking-at org-dblock-start-re)
12126 (user-error "Not at a dynamic block"))
12127 (let* ((begdel (1+ (match-end 0)))
12128 (name (org-no-properties (match-string 1)))
12129 (params (append (list :name name)
12130 (read (concat "(" (match-string 3) ")")))))
12131 (save-excursion
12132 (beginning-of-line 1)
12133 (skip-chars-forward " \t")
12134 (setq params (plist-put params :indentation-column (current-column))))
12135 (unless (re-search-forward org-dblock-end-re nil t)
12136 (error "Dynamic block not terminated"))
12137 (setq params
12138 (append params
12139 (list :content (buffer-substring
12140 begdel (match-beginning 0)))))
12141 (delete-region begdel (match-beginning 0))
12142 (goto-char begdel)
12143 (open-line 1)
12144 params))
12146 (defun org-map-dblocks (&optional command)
12147 "Apply COMMAND to all dynamic blocks in the current buffer.
12148 If COMMAND is not given, use `org-update-dblock'."
12149 (let ((cmd (or command 'org-update-dblock)))
12150 (save-excursion
12151 (goto-char (point-min))
12152 (while (re-search-forward org-dblock-start-re nil t)
12153 (goto-char (match-beginning 0))
12154 (save-excursion
12155 (condition-case nil
12156 (funcall cmd)
12157 (error (message "Error during update of dynamic block"))))
12158 (unless (re-search-forward org-dblock-end-re nil t)
12159 (error "Dynamic block not terminated"))))))
12161 (defun org-dblock-update (&optional arg)
12162 "User command for updating dynamic blocks.
12163 Update the dynamic block at point. With prefix ARG, update all dynamic
12164 blocks in the buffer."
12165 (interactive "P")
12166 (if arg
12167 (org-update-all-dblocks)
12168 (or (looking-at org-dblock-start-re)
12169 (org-beginning-of-dblock))
12170 (org-update-dblock)))
12172 (defun org-update-dblock ()
12173 "Update the dynamic block at point.
12174 This means to empty the block, parse for parameters and then call
12175 the correct writing function."
12176 (interactive)
12177 (save-excursion
12178 (let* ((win (selected-window))
12179 (pos (point))
12180 (line (org-current-line))
12181 (params (org-prepare-dblock))
12182 (name (plist-get params :name))
12183 (indent (plist-get params :indentation-column))
12184 (cmd (intern (concat "org-dblock-write:" name))))
12185 (message "Updating dynamic block `%s' at line %d..." name line)
12186 (funcall cmd params)
12187 (message "Updating dynamic block `%s' at line %d...done" name line)
12188 (goto-char pos)
12189 (when (and indent (> indent 0))
12190 (setq indent (make-string indent ?\ ))
12191 (save-excursion
12192 (select-window win)
12193 (org-beginning-of-dblock)
12194 (forward-line 1)
12195 (while (not (looking-at org-dblock-end-re))
12196 (insert indent)
12197 (beginning-of-line 2))
12198 (when (looking-at org-dblock-end-re)
12199 (and (looking-at "[ \t]+")
12200 (replace-match ""))
12201 (insert indent)))))))
12203 (defun org-beginning-of-dblock ()
12204 "Find the beginning of the dynamic block at point.
12205 Error if there is no such block at point."
12206 (let ((pos (point))
12207 beg)
12208 (end-of-line 1)
12209 (if (and (re-search-backward org-dblock-start-re nil t)
12210 (setq beg (match-beginning 0))
12211 (re-search-forward org-dblock-end-re nil t)
12212 (> (match-end 0) pos))
12213 (goto-char beg)
12214 (goto-char pos)
12215 (error "Not in a dynamic block"))))
12217 (defun org-update-all-dblocks ()
12218 "Update all dynamic blocks in the buffer.
12219 This function can be used in a hook."
12220 (interactive)
12221 (when (derived-mode-p 'org-mode)
12222 (org-map-dblocks 'org-update-dblock)))
12225 ;;;; Completion
12227 (declare-function org-export-backend-name "org-export" (cl-x))
12228 (declare-function org-export-backend-options "org-export" (cl-x))
12229 (defun org-get-export-keywords ()
12230 "Return a list of all currently understood export keywords.
12231 Export keywords include options, block names, attributes and
12232 keywords relative to each registered export back-end."
12233 (let (keywords)
12234 (dolist (backend
12235 (org-bound-and-true-p org-export--registered-backends)
12236 (delq nil keywords))
12237 ;; Back-end name (for keywords, like #+LATEX:)
12238 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12239 (dolist (option-entry (org-export-backend-options backend))
12240 ;; Back-end options.
12241 (push (nth 1 option-entry) keywords)))))
12243 (defconst org-options-keywords
12244 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12245 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12246 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12247 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12248 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12250 (defcustom org-structure-template-alist
12251 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12252 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12253 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12254 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12255 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12256 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12257 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12258 ("L" "#+LaTeX: ")
12259 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12260 ("H" "#+HTML: ")
12261 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12262 ("A" "#+ASCII: ")
12263 ("i" "#+INDEX: ?")
12264 ("I" "#+INCLUDE: %file ?"))
12265 "Structure completion elements.
12266 This is a list of abbreviation keys and values. The value gets inserted
12267 if you type `<' followed by the key and then press the completion key,
12268 usually `TAB'. %file will be replaced by a file name after prompting
12269 for the file using completion. The cursor will be placed at the position
12270 of the `?` in the template.
12271 There are two templates for each key, the first uses the original Org syntax,
12272 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12273 the default when the /org-mtags.el/ module has been loaded. See also the
12274 variable `org-mtags-prefer-muse-templates'."
12275 :group 'org-completion
12276 :type '(repeat
12277 (list
12278 (string :tag "Key")
12279 (string :tag "Template")))
12280 :version 24.4
12281 :package-version '(Org . "8.3"))
12283 (defun org-try-structure-completion ()
12284 "Try to complete a structure template before point.
12285 This looks for strings like \"<e\" on an otherwise empty line and
12286 expands them."
12287 (let ((l (buffer-substring (point-at-bol) (point)))
12289 (when (and (looking-at "[ \t]*$")
12290 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12291 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12292 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12293 (match-beginning 1)) a)
12294 t)))
12296 (defun org-complete-expand-structure-template (start cell)
12297 "Expand a structure template."
12298 (let ((rpl (nth 1 cell))
12299 (ind ""))
12300 (delete-region start (point))
12301 (when (string-match "\\`[ \t]*#\\+" rpl)
12302 (cond
12303 ((bolp))
12304 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12305 (setq ind (buffer-substring (point-at-bol) (point))))
12306 (t (newline))))
12307 (setq start (point))
12308 (if (string-match "%file" rpl)
12309 (setq rpl (replace-match
12310 (concat
12311 "\""
12312 (save-match-data
12313 (abbreviate-file-name (read-file-name "Include file: ")))
12314 "\"")
12315 t t rpl)))
12316 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12317 (concat "\n" ind)))
12318 (insert rpl)
12319 (if (re-search-backward "\\?" start t) (delete-char 1))))
12321 ;;;; TODO, DEADLINE, Comments
12323 (defun org-toggle-comment ()
12324 "Change the COMMENT state of an entry."
12325 (interactive)
12326 (save-excursion
12327 (org-back-to-heading)
12328 (looking-at org-complex-heading-regexp)
12329 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12330 (skip-chars-forward " \t")
12331 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12332 (if (org-in-commented-heading-p t)
12333 (delete-region (point)
12334 (progn (search-forward " " (line-end-position) 'move)
12335 (skip-chars-forward " \t")
12336 (point)))
12337 (insert org-comment-string)
12338 (unless (eolp) (insert " ")))))
12340 (defvar org-last-todo-state-is-todo nil
12341 "This is non-nil when the last TODO state change led to a TODO state.
12342 If the last change removed the TODO tag or switched to DONE, then
12343 this is nil.")
12345 (defvar org-setting-tags nil) ; dynamically skipped
12347 (defvar org-todo-setup-filter-hook nil
12348 "Hook for functions that pre-filter todo specs.
12349 Each function takes a todo spec and returns either nil or the spec
12350 transformed into canonical form." )
12352 (defvar org-todo-get-default-hook nil
12353 "Hook for functions that get a default item for todo.
12354 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12355 nil or a string to be used for the todo mark." )
12357 (defvar org-agenda-headline-snapshot-before-repeat)
12359 (defun org-current-effective-time ()
12360 "Return current time adjusted for `org-extend-today-until' variable."
12361 (let* ((ct (org-current-time))
12362 (dct (decode-time ct))
12363 (ct1
12364 (cond
12365 (org-use-last-clock-out-time-as-effective-time
12366 (or (org-clock-get-last-clock-out-time) ct))
12367 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12368 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12369 (t ct))))
12370 ct1))
12372 (defun org-todo-yesterday (&optional arg)
12373 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12374 (interactive "P")
12375 (if (eq major-mode 'org-agenda-mode)
12376 (apply 'org-agenda-todo-yesterday arg)
12377 (let* ((hour (third (decode-time
12378 (org-current-time))))
12379 (org-extend-today-until (1+ hour)))
12380 (org-todo arg))))
12382 (defvar org-block-entry-blocking ""
12383 "First entry preventing the TODO state change.")
12385 (defun org-cancel-repeater ()
12386 "Cancel a repeater by setting its numeric value to zero."
12387 (interactive)
12388 (save-excursion
12389 (org-back-to-heading t)
12390 (let ((bound1 (point))
12391 (bound0 (save-excursion (outline-next-heading) (point))))
12392 (when (re-search-forward
12393 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12394 org-deadline-time-regexp "\\)\\|\\("
12395 org-ts-regexp "\\)")
12396 bound0 t)
12397 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12398 (replace-match "0" t nil nil 1))))))
12400 (defun org-todo (&optional arg)
12401 "Change the TODO state of an item.
12402 The state of an item is given by a keyword at the start of the heading,
12403 like
12404 *** TODO Write paper
12405 *** DONE Call mom
12407 The different keywords are specified in the variable `org-todo-keywords'.
12408 By default the available states are \"TODO\" and \"DONE\".
12409 So for this example: when the item starts with TODO, it is changed to DONE.
12410 When it starts with DONE, the DONE is removed. And when neither TODO nor
12411 DONE are present, add TODO at the beginning of the heading.
12413 With \\[universal-argument] prefix arg, use completion to determine the new \
12414 state.
12415 With numeric prefix arg, switch to that state.
12416 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12417 keywords (nextset).
12418 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12419 With a numeric prefix arg of 0, inhibit note taking for the change.
12420 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12422 When called through ELisp, arg is also interpreted in the following way:
12423 'none -> empty state
12424 \"\"(empty string) -> switch to empty state
12425 'done -> switch to DONE
12426 'nextset -> switch to the next set of keywords
12427 'previousset -> switch to the previous set of keywords
12428 \"WAITING\" -> switch to the specified keyword, but only if it
12429 really is a member of `org-todo-keywords'."
12430 (interactive "P")
12431 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12432 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12433 'region-start-level 'region))
12434 org-loop-over-headlines-in-active-region)
12435 (org-map-entries
12436 `(org-todo ,arg)
12437 org-loop-over-headlines-in-active-region
12438 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12439 (if (equal arg '(16)) (setq arg 'nextset))
12440 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12441 (let ((org-blocker-hook org-blocker-hook)
12442 commentp
12443 case-fold-search)
12444 (when (equal arg '(64))
12445 (setq arg nil org-blocker-hook nil))
12446 (when (and org-blocker-hook
12447 (or org-inhibit-blocking
12448 (org-entry-get nil "NOBLOCKING")))
12449 (setq org-blocker-hook nil))
12450 (save-excursion
12451 (catch 'exit
12452 (org-back-to-heading t)
12453 (when (org-in-commented-heading-p t)
12454 (org-toggle-comment)
12455 (setq commentp t))
12456 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12457 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12458 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12459 (let* ((match-data (match-data))
12460 (startpos (point-at-bol))
12461 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12462 (org-log-done org-log-done)
12463 (org-log-repeat org-log-repeat)
12464 (org-todo-log-states org-todo-log-states)
12465 (org-inhibit-logging
12466 (if (equal arg 0)
12467 (progn (setq arg nil) 'note) org-inhibit-logging))
12468 (this (match-string 1))
12469 (hl-pos (match-beginning 0))
12470 (head (org-get-todo-sequence-head this))
12471 (ass (assoc head org-todo-kwd-alist))
12472 (interpret (nth 1 ass))
12473 (done-word (nth 3 ass))
12474 (final-done-word (nth 4 ass))
12475 (org-last-state (or this ""))
12476 (completion-ignore-case t)
12477 (member (member this org-todo-keywords-1))
12478 (tail (cdr member))
12479 (org-state (cond
12480 ((and org-todo-key-trigger
12481 (or (and (equal arg '(4))
12482 (eq org-use-fast-todo-selection 'prefix))
12483 (and (not arg) org-use-fast-todo-selection
12484 (not (eq org-use-fast-todo-selection
12485 'prefix)))))
12486 ;; Use fast selection
12487 (org-fast-todo-selection))
12488 ((and (equal arg '(4))
12489 (or (not org-use-fast-todo-selection)
12490 (not org-todo-key-trigger)))
12491 ;; Read a state with completion
12492 (org-icompleting-read
12493 "State: " (mapcar 'list org-todo-keywords-1)
12494 nil t))
12495 ((eq arg 'right)
12496 (if this
12497 (if tail (car tail) nil)
12498 (car org-todo-keywords-1)))
12499 ((eq arg 'left)
12500 (if (equal member org-todo-keywords-1)
12502 (if this
12503 (nth (- (length org-todo-keywords-1)
12504 (length tail) 2)
12505 org-todo-keywords-1)
12506 (org-last org-todo-keywords-1))))
12507 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12508 (setq arg nil))) ; hack to fall back to cycling
12509 (arg
12510 ;; user or caller requests a specific state
12511 (cond
12512 ((equal arg "") nil)
12513 ((eq arg 'none) nil)
12514 ((eq arg 'done) (or done-word (car org-done-keywords)))
12515 ((eq arg 'nextset)
12516 (or (car (cdr (member head org-todo-heads)))
12517 (car org-todo-heads)))
12518 ((eq arg 'previousset)
12519 (let ((org-todo-heads (reverse org-todo-heads)))
12520 (or (car (cdr (member head org-todo-heads)))
12521 (car org-todo-heads))))
12522 ((car (member arg org-todo-keywords-1)))
12523 ((stringp arg)
12524 (user-error "State `%s' not valid in this file" arg))
12525 ((nth (1- (prefix-numeric-value arg))
12526 org-todo-keywords-1))))
12527 ((null member) (or head (car org-todo-keywords-1)))
12528 ((equal this final-done-word) nil) ;; -> make empty
12529 ((null tail) nil) ;; -> first entry
12530 ((memq interpret '(type priority))
12531 (if (eq this-command last-command)
12532 (car tail)
12533 (if (> (length tail) 0)
12534 (or done-word (car org-done-keywords))
12535 nil)))
12537 (car tail))))
12538 (org-state (or
12539 (run-hook-with-args-until-success
12540 'org-todo-get-default-hook org-state org-last-state)
12541 org-state))
12542 (next (if org-state (concat " " org-state " ") " "))
12543 (change-plist (list :type 'todo-state-change :from this :to org-state
12544 :position startpos))
12545 dolog now-done-p)
12546 (when org-blocker-hook
12547 (setq org-last-todo-state-is-todo
12548 (not (member this org-done-keywords)))
12549 (unless (save-excursion
12550 (save-match-data
12551 (org-with-wide-buffer
12552 (run-hook-with-args-until-failure
12553 'org-blocker-hook change-plist))))
12554 (if (org-called-interactively-p 'interactive)
12555 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12556 this org-state org-block-entry-blocking)
12557 ;; fail silently
12558 (message "TODO state change from %s to %s blocked (by \"%s\")"
12559 this org-state org-block-entry-blocking)
12560 (throw 'exit nil))))
12561 (store-match-data match-data)
12562 (replace-match next t t)
12563 (cond ((equal this org-state)
12564 (message "TODO state was already %s" (org-trim next)))
12565 ((pos-visible-in-window-p hl-pos)
12566 (message "TODO state changed to %s" (org-trim next))))
12567 (unless head
12568 (setq head (org-get-todo-sequence-head org-state)
12569 ass (assoc head org-todo-kwd-alist)
12570 interpret (nth 1 ass)
12571 done-word (nth 3 ass)
12572 final-done-word (nth 4 ass)))
12573 (when (memq arg '(nextset previousset))
12574 (message "Keyword-Set %d/%d: %s"
12575 (- (length org-todo-sets) -1
12576 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12577 (length org-todo-sets)
12578 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12579 (setq org-last-todo-state-is-todo
12580 (not (member org-state org-done-keywords)))
12581 (setq now-done-p (and (member org-state org-done-keywords)
12582 (not (member this org-done-keywords))))
12583 (and logging (org-local-logging logging))
12584 (when (and (or org-todo-log-states org-log-done)
12585 (not (eq org-inhibit-logging t))
12586 (not (memq arg '(nextset previousset))))
12587 ;; we need to look at recording a time and note
12588 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12589 (nth 2 (assoc this org-todo-log-states))))
12590 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12591 (setq dolog 'time))
12592 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12593 (and org-state
12594 (member org-state org-not-done-keywords)
12595 (not (member this org-not-done-keywords))))
12596 ;; This is now a todo state and was not one before
12597 ;; If there was a CLOSED time stamp, get rid of it.
12598 (org-add-planning-info nil nil 'closed))
12599 (when (and now-done-p org-log-done)
12600 ;; It is now done, and it was not done before
12601 (org-add-planning-info 'closed (org-current-effective-time))
12602 (if (and (not dolog) (eq 'note org-log-done))
12603 (org-add-log-setup 'done org-state this 'findpos 'note)))
12604 (when (and org-state dolog)
12605 ;; This is a non-nil state, and we need to log it
12606 (org-add-log-setup 'state org-state this 'findpos dolog)))
12607 ;; Fixup tag positioning
12608 (org-todo-trigger-tag-changes org-state)
12609 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12610 (when org-provide-todo-statistics
12611 (org-update-parent-todo-statistics))
12612 (run-hooks 'org-after-todo-state-change-hook)
12613 (if (and arg (not (member org-state org-done-keywords)))
12614 (setq head (org-get-todo-sequence-head org-state)))
12615 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12616 ;; Do we need to trigger a repeat?
12617 (when now-done-p
12618 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12619 ;; This is for the agenda, take a snapshot of the headline.
12620 (save-match-data
12621 (setq org-agenda-headline-snapshot-before-repeat
12622 (org-get-heading))))
12623 (org-auto-repeat-maybe org-state))
12624 ;; Fixup cursor location if close to the keyword
12625 (if (and (outline-on-heading-p)
12626 (not (bolp))
12627 (save-excursion (beginning-of-line 1)
12628 (looking-at org-todo-line-regexp))
12629 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12630 (progn
12631 (goto-char (or (match-end 2) (match-end 1)))
12632 (and (looking-at " ") (just-one-space))))
12633 (when org-trigger-hook
12634 (save-excursion
12635 (run-hook-with-args 'org-trigger-hook change-plist)))
12636 (when commentp (org-toggle-comment))))))))
12638 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12639 "Block turning an entry into a TODO, using the hierarchy.
12640 This checks whether the current task should be blocked from state
12641 changes. Such blocking occurs when:
12643 1. The task has children which are not all in a completed state.
12645 2. A task has a parent with the property :ORDERED:, and there
12646 are siblings prior to the current task with incomplete
12647 status.
12649 3. The parent of the task is blocked because it has siblings that should
12650 be done first, or is child of a block grandparent TODO entry."
12652 (if (not org-enforce-todo-dependencies)
12653 t ; if locally turned off don't block
12654 (catch 'dont-block
12655 ;; If this is not a todo state change, or if this entry is already DONE,
12656 ;; do not block
12657 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12658 (member (plist-get change-plist :from)
12659 (cons 'done org-done-keywords))
12660 (member (plist-get change-plist :to)
12661 (cons 'todo org-not-done-keywords))
12662 (not (plist-get change-plist :to)))
12663 (throw 'dont-block t))
12664 ;; If this task has children, and any are undone, it's blocked
12665 (save-excursion
12666 (org-back-to-heading t)
12667 (let ((this-level (funcall outline-level)))
12668 (outline-next-heading)
12669 (let ((child-level (funcall outline-level)))
12670 (while (and (not (eobp))
12671 (> child-level this-level))
12672 ;; this todo has children, check whether they are all
12673 ;; completed
12674 (if (and (not (org-entry-is-done-p))
12675 (org-entry-is-todo-p))
12676 (progn (setq org-block-entry-blocking (org-get-heading))
12677 (throw 'dont-block nil)))
12678 (outline-next-heading)
12679 (setq child-level (funcall outline-level))))))
12680 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12681 ;; any previous siblings are undone, it's blocked
12682 (save-excursion
12683 (org-back-to-heading t)
12684 (let* ((pos (point))
12685 (parent-pos (and (org-up-heading-safe) (point))))
12686 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12687 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12688 (forward-line 1)
12689 (re-search-forward org-not-done-heading-regexp pos t))
12690 (setq org-block-entry-blocking (match-string 0))
12691 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12692 ;; Search further up the hierarchy, to see if an ancestor is blocked
12693 (while t
12694 (goto-char parent-pos)
12695 (if (not (looking-at org-not-done-heading-regexp))
12696 (throw 'dont-block t)) ; do not block, parent is not a TODO
12697 (setq pos (point))
12698 (setq parent-pos (and (org-up-heading-safe) (point)))
12699 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12700 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12701 (forward-line 1)
12702 (re-search-forward org-not-done-heading-regexp pos t)
12703 (setq org-block-entry-blocking (org-get-heading)))
12704 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12706 (defcustom org-track-ordered-property-with-tag nil
12707 "Should the ORDERED property also be shown as a tag?
12708 The ORDERED property decides if an entry should require subtasks to be
12709 completed in sequence. Since a property is not very visible, setting
12710 this option means that toggling the ORDERED property with the command
12711 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12712 not relevant for the behavior, but it makes things more visible.
12714 Note that toggling the tag with tags commands will not change the property
12715 and therefore not influence behavior!
12717 This can be t, meaning the tag ORDERED should be used, It can also be a
12718 string to select a different tag for this task."
12719 :group 'org-todo
12720 :type '(choice
12721 (const :tag "No tracking" nil)
12722 (const :tag "Track with ORDERED tag" t)
12723 (string :tag "Use other tag")))
12725 (defun org-toggle-ordered-property ()
12726 "Toggle the ORDERED property of the current entry.
12727 For better visibility, you can track the value of this property with a tag.
12728 See variable `org-track-ordered-property-with-tag'."
12729 (interactive)
12730 (let* ((t1 org-track-ordered-property-with-tag)
12731 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12732 (save-excursion
12733 (org-back-to-heading)
12734 (if (org-entry-get nil "ORDERED")
12735 (progn
12736 (org-delete-property "ORDERED")
12737 (and tag (org-toggle-tag tag 'off))
12738 (message "Subtasks can be completed in arbitrary order"))
12739 (org-entry-put nil "ORDERED" "t")
12740 (and tag (org-toggle-tag tag 'on))
12741 (message "Subtasks must be completed in sequence")))))
12743 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12744 (defun org-block-todo-from-checkboxes (change-plist)
12745 "Block turning an entry into a TODO, using checkboxes.
12746 This checks whether the current task should be blocked from state
12747 changes because there are unchecked boxes in this entry."
12748 (if (not org-enforce-todo-checkbox-dependencies)
12749 t ; if locally turned off don't block
12750 (catch 'dont-block
12751 ;; If this is not a todo state change, or if this entry is already DONE,
12752 ;; do not block
12753 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12754 (member (plist-get change-plist :from)
12755 (cons 'done org-done-keywords))
12756 (member (plist-get change-plist :to)
12757 (cons 'todo org-not-done-keywords))
12758 (not (plist-get change-plist :to)))
12759 (throw 'dont-block t))
12760 ;; If this task has checkboxes that are not checked, it's blocked
12761 (save-excursion
12762 (org-back-to-heading t)
12763 (let ((beg (point)) end)
12764 (outline-next-heading)
12765 (setq end (point))
12766 (goto-char beg)
12767 (if (org-list-search-forward
12768 (concat (org-item-beginning-re)
12769 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12770 "\\[[- ]\\]")
12771 end t)
12772 (progn
12773 (if (boundp 'org-blocked-by-checkboxes)
12774 (setq org-blocked-by-checkboxes t))
12775 (throw 'dont-block nil)))))
12776 t))) ; do not block
12778 (defun org-entry-blocked-p ()
12779 "Is the current entry blocked?"
12780 (org-with-silent-modifications
12781 (if (org-entry-get nil "NOBLOCKING")
12782 nil ;; Never block this entry
12783 (not (run-hook-with-args-until-failure
12784 'org-blocker-hook
12785 (list :type 'todo-state-change
12786 :position (point)
12787 :from 'todo
12788 :to 'done))))))
12790 (defun org-update-statistics-cookies (all)
12791 "Update the statistics cookie, either from TODO or from checkboxes.
12792 This should be called with the cursor in a line with a statistics cookie."
12793 (interactive "P")
12794 (if all
12795 (progn
12796 (org-update-checkbox-count 'all)
12797 (org-map-entries 'org-update-parent-todo-statistics))
12798 (if (not (org-at-heading-p))
12799 (org-update-checkbox-count)
12800 (let ((pos (point-marker))
12801 end l1 l2)
12802 (ignore-errors (org-back-to-heading t))
12803 (if (not (org-at-heading-p))
12804 (org-update-checkbox-count)
12805 (setq l1 (org-outline-level))
12806 (setq end (save-excursion
12807 (outline-next-heading)
12808 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12809 (point)))
12810 (if (and (save-excursion
12811 (re-search-forward
12812 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12813 (not (save-excursion (re-search-forward
12814 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12815 (org-update-checkbox-count)
12816 (if (and l2 (> l2 l1))
12817 (progn
12818 (goto-char end)
12819 (org-update-parent-todo-statistics))
12820 (goto-char pos)
12821 (beginning-of-line 1)
12822 (while (re-search-forward
12823 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12824 (point-at-eol) t)
12825 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12826 (goto-char pos)
12827 (move-marker pos nil)))))
12829 (defvar org-entry-property-inherited-from) ;; defined below
12830 (defun org-update-parent-todo-statistics ()
12831 "Update any statistics cookie in the parent of the current headline.
12832 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12833 the entire subtree and this will travel up the hierarchy and update
12834 statistics everywhere."
12835 (let* ((prop (save-excursion (org-up-heading-safe)
12836 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12837 (recursive (or (not org-hierarchical-todo-statistics)
12838 (and prop (string-match "\\<recursive\\>" prop))))
12839 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12841 (first t)
12842 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12843 level ltoggle l1 new ndel
12844 (cnt-all 0) (cnt-done 0) is-percent kwd
12845 checkbox-beg ov ovs ove cookie-present)
12846 (catch 'exit
12847 (save-excursion
12848 (beginning-of-line 1)
12849 (setq ltoggle (funcall outline-level))
12850 ;; Three situations are to consider:
12852 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12853 ;; to the top-level ancestor on the headline;
12855 ;; 2. If parent has "recursive" property, repeat up to the
12856 ;; headline setting that property, taking inheritance into
12857 ;; account;
12859 ;; 3. Else, move up to direct parent and proceed only once.
12860 (while (and (setq level (org-up-heading-safe))
12861 (or recursive first)
12862 (>= (point) lim))
12863 (setq first nil cookie-present nil)
12864 (unless (and level
12865 (not (string-match
12866 "\\<checkbox\\>"
12867 (downcase (or (org-entry-get nil "COOKIE_DATA")
12868 "")))))
12869 (throw 'exit nil))
12870 (while (re-search-forward box-re (point-at-eol) t)
12871 (setq cnt-all 0 cnt-done 0 cookie-present t)
12872 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12873 (save-match-data
12874 (unless (outline-next-heading) (throw 'exit nil))
12875 (while (and (looking-at org-complex-heading-regexp)
12876 (> (setq l1 (length (match-string 1))) level))
12877 (setq kwd (and (or recursive (= l1 ltoggle))
12878 (match-string 2)))
12879 (if (or (eq org-provide-todo-statistics 'all-headlines)
12880 (and (eq org-provide-todo-statistics t)
12881 (or (member kwd org-done-keywords)))
12882 (and (listp org-provide-todo-statistics)
12883 (stringp (car org-provide-todo-statistics))
12884 (or (member kwd org-provide-todo-statistics)
12885 (member kwd org-done-keywords)))
12886 (and (listp org-provide-todo-statistics)
12887 (listp (car org-provide-todo-statistics))
12888 (or (member kwd (car org-provide-todo-statistics))
12889 (and (member kwd org-done-keywords)
12890 (member kwd (cadr org-provide-todo-statistics))))))
12891 (setq cnt-all (1+ cnt-all))
12892 (if (eq org-provide-todo-statistics t)
12893 (and kwd (setq cnt-all (1+ cnt-all)))))
12894 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12895 (member kwd org-done-keywords))
12896 (and (listp org-provide-todo-statistics)
12897 (listp (car org-provide-todo-statistics))
12898 (member kwd org-done-keywords)
12899 (member kwd (cadr org-provide-todo-statistics)))
12900 (and (listp org-provide-todo-statistics)
12901 (stringp (car org-provide-todo-statistics))
12902 (member kwd org-done-keywords)))
12903 (setq cnt-done (1+ cnt-done)))
12904 (outline-next-heading)))
12905 (setq new
12906 (if is-percent
12907 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12908 (format "[%d/%d]" cnt-done cnt-all))
12909 ndel (- (match-end 0) checkbox-beg))
12910 ;; handle overlays when updating cookie from column view
12911 (when (setq ov (car (overlays-at checkbox-beg)))
12912 (setq ovs (overlay-start ov) ove (overlay-end ov))
12913 (delete-overlay ov))
12914 (goto-char checkbox-beg)
12915 (insert new)
12916 (delete-region (point) (+ (point) ndel))
12917 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12918 (when ov (move-overlay ov ovs ove)))
12919 (when cookie-present
12920 (run-hook-with-args 'org-after-todo-statistics-hook
12921 cnt-done (- cnt-all cnt-done))))))
12922 (run-hooks 'org-todo-statistics-hook)))
12924 (defvar org-after-todo-statistics-hook nil
12925 "Hook that is called after a TODO statistics cookie has been updated.
12926 Each function is called with two arguments: the number of not-done entries
12927 and the number of done entries.
12929 For example, the following function, when added to this hook, will switch
12930 an entry to DONE when all children are done, and back to TODO when new
12931 entries are set to a TODO status. Note that this hook is only called
12932 when there is a statistics cookie in the headline!
12934 (defun org-summary-todo (n-done n-not-done)
12935 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12936 (let (org-log-done org-log-states) ; turn off logging
12937 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12940 (defvar org-todo-statistics-hook nil
12941 "Hook that is run whenever Org thinks TODO statistics should be updated.
12942 This hook runs even if there is no statistics cookie present, in which case
12943 `org-after-todo-statistics-hook' would not run.")
12945 (defun org-todo-trigger-tag-changes (state)
12946 "Apply the changes defined in `org-todo-state-tags-triggers'."
12947 (let ((l org-todo-state-tags-triggers)
12948 changes)
12949 (when (or (not state) (equal state ""))
12950 (setq changes (append changes (cdr (assoc "" l)))))
12951 (when (and (stringp state) (> (length state) 0))
12952 (setq changes (append changes (cdr (assoc state l)))))
12953 (when (member state org-not-done-keywords)
12954 (setq changes (append changes (cdr (assoc 'todo l)))))
12955 (when (member state org-done-keywords)
12956 (setq changes (append changes (cdr (assoc 'done l)))))
12957 (dolist (c changes)
12958 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12960 (defun org-local-logging (value)
12961 "Get logging settings from a property VALUE."
12962 (let* (words w a)
12963 ;; directly set the variables, they are already local.
12964 (setq org-log-done nil
12965 org-log-repeat nil
12966 org-todo-log-states nil)
12967 (setq words (org-split-string value))
12968 (while (setq w (pop words))
12969 (cond
12970 ((setq a (assoc w org-startup-options))
12971 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12972 (set (nth 1 a) (nth 2 a))))
12973 ((setq a (org-extract-log-state-settings w))
12974 (and (member (car a) org-todo-keywords-1)
12975 (push a org-todo-log-states)))))))
12977 (defun org-get-todo-sequence-head (kwd)
12978 "Return the head of the TODO sequence to which KWD belongs.
12979 If KWD is not set, check if there is a text property remembering the
12980 right sequence."
12981 (let (p)
12982 (cond
12983 ((not kwd)
12984 (or (get-text-property (point-at-bol) 'org-todo-head)
12985 (progn
12986 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12987 nil (point-at-eol)))
12988 (get-text-property p 'org-todo-head))))
12989 ((not (member kwd org-todo-keywords-1))
12990 (car org-todo-keywords-1))
12991 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12993 (defun org-fast-todo-selection ()
12994 "Fast TODO keyword selection with single keys.
12995 Returns the new TODO keyword, or nil if no state change should occur."
12996 (let* ((fulltable org-todo-key-alist)
12997 (done-keywords org-done-keywords) ;; needed for the faces.
12998 (maxlen (apply 'max (mapcar
12999 (lambda (x)
13000 (if (stringp (car x)) (string-width (car x)) 0))
13001 fulltable)))
13002 (expert nil)
13003 (fwidth (+ maxlen 3 1 3))
13004 (ncol (/ (- (window-width) 4) fwidth))
13005 tg cnt e c tbl
13006 groups ingroup)
13007 (save-excursion
13008 (save-window-excursion
13009 (if expert
13010 (set-buffer (get-buffer-create " *Org todo*"))
13011 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13012 (erase-buffer)
13013 (org-set-local 'org-done-keywords done-keywords)
13014 (setq tbl fulltable cnt 0)
13015 (while (setq e (pop tbl))
13016 (cond
13017 ((equal e '(:startgroup))
13018 (push '() groups) (setq ingroup t)
13019 (when (not (= cnt 0))
13020 (setq cnt 0)
13021 (insert "\n"))
13022 (insert "{ "))
13023 ((equal e '(:endgroup))
13024 (setq ingroup nil cnt 0)
13025 (insert "}\n"))
13026 ((equal e '(:newline))
13027 (when (not (= cnt 0))
13028 (setq cnt 0)
13029 (insert "\n")
13030 (setq e (car tbl))
13031 (while (equal (car tbl) '(:newline))
13032 (insert "\n")
13033 (setq tbl (cdr tbl)))))
13035 (setq tg (car e) c (cdr e))
13036 (if ingroup (push tg (car groups)))
13037 (setq tg (org-add-props tg nil 'face
13038 (org-get-todo-face tg)))
13039 (if (and (= cnt 0) (not ingroup)) (insert " "))
13040 (insert "[" c "] " tg (make-string
13041 (- fwidth 4 (length tg)) ?\ ))
13042 (when (= (setq cnt (1+ cnt)) ncol)
13043 (insert "\n")
13044 (if ingroup (insert " "))
13045 (setq cnt 0)))))
13046 (insert "\n")
13047 (goto-char (point-min))
13048 (if (not expert) (org-fit-window-to-buffer))
13049 (message "[a-z..]:Set [SPC]:clear")
13050 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13051 (cond
13052 ((or (= c ?\C-g)
13053 (and (= c ?q) (not (rassoc c fulltable))))
13054 (setq quit-flag t))
13055 ((= c ?\ ) nil)
13056 ((setq e (rassoc c fulltable) tg (car e))
13058 (t (setq quit-flag t)))))))
13060 (defun org-entry-is-todo-p ()
13061 (member (org-get-todo-state) org-not-done-keywords))
13063 (defun org-entry-is-done-p ()
13064 (member (org-get-todo-state) org-done-keywords))
13066 (defun org-get-todo-state ()
13067 "Return the TODO keyword of the current subtree."
13068 (save-excursion
13069 (org-back-to-heading t)
13070 (and (looking-at org-todo-line-regexp)
13071 (match-end 2)
13072 (match-string 2))))
13074 (defun org-at-date-range-p (&optional inactive-ok)
13075 "Is the cursor inside a date range?"
13076 (interactive)
13077 (save-excursion
13078 (catch 'exit
13079 (let ((pos (point)))
13080 (skip-chars-backward "^[<\r\n")
13081 (skip-chars-backward "<[")
13082 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13083 (>= (match-end 0) pos)
13084 (throw 'exit t))
13085 (skip-chars-backward "^<[\r\n")
13086 (skip-chars-backward "<[")
13087 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13088 (>= (match-end 0) pos)
13089 (throw 'exit t)))
13090 nil)))
13092 (defun org-get-repeat (&optional tagline)
13093 "Check if there is a deadline/schedule with repeater in this entry."
13094 (save-match-data
13095 (save-excursion
13096 (org-back-to-heading t)
13097 (and (re-search-forward (if tagline
13098 (concat tagline "\\s-*" org-repeat-re)
13099 org-repeat-re)
13100 (org-entry-end-position) t)
13101 (match-string-no-properties 1)))))
13103 (defvar org-last-changed-timestamp)
13104 (defvar org-last-inserted-timestamp)
13105 (defvar org-log-post-message)
13106 (defvar org-log-note-purpose)
13107 (defvar org-log-note-how nil)
13108 (defvar org-log-note-extra)
13109 (defun org-auto-repeat-maybe (done-word)
13110 "Check if the current headline contains a repeated deadline/schedule.
13111 If yes, set TODO state back to what it was and change the base date
13112 of repeating deadline/scheduled time stamps to new date.
13113 This function is run automatically after each state change to a DONE state."
13114 ;; last-state is dynamically scoped into this function
13115 (let* ((repeat (org-get-repeat))
13116 (aa (assoc org-last-state org-todo-kwd-alist))
13117 (interpret (nth 1 aa))
13118 (head (nth 2 aa))
13119 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13120 (msg "Entry repeats: ")
13121 (org-log-done nil)
13122 (org-todo-log-states nil)
13123 re type n what ts time to-state)
13124 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13125 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13126 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13127 org-todo-repeat-to-state))
13128 (unless (and to-state (member to-state org-todo-keywords-1))
13129 (setq to-state (if (eq interpret 'type) org-last-state head)))
13130 (org-todo to-state)
13131 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13132 (org-entry-put nil "LAST_REPEAT" (format-time-string
13133 (org-time-stamp-format t t))))
13134 (when org-log-repeat
13135 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13136 (memq 'org-add-log-note post-command-hook))
13137 ;; OK, we are already setup for some record
13138 (if (eq org-log-repeat 'note)
13139 ;; make sure we take a note, not only a time stamp
13140 (setq org-log-note-how 'note))
13141 ;; Set up for taking a record
13142 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13143 org-last-state
13144 'findpos org-log-repeat)))
13145 (org-back-to-heading t)
13146 (org-add-planning-info nil nil 'closed)
13147 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13148 org-deadline-time-regexp "\\)\\|\\("
13149 org-ts-regexp "\\)"))
13150 (while (re-search-forward
13151 re (save-excursion (outline-next-heading) (point)) t)
13152 (setq type (if (match-end 1) org-scheduled-string
13153 (if (match-end 3) org-deadline-string "Plain:"))
13154 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13155 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13156 (setq n (string-to-number (match-string 2 ts))
13157 what (match-string 3 ts))
13158 (if (equal what "w") (setq n (* n 7) what "d"))
13159 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13160 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13161 ;; Preparation, see if we need to modify the start date for the change
13162 (when (match-end 1)
13163 (setq time (save-match-data (org-time-string-to-time ts)))
13164 (cond
13165 ((equal (match-string 1 ts) ".")
13166 ;; Shift starting date to today
13167 (org-timestamp-change
13168 (- (org-today) (time-to-days time))
13169 'day))
13170 ((equal (match-string 1 ts) "+")
13171 (let ((nshiftmax 10) (nshift 0))
13172 (while (or (= nshift 0)
13173 (<= (time-to-days time)
13174 (time-to-days (current-time))))
13175 (when (= (incf nshift) nshiftmax)
13176 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13177 (user-error "Abort")))
13178 (org-timestamp-change n (cdr (assoc what whata)))
13179 (org-at-timestamp-p t)
13180 (setq ts (match-string 1))
13181 (setq time (save-match-data (org-time-string-to-time ts)))))
13182 (org-timestamp-change (- n) (cdr (assoc what whata)))
13183 ;; rematch, so that we have everything in place for the real shift
13184 (org-at-timestamp-p t)
13185 (setq ts (match-string 1))
13186 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13187 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13188 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13189 (setq org-log-post-message msg)
13190 (message "%s" msg))))
13192 (defun org-show-todo-tree (arg)
13193 "Make a compact tree which shows all headlines marked with TODO.
13194 The tree will show the lines where the regexp matches, and all higher
13195 headlines above the match.
13196 With a \\[universal-argument] prefix, prompt for a regexp to match.
13197 With a numeric prefix N, construct a sparse tree for the Nth element
13198 of `org-todo-keywords-1'."
13199 (interactive "P")
13200 (let ((case-fold-search nil)
13201 (kwd-re
13202 (cond ((null arg) org-not-done-regexp)
13203 ((equal arg '(4))
13204 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13205 (mapcar 'list org-todo-keywords-1))))
13206 (concat "\\("
13207 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13208 "\\)\\>")))
13209 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13210 (regexp-quote (nth (1- (prefix-numeric-value arg))
13211 org-todo-keywords-1)))
13212 (t (user-error "Invalid prefix argument: %s" arg)))))
13213 (message "%d TODO entries found"
13214 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13216 (defun org-deadline (arg &optional time)
13217 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13218 With one universal prefix argument, remove any deadline from the item.
13219 With two universal prefix arguments, prompt for a warning delay.
13220 With argument TIME, set the deadline at the corresponding date. TIME
13221 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13222 (interactive "P")
13223 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13224 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13225 'region-start-level 'region))
13226 org-loop-over-headlines-in-active-region)
13227 (org-map-entries
13228 `(org-deadline ',arg ,time)
13229 org-loop-over-headlines-in-active-region
13230 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13231 (let* ((old-date (org-entry-get nil "DEADLINE"))
13232 (old-date-time (if old-date (org-time-string-to-time old-date)))
13233 (repeater (and old-date
13234 (string-match
13235 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13236 old-date)
13237 (match-string 1 old-date))))
13238 (cond
13239 ((equal arg '(4))
13240 (when (and old-date org-log-redeadline)
13241 (org-add-log-setup 'deldeadline nil old-date 'findpos
13242 org-log-redeadline))
13243 (org-remove-timestamp-with-keyword org-deadline-string)
13244 (message "Item no longer has a deadline."))
13245 ((equal arg '(16))
13246 (save-excursion
13247 (org-back-to-heading t)
13248 (if (re-search-forward
13249 org-deadline-time-regexp
13250 (save-excursion (outline-next-heading) (point)) t)
13251 (let* ((rpl0 (match-string 1))
13252 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13253 (replace-match
13254 (concat org-deadline-string
13255 " <" rpl
13256 (format " -%dd"
13257 (abs
13258 (- (time-to-days
13259 (save-match-data
13260 (org-read-date nil t nil "Warn starting from" old-date-time)))
13261 (time-to-days old-date-time))))
13262 ">") t t))
13263 (user-error "No deadline information to update"))))
13265 (org-add-planning-info 'deadline time 'closed)
13266 (when (and old-date org-log-redeadline
13267 (not (equal old-date
13268 (substring org-last-inserted-timestamp 1 -1))))
13269 (org-add-log-setup 'redeadline nil old-date 'findpos
13270 org-log-redeadline))
13271 (when repeater
13272 (save-excursion
13273 (org-back-to-heading t)
13274 (when (re-search-forward (concat org-deadline-string " "
13275 org-last-inserted-timestamp)
13276 (save-excursion
13277 (outline-next-heading) (point)) t)
13278 (goto-char (1- (match-end 0)))
13279 (insert " " repeater)
13280 (setq org-last-inserted-timestamp
13281 (concat (substring org-last-inserted-timestamp 0 -1)
13282 " " repeater
13283 (substring org-last-inserted-timestamp -1))))))
13284 (message "Deadline on %s" org-last-inserted-timestamp))))))
13286 (defun org-schedule (arg &optional time)
13287 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13288 With one universal prefix argument, remove any scheduling date from the item.
13289 With two universal prefix arguments, prompt for a delay cookie.
13290 With argument TIME, scheduled at the corresponding date. TIME can
13291 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13292 (interactive "P")
13293 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13294 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13295 'region-start-level 'region))
13296 org-loop-over-headlines-in-active-region)
13297 (org-map-entries
13298 `(org-schedule ',arg ,time)
13299 org-loop-over-headlines-in-active-region
13300 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13301 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13302 (old-date-time (if old-date (org-time-string-to-time old-date)))
13303 (repeater (and old-date
13304 (string-match
13305 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13306 old-date)
13307 (match-string 1 old-date))))
13308 (cond
13309 ((equal arg '(4))
13310 (progn
13311 (when (and old-date org-log-reschedule)
13312 (org-add-log-setup 'delschedule nil old-date 'findpos
13313 org-log-reschedule))
13314 (org-remove-timestamp-with-keyword org-scheduled-string)
13315 (message "Item is no longer scheduled.")))
13316 ((equal arg '(16))
13317 (save-excursion
13318 (org-back-to-heading t)
13319 (if (re-search-forward
13320 org-scheduled-time-regexp
13321 (save-excursion (outline-next-heading) (point)) t)
13322 (let* ((rpl0 (match-string 1))
13323 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13324 (replace-match
13325 (concat org-scheduled-string
13326 " <" rpl
13327 (format " -%dd"
13328 (abs
13329 (- (time-to-days
13330 (save-match-data
13331 (org-read-date nil t nil "Delay until" old-date-time)))
13332 (time-to-days old-date-time))))
13333 ">") t t))
13334 (user-error "No scheduled information to update"))))
13336 (org-add-planning-info 'scheduled time 'closed)
13337 (when (and old-date org-log-reschedule
13338 (not (equal old-date
13339 (substring org-last-inserted-timestamp 1 -1))))
13340 (org-add-log-setup 'reschedule nil old-date 'findpos
13341 org-log-reschedule))
13342 (when repeater
13343 (save-excursion
13344 (org-back-to-heading t)
13345 (when (re-search-forward (concat org-scheduled-string " "
13346 org-last-inserted-timestamp)
13347 (save-excursion
13348 (outline-next-heading) (point)) t)
13349 (goto-char (1- (match-end 0)))
13350 (insert " " repeater)
13351 (setq org-last-inserted-timestamp
13352 (concat (substring org-last-inserted-timestamp 0 -1)
13353 " " repeater
13354 (substring org-last-inserted-timestamp -1))))))
13355 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13357 (defun org-get-scheduled-time (pom &optional inherit)
13358 "Get the scheduled time as a time tuple, of a format suitable
13359 for calling org-schedule with, or if there is no scheduling,
13360 returns nil."
13361 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13362 (when time
13363 (apply 'encode-time (org-parse-time-string time)))))
13365 (defun org-get-deadline-time (pom &optional inherit)
13366 "Get the deadline as a time tuple, of a format suitable for
13367 calling org-deadline with, or if there is no scheduling, returns
13368 nil."
13369 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13370 (when time
13371 (apply 'encode-time (org-parse-time-string time)))))
13373 (defun org-remove-timestamp-with-keyword (keyword)
13374 "Remove all time stamps with KEYWORD in the current entry."
13375 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13376 beg)
13377 (save-excursion
13378 (org-back-to-heading t)
13379 (setq beg (point))
13380 (outline-next-heading)
13381 (while (re-search-backward re beg t)
13382 (replace-match "")
13383 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13384 (equal (char-before) ?\ ))
13385 (backward-delete-char 1)
13386 (if (string-match "^[ \t]*$" (buffer-substring
13387 (point-at-bol) (point-at-eol)))
13388 (delete-region (point-at-bol)
13389 (min (point-max) (1+ (point-at-eol))))))))))
13391 (defvar org-time-was-given) ; dynamically scoped parameter
13392 (defvar org-end-time-was-given) ; dynamically scoped parameter
13394 (defun org-add-planning-info (what &optional time &rest remove)
13395 "Insert new timestamp with keyword in the line directly after the headline.
13396 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13397 If non is given, the user is prompted for a date.
13398 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13399 be removed."
13400 (interactive)
13401 (let (org-time-was-given org-end-time-was-given default-time default-input)
13402 (catch 'exit
13403 (when (and (memq what '(scheduled deadline))
13404 (or (not time)
13405 (and (stringp time)
13406 (string-match "^[-+]+[0-9]" time))))
13407 ;; Try to get a default date/time from existing timestamp
13408 (save-excursion
13409 (org-back-to-heading t)
13410 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13411 (when (re-search-forward (if (eq what 'scheduled)
13412 org-scheduled-time-regexp
13413 org-deadline-time-regexp)
13414 end t)
13415 (setq ts (match-string 1)
13416 default-time (apply 'encode-time (org-parse-time-string ts))
13417 default-input (and ts (org-get-compact-tod ts)))))))
13418 (when what
13419 (setq time
13420 (if (stringp time)
13421 ;; This is a string (relative or absolute), set proper date
13422 (apply 'encode-time
13423 (org-read-date-analyze
13424 time default-time (decode-time default-time)))
13425 ;; If necessary, get the time from the user
13426 (or time (org-read-date nil 'to-time nil nil
13427 default-time default-input)))))
13429 (when (and org-insert-labeled-timestamps-at-point
13430 (memq what '(scheduled deadline)))
13431 (insert
13432 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13433 (org-insert-time-stamp time org-time-was-given
13434 nil nil nil (list org-end-time-was-given))
13435 (setq what nil))
13436 (org-with-wide-buffer
13437 (let (col list elt ts buffer-invisibility-spec)
13438 (org-back-to-heading t)
13439 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13440 (goto-char (match-end 1))
13441 (setq col (current-column))
13442 (goto-char (match-end 0))
13443 (if (eobp) (insert "\n") (forward-char 1))
13444 (unless (or what (org-looking-at-p org-planning-line-re))
13445 ;; Nothing to add, nothing to remove...... :-)
13446 (throw 'exit nil))
13447 (if (and (not (looking-at org-outline-regexp))
13448 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13449 "[^\r\n]*"))
13450 (not (equal (match-string 1) org-clock-string)))
13451 (narrow-to-region (match-beginning 0) (match-end 0))
13452 (insert-before-markers "\n")
13453 (backward-char 1)
13454 (narrow-to-region (point) (point))
13455 (and org-adapt-indentation (org-indent-to-column col)))
13456 ;; Check if we have to remove something.
13457 (setq list (cons what remove))
13458 (while list
13459 (setq elt (pop list))
13460 (when (or (and (eq elt 'scheduled)
13461 (re-search-forward org-scheduled-time-regexp nil t))
13462 (and (eq elt 'deadline)
13463 (re-search-forward org-deadline-time-regexp nil t))
13464 (and (eq elt 'closed)
13465 (re-search-forward org-closed-time-regexp nil t)))
13466 (replace-match "")
13467 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13468 (and (looking-at "[ \t]+") (replace-match ""))
13469 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13470 (when what
13471 (insert
13472 (if (or (bolp) (eq (char-before) ?\s)) "" " ")
13473 (cond ((eq what 'scheduled) org-scheduled-string)
13474 ((eq what 'deadline) org-deadline-string)
13475 ((eq what 'closed) org-closed-string))
13476 " ")
13477 (setq ts (org-insert-time-stamp
13478 time
13479 (or org-time-was-given
13480 (and (eq what 'closed) org-log-done-with-time))
13481 (eq what 'closed)
13482 nil nil (list org-end-time-was-given)))
13483 (unless (or (bolp)
13484 (eq (char-before) ?\s)
13485 (memq (char-after) '(?\n ?\s))
13486 (eobp))
13487 (insert " "))
13488 (end-of-line 1))
13489 (goto-char (point-min))
13490 (widen)
13491 (when (and (looking-at "[ \t]*\n") (eq (char-before) ?\n))
13492 (delete-region (1- (point)) (line-end-position)))
13493 ts)))))
13495 (defvar org-log-note-marker (make-marker))
13496 (defvar org-log-note-purpose nil)
13497 (defvar org-log-note-state nil)
13498 (defvar org-log-note-previous-state nil)
13499 (defvar org-log-note-extra nil)
13500 (defvar org-log-note-window-configuration nil)
13501 (defvar org-log-note-return-to (make-marker))
13502 (defvar org-log-note-effective-time nil
13503 "Remembered current time so that dynamically scoped
13504 `org-extend-today-until' affects tha timestamps in state change
13505 log")
13507 (defvar org-log-post-message nil
13508 "Message to be displayed after a log note has been stored.
13509 The auto-repeater uses this.")
13511 (defun org-add-note ()
13512 "Add a note to the current entry.
13513 This is done in the same way as adding a state change note."
13514 (interactive)
13515 (org-add-log-setup 'note nil nil 'findpos nil))
13517 (defun org-log-beginning (&optional create)
13518 "Return expected start of log notes in current entry.
13519 When optional argument CREATE is non-nil, the function creates
13520 a drawer to store notes, if necessary. Returned position ignores
13521 narrowing."
13522 (org-with-wide-buffer
13523 (org-back-to-heading t)
13524 ;; Skip planning info and property drawer.
13525 (forward-line)
13526 (when (org-looking-at-p org-planning-line-re) (forward-line))
13527 (when (looking-at org-property-drawer-re)
13528 (goto-char (match-end 0))
13529 (forward-line))
13530 (if (org-at-heading-p) (point)
13531 (let ((end (save-excursion (outline-next-heading) (point)))
13532 (drawer (cond ((stringp org-log-into-drawer) org-log-into-drawer)
13533 (org-log-into-drawer "LOGBOOK"))))
13534 (cond
13535 (drawer
13536 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13537 (case-fold-search t))
13538 (catch 'exit
13539 ;; Try to find existing drawer.
13540 (while (re-search-forward regexp end t)
13541 (let ((element (org-element-at-point)))
13542 (when (eq (org-element-type element) 'drawer)
13543 (let ((cend (org-element-property :contents-end element)))
13544 (when (and (not org-log-states-order-reversed) cend)
13545 (goto-char cend)))
13546 (throw 'exit nil))))
13547 ;; No drawer found. Create one, if permitted.
13548 (when create
13549 (unless (bolp) (insert "\n"))
13550 (let ((beg (point)))
13551 (insert ":" drawer ":\n:END:\n")
13552 (org-indent-region beg (point)))
13553 (end-of-line -1)))))
13554 (org-log-state-notes-insert-after-drawers
13555 (while (and (looking-at org-drawer-regexp)
13556 (progn (goto-char (match-end 0))
13557 (re-search-forward org-property-end-re end t)))
13558 (forward-line)))))
13559 (if (bolp) (point) (line-beginning-position 2)))))
13561 (defun org-add-log-setup (&optional purpose state prev-state findpos how extra)
13562 "Set up the post command hook to take a note.
13563 If this is about to TODO state change, the new state is expected in STATE.
13564 When FINDPOS is non-nil, find the correct position for the note in
13565 the current entry. If not, assume that it can be inserted at point.
13566 HOW is an indicator what kind of note should be created.
13567 EXTRA is additional text that will be inserted into the notes buffer."
13568 (org-with-wide-buffer
13569 (when findpos
13570 (goto-char (org-log-beginning t))
13571 (unless org-log-states-order-reversed
13572 (org-skip-over-state-notes)
13573 (skip-chars-backward " \t\n\r")
13574 (forward-line)))
13575 (move-marker org-log-note-marker (point))
13576 (setq org-log-note-purpose purpose
13577 org-log-note-state state
13578 org-log-note-previous-state prev-state
13579 org-log-note-how how
13580 org-log-note-extra extra
13581 org-log-note-effective-time (org-current-effective-time))
13582 (add-hook 'post-command-hook 'org-add-log-note 'append)))
13584 (defun org-skip-over-state-notes ()
13585 "Skip past the list of State notes in an entry."
13586 (when (ignore-errors (goto-char (org-in-item-p)))
13587 (let* ((struct (org-list-struct))
13588 (prevs (org-list-prevs-alist struct))
13589 (regexp
13590 (concat "[ \t]*- +"
13591 (replace-regexp-in-string
13592 " +" " +"
13593 (org-replace-escapes
13594 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13595 `(("%d" . ,org-ts-regexp-inactive)
13596 ("%D" . ,org-ts-regexp)
13597 ("%s" . "\"\\S-+\"")
13598 ("%S" . "\"\\S-+\"")
13599 ("%t" . ,org-ts-regexp-inactive)
13600 ("%T" . ,org-ts-regexp)
13601 ("%u" . ".*?")
13602 ("%U" . ".*?")))))))
13603 (while (org-looking-at-p regexp)
13604 (goto-char (or (org-list-get-next-item (point) struct prevs)
13605 (org-list-get-item-end (point) struct)))))))
13607 (defun org-add-log-note (&optional purpose)
13608 "Pop up a window for taking a note, and add this note later at point."
13609 (remove-hook 'post-command-hook 'org-add-log-note)
13610 (setq org-log-note-window-configuration (current-window-configuration))
13611 (delete-other-windows)
13612 (move-marker org-log-note-return-to (point))
13613 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13614 (goto-char org-log-note-marker)
13615 (org-switch-to-buffer-other-window "*Org Note*")
13616 (erase-buffer)
13617 (if (memq org-log-note-how '(time state))
13618 (let (current-prefix-arg) (org-store-log-note))
13619 (let ((org-inhibit-startup t)) (org-mode))
13620 (insert (format "# Insert note for %s.
13621 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13622 (cond
13623 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13624 ((eq org-log-note-purpose 'done) "closed todo item")
13625 ((eq org-log-note-purpose 'state)
13626 (format "state change from \"%s\" to \"%s\""
13627 (or org-log-note-previous-state "")
13628 (or org-log-note-state "")))
13629 ((eq org-log-note-purpose 'reschedule)
13630 "rescheduling")
13631 ((eq org-log-note-purpose 'delschedule)
13632 "no longer scheduled")
13633 ((eq org-log-note-purpose 'redeadline)
13634 "changing deadline")
13635 ((eq org-log-note-purpose 'deldeadline)
13636 "removing deadline")
13637 ((eq org-log-note-purpose 'refile)
13638 "refiling")
13639 ((eq org-log-note-purpose 'note)
13640 "this entry")
13641 (t (error "This should not happen")))))
13642 (if org-log-note-extra (insert org-log-note-extra))
13643 (org-set-local 'org-finish-function 'org-store-log-note)
13644 (run-hooks 'org-log-buffer-setup-hook)))
13646 (defvar org-note-abort nil) ; dynamically scoped
13647 (defun org-store-log-note ()
13648 "Finish taking a log note, and insert it to where it belongs."
13649 (let ((txt (buffer-string)))
13650 (kill-buffer (current-buffer))
13651 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings))) lines)
13652 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13653 (setq txt (replace-match "" t t txt)))
13654 (if (string-match "\\s-+\\'" txt)
13655 (setq txt (replace-match "" t t txt)))
13656 (setq lines (org-split-string txt "\n"))
13657 (when (and note (string-match "\\S-" note))
13658 (setq note
13659 (org-replace-escapes
13660 note
13661 (list (cons "%u" (user-login-name))
13662 (cons "%U" user-full-name)
13663 (cons "%t" (format-time-string
13664 (org-time-stamp-format 'long 'inactive)
13665 org-log-note-effective-time))
13666 (cons "%T" (format-time-string
13667 (org-time-stamp-format 'long nil)
13668 org-log-note-effective-time))
13669 (cons "%d" (format-time-string
13670 (org-time-stamp-format nil 'inactive)
13671 org-log-note-effective-time))
13672 (cons "%D" (format-time-string
13673 (org-time-stamp-format nil nil)
13674 org-log-note-effective-time))
13675 (cons "%s" (if org-log-note-state
13676 (concat "\"" org-log-note-state "\"")
13677 ""))
13678 (cons "%S" (if org-log-note-previous-state
13679 (concat "\"" org-log-note-previous-state "\"")
13680 "\"\"")))))
13681 (when lines (setq note (concat note " \\\\")))
13682 (push note lines))
13683 (when (or current-prefix-arg org-note-abort)
13684 (when (org-log-into-drawer)
13685 (org-remove-empty-drawer-at org-log-note-marker))
13686 (setq lines nil))
13687 (when lines
13688 (with-current-buffer (marker-buffer org-log-note-marker)
13689 (save-excursion
13690 (goto-char org-log-note-marker)
13691 (move-marker org-log-note-marker nil)
13692 ;; Make sure point is at the beginning of an empty line.
13693 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13694 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13695 ;; In an existing list, add a new item at the top level.
13696 ;; Otherwise, indent line like a regular one.
13697 (let ((itemp (org-in-item-p)))
13698 (if itemp
13699 (org-indent-line-to
13700 (let ((struct (save-excursion
13701 (goto-char itemp) (org-list-struct))))
13702 (org-list-get-ind (org-list-get-top-point struct) struct)))
13703 (org-indent-line)))
13704 (insert (org-list-bullet-string "-") (pop lines))
13705 (let ((ind (org-list-item-body-column (line-beginning-position))))
13706 (dolist (line lines)
13707 (insert "\n")
13708 (org-indent-line-to ind)
13709 (insert line)))
13710 (message "Note stored")
13711 (org-back-to-heading t)
13712 (org-cycle-hide-drawers 'children))
13713 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13714 ;; from within `org-add-log-note' because `buffer-undo-list'
13715 ;; is then modified outside of `org-with-remote-undo'.
13716 (when (eq this-command 'org-agenda-todo)
13717 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13718 ;; Don't add undo information when called from `org-agenda-todo'
13719 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13720 (set-window-configuration org-log-note-window-configuration)
13721 (with-current-buffer (marker-buffer org-log-note-return-to)
13722 (goto-char org-log-note-return-to))
13723 (move-marker org-log-note-return-to nil)
13724 (and org-log-post-message (message "%s" org-log-post-message))))
13726 (defun org-remove-empty-drawer-at (pos)
13727 "Remove an empty drawer at position POS.
13728 POS may also be a marker."
13729 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13730 (org-with-wide-buffer
13731 (goto-char pos)
13732 (let ((drawer (org-element-at-point)))
13733 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13734 (not (org-element-property :contents-begin drawer)))
13735 (delete-region (org-element-property :begin drawer)
13736 (progn (goto-char (org-element-property :end drawer))
13737 (skip-chars-backward " \r\t\n")
13738 (forward-line)
13739 (point))))))))
13741 (defvar org-ts-type nil)
13742 (defun org-sparse-tree (&optional arg type)
13743 "Create a sparse tree, prompt for the details.
13744 This command can create sparse trees. You first need to select the type
13745 of match used to create the tree:
13747 t Show all TODO entries.
13748 T Show entries with a specific TODO keyword.
13749 m Show entries selected by a tags/property match.
13750 p Enter a property name and its value (both with completion on existing
13751 names/values) and show entries with that property.
13752 r Show entries matching a regular expression (`/' can be used as well).
13753 b Show deadlines and scheduled items before a date.
13754 a Show deadlines and scheduled items after a date.
13755 d Show deadlines due within `org-deadline-warning-days'.
13756 D Show deadlines and scheduled items between a date range."
13757 (interactive "P")
13758 (setq type (or type org-sparse-tree-default-date-type))
13759 (setq org-ts-type type)
13760 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13761 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13762 [c]ycle through date types: %s"
13763 (case type
13764 (all "all timestamps")
13765 (scheduled "only scheduled")
13766 (deadline "only deadline")
13767 (active "only active timestamps")
13768 (inactive "only inactive timestamps")
13769 (scheduled-or-deadline "scheduled/deadline")
13770 (closed "with a closed time-stamp")
13771 (otherwise "scheduled/deadline")))
13772 (let ((answer (read-char-exclusive)))
13773 (case answer
13775 (org-sparse-tree
13777 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13778 inactive closed)))))
13779 (?d (call-interactively 'org-check-deadlines))
13780 (?b (call-interactively 'org-check-before-date))
13781 (?a (call-interactively 'org-check-after-date))
13782 (?D (call-interactively 'org-check-dates-range))
13783 (?t (call-interactively 'org-show-todo-tree))
13784 (?T (org-show-todo-tree '(4)))
13785 (?m (call-interactively 'org-match-sparse-tree))
13786 ((?p ?P)
13787 (let* ((kwd (org-icompleting-read
13788 "Property: " (mapcar 'list (org-buffer-property-keys))))
13789 (value (org-icompleting-read
13790 "Value: " (mapcar 'list (org-property-values kwd)))))
13791 (unless (string-match "\\`{.*}\\'" value)
13792 (setq value (concat "\"" value "\"")))
13793 (org-match-sparse-tree arg (concat kwd "=" value))))
13794 ((?r ?R ?/) (call-interactively 'org-occur))
13795 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13797 (defvar org-occur-highlights nil
13798 "List of overlays used for occur matches.")
13799 (make-variable-buffer-local 'org-occur-highlights)
13800 (defvar org-occur-parameters nil
13801 "Parameters of the active org-occur calls.
13802 This is a list, each call to org-occur pushes as cons cell,
13803 containing the regular expression and the callback, onto the list.
13804 The list can contain several entries if `org-occur' has been called
13805 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13806 will only contain one set of parameters. When the highlights are
13807 removed (for example with `C-c C-c', or with the next edit (depending
13808 on `org-remove-highlights-with-change'), this variable is emptied
13809 as well.")
13810 (make-variable-buffer-local 'org-occur-parameters)
13812 (defun org-occur (regexp &optional keep-previous callback)
13813 "Make a compact tree which shows all matches of REGEXP.
13814 The tree will show the lines where the regexp matches, and all higher
13815 headlines above the match. It will also show the heading after the match,
13816 to make sure editing the matching entry is easy.
13817 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13818 call to `org-occur' will be kept, to allow stacking of calls to this
13819 command.
13820 If CALLBACK is non-nil, it is a function which is called to confirm
13821 that the match should indeed be shown."
13822 (interactive "sRegexp: \nP")
13823 (when (equal regexp "")
13824 (user-error "Regexp cannot be empty"))
13825 (unless keep-previous
13826 (org-remove-occur-highlights nil nil t))
13827 (push (cons regexp callback) org-occur-parameters)
13828 (let ((cnt 0))
13829 (save-excursion
13830 (goto-char (point-min))
13831 (if (or (not keep-previous) ; do not want to keep
13832 (not org-occur-highlights)) ; no previous matches
13833 ;; hide everything
13834 (org-overview))
13835 (while (re-search-forward regexp nil t)
13836 (when (or (not callback)
13837 (save-match-data (funcall callback)))
13838 (setq cnt (1+ cnt))
13839 (when org-highlight-sparse-tree-matches
13840 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13841 (org-show-context 'occur-tree))))
13842 (when org-remove-highlights-with-change
13843 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13844 nil 'local))
13845 (unless org-sparse-tree-open-archived-trees
13846 (org-hide-archived-subtrees (point-min) (point-max)))
13847 (run-hooks 'org-occur-hook)
13848 (if (org-called-interactively-p 'interactive)
13849 (message "%d match(es) for regexp %s" cnt regexp))
13850 cnt))
13852 (defun org-occur-next-match (&optional n reset)
13853 "Function for `next-error-function' to find sparse tree matches.
13854 N is the number of matches to move, when negative move backwards.
13855 RESET is entirely ignored - this function always goes back to the
13856 starting point when no match is found."
13857 (let* ((limit (if (< n 0) (point-min) (point-max)))
13858 (search-func (if (< n 0)
13859 'previous-single-char-property-change
13860 'next-single-char-property-change))
13861 (n (abs n))
13862 (pos (point))
13864 (catch 'exit
13865 (while (setq p1 (funcall search-func (point) 'org-type))
13866 (when (equal p1 limit)
13867 (goto-char pos)
13868 (user-error "No more matches"))
13869 (when (equal (get-char-property p1 'org-type) 'org-occur)
13870 (setq n (1- n))
13871 (when (= n 0)
13872 (goto-char p1)
13873 (throw 'exit (point))))
13874 (goto-char p1))
13875 (goto-char p1)
13876 (user-error "No more matches"))))
13878 (defun org-show-context (&optional key)
13879 "Make sure point and context are visible.
13880 How much context is shown depends upon the variables
13881 `org-show-hierarchy-above', `org-show-following-heading',
13882 `org-show-entry-below' and `org-show-siblings'."
13883 (let ((heading-p (org-at-heading-p t))
13884 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13885 (following-p (org-get-alist-option org-show-following-heading key))
13886 (entry-p (org-get-alist-option org-show-entry-below key))
13887 (siblings-p (org-get-alist-option org-show-siblings key)))
13888 ;; Show heading or entry text
13889 (if (and heading-p (not entry-p))
13890 (org-flag-heading nil) ; only show the heading
13891 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13892 (org-show-hidden-entry))) ; show entire entry
13893 (when following-p
13894 ;; Show next sibling, or heading below text
13895 (save-excursion
13896 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13897 (org-flag-heading nil))))
13898 (when siblings-p (org-show-siblings))
13899 (when hierarchy-p
13900 ;; show all higher headings, possibly with siblings
13901 (save-excursion
13902 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13903 (not (bobp)))
13904 (org-flag-heading nil)
13905 (when siblings-p (org-show-siblings)))))))
13907 (defvar org-reveal-start-hook nil
13908 "Hook run before revealing a location.")
13910 (defun org-reveal (&optional siblings)
13911 "Show current entry, hierarchy above it, and the following headline.
13912 This can be used to show a consistent set of context around locations
13913 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13914 not t for the search context.
13916 With optional argument SIBLINGS, on each level of the hierarchy all
13917 siblings are shown. This repairs the tree structure to what it would
13918 look like when opened with hierarchical calls to `org-cycle'.
13919 With double optional argument \\[universal-argument] \\[universal-argument], \
13920 go to the parent and show the
13921 entire tree."
13922 (interactive "P")
13923 (run-hooks 'org-reveal-start-hook)
13924 (let ((org-show-hierarchy-above t)
13925 (org-show-following-heading t)
13926 (org-show-siblings (if siblings t org-show-siblings)))
13927 (org-show-context nil))
13928 (when (equal siblings '(16))
13929 (save-excursion
13930 (when (org-up-heading-safe)
13931 (org-show-subtree)
13932 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13934 (defun org-highlight-new-match (beg end)
13935 "Highlight from BEG to END and mark the highlight is an occur headline."
13936 (let ((ov (make-overlay beg end)))
13937 (overlay-put ov 'face 'secondary-selection)
13938 (overlay-put ov 'org-type 'org-occur)
13939 (push ov org-occur-highlights)))
13941 (defun org-remove-occur-highlights (&optional beg end noremove)
13942 "Remove the occur highlights from the buffer.
13943 BEG and END are ignored. If NOREMOVE is nil, remove this function
13944 from the `before-change-functions' in the current buffer."
13945 (interactive)
13946 (unless org-inhibit-highlight-removal
13947 (mapc 'delete-overlay org-occur-highlights)
13948 (setq org-occur-highlights nil)
13949 (setq org-occur-parameters nil)
13950 (unless noremove
13951 (remove-hook 'before-change-functions
13952 'org-remove-occur-highlights 'local))))
13954 ;;;; Priorities
13956 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13957 "Regular expression matching the priority indicator.")
13959 (defvar org-remove-priority-next-time nil)
13961 (defun org-priority-up ()
13962 "Increase the priority of the current item."
13963 (interactive)
13964 (org-priority 'up))
13966 (defun org-priority-down ()
13967 "Decrease the priority of the current item."
13968 (interactive)
13969 (org-priority 'down))
13971 (defun org-priority (&optional action show)
13972 "Change the priority of an item.
13973 ACTION can be `set', `up', `down', or a character."
13974 (interactive "P")
13975 (if (equal action '(4))
13976 (org-show-priority)
13977 (unless org-enable-priority-commands
13978 (user-error "Priority commands are disabled"))
13979 (setq action (or action 'set))
13980 (let (current new news have remove)
13981 (save-excursion
13982 (org-back-to-heading t)
13983 (if (looking-at org-priority-regexp)
13984 (setq current (string-to-char (match-string 2))
13985 have t))
13986 (cond
13987 ((eq action 'remove)
13988 (setq remove t new ?\ ))
13989 ((or (eq action 'set)
13990 (if (featurep 'xemacs) (characterp action) (integerp action)))
13991 (if (not (eq action 'set))
13992 (setq new action)
13993 (message "Priority %c-%c, SPC to remove: "
13994 org-highest-priority org-lowest-priority)
13995 (save-match-data
13996 (setq new (read-char-exclusive))))
13997 (if (and (= (upcase org-highest-priority) org-highest-priority)
13998 (= (upcase org-lowest-priority) org-lowest-priority))
13999 (setq new (upcase new)))
14000 (cond ((equal new ?\ ) (setq remove t))
14001 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14002 (user-error "Priority must be between `%c' and `%c'"
14003 org-highest-priority org-lowest-priority))))
14004 ((eq action 'up)
14005 (setq new (if have
14006 (1- current) ; normal cycling
14007 ;; last priority was empty
14008 (if (eq last-command this-command)
14009 org-lowest-priority ; wrap around empty to lowest
14010 ;; default
14011 (if org-priority-start-cycle-with-default
14012 org-default-priority
14013 (1- org-default-priority))))))
14014 ((eq action 'down)
14015 (setq new (if have
14016 (1+ current) ; normal cycling
14017 ;; last priority was empty
14018 (if (eq last-command this-command)
14019 org-highest-priority ; wrap around empty to highest
14020 ;; default
14021 (if org-priority-start-cycle-with-default
14022 org-default-priority
14023 (1+ org-default-priority))))))
14024 (t (user-error "Invalid action")))
14025 (if (or (< (upcase new) org-highest-priority)
14026 (> (upcase new) org-lowest-priority))
14027 (if (and (memq action '(up down))
14028 (not have) (not (eq last-command this-command)))
14029 ;; `new' is from default priority
14030 (error
14031 "The default can not be set, see `org-default-priority' why")
14032 ;; normal cycling: `new' is beyond highest/lowest priority
14033 ;; and is wrapped around to the empty priority
14034 (setq remove t)))
14035 (setq news (format "%c" new))
14036 (if have
14037 (if remove
14038 (replace-match "" t t nil 1)
14039 (replace-match news t t nil 2))
14040 (if remove
14041 (user-error "No priority cookie found in line")
14042 (let ((case-fold-search nil))
14043 (looking-at org-todo-line-regexp))
14044 (if (match-end 2)
14045 (progn
14046 (goto-char (match-end 2))
14047 (insert " [#" news "]"))
14048 (goto-char (match-beginning 3))
14049 (insert "[#" news "] "))))
14050 (org-set-tags nil 'align))
14051 (if remove
14052 (message "Priority removed")
14053 (message "Priority of current item set to %s" news)))))
14055 (defun org-show-priority ()
14056 "Show the priority of the current item.
14057 This priority is composed of the main priority given with the [#A] cookies,
14058 and by additional input from the age of a schedules or deadline entry."
14059 (interactive)
14060 (let ((pri (if (eq major-mode 'org-agenda-mode)
14061 (org-get-at-bol 'priority)
14062 (save-excursion
14063 (save-match-data
14064 (beginning-of-line)
14065 (and (looking-at org-heading-regexp)
14066 (org-get-priority (match-string 0))))))))
14067 (message "Priority is %d" (if pri pri -1000))))
14069 (defun org-get-priority (s)
14070 "Find priority cookie and return priority."
14071 (save-match-data
14072 (if (functionp org-get-priority-function)
14073 (funcall org-get-priority-function)
14074 (if (not (string-match org-priority-regexp s))
14075 (* 1000 (- org-lowest-priority org-default-priority))
14076 (* 1000 (- org-lowest-priority
14077 (string-to-char (match-string 2 s))))))))
14079 ;;;; Tags
14081 (defvar org-agenda-archives-mode)
14082 (defvar org-map-continue-from nil
14083 "Position from where mapping should continue.
14084 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14086 (defvar org-scanner-tags nil
14087 "The current tag list while the tags scanner is running.")
14088 (defvar org-trust-scanner-tags nil
14089 "Should `org-get-tags-at' use the tags for the scanner.
14090 This is for internal dynamical scoping only.
14091 When this is non-nil, the function `org-get-tags-at' will return the value
14092 of `org-scanner-tags' instead of building the list by itself. This
14093 can lead to large speed-ups when the tags scanner is used in a file with
14094 many entries, and when the list of tags is retrieved, for example to
14095 obtain a list of properties. Building the tags list for each entry in such
14096 a file becomes an N^2 operation - but with this variable set, it scales
14097 as N.")
14099 (defun org-scan-tags (action matcher todo-only &optional start-level)
14100 "Scan headline tags with inheritance and produce output ACTION.
14102 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14103 or `agenda' to produce an entry list for an agenda view. It can also be
14104 a Lisp form or a function that should be called at each matched headline, in
14105 this case the return value is a list of all return values from these calls.
14107 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14108 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14109 only lines with a not-done TODO keyword are included in the output.
14110 This should be the same variable that was scoped into
14111 and set by `org-make-tags-matcher' when it constructed MATCHER.
14113 START-LEVEL can be a string with asterisks, reducing the scope to
14114 headlines matching this string."
14115 (require 'org-agenda)
14116 (let* ((re (concat "^"
14117 (if start-level
14118 ;; Get the correct level to match
14119 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14120 org-outline-regexp)
14121 " *\\(\\<\\("
14122 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14123 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14124 (props (list 'face 'default
14125 'done-face 'org-agenda-done
14126 'undone-face 'default
14127 'mouse-face 'highlight
14128 'org-not-done-regexp org-not-done-regexp
14129 'org-todo-regexp org-todo-regexp
14130 'org-complex-heading-regexp org-complex-heading-regexp
14131 'help-echo
14132 (format "mouse-2 or RET jump to org file %s"
14133 (abbreviate-file-name
14134 (or (buffer-file-name (buffer-base-buffer))
14135 (buffer-name (buffer-base-buffer)))))))
14136 (org-map-continue-from nil)
14137 lspos tags tags-list
14138 (tags-alist (list (cons 0 org-file-tags)))
14139 (llast 0) rtn rtn1 level category i txt
14140 todo marker entry priority)
14141 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14142 (setq action (list 'lambda nil action)))
14143 (save-excursion
14144 (goto-char (point-min))
14145 (when (eq action 'sparse-tree)
14146 (org-overview)
14147 (org-remove-occur-highlights))
14148 (while (let (case-fold-search)
14149 (re-search-forward re nil t))
14150 (setq org-map-continue-from nil)
14151 (catch :skip
14152 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14153 tags (if (match-end 4) (org-match-string-no-properties 4)))
14154 (goto-char (setq lspos (match-beginning 0)))
14155 (setq level (org-reduced-level (org-outline-level))
14156 category (org-get-category))
14157 (setq i llast llast level)
14158 ;; remove tag lists from same and sublevels
14159 (while (>= i level)
14160 (when (setq entry (assoc i tags-alist))
14161 (setq tags-alist (delete entry tags-alist)))
14162 (setq i (1- i)))
14163 ;; add the next tags
14164 (when tags
14165 (setq tags (org-split-string tags ":")
14166 tags-alist
14167 (cons (cons level tags) tags-alist)))
14168 ;; compile tags for current headline
14169 (setq tags-list
14170 (if org-use-tag-inheritance
14171 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14172 tags)
14173 org-scanner-tags tags-list)
14174 (when org-use-tag-inheritance
14175 (setcdr (car tags-alist)
14176 (mapcar (lambda (x)
14177 (setq x (copy-sequence x))
14178 (org-add-prop-inherited x))
14179 (cdar tags-alist))))
14180 (when (and tags org-use-tag-inheritance
14181 (or (not (eq t org-use-tag-inheritance))
14182 org-tags-exclude-from-inheritance))
14183 ;; selective inheritance, remove uninherited ones
14184 (setcdr (car tags-alist)
14185 (org-remove-uninherited-tags (cdar tags-alist))))
14186 (when (and
14188 ;; eval matcher only when the todo condition is OK
14189 (and (or (not todo-only) (member todo org-not-done-keywords))
14190 (let ((case-fold-search t) (org-trust-scanner-tags t))
14191 (eval matcher)))
14193 ;; Call the skipper, but return t if it does not skip,
14194 ;; so that the `and' form continues evaluating
14195 (progn
14196 (unless (eq action 'sparse-tree) (org-agenda-skip))
14199 ;; Check if timestamps are deselecting this entry
14200 (or (not todo-only)
14201 (and (member todo org-not-done-keywords)
14202 (or (not org-agenda-tags-todo-honor-ignore-options)
14203 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14205 ;; select this headline
14206 (cond
14207 ((eq action 'sparse-tree)
14208 (and org-highlight-sparse-tree-matches
14209 (org-get-heading) (match-end 0)
14210 (org-highlight-new-match
14211 (match-beginning 1) (match-end 1)))
14212 (org-show-context 'tags-tree))
14213 ((eq action 'agenda)
14214 (setq txt (org-agenda-format-item
14216 (concat
14217 (if (eq org-tags-match-list-sublevels 'indented)
14218 (make-string (1- level) ?.) "")
14219 (org-get-heading))
14220 level category
14221 tags-list)
14222 priority (org-get-priority txt))
14223 (goto-char lspos)
14224 (setq marker (org-agenda-new-marker))
14225 (org-add-props txt props
14226 'org-marker marker 'org-hd-marker marker 'org-category category
14227 'todo-state todo
14228 'priority priority 'type "tagsmatch")
14229 (push txt rtn))
14230 ((functionp action)
14231 (setq org-map-continue-from nil)
14232 (save-excursion
14233 (setq rtn1 (funcall action))
14234 (push rtn1 rtn)))
14235 (t (user-error "Invalid action")))
14237 ;; if we are to skip sublevels, jump to end of subtree
14238 (unless org-tags-match-list-sublevels
14239 (org-end-of-subtree t)
14240 (backward-char 1))))
14241 ;; Get the correct position from where to continue
14242 (if org-map-continue-from
14243 (goto-char org-map-continue-from)
14244 (and (= (point) lspos) (end-of-line 1)))))
14245 (when (and (eq action 'sparse-tree)
14246 (not org-sparse-tree-open-archived-trees))
14247 (org-hide-archived-subtrees (point-min) (point-max)))
14248 (nreverse rtn)))
14250 (defun org-remove-uninherited-tags (tags)
14251 "Remove all tags that are not inherited from the list TAGS."
14252 (cond
14253 ((eq org-use-tag-inheritance t)
14254 (if org-tags-exclude-from-inheritance
14255 (org-delete-all org-tags-exclude-from-inheritance tags)
14256 tags))
14257 ((not org-use-tag-inheritance) nil)
14258 ((stringp org-use-tag-inheritance)
14259 (delq nil (mapcar
14260 (lambda (x)
14261 (if (and (string-match org-use-tag-inheritance x)
14262 (not (member x org-tags-exclude-from-inheritance)))
14263 x nil))
14264 tags)))
14265 ((listp org-use-tag-inheritance)
14266 (delq nil (mapcar
14267 (lambda (x)
14268 (if (member x org-use-tag-inheritance) x nil))
14269 tags)))))
14271 (defun org-match-sparse-tree (&optional todo-only match)
14272 "Create a sparse tree according to tags string MATCH.
14273 MATCH can contain positive and negative selection of tags, like
14274 \"+WORK+URGENT-WITHBOSS\".
14275 If optional argument TODO-ONLY is non-nil, only select lines that are
14276 also TODO lines."
14277 (interactive "P")
14278 (org-agenda-prepare-buffers (list (current-buffer)))
14279 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14281 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14283 (defvar org-cached-props nil)
14284 (defun org-cached-entry-get (pom property)
14285 (if (or (eq t org-use-property-inheritance)
14286 (and (stringp org-use-property-inheritance)
14287 (string-match org-use-property-inheritance property))
14288 (and (listp org-use-property-inheritance)
14289 (member property org-use-property-inheritance)))
14290 ;; Caching is not possible, check it directly
14291 (org-entry-get pom property 'inherit)
14292 ;; Get all properties, so that we can do complicated checks easily
14293 (cdr (assoc property (or org-cached-props
14294 (setq org-cached-props
14295 (org-entry-properties pom)))))))
14297 (defun org-global-tags-completion-table (&optional files)
14298 "Return the list of all tags in all agenda buffer/files.
14299 Optional FILES argument is a list of files which can be used
14300 instead of the agenda files."
14301 (save-excursion
14302 (org-uniquify
14303 (delq nil
14304 (apply 'append
14305 (mapcar
14306 (lambda (file)
14307 (set-buffer (find-file-noselect file))
14308 (append (org-get-buffer-tags)
14309 (mapcar (lambda (x) (if (stringp (car-safe x))
14310 (list (car-safe x)) nil))
14311 org-tag-alist)))
14312 (if (and files (car files))
14313 files
14314 (org-agenda-files))))))))
14316 (defun org-make-tags-matcher (match)
14317 "Create the TAGS/TODO matcher form for the selection string MATCH.
14319 The variable `todo-only' is scoped dynamically into this function.
14320 It will be set to t if the matcher restricts matching to TODO entries,
14321 otherwise will not be touched.
14323 Returns a cons of the selection string MATCH and the constructed
14324 lisp form implementing the matcher. The matcher is to be evaluated
14325 at an Org entry, with point on the headline, and returns t if the
14326 entry matches the selection string MATCH. The returned lisp form
14327 references two variables with information about the entry, which
14328 must be bound around the form's evaluation: todo, the TODO keyword
14329 at the entry (or nil of none); and tags-list, the list of all tags
14330 at the entry including inherited ones. Additionally, the category
14331 of the entry (if any) must be specified as the text property
14332 'org-category on the headline.
14334 See also `org-scan-tags'.
14336 (declare (special todo-only))
14337 (unless (boundp 'todo-only)
14338 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14339 (unless match
14340 ;; Get a new match request, with completion against the global
14341 ;; tags table and the local tags in current buffer
14342 (let ((org-last-tags-completion-table
14343 (org-uniquify
14344 (delq nil (append (org-get-buffer-tags)
14345 (org-global-tags-completion-table))))))
14346 (setq match (org-completing-read-no-i
14347 "Match: " 'org-tags-completion-function nil nil nil
14348 'org-tags-history))))
14350 ;; Parse the string and create a lisp form
14351 (let ((match0 match)
14352 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14353 minus tag mm
14354 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14355 orterms term orlist re-p str-p level-p level-op time-p
14356 prop-p pn pv po gv rest (start 0) (ss 0))
14357 ;; Expand group tags
14358 (setq match (org-tags-expand match))
14360 ;; Check if there is a TODO part of this match, which would be the
14361 ;; part after a "/". TO make sure that this slash is not part of
14362 ;; a property value to be matched against, we also check that there
14363 ;; is no " after that slash.
14364 ;; First, find the last slash
14365 (while (string-match "/+" match ss)
14366 (setq start (match-beginning 0) ss (match-end 0)))
14367 (if (and (string-match "/+" match start)
14368 (not (save-match-data (string-match "\"" match start))))
14369 ;; match contains also a todo-matching request
14370 (progn
14371 (setq tagsmatch (substring match 0 (match-beginning 0))
14372 todomatch (substring match (match-end 0)))
14373 (if (string-match "^!" todomatch)
14374 (setq todo-only t todomatch (substring todomatch 1)))
14375 (if (string-match "^\\s-*$" todomatch)
14376 (setq todomatch nil)))
14377 ;; only matching tags
14378 (setq tagsmatch match todomatch nil))
14380 ;; Make the tags matcher
14381 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14382 (setq tagsmatcher t)
14383 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14384 (while (setq term (pop orterms))
14385 (while (and (equal (substring term -1) "\\") orterms)
14386 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14387 (while (string-match re term)
14388 (setq rest (substring term (match-end 0))
14389 minus (and (match-end 1)
14390 (equal (match-string 1 term) "-"))
14391 tag (save-match-data (replace-regexp-in-string
14392 "\\\\-" "-"
14393 (match-string 2 term)))
14394 re-p (equal (string-to-char tag) ?{)
14395 level-p (match-end 4)
14396 prop-p (match-end 5)
14397 mm (cond
14398 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14399 (level-p
14400 (setq level-op (org-op-to-function (match-string 3 term)))
14401 `(,level-op level ,(string-to-number
14402 (match-string 4 term))))
14403 (prop-p
14404 (setq pn (match-string 5 term)
14405 po (match-string 6 term)
14406 pv (match-string 7 term)
14407 re-p (equal (string-to-char pv) ?{)
14408 str-p (equal (string-to-char pv) ?\")
14409 time-p (save-match-data
14410 (string-match "^\"[[<].*[]>]\"$" pv))
14411 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14412 (if time-p (setq pv (org-matcher-time pv)))
14413 (setq po (org-op-to-function po (if time-p 'time str-p)))
14414 (cond
14415 ((equal pn "CATEGORY")
14416 (setq gv '(get-text-property (point) 'org-category)))
14417 ((equal pn "TODO")
14418 (setq gv 'todo))
14420 (setq gv `(org-cached-entry-get nil ,pn))))
14421 (if re-p
14422 (if (eq po 'org<>)
14423 `(not (string-match ,pv (or ,gv "")))
14424 `(string-match ,pv (or ,gv "")))
14425 (if str-p
14426 `(,po (or ,gv "") ,pv)
14427 `(,po (string-to-number (or ,gv ""))
14428 ,(string-to-number pv) ))))
14429 (t `(member ,tag tags-list)))
14430 mm (if minus (list 'not mm) mm)
14431 term rest)
14432 (push mm tagsmatcher))
14433 (push (if (> (length tagsmatcher) 1)
14434 (cons 'and tagsmatcher)
14435 (car tagsmatcher))
14436 orlist)
14437 (setq tagsmatcher nil))
14438 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14439 (setq tagsmatcher
14440 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14441 ;; Make the todo matcher
14442 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14443 (setq todomatcher t)
14444 (setq orterms (org-split-string todomatch "|") orlist nil)
14445 (while (setq term (pop orterms))
14446 (while (string-match re term)
14447 (setq minus (and (match-end 1)
14448 (equal (match-string 1 term) "-"))
14449 kwd (match-string 2 term)
14450 re-p (equal (string-to-char kwd) ?{)
14451 term (substring term (match-end 0))
14452 mm (if re-p
14453 `(string-match ,(substring kwd 1 -1) todo)
14454 (list 'equal 'todo kwd))
14455 mm (if minus (list 'not mm) mm))
14456 (push mm todomatcher))
14457 (push (if (> (length todomatcher) 1)
14458 (cons 'and todomatcher)
14459 (car todomatcher))
14460 orlist)
14461 (setq todomatcher nil))
14462 (setq todomatcher (if (> (length orlist) 1)
14463 (cons 'or orlist) (car orlist))))
14465 ;; Return the string and lisp forms of the matcher
14466 (setq matcher (if todomatcher
14467 (list 'and tagsmatcher todomatcher)
14468 tagsmatcher))
14469 (when todo-only
14470 (setq matcher (list 'and '(member todo org-not-done-keywords)
14471 matcher)))
14472 (cons match0 matcher)))
14474 (defun org-tags-expand (match &optional single-as-list downcased)
14475 "Expand group tags in MATCH.
14477 This replaces every group tag in MATCH with a regexp tag search.
14478 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14479 will be replaced like this:
14481 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14482 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14483 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14485 Replacing by a regexp preserves the structure of the match.
14486 E.g., this expansion
14488 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14490 will match anything tagged with \"Lab\" and \"Home\", or tagged
14491 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14493 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14494 assumed to be a single group tag, and the function will return
14495 the list of tags in this group.
14497 When DOWNCASE is non-nil, expand downcased TAGS."
14498 (if org-group-tags
14499 (let* ((case-fold-search t)
14500 (stable org-mode-syntax-table)
14501 (tal (or org-tag-groups-alist-for-agenda
14502 org-tag-groups-alist))
14503 (tal (if downcased
14504 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14505 (tml (mapcar 'car tal))
14506 (rtnmatch match) rpl)
14507 ;; @ and _ are allowed as word-components in tags
14508 (modify-syntax-entry ?@ "w" stable)
14509 (modify-syntax-entry ?_ "w" stable)
14510 (while (and tml
14511 (with-syntax-table stable
14512 (string-match
14513 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14514 (regexp-opt tml) "\\>\\)") rtnmatch)))
14515 (let* ((dir (match-string 1 rtnmatch))
14516 (tag (match-string 2 rtnmatch))
14517 (tag (if downcased (downcase tag) tag)))
14518 (setq tml (delete tag tml))
14519 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14520 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14521 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14522 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14523 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14524 (if single-as-list
14525 (or (reverse rpl) (list rtnmatch))
14526 rtnmatch))
14527 (if single-as-list (list (if downcased (downcase match) match))
14528 match)))
14530 (defun org-op-to-function (op &optional stringp)
14531 "Turn an operator into the appropriate function."
14532 (setq op
14533 (cond
14534 ((equal op "<" ) '(< string< org-time<))
14535 ((equal op ">" ) '(> org-string> org-time>))
14536 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14537 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14538 ((member op '("=" "==")) '(= string= org-time=))
14539 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14540 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14542 (defun org<> (a b) (not (= a b)))
14543 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14544 (defun org-string>= (a b) (not (string< a b)))
14545 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14546 (defun org-string<> (a b) (not (string= a b)))
14547 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14548 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14549 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14550 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14551 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14552 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14553 (defun org-2ft (s)
14554 "Convert S to a floating point time.
14555 If S is already a number, just return it. If it is a string, parse
14556 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14557 (cond
14558 ((numberp s) s)
14559 ((stringp s)
14560 (condition-case nil
14561 (float-time (apply 'encode-time (org-parse-time-string s)))
14562 (error 0.)))
14563 (t 0.)))
14565 (defun org-time-today ()
14566 "Time in seconds today at 0:00.
14567 Returns the float number of seconds since the beginning of the
14568 epoch to the beginning of today (00:00)."
14569 (float-time (apply 'encode-time
14570 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14572 (defun org-matcher-time (s)
14573 "Interpret a time comparison value."
14574 (save-match-data
14575 (cond
14576 ((string= s "<now>") (float-time))
14577 ((string= s "<today>") (org-time-today))
14578 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14579 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14580 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14581 (+ (org-time-today)
14582 (* (string-to-number (match-string 1 s))
14583 (cdr (assoc (match-string 2 s)
14584 '(("d" . 86400.0) ("w" . 604800.0)
14585 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14586 (t (org-2ft s)))))
14588 (defun org-match-any-p (re list)
14589 "Does re match any element of list?"
14590 (setq list (mapcar (lambda (x) (string-match re x)) list))
14591 (delq nil list))
14593 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14594 (defvar org-tags-overlay (make-overlay 1 1))
14595 (org-detach-overlay org-tags-overlay)
14597 (defun org-get-local-tags-at (&optional pos)
14598 "Get a list of tags defined in the current headline."
14599 (org-get-tags-at pos 'local))
14601 (defun org-get-local-tags ()
14602 "Get a list of tags defined in the current headline."
14603 (org-get-tags-at nil 'local))
14605 (defun org-get-tags-at (&optional pos local)
14606 "Get a list of all headline tags applicable at POS.
14607 POS defaults to point. If tags are inherited, the list contains
14608 the targets in the same sequence as the headlines appear, i.e.
14609 the tags of the current headline come last.
14610 When LOCAL is non-nil, only return tags from the current headline,
14611 ignore inherited ones."
14612 (interactive)
14613 (if (and org-trust-scanner-tags
14614 (or (not pos) (equal pos (point)))
14615 (not local))
14616 org-scanner-tags
14617 (let (tags ltags lastpos parent)
14618 (save-excursion
14619 (save-restriction
14620 (widen)
14621 (goto-char (or pos (point)))
14622 (save-match-data
14623 (catch 'done
14624 (condition-case nil
14625 (progn
14626 (org-back-to-heading t)
14627 (while (not (equal lastpos (point)))
14628 (setq lastpos (point))
14629 (when (looking-at
14630 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14631 (setq ltags (org-split-string
14632 (org-match-string-no-properties 1) ":"))
14633 (when parent
14634 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14635 (setq tags (append
14636 (if parent
14637 (org-remove-uninherited-tags ltags)
14638 ltags)
14639 tags)))
14640 (or org-use-tag-inheritance (throw 'done t))
14641 (if local (throw 'done t))
14642 (or (org-up-heading-safe) (error nil))
14643 (setq parent t)))
14644 (error nil)))))
14645 (if local
14646 tags
14647 (reverse (delete-dups
14648 (reverse (append
14649 (org-remove-uninherited-tags
14650 org-file-tags) tags)))))))))
14652 (defun org-add-prop-inherited (s)
14653 (add-text-properties 0 (length s) '(inherited t) s)
14656 (defun org-toggle-tag (tag &optional onoff)
14657 "Toggle the tag TAG for the current line.
14658 If ONOFF is `on' or `off', don't toggle but set to this state."
14659 (let (res current)
14660 (save-excursion
14661 (org-back-to-heading t)
14662 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14663 (point-at-eol) t)
14664 (progn
14665 (setq current (match-string 1))
14666 (replace-match ""))
14667 (setq current ""))
14668 (setq current (nreverse (org-split-string current ":")))
14669 (cond
14670 ((eq onoff 'on)
14671 (setq res t)
14672 (or (member tag current) (push tag current)))
14673 ((eq onoff 'off)
14674 (or (not (member tag current)) (setq current (delete tag current))))
14675 (t (if (member tag current)
14676 (setq current (delete tag current))
14677 (setq res t)
14678 (push tag current))))
14679 (end-of-line 1)
14680 (if current
14681 (progn
14682 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14683 (org-set-tags nil t))
14684 (delete-horizontal-space))
14685 (run-hooks 'org-after-tags-change-hook))
14686 res))
14688 (defun org-align-tags-here (to-col)
14689 ;; Assumes that this is a headline
14690 "Align tags on the current headline to TO-COL."
14691 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14692 (beginning-of-line 1)
14693 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14694 (< pos (match-beginning 2)))
14695 (progn
14696 (setq tags-l (- (match-end 2) (match-beginning 2)))
14697 (goto-char (match-beginning 1))
14698 (insert " ")
14699 (delete-region (point) (1+ (match-beginning 2)))
14700 (setq ncol (max (current-column)
14701 (1+ col)
14702 (if (> to-col 0)
14703 to-col
14704 (- (abs to-col) tags-l))))
14705 (setq p (point))
14706 (insert (make-string (- ncol (current-column)) ?\ ))
14707 (setq ncol (current-column))
14708 (when indent-tabs-mode (tabify p (point-at-eol)))
14709 (org-move-to-column (min ncol col)))
14710 (goto-char pos))))
14712 (defun org-set-tags-command (&optional arg just-align)
14713 "Call the set-tags command for the current entry."
14714 (interactive "P")
14715 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14716 (org-set-tags arg just-align)
14717 (save-excursion
14718 (unless (and (org-region-active-p)
14719 org-loop-over-headlines-in-active-region)
14720 (org-back-to-heading t))
14721 (org-set-tags arg just-align))))
14723 (defun org-set-tags-to (data)
14724 "Set the tags of the current entry to DATA, replacing the current tags.
14725 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14726 If DATA is nil or the empty string, any tags will be removed."
14727 (interactive "sTags: ")
14728 (setq data
14729 (cond
14730 ((eq data nil) "")
14731 ((equal data "") "")
14732 ((stringp data)
14733 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14734 ":"))
14735 ((listp data)
14736 (concat ":" (mapconcat 'identity data ":") ":"))))
14737 (when data
14738 (save-excursion
14739 (org-back-to-heading t)
14740 (when (looking-at org-complex-heading-regexp)
14741 (if (match-end 5)
14742 (progn
14743 (goto-char (match-beginning 5))
14744 (insert data)
14745 (delete-region (point) (point-at-eol))
14746 (org-set-tags nil 'align))
14747 (goto-char (point-at-eol))
14748 (insert " " data)
14749 (org-set-tags nil 'align)))
14750 (beginning-of-line 1)
14751 (if (looking-at ".*?\\([ \t]+\\)$")
14752 (delete-region (match-beginning 1) (match-end 1))))))
14754 (defun org-align-all-tags ()
14755 "Align the tags i all headings."
14756 (interactive)
14757 (save-excursion
14758 (or (ignore-errors (org-back-to-heading t))
14759 (outline-next-heading))
14760 (if (org-at-heading-p)
14761 (org-set-tags t)
14762 (message "No headings"))))
14764 (defvar org-indent-indentation-per-level)
14765 (defun org-set-tags (&optional arg just-align)
14766 "Set the tags for the current headline.
14767 With prefix ARG, realign all tags in headings in the current buffer.
14768 When JUST-ALIGN is non-nil, only align tags."
14769 (interactive "P")
14770 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14771 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14772 'region-start-level 'region))
14773 org-loop-over-headlines-in-active-region)
14774 (org-map-entries
14775 ;; We don't use ARG and JUST-ALIGN here because these args
14776 ;; are not useful when looping over headlines.
14777 `(org-set-tags)
14778 org-loop-over-headlines-in-active-region
14779 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14780 (let* ((re org-outline-regexp-bol)
14781 (current (unless arg (org-get-tags-string)))
14782 (col (current-column))
14783 (org-setting-tags t)
14784 table current-tags inherited-tags ; computed below when needed
14785 tags p0 c0 c1 rpl di tc level)
14786 (if arg
14787 (save-excursion
14788 (goto-char (point-min))
14789 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14790 (while (re-search-forward re nil t)
14791 (org-set-tags nil t)
14792 (end-of-line 1)))
14793 (message "All tags realigned to column %d" org-tags-column))
14794 (if just-align
14795 (setq tags current)
14796 ;; Get a new set of tags from the user
14797 (save-excursion
14798 (setq table (append org-tag-persistent-alist
14799 (or org-tag-alist (org-get-buffer-tags))
14800 (and
14801 org-complete-tags-always-offer-all-agenda-tags
14802 (org-global-tags-completion-table
14803 (org-agenda-files))))
14804 org-last-tags-completion-table table
14805 current-tags (org-split-string current ":")
14806 inherited-tags (nreverse
14807 (nthcdr (length current-tags)
14808 (nreverse (org-get-tags-at))))
14809 tags
14810 (if (or (eq t org-use-fast-tag-selection)
14811 (and org-use-fast-tag-selection
14812 (delq nil (mapcar 'cdr table))))
14813 (org-fast-tag-selection
14814 current-tags inherited-tags table
14815 (if org-fast-tag-selection-include-todo
14816 org-todo-key-alist))
14817 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14818 (org-trim
14819 (org-icompleting-read "Tags: "
14820 'org-tags-completion-function
14821 nil nil current 'org-tags-history))))))
14822 (while (string-match "[-+&]+" tags)
14823 ;; No boolean logic, just a list
14824 (setq tags (replace-match ":" t t tags))))
14826 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14828 (if org-tags-sort-function
14829 (setq tags (mapconcat 'identity
14830 (sort (org-split-string
14831 tags (org-re "[^[:alnum:]_@#%]+"))
14832 org-tags-sort-function) ":")))
14834 (if (string-match "\\`[\t ]*\\'" tags)
14835 (setq tags "")
14836 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14837 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14839 ;; Insert new tags at the correct column
14840 (beginning-of-line 1)
14841 (setq level (or (and (looking-at org-outline-regexp)
14842 (- (match-end 0) (point) 1))
14844 (cond
14845 ((and (equal current "") (equal tags "")))
14846 ((re-search-forward
14847 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14848 (point-at-eol) t)
14849 (if (equal tags "")
14850 (setq rpl "")
14851 (goto-char (match-beginning 0))
14852 (setq c0 (current-column)
14853 ;; compute offset for the case of org-indent-mode active
14854 di (if (org-bound-and-true-p org-indent-mode)
14855 (* (1- org-indent-indentation-per-level) (1- level))
14857 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14858 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14859 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14860 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14861 (replace-match rpl t t)
14862 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14863 tags)
14864 (t (error "Tags alignment failed")))
14865 (org-move-to-column col)
14866 (unless just-align
14867 (run-hooks 'org-after-tags-change-hook))))))
14869 (defun org-change-tag-in-region (beg end tag off)
14870 "Add or remove TAG for each entry in the region.
14871 This works in the agenda, and also in an org-mode buffer."
14872 (interactive
14873 (list (region-beginning) (region-end)
14874 (let ((org-last-tags-completion-table
14875 (if (derived-mode-p 'org-mode)
14876 (org-uniquify
14877 (delq nil (append (org-get-buffer-tags)
14878 (org-global-tags-completion-table))))
14879 (org-global-tags-completion-table))))
14880 (org-icompleting-read
14881 "Tag: " 'org-tags-completion-function nil nil nil
14882 'org-tags-history))
14883 (progn
14884 (message "[s]et or [r]emove? ")
14885 (equal (read-char-exclusive) ?r))))
14886 (if (fboundp 'deactivate-mark) (deactivate-mark))
14887 (let ((agendap (equal major-mode 'org-agenda-mode))
14888 l1 l2 m buf pos newhead (cnt 0))
14889 (goto-char end)
14890 (setq l2 (1- (org-current-line)))
14891 (goto-char beg)
14892 (setq l1 (org-current-line))
14893 (loop for l from l1 to l2 do
14894 (org-goto-line l)
14895 (setq m (get-text-property (point) 'org-hd-marker))
14896 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14897 (and agendap m))
14898 (setq buf (if agendap (marker-buffer m) (current-buffer))
14899 pos (if agendap m (point)))
14900 (with-current-buffer buf
14901 (save-excursion
14902 (save-restriction
14903 (goto-char pos)
14904 (setq cnt (1+ cnt))
14905 (org-toggle-tag tag (if off 'off 'on))
14906 (setq newhead (org-get-heading)))))
14907 (and agendap (org-agenda-change-all-lines newhead m))))
14908 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14910 (defun org-tags-completion-function (string predicate &optional flag)
14911 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14912 (confirm (lambda (x) (stringp (car x)))))
14913 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14914 (setq s1 (match-string 1 string)
14915 s2 (match-string 2 string))
14916 (setq s1 "" s2 string))
14917 (cond
14918 ((eq flag nil)
14919 ;; try completion
14920 (setq rtn (try-completion s2 ctable confirm))
14921 (if (stringp rtn)
14922 (setq rtn
14923 (concat s1 s2 (substring rtn (length s2))
14924 (if (and org-add-colon-after-tag-completion
14925 (assoc rtn ctable))
14926 ":" ""))))
14927 rtn)
14928 ((eq flag t)
14929 ;; all-completions
14930 (all-completions s2 ctable confirm))
14931 ((eq flag 'lambda)
14932 ;; exact match?
14933 (assoc s2 ctable)))))
14935 (defun org-fast-tag-insert (kwd tags face &optional end)
14936 "Insert KDW, and the TAGS, the latter with face FACE.
14937 Also insert END."
14938 (insert (format "%-12s" (concat kwd ":"))
14939 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14940 (or end "")))
14942 (defun org-fast-tag-show-exit (flag)
14943 (save-excursion
14944 (org-goto-line 3)
14945 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14946 (replace-match ""))
14947 (when flag
14948 (end-of-line 1)
14949 (org-move-to-column (- (window-width) 19) t)
14950 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14952 (defun org-set-current-tags-overlay (current prefix)
14953 "Add an overlay to CURRENT tag with PREFIX."
14954 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14955 (if (featurep 'xemacs)
14956 (org-overlay-display org-tags-overlay (concat prefix s)
14957 'secondary-selection)
14958 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14959 (org-overlay-display org-tags-overlay (concat prefix s)))))
14961 (defvar org-last-tag-selection-key nil)
14962 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14963 "Fast tag selection with single keys.
14964 CURRENT is the current list of tags in the headline, INHERITED is the
14965 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14966 possibly with grouping information. TODO-TABLE is a similar table with
14967 TODO keywords, should these have keys assigned to them.
14968 If the keys are nil, a-z are automatically assigned.
14969 Returns the new tags string, or nil to not change the current settings."
14970 (let* ((fulltable (append table todo-table))
14971 (maxlen (apply 'max (mapcar
14972 (lambda (x)
14973 (if (stringp (car x)) (string-width (car x)) 0))
14974 fulltable)))
14975 (buf (current-buffer))
14976 (expert (eq org-fast-tag-selection-single-key 'expert))
14977 (buffer-tags nil)
14978 (fwidth (+ maxlen 3 1 3))
14979 (ncol (/ (- (window-width) 4) fwidth))
14980 (i-face 'org-done)
14981 (c-face 'org-todo)
14982 tg cnt e c char c1 c2 ntable tbl rtn
14983 ov-start ov-end ov-prefix
14984 (exit-after-next org-fast-tag-selection-single-key)
14985 (done-keywords org-done-keywords)
14986 groups ingroup)
14987 (save-excursion
14988 (beginning-of-line 1)
14989 (if (looking-at
14990 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14991 (setq ov-start (match-beginning 1)
14992 ov-end (match-end 1)
14993 ov-prefix "")
14994 (setq ov-start (1- (point-at-eol))
14995 ov-end (1+ ov-start))
14996 (skip-chars-forward "^\n\r")
14997 (setq ov-prefix
14998 (concat
14999 (buffer-substring (1- (point)) (point))
15000 (if (> (current-column) org-tags-column)
15002 (make-string (- org-tags-column (current-column)) ?\ ))))))
15003 (move-overlay org-tags-overlay ov-start ov-end)
15004 (save-window-excursion
15005 (if expert
15006 (set-buffer (get-buffer-create " *Org tags*"))
15007 (delete-other-windows)
15008 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15009 (org-switch-to-buffer-other-window " *Org tags*"))
15010 (erase-buffer)
15011 (org-set-local 'org-done-keywords done-keywords)
15012 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15013 (org-fast-tag-insert "Current" current c-face "\n\n")
15014 (org-fast-tag-show-exit exit-after-next)
15015 (org-set-current-tags-overlay current ov-prefix)
15016 (setq tbl fulltable char ?a cnt 0)
15017 (while (setq e (pop tbl))
15018 (cond
15019 ((equal (car e) :startgroup)
15020 (push '() groups) (setq ingroup t)
15021 (when (not (= cnt 0))
15022 (setq cnt 0)
15023 (insert "\n"))
15024 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15025 ((equal (car e) :endgroup)
15026 (setq ingroup nil cnt 0)
15027 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15028 ((equal e '(:newline))
15029 (when (not (= cnt 0))
15030 (setq cnt 0)
15031 (insert "\n")
15032 (setq e (car tbl))
15033 (while (equal (car tbl) '(:newline))
15034 (insert "\n")
15035 (setq tbl (cdr tbl)))))
15036 ((equal e '(:grouptags)) nil)
15038 (setq tg (copy-sequence (car e)) c2 nil)
15039 (if (cdr e)
15040 (setq c (cdr e))
15041 ;; automatically assign a character.
15042 (setq c1 (string-to-char
15043 (downcase (substring
15044 tg (if (= (string-to-char tg) ?@) 1 0)))))
15045 (if (or (rassoc c1 ntable) (rassoc c1 table))
15046 (while (or (rassoc char ntable) (rassoc char table))
15047 (setq char (1+ char)))
15048 (setq c2 c1))
15049 (setq c (or c2 char)))
15050 (if ingroup (push tg (car groups)))
15051 (setq tg (org-add-props tg nil 'face
15052 (cond
15053 ((not (assoc tg table))
15054 (org-get-todo-face tg))
15055 ((member tg current) c-face)
15056 ((member tg inherited) i-face))))
15057 (if (equal (caar tbl) :grouptags)
15058 (org-add-props tg nil 'face 'org-tag-group))
15059 (if (and (= cnt 0) (not ingroup)) (insert " "))
15060 (insert "[" c "] " tg (make-string
15061 (- fwidth 4 (length tg)) ?\ ))
15062 (push (cons tg c) ntable)
15063 (when (= (setq cnt (1+ cnt)) ncol)
15064 (insert "\n")
15065 (if ingroup (insert " "))
15066 (setq cnt 0)))))
15067 (setq ntable (nreverse ntable))
15068 (insert "\n")
15069 (goto-char (point-min))
15070 (if (not expert) (org-fit-window-to-buffer))
15071 (setq rtn
15072 (catch 'exit
15073 (while t
15074 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15075 (if (not groups) "no " "")
15076 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15077 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15078 (setq org-last-tag-selection-key c)
15079 (cond
15080 ((= c ?\r) (throw 'exit t))
15081 ((= c ?!)
15082 (setq groups (not groups))
15083 (goto-char (point-min))
15084 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15085 ((= c ?\C-c)
15086 (if (not expert)
15087 (org-fast-tag-show-exit
15088 (setq exit-after-next (not exit-after-next)))
15089 (setq expert nil)
15090 (delete-other-windows)
15091 (set-window-buffer (split-window-vertically) " *Org tags*")
15092 (org-switch-to-buffer-other-window " *Org tags*")
15093 (org-fit-window-to-buffer)))
15094 ((or (= c ?\C-g)
15095 (and (= c ?q) (not (rassoc c ntable))))
15096 (org-detach-overlay org-tags-overlay)
15097 (setq quit-flag t))
15098 ((= c ?\ )
15099 (setq current nil)
15100 (if exit-after-next (setq exit-after-next 'now)))
15101 ((= c ?\t)
15102 (condition-case nil
15103 (setq tg (org-icompleting-read
15104 "Tag: "
15105 (or buffer-tags
15106 (with-current-buffer buf
15107 (org-get-buffer-tags)))))
15108 (quit (setq tg "")))
15109 (when (string-match "\\S-" tg)
15110 (add-to-list 'buffer-tags (list tg))
15111 (if (member tg current)
15112 (setq current (delete tg current))
15113 (push tg current)))
15114 (if exit-after-next (setq exit-after-next 'now)))
15115 ((setq e (rassoc c todo-table) tg (car e))
15116 (with-current-buffer buf
15117 (save-excursion (org-todo tg)))
15118 (if exit-after-next (setq exit-after-next 'now)))
15119 ((setq e (rassoc c ntable) tg (car e))
15120 (if (member tg current)
15121 (setq current (delete tg current))
15122 (loop for g in groups do
15123 (if (member tg g)
15124 (mapc (lambda (x)
15125 (setq current (delete x current)))
15126 g)))
15127 (push tg current))
15128 (if exit-after-next (setq exit-after-next 'now))))
15130 ;; Create a sorted list
15131 (setq current
15132 (sort current
15133 (lambda (a b)
15134 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15135 (if (eq exit-after-next 'now) (throw 'exit t))
15136 (goto-char (point-min))
15137 (beginning-of-line 2)
15138 (delete-region (point) (point-at-eol))
15139 (org-fast-tag-insert "Current" current c-face)
15140 (org-set-current-tags-overlay current ov-prefix)
15141 (while (re-search-forward
15142 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15143 (setq tg (match-string 1))
15144 (add-text-properties
15145 (match-beginning 1) (match-end 1)
15146 (list 'face
15147 (cond
15148 ((member tg current) c-face)
15149 ((member tg inherited) i-face)
15150 (t (get-text-property (match-beginning 1) 'face))))))
15151 (goto-char (point-min)))))
15152 (org-detach-overlay org-tags-overlay)
15153 (if rtn
15154 (mapconcat 'identity current ":")
15155 nil))))
15157 (defun org-get-tags-string ()
15158 "Get the TAGS string in the current headline."
15159 (unless (org-at-heading-p t)
15160 (user-error "Not on a heading"))
15161 (save-excursion
15162 (beginning-of-line 1)
15163 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15164 (org-match-string-no-properties 1)
15165 "")))
15167 (defun org-get-tags ()
15168 "Get the list of tags specified in the current headline."
15169 (org-split-string (org-get-tags-string) ":"))
15171 (defun org-get-buffer-tags ()
15172 "Get a table of all tags used in the buffer, for completion."
15173 (let (tags)
15174 (save-excursion
15175 (goto-char (point-min))
15176 (while (re-search-forward
15177 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15178 (when (equal (char-after (point-at-bol 0)) ?*)
15179 (mapc (lambda (x) (add-to-list 'tags x))
15180 (org-split-string (org-match-string-no-properties 1) ":")))))
15181 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15182 (mapcar 'list tags)))
15184 ;;;; The mapping API
15186 (defun org-map-entries (func &optional match scope &rest skip)
15187 "Call FUNC at each headline selected by MATCH in SCOPE.
15189 FUNC is a function or a lisp form. The function will be called without
15190 arguments, with the cursor positioned at the beginning of the headline.
15191 The return values of all calls to the function will be collected and
15192 returned as a list.
15194 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15195 does not need to preserve point. After evaluation, the cursor will be
15196 moved to the end of the line (presumably of the headline of the
15197 processed entry) and search continues from there. Under some
15198 circumstances, this may not produce the wanted results. For example,
15199 if you have removed (e.g. archived) the current (sub)tree it could
15200 mean that the next entry will be skipped entirely. In such cases, you
15201 can specify the position from where search should continue by making
15202 FUNC set the variable `org-map-continue-from' to the desired buffer
15203 position.
15205 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15206 Only headlines that are matched by this query will be considered during
15207 the iteration. When MATCH is nil or t, all headlines will be
15208 visited by the iteration.
15210 SCOPE determines the scope of this command. It can be any of:
15212 nil The current buffer, respecting the restriction if any
15213 tree The subtree started with the entry at point
15214 region The entries within the active region, if any
15215 region-start-level
15216 The entries within the active region, but only those at
15217 the same level than the first one.
15218 file The current buffer, without restriction
15219 file-with-archives
15220 The current buffer, and any archives associated with it
15221 agenda All agenda files
15222 agenda-with-archives
15223 All agenda files with any archive files associated with them
15224 \(file1 file2 ...)
15225 If this is a list, all files in the list will be scanned
15227 The remaining args are treated as settings for the skipping facilities of
15228 the scanner. The following items can be given here:
15230 archive skip trees with the archive tag
15231 comment skip trees with the COMMENT keyword
15232 function or Emacs Lisp form:
15233 will be used as value for `org-agenda-skip-function', so
15234 whenever the function returns a position, FUNC will not be
15235 called for that entry and search will continue from the
15236 position returned
15238 If your function needs to retrieve the tags including inherited tags
15239 at the *current* entry, you can use the value of the variable
15240 `org-scanner-tags' which will be much faster than getting the value
15241 with `org-get-tags-at'. If your function gets properties with
15242 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15243 to t around the call to `org-entry-properties' to get the same speedup.
15244 Note that if your function moves around to retrieve tags and properties at
15245 a *different* entry, you cannot use these techniques."
15246 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15247 (not (org-region-active-p)))
15248 (let* ((org-agenda-archives-mode nil) ; just to make sure
15249 (org-agenda-skip-archived-trees (memq 'archive skip))
15250 (org-agenda-skip-comment-trees (memq 'comment skip))
15251 (org-agenda-skip-function
15252 (car (org-delete-all '(comment archive) skip)))
15253 (org-tags-match-list-sublevels t)
15254 (start-level (eq scope 'region-start-level))
15255 matcher file res
15256 org-todo-keywords-for-agenda
15257 org-done-keywords-for-agenda
15258 org-todo-keyword-alist-for-agenda
15259 org-tag-alist-for-agenda
15260 todo-only)
15262 (cond
15263 ((eq match t) (setq matcher t))
15264 ((eq match nil) (setq matcher t))
15265 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15267 (save-excursion
15268 (save-restriction
15269 (cond ((eq scope 'tree)
15270 (org-back-to-heading t)
15271 (org-narrow-to-subtree)
15272 (setq scope nil))
15273 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15274 (org-region-active-p))
15275 ;; If needed, set start-level to a string like "2"
15276 (when start-level
15277 (save-excursion
15278 (goto-char (region-beginning))
15279 (unless (org-at-heading-p) (outline-next-heading))
15280 (setq start-level (org-current-level))))
15281 (narrow-to-region (region-beginning)
15282 (save-excursion
15283 (goto-char (region-end))
15284 (unless (and (bolp) (org-at-heading-p))
15285 (outline-next-heading))
15286 (point)))
15287 (setq scope nil)))
15289 (if (not scope)
15290 (progn
15291 (org-agenda-prepare-buffers
15292 (list (buffer-file-name (current-buffer))))
15293 (setq res (org-scan-tags func matcher todo-only start-level)))
15294 ;; Get the right scope
15295 (cond
15296 ((and scope (listp scope) (symbolp (car scope)))
15297 (setq scope (eval scope)))
15298 ((eq scope 'agenda)
15299 (setq scope (org-agenda-files t)))
15300 ((eq scope 'agenda-with-archives)
15301 (setq scope (org-agenda-files t))
15302 (setq scope (org-add-archive-files scope)))
15303 ((eq scope 'file)
15304 (setq scope (list (buffer-file-name))))
15305 ((eq scope 'file-with-archives)
15306 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15307 (org-agenda-prepare-buffers scope)
15308 (while (setq file (pop scope))
15309 (with-current-buffer (org-find-base-buffer-visiting file)
15310 (save-excursion
15311 (save-restriction
15312 (widen)
15313 (goto-char (point-min))
15314 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15315 res)))
15317 ;;; Properties API
15319 (defconst org-special-properties
15320 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOSED" "PRIORITY"
15321 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15322 "The special properties valid in Org-mode.
15323 These are properties that are not defined in the property drawer,
15324 but in some other way.")
15326 (defconst org-default-properties
15327 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15328 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15329 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15330 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15331 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15332 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15333 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15334 "Some properties that are used by Org mode for various purposes.
15335 Being in this list makes sure that they are offered for completion.")
15337 (defun org--update-property-plist (key val props)
15338 "Associate KEY to VAL in alist PROPS.
15339 Modifications are made by side-effect. Return new alist."
15340 (let* ((appending (string= (substring key -1) "+"))
15341 (key (if appending (substring key 0 -1) key))
15342 (old (assoc-string key props t)))
15343 (if (not old) (cons (cons key val) props)
15344 (setcdr old (if appending (concat (cdr old) " " val) val))
15345 props)))
15347 (defun org-get-property-block (&optional beg force)
15348 "Return the (beg . end) range of the body of the property drawer.
15349 BEG is the beginning of the current subtree, or of the part
15350 before the first headline. If it is not given, it will be found.
15351 If the drawer does not exist, create it if FORCE is non-nil, or
15352 return nil."
15353 (org-with-wide-buffer
15354 (when beg (goto-char beg))
15355 (unless (org-before-first-heading-p)
15356 (let ((beg (cond (beg)
15357 ((or (not (featurep 'org-inlinetask))
15358 (org-inlinetask-in-task-p))
15359 (org-back-to-heading t))
15360 (t (org-with-limited-levels (org-back-to-heading t))))))
15361 (forward-line)
15362 (when (org-looking-at-p org-planning-line-re) (forward-line))
15363 (cond ((looking-at org-property-drawer-re)
15364 (forward-line)
15365 (cons (point) (progn (goto-char (match-end 0))
15366 (line-beginning-position))))
15367 (force
15368 (goto-char beg)
15369 (org-insert-property-drawer)
15370 (let ((pos (save-excursion (search-forward ":END:")
15371 (line-beginning-position))))
15372 (cons pos pos))))))))
15374 (defun org-at-property-p ()
15375 "Non-nil when point is inside a property drawer.
15376 See `org-property-re' for match data, if applicable."
15377 (save-excursion
15378 (beginning-of-line)
15379 (and (looking-at org-property-re)
15380 (let ((property-drawer (save-match-data (org-get-property-block))))
15381 (and property-drawer (< (point) (cdr property-drawer)))))))
15383 (defun org-property-action ()
15384 "Do an action on properties."
15385 (interactive)
15386 (unless (org-at-property-p) (user-error "Not at a property"))
15387 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15388 (let ((c (read-char-exclusive)))
15389 (case c
15390 (?s (call-interactively #'org-set-property))
15391 (?d (call-interactively #'org-delete-property))
15392 (?D (call-interactively #'org-delete-property-globally))
15393 (?c (call-interactively #'org-compute-property-at-point))
15394 (otherwise (user-error "No such property action %c" c)))))
15396 (defun org-inc-effort ()
15397 "Increment the value of the effort property in the current entry."
15398 (interactive)
15399 (org-set-effort nil t))
15401 (defvar org-clock-effort) ; Defined in org-clock.el.
15402 (defvar org-clock-current-task) ; Defined in org-clock.el.
15403 (defun org-set-effort (&optional value increment)
15404 "Set the effort property of the current entry.
15405 With numerical prefix arg, use the nth allowed value, 0 stands for the
15406 10th allowed value.
15408 When INCREMENT is non-nil, set the property to the next allowed value."
15409 (interactive "P")
15410 (if (equal value 0) (setq value 10))
15411 (let* ((completion-ignore-case t)
15412 (prop org-effort-property)
15413 (cur (org-entry-get nil prop))
15414 (allowed (org-property-get-allowed-values nil prop 'table))
15415 (existing (mapcar 'list (org-property-values prop)))
15416 (heading (nth 4 (org-heading-components)))
15418 (val (cond
15419 ((stringp value) value)
15420 ((and allowed (integerp value))
15421 (or (car (nth (1- value) allowed))
15422 (car (org-last allowed))))
15423 ((and allowed increment)
15424 (or (caadr (member (list cur) allowed))
15425 (user-error "Allowed effort values are not set")))
15426 (allowed
15427 (message "Select 1-9,0, [RET%s]: %s"
15428 (if cur (concat "=" cur) "")
15429 (mapconcat 'car allowed " "))
15430 (setq rpl (read-char-exclusive))
15431 (if (equal rpl ?\r)
15433 (setq rpl (- rpl ?0))
15434 (if (equal rpl 0) (setq rpl 10))
15435 (if (and (> rpl 0) (<= rpl (length allowed)))
15436 (car (nth (1- rpl) allowed))
15437 (org-completing-read "Effort: " allowed nil))))
15439 (let (org-completion-use-ido org-completion-use-iswitchb)
15440 (org-completing-read
15441 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15442 (concat "[" cur "]") "")
15443 ": ")
15444 existing nil nil "" nil cur))))))
15445 (unless (equal (org-entry-get nil prop) val)
15446 (org-entry-put nil prop val))
15447 (org-refresh-property
15448 '((effort . identity)
15449 (effort-minutes . org-duration-string-to-minutes))
15450 val)
15451 (when (string= heading org-clock-current-task)
15452 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15453 (org-clock-update-mode-line))
15454 (message "%s is now %s" prop val)))
15456 (defun org-entry-properties (&optional pom which)
15457 "Get all properties of the current entry.
15459 When POM is a buffer position, get all properties from the entry
15460 there instead.
15462 This includes the TODO keyword, the tags, time strings for
15463 deadline, scheduled, and clocking, and any additional properties
15464 defined in the entry.
15466 If WHICH is nil or `all', get all properties. If WHICH is
15467 `special' or `standard', only get that subclass. If WHICH is
15468 a string, only get that property.
15470 Return value is an alist. Keys are properties, as upcased
15471 strings."
15472 (org-with-point-at pom
15473 (when (and (derived-mode-p 'org-mode)
15474 (ignore-errors (org-back-to-heading t)))
15475 (catch 'exit
15476 (let* ((beg (point))
15477 (specific (and (stringp which) (upcase which)))
15478 (which (cond ((not specific) which)
15479 ((member specific org-special-properties) 'special)
15480 (t 'standard)))
15481 props)
15482 ;; Get the special properties, like TODO and TAGS.
15483 (when (memq which '(nil all special))
15484 (when (or (not specific) (string= specific "CLOCKSUM"))
15485 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15486 (when clocksum
15487 (push (cons "CLOCKSUM"
15488 (org-columns-number-to-string
15489 (/ (float clocksum) 60.) 'add_times))
15490 props)))
15491 (when specific (throw 'exit props)))
15492 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15493 (let ((clocksumt (get-text-property (point)
15494 :org-clock-minutes-today)))
15495 (when clocksumt
15496 (push (cons "CLOCKSUM_T"
15497 (org-columns-number-to-string
15498 (/ (float clocksumt) 60.) 'add_times))
15499 props)))
15500 (when specific (throw 'exit props)))
15501 (when (or (not specific) (string= specific "TODO"))
15502 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15503 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15504 (when specific (throw 'exit props)))
15505 (when (or (not specific) (string= specific "PRIORITY"))
15506 (when (looking-at org-priority-regexp)
15507 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15508 (when specific (throw 'exit props)))
15509 (when (or (not specific) (string= specific "FILE"))
15510 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15511 props)
15512 (when specific (throw 'exit props)))
15513 (when (or (not specific) (string= specific "TAGS"))
15514 (let ((value (org-string-nw-p (org-get-tags-string))))
15515 (when value (push (cons "TAGS" value) props)))
15516 (when specific (throw 'exit props)))
15517 (when (or (not specific) (string= specific "ALLTAGS"))
15518 (let ((value (org-get-tags-at)))
15519 (when value
15520 (push (cons "ALLTAGS"
15521 (format ":%s:" (mapconcat #'identity value ":")))
15522 props)))
15523 (when specific (throw 'exit props)))
15524 (when (or (not specific) (string= specific "BLOCKED"))
15525 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15526 (when specific (throw 'exit props)))
15527 (when (or (not specific)
15528 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15529 (forward-line)
15530 (when (org-looking-at-p org-planning-line-re)
15531 (end-of-line)
15532 (let ((bol (line-beginning-position)))
15533 ;; Backward compatibility: time keywords used to be
15534 ;; configurable (before 8.3). Make sure we get the
15535 ;; correct keyword.
15536 (dolist (k (if (not specific)
15537 (list org-closed-string
15538 org-deadline-string
15539 org-scheduled-string)
15540 (list (cond ((string= specific "CLOSED")
15541 org-closed-string)
15542 ((string= specific "DEADLINE")
15543 org-deadline-string)
15544 (t org-scheduled-string)))))
15545 (save-excursion
15546 (when (search-backward k bol t)
15547 (goto-char (match-end 0))
15548 (skip-chars-forward " \t")
15549 (and (looking-at org-ts-regexp-both)
15550 (push (cons specific (match-string 0)) props)))))))
15551 (when specific (throw 'exit props)))
15552 (when (or (not specific)
15553 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15554 (let ((find-ts
15555 (lambda (end ts)
15556 (let ((regexp (if (or (string= specific "TIMESTAMP")
15557 (assoc "TIMESTAMP_IA" ts))
15558 org-ts-regexp
15559 org-ts-regexp-both)))
15560 (catch 'next
15561 (while (re-search-forward regexp end t)
15562 (backward-char)
15563 (let ((object (org-element-context)))
15564 ;; Accept to match timestamps in node
15565 ;; properties, too.
15566 (when (memq (org-element-type object)
15567 '(node-property timestamp))
15568 (let ((type
15569 (org-element-property :type object)))
15570 (cond
15571 ((and (memq type '(active active-range))
15572 (not (equal specific "TIMESTAMP_IA")))
15573 (unless (assoc "TIMESTAMP" ts)
15574 (push (cons "TIMESTAMP"
15575 (org-element-property
15576 :raw-value object))
15578 (when specific (throw 'exit ts))))
15579 ((and (memq type '(inactive inactive-range))
15580 (not (string= specific "TIMESTAMP")))
15581 (unless (assoc "TIMESTAMP_IA" ts)
15582 (push (cons "TIMESTAMP_IA"
15583 (org-element-property
15584 :raw-value object))
15586 (when specific (throw 'exit ts))))))
15587 ;; Both timestamp types are found,
15588 ;; move to next part.
15589 (when (= (length ts) 2) (throw 'next ts)))))
15590 ts)))))
15591 (goto-char beg)
15592 ;; First look for timestamps within headline.
15593 (let ((ts (funcall find-ts (line-end-position) nil)))
15594 (if (= (length ts) 2) (setq props (nconc ts props))
15595 (forward-line)
15596 ;; Then find timestamps in the section, skipping
15597 ;; planning line.
15598 (when (org-looking-at-p org-planning-line-re)
15599 (forward-line))
15600 (let ((end (save-excursion (outline-next-heading))))
15601 (setq props (nconc (funcall find-ts end ts) props))))))))
15602 ;; Get the standard properties, like :PROP:.
15603 (when (memq which '(nil all standard))
15604 ;; If we are looking after a specific property, delegate
15605 ;; to `org-entry-get', which is faster. However, make an
15606 ;; exception for "CATEGORY", since it can be also set
15607 ;; through keywords (i.e. #+CATEGORY).
15608 (if (and specific (not (equal specific "CATEGORY")))
15609 (let ((value (org-entry-get beg specific nil t)))
15610 (throw 'exit (and value (list (cons specific value)))))
15611 (let ((range (org-get-property-block beg)))
15612 (when range
15613 (let ((end (cdr range)) seen-base)
15614 (goto-char (car range))
15615 ;; Unlike to `org--update-property-plist', we
15616 ;; handle the case where base values is found
15617 ;; after its extension. We also forbid standard
15618 ;; properties to be named as special properties.
15619 (while (re-search-forward org-property-re end t)
15620 (let* ((key (upcase (org-match-string-no-properties 2)))
15621 (extendp (org-string-match-p "\\+\\'" key))
15622 (key-base (if extendp (substring key 0 -1) key))
15623 (value (org-match-string-no-properties 3)))
15624 (cond
15625 ((member-ignore-case key-base org-special-properties))
15626 (extendp
15627 (setq props
15628 (org--update-property-plist key value props)))
15629 ((member key seen-base))
15630 (t (push key seen-base)
15631 (let ((p (assoc-string key props t)))
15632 (if p (setcdr p (concat value " " (cdr p)))
15633 (push (cons key value) props))))))))))))
15634 (unless (assoc "CATEGORY" props)
15635 (push (cons "CATEGORY" (org-get-category)) props)
15636 (when (string= specific "CATEGORY") (throw 'exit props)))
15637 ;; Return value.
15638 (append (get-text-property beg 'org-summaries) props))))))
15640 (defun org-entry-get (pom property &optional inherit literal-nil)
15641 "Get value of PROPERTY for entry or content at point-or-marker POM.
15643 If INHERIT is non-nil and the entry does not have the property,
15644 then also check higher levels of the hierarchy. If INHERIT is
15645 the symbol `selective', use inheritance only if the setting in
15646 `org-use-property-inheritance' selects PROPERTY for inheritance.
15648 If the property is present but empty, the return value is the
15649 empty string. If the property is not present at all, nil is
15650 returned. In any other case, return the value as a string.
15651 Search is case-insensitive.
15653 If LITERAL-NIL is set, return the string value \"nil\" as
15654 a string, do not interpret it as the list atom nil. This is used
15655 for inheritance when a \"nil\" value can supersede a non-nil
15656 value higher up the hierarchy."
15657 (org-with-point-at pom
15658 (cond
15659 ((and inherit
15660 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15661 (org-entry-get-with-inheritance property literal-nil))
15662 ((member-ignore-case property org-special-properties)
15663 ;; We need a special property. Use `org-entry-properties' to
15664 ;; retrieve it, but specify the wanted property.
15665 (cdr (assoc-string property (org-entry-properties nil property))))
15667 (let ((range (org-get-property-block)))
15668 (when range
15669 (let* ((case-fold-search t)
15670 (end (cdr range))
15671 (props
15672 (let ((global
15673 (or (assoc-string property org-file-properties t)
15674 (assoc-string property org-global-properties t)
15675 (assoc-string
15676 property org-global-properties-fixed t))))
15677 ;; Make sure to not re-use GLOBAL as
15678 ;; `org--update-property-plist' would alter it by
15679 ;; side-effect.
15680 (and global (list (cons property (cdr global))))))
15681 (find-value
15682 (lambda (key)
15683 (when (re-search-forward (org-re-property key nil t) end t)
15684 (setq props
15685 (org--update-property-plist
15686 key (org-match-string-no-properties 3) props))))))
15687 (goto-char (car range))
15688 ;; Find base value.
15689 (save-excursion (funcall find-value property))
15690 ;; Find additional values.
15691 (let ((property+ (concat property "+")))
15692 (while (funcall find-value property+)))
15693 ;; Return final value.
15694 (let ((val (cdr (assoc-string property props t))))
15695 (if literal-nil val (org-not-nil val))))))))))
15697 (defun org-property-or-variable-value (var &optional inherit)
15698 "Check if there is a property fixing the value of VAR.
15699 If yes, return this value. If not, return the current value of the variable."
15700 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15701 (if (and prop (stringp prop) (string-match "\\S-" prop))
15702 (read prop)
15703 (symbol-value var))))
15705 (defun org-entry-delete (pom property)
15706 "Delete the property PROPERTY from entry at point-or-marker POM."
15707 (unless (member property org-special-properties)
15708 (org-with-point-at pom
15709 (let ((range (org-get-property-block)))
15710 (when range
15711 (let ((begin (car range))
15712 (end (copy-marker (cdr range))))
15713 (goto-char begin)
15714 (when (re-search-forward (org-re-property property nil t) end t)
15715 (delete-region (match-beginning 0) (line-beginning-position 2))
15716 ;; If drawer is empty, remove it altogether.
15717 (when (= begin end)
15718 (delete-region (line-beginning-position 0)
15719 (line-beginning-position 2)))
15720 (set-marker end nil))))))))
15722 ;; Multi-values properties are properties that contain multiple values
15723 ;; These values are assumed to be single words, separated by whitespace.
15724 (defun org-entry-add-to-multivalued-property (pom property value)
15725 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15726 (let* ((old (org-entry-get pom property))
15727 (values (and old (org-split-string old "[ \t]"))))
15728 (setq value (org-entry-protect-space value))
15729 (unless (member value values)
15730 (setq values (append values (list value)))
15731 (org-entry-put pom property
15732 (mapconcat 'identity values " ")))))
15734 (defun org-entry-remove-from-multivalued-property (pom property value)
15735 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15736 (let* ((old (org-entry-get pom property))
15737 (values (and old (org-split-string old "[ \t]"))))
15738 (setq value (org-entry-protect-space value))
15739 (when (member value values)
15740 (setq values (delete value values))
15741 (org-entry-put pom property
15742 (mapconcat 'identity values " ")))))
15744 (defun org-entry-member-in-multivalued-property (pom property value)
15745 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15746 (let* ((old (org-entry-get pom property))
15747 (values (and old (org-split-string old "[ \t]"))))
15748 (setq value (org-entry-protect-space value))
15749 (member value values)))
15751 (defun org-entry-get-multivalued-property (pom property)
15752 "Return a list of values in a multivalued property."
15753 (let* ((value (org-entry-get pom property))
15754 (values (and value (org-split-string value "[ \t]"))))
15755 (mapcar 'org-entry-restore-space values)))
15757 (defun org-entry-put-multivalued-property (pom property &rest values)
15758 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15759 VALUES should be a list of strings. Spaces will be protected."
15760 (org-entry-put pom property
15761 (mapconcat 'org-entry-protect-space values " "))
15762 (let* ((value (org-entry-get pom property))
15763 (values (and value (org-split-string value "[ \t]"))))
15764 (mapcar 'org-entry-restore-space values)))
15766 (defun org-entry-protect-space (s)
15767 "Protect spaces and newline in string S."
15768 (while (string-match " " s)
15769 (setq s (replace-match "%20" t t s)))
15770 (while (string-match "\n" s)
15771 (setq s (replace-match "%0A" t t s)))
15774 (defun org-entry-restore-space (s)
15775 "Restore spaces and newline in string S."
15776 (while (string-match "%20" s)
15777 (setq s (replace-match " " t t s)))
15778 (while (string-match "%0A" s)
15779 (setq s (replace-match "\n" t t s)))
15782 (defvar org-entry-property-inherited-from (make-marker)
15783 "Marker pointing to the entry from where a property was inherited.
15784 Each call to `org-entry-get-with-inheritance' will set this marker to the
15785 location of the entry where the inheritance search matched. If there was
15786 no match, the marker will point nowhere.
15787 Note that also `org-entry-get' calls this function, if the INHERIT flag
15788 is set.")
15790 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15791 "Get PROPERTY of entry or content at point, search higher levels if needed.
15792 The search will stop at the first ancestor which has the property defined.
15793 If the value found is \"nil\", return nil to show that the property
15794 should be considered as undefined (this is the meaning of nil here).
15795 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15796 (move-marker org-entry-property-inherited-from nil)
15797 (let (value)
15798 (org-with-wide-buffer
15799 (catch 'exit
15800 (while t
15801 (when (setq value (org-entry-get nil property nil literal-nil))
15802 (org-back-to-heading t)
15803 (move-marker org-entry-property-inherited-from (point))
15804 (throw 'exit nil))
15805 (or (org-up-heading-safe) (throw 'exit nil)))))
15806 (unless value
15807 (setq value
15808 (cdr (or (assoc-string property org-file-properties t)
15809 (assoc-string property org-global-properties t)
15810 (assoc-string property org-global-properties-fixed t)))))
15811 (if literal-nil value (org-not-nil value))))
15813 (defvar org-property-changed-functions nil
15814 "Hook called when the value of a property has changed.
15815 Each hook function should accept two arguments, the name of the property
15816 and the new value.")
15818 (defun org-entry-put (pom property value)
15819 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15821 If the value is `nil', it is converted to the empty string. If
15822 it is not a string, an error is raised.
15824 PROPERTY can be any regular property (see
15825 `org-special-properties'). It can also be \"TODO\",
15826 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15828 For the last two properties, VALUE may have any of the special
15829 values \"earlier\" and \"later\". The function then increases or
15830 decreases scheduled or deadline date by one day."
15831 (cond ((null value) (setq value ""))
15832 ((not (stringp value)) (error "Properties values should be strings")))
15833 (org-with-point-at pom
15834 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15835 (org-back-to-heading t)
15836 (org-with-limited-levels (org-back-to-heading t)))
15837 (let ((beg (point)))
15838 (cond
15839 ((equal property "TODO")
15840 (cond ((not (org-string-nw-p value)) (setq value 'none))
15841 ((not (member value org-todo-keywords-1))
15842 (user-error "\"%s\" is not a valid TODO state" value)))
15843 (org-todo value)
15844 (org-set-tags nil 'align))
15845 ((equal property "PRIORITY")
15846 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15847 (org-set-tags nil 'align))
15848 ((equal property "SCHEDULED")
15849 (forward-line)
15850 (if (and (org-looking-at-p org-planning-line-re)
15851 (re-search-forward
15852 org-scheduled-time-regexp (line-end-position) t))
15853 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15854 ((string= value "later") (org-timestamp-change 1 'day))
15855 ((string= value "") (org-schedule '(4)))
15856 (t (org-schedule nil value)))
15857 (if (member value '("earlier" "later" ""))
15858 (call-interactively #'org-schedule)
15859 (org-schedule nil value))))
15860 ((equal property "DEADLINE")
15861 (forward-line)
15862 (if (and (org-looking-at-p org-planning-line-re)
15863 (re-search-forward
15864 org-deadline-time-regexp (line-end-position) t))
15865 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15866 ((string= value "later") (org-timestamp-change 1 'day))
15867 ((string= value "") (org-deadline '(4)))
15868 (t (org-deadline nil value)))
15869 (if (member value '("earlier" "later" ""))
15870 (call-interactively #'org-deadline)
15871 (org-deadline nil value))))
15872 ((member property org-special-properties)
15873 (error "The %s property cannot be set with `org-entry-put'" property))
15875 (let* ((range (org-get-property-block beg 'force))
15876 (end (cdr range))
15877 (case-fold-search t))
15878 (goto-char (car range))
15879 (if (re-search-forward (org-re-property property nil t) end t)
15880 (progn (delete-region (match-beginning 0) (match-end 0))
15881 (goto-char (match-beginning 0)))
15882 (goto-char end)
15883 (insert "\n")
15884 (backward-char))
15885 (insert ":" property ":")
15886 (when value (insert " " value))
15887 (org-indent-line)))))
15888 (run-hook-with-args 'org-property-changed-functions property value)))
15890 (defun org-buffer-property-keys (&optional specials defaults columns)
15891 "Get all property keys in the current buffer.
15893 When SPECIALS is non-nil, also list the special properties that
15894 reflect things like tags and TODO state.
15896 When DEFAULTS is non-nil, also include properties that has
15897 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15898 DESCRIPTION, LOCATION, and LOGGING and others.
15900 When COLUMNS in non-nil, also include property names given in
15901 COLUMN formats in the current buffer."
15902 (let ((case-fold-search t)
15903 (props (append
15904 (and specials org-special-properties)
15905 (and defaults (cons org-effort-property org-default-properties))
15906 nil)))
15907 (org-with-wide-buffer
15908 (goto-char (point-min))
15909 (while (re-search-forward org-property-start-re nil t)
15910 (let ((range (org-get-property-block)))
15911 (catch 'skip
15912 (unless range
15913 (when (and (not (org-before-first-heading-p))
15914 (y-or-n-p (format "Malformed drawer at %d, repair?"
15915 (line-beginning-position))))
15916 (org-get-property-block nil t))
15917 (throw 'skip nil))
15918 (goto-char (car range))
15919 (let ((begin (car range))
15920 (end (cdr range)))
15921 ;; Make sure that found property block is not located
15922 ;; before current point, as it would generate an infloop.
15923 ;; It can happen, for example, in the following
15924 ;; situation:
15926 ;; * Headline
15927 ;; :PROPERTIES:
15928 ;; ...
15929 ;; :END:
15930 ;; *************** Inlinetask
15931 ;; #+BEGIN_EXAMPLE
15932 ;; :PROPERTIES:
15933 ;; #+END_EXAMPLE
15935 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
15936 (while (< (point) end)
15937 (let ((p (progn (looking-at org-property-re)
15938 (org-match-string-no-properties 2))))
15939 ;; Only add true property name, not extension symbol.
15940 (add-to-list 'props
15941 (if (not (org-string-match-p "\\+\\'" p)) p
15942 (substring p 0 -1))))
15943 (forward-line))))
15944 (outline-next-heading)))
15945 (when columns
15946 (goto-char (point-min))
15947 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15948 (let ((element (org-element-at-point)))
15949 (when (memq (org-element-type element) '(keyword node-property))
15950 (let ((value (org-element-property :value element))
15951 (start 0))
15952 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
15953 (setq start (match-end 0))
15954 (let ((p (org-match-string-no-properties 1 value)))
15955 (unless (member-ignore-case
15956 p (cons "ITEM" org-special-properties))
15957 (add-to-list 'props p))))))))))
15958 (sort props (lambda (a b) (string< (upcase a) (upcase b))))))
15960 (defun org-property-values (key)
15961 "List all non-nil values of property KEY in current buffer."
15962 (org-with-wide-buffer
15963 (goto-char (point-min))
15964 (let ((case-fold-search t)
15965 (re (org-re-property key))
15966 values)
15967 (while (re-search-forward re nil t)
15968 (add-to-list 'values (org-entry-get (point) key)))
15969 values)))
15971 (defun org-insert-property-drawer ()
15972 "Insert a property drawer into the current entry."
15973 (org-with-wide-buffer
15974 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15975 (org-back-to-heading t)
15976 (org-with-limited-levels (org-back-to-heading t)))
15977 (forward-line)
15978 (when (org-looking-at-p org-planning-line-re) (forward-line))
15979 (unless (org-looking-at-p org-property-drawer-re)
15980 (let ((inhibit-read-only t))
15981 (unless (bolp) (insert "\n"))
15982 (let ((begin (point)))
15983 (insert ":PROPERTIES:\n:END:\n")
15984 (org-indent-region begin (point)))))))
15986 (defun org-insert-drawer (&optional arg drawer)
15987 "Insert a drawer at point.
15989 When optional argument ARG is non-nil, insert a property drawer.
15991 Optional argument DRAWER, when non-nil, is a string representing
15992 drawer's name. Otherwise, the user is prompted for a name.
15994 If a region is active, insert the drawer around that region
15995 instead.
15997 Point is left between drawer's boundaries."
15998 (interactive "P")
15999 (let* ((drawer (if arg "PROPERTIES"
16000 (or drawer (read-from-minibuffer "Drawer: ")))))
16001 (cond
16002 ;; With C-u, fall back on `org-insert-property-drawer'
16003 (arg (org-insert-property-drawer))
16004 ;; Check validity of suggested drawer's name.
16005 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16006 (user-error "Invalid drawer name"))
16007 ;; With an active region, insert a drawer at point.
16008 ((not (org-region-active-p))
16009 (progn
16010 (unless (bolp) (insert "\n"))
16011 (insert (format ":%s:\n\n:END:\n" drawer))
16012 (forward-line -2)))
16013 ;; Otherwise, insert the drawer at point
16015 (let ((rbeg (region-beginning))
16016 (rend (copy-marker (region-end))))
16017 (unwind-protect
16018 (progn
16019 (goto-char rbeg)
16020 (beginning-of-line)
16021 (when (save-excursion
16022 (re-search-forward org-outline-regexp-bol rend t))
16023 (user-error "Drawers cannot contain headlines"))
16024 ;; Position point at the beginning of the first
16025 ;; non-blank line in region. Insert drawer's opening
16026 ;; there, then indent it.
16027 (org-skip-whitespace)
16028 (beginning-of-line)
16029 (insert ":" drawer ":\n")
16030 (forward-line -1)
16031 (indent-for-tab-command)
16032 ;; Move point to the beginning of the first blank line
16033 ;; after the last non-blank line in region. Insert
16034 ;; drawer's closing, then indent it.
16035 (goto-char rend)
16036 (skip-chars-backward " \r\t\n")
16037 (insert "\n:END:")
16038 (deactivate-mark t)
16039 (indent-for-tab-command)
16040 (unless (eolp) (insert "\n")))
16041 ;; Clear marker, whatever the outcome of insertion is.
16042 (set-marker rend nil)))))))
16044 (defvar org-property-set-functions-alist nil
16045 "Property set function alist.
16046 Each entry should have the following format:
16048 (PROPERTY . READ-FUNCTION)
16050 The read function will be called with the same argument as
16051 `org-completing-read'.")
16053 (defun org-set-property-function (property)
16054 "Get the function that should be used to set PROPERTY.
16055 This is computed according to `org-property-set-functions-alist'."
16056 (or (cdr (assoc property org-property-set-functions-alist))
16057 'org-completing-read))
16059 (defun org-read-property-value (property)
16060 "Read PROPERTY value from user."
16061 (let* ((completion-ignore-case t)
16062 (allowed (org-property-get-allowed-values nil property 'table))
16063 (cur (org-entry-get nil property))
16064 (prompt (concat property " value"
16065 (if (and cur (string-match "\\S-" cur))
16066 (concat " [" cur "]") "") ": "))
16067 (set-function (org-set-property-function property))
16068 (val (if allowed
16069 (funcall set-function prompt allowed nil
16070 (not (get-text-property 0 'org-unrestricted
16071 (caar allowed))))
16072 (let (org-completion-use-ido org-completion-use-iswitchb)
16073 (funcall set-function prompt
16074 (mapcar 'list (org-property-values property))
16075 nil nil "" nil cur)))))
16076 (org-trim val)))
16078 (defvar org-last-set-property nil)
16079 (defvar org-last-set-property-value nil)
16080 (defun org-read-property-name ()
16081 "Read a property name."
16082 (let* ((completion-ignore-case t)
16083 (keys (org-buffer-property-keys nil t t))
16084 (default-prop (or (save-excursion
16085 (save-match-data
16086 (beginning-of-line)
16087 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16088 (null (string= (match-string 1) "END"))
16089 (match-string 1))))
16090 org-last-set-property))
16091 (property (org-icompleting-read
16092 (concat "Property"
16093 (if default-prop (concat " [" default-prop "]") "")
16094 ": ")
16095 (mapcar 'list keys)
16096 nil nil nil nil
16097 default-prop)))
16098 (if (member property keys)
16099 property
16100 (or (cdr (assoc (downcase property)
16101 (mapcar (lambda (x) (cons (downcase x) x))
16102 keys)))
16103 property))))
16105 (defun org-set-property-and-value (use-last)
16106 "Allow to set [PROPERTY]: [value] direction from prompt.
16107 When use-default, don't even ask, just use the last
16108 \"[PROPERTY]: [value]\" string from the history."
16109 (interactive "P")
16110 (let* ((completion-ignore-case t)
16111 (pv (or (and use-last org-last-set-property-value)
16112 (org-completing-read
16113 "Enter a \"[Property]: [value]\" pair: "
16114 nil nil nil nil nil
16115 org-last-set-property-value)))
16116 prop val)
16117 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16118 (setq prop (match-string 1 pv)
16119 val (match-string 2 pv))
16120 (org-set-property prop val))))
16122 (defun org-set-property (property value)
16123 "In the current entry, set PROPERTY to VALUE.
16124 When called interactively, this will prompt for a property name, offering
16125 completion on existing and default properties. And then it will prompt
16126 for a value, offering completion either on allowed values (via an inherited
16127 xxx_ALL property) or on existing values in other instances of this property
16128 in the current file."
16129 (interactive (list nil nil))
16130 (let* ((property (or property (org-read-property-name)))
16131 (value (or value (org-read-property-value property)))
16132 (fn (cdr (assoc property org-properties-postprocess-alist))))
16133 (setq org-last-set-property property)
16134 (setq org-last-set-property-value (concat property ": " value))
16135 ;; Possibly postprocess the inserted value:
16136 (when fn (setq value (funcall fn value)))
16137 (unless (equal (org-entry-get nil property) value)
16138 (org-entry-put nil property value))))
16140 (defun org-delete-property (property)
16141 "In the current entry, delete PROPERTY."
16142 (interactive
16143 (let* ((completion-ignore-case t)
16144 (cat (org-entry-get (point) "CATEGORY"))
16145 (props0 (org-entry-properties nil 'standard))
16146 (props (if cat props0
16147 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16148 (prop (if (< 1 (length props))
16149 (org-icompleting-read "Property: " props nil t)
16150 (caar props))))
16151 (list prop)))
16152 (if (not property)
16153 (message "No property to delete in this entry")
16154 (org-entry-delete nil property)
16155 (message "Property \"%s\" deleted" property)))
16157 (defun org-delete-property-globally (property)
16158 "Remove PROPERTY globally, from all entries."
16159 (interactive
16160 (let* ((completion-ignore-case t)
16161 (prop (org-icompleting-read
16162 "Globally remove property: "
16163 (mapcar 'list (org-buffer-property-keys)))))
16164 (list prop)))
16165 (save-excursion
16166 (save-restriction
16167 (widen)
16168 (goto-char (point-min))
16169 (let ((cnt 0))
16170 (while (re-search-forward
16171 (org-re-property property)
16172 nil t)
16173 (setq cnt (1+ cnt))
16174 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16175 (message "Property \"%s\" removed from %d entries" property cnt)))))
16177 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16179 (defun org-compute-property-at-point ()
16180 "Compute the property at point.
16181 This looks for an enclosing column format, extracts the operator and
16182 then applies it to the property in the column format's scope."
16183 (interactive)
16184 (unless (org-at-property-p)
16185 (user-error "Not at a property"))
16186 (let ((prop (org-match-string-no-properties 2)))
16187 (org-columns-get-format-and-top-level)
16188 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16189 (user-error "No operator defined for property %s" prop))
16190 (org-columns-compute prop)))
16192 (defvar org-property-allowed-value-functions nil
16193 "Hook for functions supplying allowed values for a specific property.
16194 The functions must take a single argument, the name of the property, and
16195 return a flat list of allowed values. If \":ETC\" is one of
16196 the values, this means that these values are intended as defaults for
16197 completion, but that other values should be allowed too.
16198 The functions must return nil if they are not responsible for this
16199 property.")
16201 (defun org-property-get-allowed-values (pom property &optional table)
16202 "Get allowed values for the property PROPERTY.
16203 When TABLE is non-nil, return an alist that can directly be used for
16204 completion."
16205 (let (vals)
16206 (cond
16207 ((equal property "TODO")
16208 (setq vals (org-with-point-at pom
16209 (append org-todo-keywords-1 '("")))))
16210 ((equal property "PRIORITY")
16211 (let ((n org-lowest-priority))
16212 (while (>= n org-highest-priority)
16213 (push (char-to-string n) vals)
16214 (setq n (1- n)))))
16215 ((member property org-special-properties))
16216 ((setq vals (run-hook-with-args-until-success
16217 'org-property-allowed-value-functions property)))
16219 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16220 (when (and vals (string-match "\\S-" vals))
16221 (setq vals (car (read-from-string (concat "(" vals ")"))))
16222 (setq vals (mapcar (lambda (x)
16223 (cond ((stringp x) x)
16224 ((numberp x) (number-to-string x))
16225 ((symbolp x) (symbol-name x))
16226 (t "???")))
16227 vals)))))
16228 (when (member ":ETC" vals)
16229 (setq vals (remove ":ETC" vals))
16230 (org-add-props (car vals) '(org-unrestricted t)))
16231 (if table (mapcar 'list vals) vals)))
16233 (defun org-property-previous-allowed-value (&optional previous)
16234 "Switch to the next allowed value for this property."
16235 (interactive)
16236 (org-property-next-allowed-value t))
16238 (defun org-property-next-allowed-value (&optional previous)
16239 "Switch to the next allowed value for this property."
16240 (interactive)
16241 (unless (org-at-property-p)
16242 (user-error "Not at a property"))
16243 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16244 (key (match-string 2))
16245 (value (match-string 3))
16246 (allowed (or (org-property-get-allowed-values (point) key)
16247 (and (member value '("[ ]" "[-]" "[X]"))
16248 '("[ ]" "[X]"))))
16249 (heading (save-match-data (nth 4 (org-heading-components))))
16250 nval)
16251 (unless allowed
16252 (user-error "Allowed values for this property have not been defined"))
16253 (if previous (setq allowed (reverse allowed)))
16254 (if (member value allowed)
16255 (setq nval (car (cdr (member value allowed)))))
16256 (setq nval (or nval (car allowed)))
16257 (if (equal nval value)
16258 (user-error "Only one allowed value for this property"))
16259 (org-at-property-p)
16260 (replace-match (concat " :" key ": " nval) t t)
16261 (org-indent-line)
16262 (beginning-of-line 1)
16263 (skip-chars-forward " \t")
16264 (when (equal prop org-effort-property)
16265 (org-refresh-property
16266 '((effort . identity)
16267 (effort-minutes . org-duration-string-to-minutes))
16268 nval)
16269 (when (string= org-clock-current-task heading)
16270 (setq org-clock-effort nval)
16271 (org-clock-update-mode-line)))
16272 (run-hook-with-args 'org-property-changed-functions key nval)))
16274 (defun org-find-olp (path &optional this-buffer)
16275 "Return a marker pointing to the entry at outline path OLP.
16276 If anything goes wrong, throw an error.
16277 You can wrap this call to catch the error like this:
16279 (condition-case msg
16280 (org-mobile-locate-entry (match-string 4))
16281 (error (nth 1 msg)))
16283 The return value will then be either a string with the error message,
16284 or a marker if everything is OK.
16286 If THIS-BUFFER is set, the outline path does not contain a file,
16287 only headings."
16288 (let* ((file (if this-buffer buffer-file-name (pop path)))
16289 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16290 (level 1)
16291 (lmin 1)
16292 (lmax 1)
16293 limit re end found pos heading cnt flevel)
16294 (unless buffer (error "File not found :%s" file))
16295 (with-current-buffer buffer
16296 (save-excursion
16297 (save-restriction
16298 (widen)
16299 (setq limit (point-max))
16300 (goto-char (point-min))
16301 (while (setq heading (pop path))
16302 (setq re (format org-complex-heading-regexp-format
16303 (regexp-quote heading)))
16304 (setq cnt 0 pos (point))
16305 (while (re-search-forward re end t)
16306 (setq level (- (match-end 1) (match-beginning 1)))
16307 (if (and (>= level lmin) (<= level lmax))
16308 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16309 (when (= cnt 0) (error "Heading not found on level %d: %s"
16310 lmax heading))
16311 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16312 lmax heading))
16313 (goto-char found)
16314 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16315 (setq end (save-excursion (org-end-of-subtree t t))))
16316 (when (org-at-heading-p)
16317 (point-marker)))))))
16319 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16320 "Find node HEADING in BUFFER.
16321 Return a marker to the heading if it was found, or nil if not.
16322 If POS-ONLY is set, return just the position instead of a marker.
16324 The heading text must match exact, but it may have a TODO keyword,
16325 a priority cookie and tags in the standard locations."
16326 (with-current-buffer (or buffer (current-buffer))
16327 (save-excursion
16328 (save-restriction
16329 (widen)
16330 (goto-char (point-min))
16331 (let (case-fold-search)
16332 (if (re-search-forward
16333 (format org-complex-heading-regexp-format
16334 (regexp-quote heading)) nil t)
16335 (if pos-only
16336 (match-beginning 0)
16337 (move-marker (make-marker) (match-beginning 0)))))))))
16339 (defun org-find-exact-heading-in-directory (heading &optional dir)
16340 "Find Org node headline HEADING in all .org files in directory DIR.
16341 When the target headline is found, return a marker to this location."
16342 (let ((files (directory-files (or dir default-directory)
16343 t "\\`[^.#].*\\.org\\'"))
16344 file visiting m buffer)
16345 (catch 'found
16346 (while (setq file (pop files))
16347 (message "trying %s" file)
16348 (setq visiting (org-find-base-buffer-visiting file))
16349 (setq buffer (or visiting (find-file-noselect file)))
16350 (setq m (org-find-exact-headline-in-buffer
16351 heading buffer))
16352 (when (and (not m) (not visiting)) (kill-buffer buffer))
16353 (and m (throw 'found m))))))
16355 (defun org-find-entry-with-id (ident)
16356 "Locate the entry that contains the ID property with exact value IDENT.
16357 IDENT can be a string, a symbol or a number, this function will search for
16358 the string representation of it.
16359 Return the position where this entry starts, or nil if there is no such entry."
16360 (interactive "sID: ")
16361 (let ((id (cond
16362 ((stringp ident) ident)
16363 ((symbol-name ident) (symbol-name ident))
16364 ((numberp ident) (number-to-string ident))
16365 (t (error "IDENT %s must be a string, symbol or number" ident))))
16366 (case-fold-search nil))
16367 (save-excursion
16368 (save-restriction
16369 (widen)
16370 (goto-char (point-min))
16371 (when (re-search-forward
16372 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16373 nil t)
16374 (org-back-to-heading t)
16375 (point))))))
16377 ;;;; Timestamps
16379 (defvar org-last-changed-timestamp nil)
16380 (defvar org-last-inserted-timestamp nil
16381 "The last time stamp inserted with `org-insert-time-stamp'.")
16382 (defvar org-ts-what) ; dynamically scoped parameter
16384 (defun org-time-stamp (arg &optional inactive)
16385 "Prompt for a date/time and insert a time stamp.
16386 If the user specifies a time like HH:MM or if this command is
16387 called with at least one prefix argument, the time stamp contains
16388 the date and the time. Otherwise, only the date is be included.
16390 All parts of a date not specified by the user is filled in from
16391 the current date/time. So if you just press return without
16392 typing anything, the time stamp will represent the current
16393 date/time.
16395 If there is already a timestamp at the cursor, it will be
16396 modified.
16398 With two universal prefix arguments, insert an active timestamp
16399 with the current time without prompting the user.
16401 When called from lisp, the timestamp is inactive if INACTIVE is
16402 non-nil."
16403 (interactive "P")
16404 (let* ((ts nil)
16405 (default-time
16406 ;; Default time is either today, or, when entering a range,
16407 ;; the range start.
16408 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16409 (save-excursion
16410 (re-search-backward
16411 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16412 (- (point) 20) t)))
16413 (apply 'encode-time (org-parse-time-string (match-string 1)))
16414 (current-time)))
16415 (default-input (and ts (org-get-compact-tod ts)))
16416 (repeater (save-excursion
16417 (save-match-data
16418 (beginning-of-line)
16419 (when (re-search-forward
16420 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16421 (save-excursion (progn (end-of-line) (point))) t)
16422 (match-string 0)))))
16423 org-time-was-given org-end-time-was-given time)
16424 (cond
16425 ((and (org-at-timestamp-p t)
16426 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16427 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16428 (insert "--")
16429 (setq time (let ((this-command this-command))
16430 (org-read-date arg 'totime nil nil
16431 default-time default-input inactive)))
16432 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16433 ((org-at-timestamp-p t)
16434 (setq time (let ((this-command this-command))
16435 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16436 (when (org-at-timestamp-p t) ; just to get the match data
16437 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16438 (replace-match "")
16439 (setq org-last-changed-timestamp
16440 (org-insert-time-stamp
16441 time (or org-time-was-given arg)
16442 inactive nil nil (list org-end-time-was-given)))
16443 (when repeater (goto-char (1- (point))) (insert " " repeater)
16444 (setq org-last-changed-timestamp
16445 (concat (substring org-last-inserted-timestamp 0 -1)
16446 " " repeater ">"))))
16447 (message "Timestamp updated"))
16448 ((equal arg '(16))
16449 (org-insert-time-stamp (current-time) t inactive))
16451 (setq time (let ((this-command this-command))
16452 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16453 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16454 nil nil (list org-end-time-was-given))))))
16456 ;; FIXME: can we use this for something else, like computing time differences?
16457 (defun org-get-compact-tod (s)
16458 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16459 (let* ((t1 (match-string 1 s))
16460 (h1 (string-to-number (match-string 2 s)))
16461 (m1 (string-to-number (match-string 3 s)))
16462 (t2 (and (match-end 4) (match-string 5 s)))
16463 (h2 (and t2 (string-to-number (match-string 6 s))))
16464 (m2 (and t2 (string-to-number (match-string 7 s))))
16465 dh dm)
16466 (if (not t2)
16468 (setq dh (- h2 h1) dm (- m2 m1))
16469 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16470 (concat t1 "+" (number-to-string dh)
16471 (and (/= 0 dm) (format ":%02d" dm)))))))
16473 (defun org-time-stamp-inactive (&optional arg)
16474 "Insert an inactive time stamp.
16475 An inactive time stamp is enclosed in square brackets instead of angle
16476 brackets. It is inactive in the sense that it does not trigger agenda entries,
16477 does not link to the calendar and cannot be changed with the S-cursor keys.
16478 So these are more for recording a certain time/date."
16479 (interactive "P")
16480 (org-time-stamp arg 'inactive))
16482 (defvar org-date-ovl (make-overlay 1 1))
16483 (overlay-put org-date-ovl 'face 'org-date-selected)
16484 (org-detach-overlay org-date-ovl)
16486 (defvar org-ans1) ; dynamically scoped parameter
16487 (defvar org-ans2) ; dynamically scoped parameter
16489 (defvar org-plain-time-of-day-regexp) ; defined below
16491 (defvar org-overriding-default-time nil) ; dynamically scoped
16492 (defvar org-read-date-overlay nil)
16493 (defvar org-dcst nil) ; dynamically scoped
16494 (defvar org-read-date-history nil)
16495 (defvar org-read-date-final-answer nil)
16496 (defvar org-read-date-analyze-futurep nil)
16497 (defvar org-read-date-analyze-forced-year nil)
16498 (defvar org-read-date-inactive)
16500 (defvar org-read-date-minibuffer-local-map
16501 (let* ((org-replace-disputed-keys nil)
16502 (map (make-sparse-keymap)))
16503 (set-keymap-parent map minibuffer-local-map)
16504 (org-defkey map (kbd ".")
16505 (lambda () (interactive)
16506 ;; Are we at the beginning of the prompt?
16507 (if (looking-back "^[^:]+: ")
16508 (org-eval-in-calendar '(calendar-goto-today))
16509 (insert "."))))
16510 (org-defkey map (kbd "C-.")
16511 (lambda () (interactive)
16512 (org-eval-in-calendar '(calendar-goto-today))))
16513 (org-defkey map [(meta shift left)]
16514 (lambda () (interactive)
16515 (org-eval-in-calendar '(calendar-backward-month 1))))
16516 (org-defkey map [(meta shift right)]
16517 (lambda () (interactive)
16518 (org-eval-in-calendar '(calendar-forward-month 1))))
16519 (org-defkey map [(meta shift up)]
16520 (lambda () (interactive)
16521 (org-eval-in-calendar '(calendar-backward-year 1))))
16522 (org-defkey map [(meta shift down)]
16523 (lambda () (interactive)
16524 (org-eval-in-calendar '(calendar-forward-year 1))))
16525 (org-defkey map [?\e (shift left)]
16526 (lambda () (interactive)
16527 (org-eval-in-calendar '(calendar-backward-month 1))))
16528 (org-defkey map [?\e (shift right)]
16529 (lambda () (interactive)
16530 (org-eval-in-calendar '(calendar-forward-month 1))))
16531 (org-defkey map [?\e (shift up)]
16532 (lambda () (interactive)
16533 (org-eval-in-calendar '(calendar-backward-year 1))))
16534 (org-defkey map [?\e (shift down)]
16535 (lambda () (interactive)
16536 (org-eval-in-calendar '(calendar-forward-year 1))))
16537 (org-defkey map [(shift up)]
16538 (lambda () (interactive)
16539 (org-eval-in-calendar '(calendar-backward-week 1))))
16540 (org-defkey map [(shift down)]
16541 (lambda () (interactive)
16542 (org-eval-in-calendar '(calendar-forward-week 1))))
16543 (org-defkey map [(shift left)]
16544 (lambda () (interactive)
16545 (org-eval-in-calendar '(calendar-backward-day 1))))
16546 (org-defkey map [(shift right)]
16547 (lambda () (interactive)
16548 (org-eval-in-calendar '(calendar-forward-day 1))))
16549 (org-defkey map "!"
16550 (lambda () (interactive)
16551 (org-eval-in-calendar '(diary-view-entries))
16552 (message "")))
16553 (org-defkey map ">"
16554 (lambda () (interactive)
16555 (org-eval-in-calendar '(calendar-scroll-left 1))))
16556 (org-defkey map "<"
16557 (lambda () (interactive)
16558 (org-eval-in-calendar '(calendar-scroll-right 1))))
16559 (org-defkey map "\C-v"
16560 (lambda () (interactive)
16561 (org-eval-in-calendar
16562 '(calendar-scroll-left-three-months 1))))
16563 (org-defkey map "\M-v"
16564 (lambda () (interactive)
16565 (org-eval-in-calendar
16566 '(calendar-scroll-right-three-months 1))))
16567 map)
16568 "Keymap for minibuffer commands when using `org-read-date'.")
16570 (defvar org-def)
16571 (defvar org-defdecode)
16572 (defvar org-with-time)
16574 (defun org-read-date (&optional org-with-time to-time from-string prompt
16575 default-time default-input inactive)
16576 "Read a date, possibly a time, and make things smooth for the user.
16577 The prompt will suggest to enter an ISO date, but you can also enter anything
16578 which will at least partially be understood by `parse-time-string'.
16579 Unrecognized parts of the date will default to the current day, month, year,
16580 hour and minute. If this command is called to replace a timestamp at point,
16581 or to enter the second timestamp of a range, the default time is taken
16582 from the existing stamp. Furthermore, the command prefers the future,
16583 so if you are giving a date where the year is not given, and the day-month
16584 combination is already past in the current year, it will assume you
16585 mean next year. For details, see the manual. A few examples:
16587 3-2-5 --> 2003-02-05
16588 feb 15 --> currentyear-02-15
16589 2/15 --> currentyear-02-15
16590 sep 12 9 --> 2009-09-12
16591 12:45 --> today 12:45
16592 22 sept 0:34 --> currentyear-09-22 0:34
16593 12 --> currentyear-currentmonth-12
16594 Fri --> nearest Friday after today
16595 -Tue --> last Tuesday
16596 etc.
16598 Furthermore you can specify a relative date by giving, as the *first* thing
16599 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16600 change in days weeks, months, years.
16601 With a single plus or minus, the date is relative to today. With a double
16602 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16603 +4d --> four days from today
16604 +4 --> same as above
16605 +2w --> two weeks from today
16606 ++5 --> five days from default date
16608 The function understands only English month and weekday abbreviations.
16610 While prompting, a calendar is popped up - you can also select the
16611 date with the mouse (button 1). The calendar shows a period of three
16612 months. To scroll it to other months, use the keys `>' and `<'.
16613 If you don't like the calendar, turn it off with
16614 \(setq org-read-date-popup-calendar nil)
16616 With optional argument TO-TIME, the date will immediately be converted
16617 to an internal time.
16618 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16619 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16620 still enter a time, and this function will inform the calling routine
16621 about this change. The calling routine may then choose to change the
16622 format used to insert the time stamp into the buffer to include the time.
16623 With optional argument FROM-STRING, read from this string instead from
16624 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16625 the time/date that is used for everything that is not specified by the
16626 user."
16627 (require 'parse-time)
16628 (let* ((org-time-stamp-rounding-minutes
16629 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16630 (org-dcst org-display-custom-times)
16631 (ct (org-current-time))
16632 (org-def (or org-overriding-default-time default-time ct))
16633 (org-defdecode (decode-time org-def))
16634 (dummy (progn
16635 (when (< (nth 2 org-defdecode) org-extend-today-until)
16636 (setcar (nthcdr 2 org-defdecode) -1)
16637 (setcar (nthcdr 1 org-defdecode) 59)
16638 (setq org-def (apply 'encode-time org-defdecode)
16639 org-defdecode (decode-time org-def)))))
16640 (mouse-autoselect-window nil) ; Don't let the mouse jump
16641 (calendar-frame-setup nil)
16642 (calendar-setup nil)
16643 (calendar-move-hook nil)
16644 (calendar-view-diary-initially-flag nil)
16645 (calendar-view-holidays-initially-flag nil)
16646 (timestr (format-time-string
16647 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16648 (prompt (concat (if prompt (concat prompt " ") "")
16649 (format "Date+time [%s]: " timestr)))
16650 ans (org-ans0 "") org-ans1 org-ans2 final)
16652 (cond
16653 (from-string (setq ans from-string))
16654 (org-read-date-popup-calendar
16655 (save-excursion
16656 (save-window-excursion
16657 (calendar)
16658 (org-eval-in-calendar '(setq cursor-type nil) t)
16659 (unwind-protect
16660 (progn
16661 (calendar-forward-day (- (time-to-days org-def)
16662 (calendar-absolute-from-gregorian
16663 (calendar-current-date))))
16664 (org-eval-in-calendar nil t)
16665 (let* ((old-map (current-local-map))
16666 (map (copy-keymap calendar-mode-map))
16667 (minibuffer-local-map
16668 (copy-keymap org-read-date-minibuffer-local-map)))
16669 (org-defkey map (kbd "RET") 'org-calendar-select)
16670 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16671 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16672 (unwind-protect
16673 (progn
16674 (use-local-map map)
16675 (setq org-read-date-inactive inactive)
16676 (add-hook 'post-command-hook 'org-read-date-display)
16677 (setq org-ans0 (read-string prompt default-input
16678 'org-read-date-history nil))
16679 ;; org-ans0: from prompt
16680 ;; org-ans1: from mouse click
16681 ;; org-ans2: from calendar motion
16682 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16683 (remove-hook 'post-command-hook 'org-read-date-display)
16684 (use-local-map old-map)
16685 (when org-read-date-overlay
16686 (delete-overlay org-read-date-overlay)
16687 (setq org-read-date-overlay nil)))))
16688 (bury-buffer "*Calendar*")))))
16690 (t ; Naked prompt only
16691 (unwind-protect
16692 (setq ans (read-string prompt default-input
16693 'org-read-date-history timestr))
16694 (when org-read-date-overlay
16695 (delete-overlay org-read-date-overlay)
16696 (setq org-read-date-overlay nil)))))
16698 (setq final (org-read-date-analyze ans org-def org-defdecode))
16700 (when org-read-date-analyze-forced-year
16701 (message "Year was forced into %s"
16702 (if org-read-date-force-compatible-dates
16703 "compatible range (1970-2037)"
16704 "range representable on this machine"))
16705 (ding))
16707 ;; One round trip to get rid of 34th of August and stuff like that....
16708 (setq final (decode-time (apply 'encode-time final)))
16710 (setq org-read-date-final-answer ans)
16712 (if to-time
16713 (apply 'encode-time final)
16714 (if (and (boundp 'org-time-was-given) org-time-was-given)
16715 (format "%04d-%02d-%02d %02d:%02d"
16716 (nth 5 final) (nth 4 final) (nth 3 final)
16717 (nth 2 final) (nth 1 final))
16718 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16720 (defun org-read-date-display ()
16721 "Display the current date prompt interpretation in the minibuffer."
16722 (when org-read-date-display-live
16723 (when org-read-date-overlay
16724 (delete-overlay org-read-date-overlay))
16725 (when (minibufferp (current-buffer))
16726 (save-excursion
16727 (end-of-line 1)
16728 (while (not (equal (buffer-substring
16729 (max (point-min) (- (point) 4)) (point))
16730 " "))
16731 (insert " ")))
16732 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16733 " " (or org-ans1 org-ans2)))
16734 (org-end-time-was-given nil)
16735 (f (org-read-date-analyze ans org-def org-defdecode))
16736 (fmts (if org-dcst
16737 org-time-stamp-custom-formats
16738 org-time-stamp-formats))
16739 (fmt (if (or org-with-time
16740 (and (boundp 'org-time-was-given) org-time-was-given))
16741 (cdr fmts)
16742 (car fmts)))
16743 (txt (format-time-string fmt (apply 'encode-time f)))
16744 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16745 (txt (concat "=> " txt)))
16746 (when (and org-end-time-was-given
16747 (string-match org-plain-time-of-day-regexp txt))
16748 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16749 org-end-time-was-given
16750 (substring txt (match-end 0)))))
16751 (when org-read-date-analyze-futurep
16752 (setq txt (concat txt " (=>F)")))
16753 (setq org-read-date-overlay
16754 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16755 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16757 (defun org-read-date-analyze (ans org-def org-defdecode)
16758 "Analyze the combined answer of the date prompt."
16759 ;; FIXME: cleanup and comment
16760 (let ((nowdecode (decode-time (current-time)))
16761 delta deltan deltaw deltadef year month day
16762 hour minute second wday pm h2 m2 tl wday1
16763 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16764 (setq org-read-date-analyze-futurep nil
16765 org-read-date-analyze-forced-year nil)
16766 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16767 (setq ans "+0"))
16769 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16770 (setq ans (replace-match "" t t ans)
16771 deltan (car delta)
16772 deltaw (nth 1 delta)
16773 deltadef (nth 2 delta)))
16775 ;; Check if there is an iso week date in there. If yes, store the
16776 ;; info and postpone interpreting it until the rest of the parsing
16777 ;; is done.
16778 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16779 (setq iso-year (if (match-end 1)
16780 (org-small-year-to-year
16781 (string-to-number (match-string 1 ans))))
16782 iso-weekday (if (match-end 3)
16783 (string-to-number (match-string 3 ans)))
16784 iso-week (string-to-number (match-string 2 ans)))
16785 (setq ans (replace-match "" t t ans)))
16787 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16788 (when (string-match
16789 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16790 (setq year (if (match-end 2)
16791 (string-to-number (match-string 2 ans))
16792 (progn (setq kill-year t)
16793 (string-to-number (format-time-string "%Y"))))
16794 month (string-to-number (match-string 3 ans))
16795 day (string-to-number (match-string 4 ans)))
16796 (if (< year 100) (setq year (+ 2000 year)))
16797 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16798 t nil ans)))
16800 ;; Help matching dotted european dates
16801 (when (string-match
16802 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16803 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16804 (setq kill-year t)
16805 (string-to-number (format-time-string "%Y")))
16806 day (string-to-number (match-string 1 ans))
16807 month (string-to-number (match-string 2 ans))
16808 ans (replace-match (format "%04d-%02d-%02d" year month day)
16809 t nil ans)))
16811 ;; Help matching american dates, like 5/30 or 5/30/7
16812 (when (string-match
16813 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16814 (setq year (if (match-end 4)
16815 (string-to-number (match-string 4 ans))
16816 (progn (setq kill-year t)
16817 (string-to-number (format-time-string "%Y"))))
16818 month (string-to-number (match-string 1 ans))
16819 day (string-to-number (match-string 2 ans)))
16820 (if (< year 100) (setq year (+ 2000 year)))
16821 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16822 t nil ans)))
16823 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16824 ;; If there is a time with am/pm, and *no* time without it, we convert
16825 ;; so that matching will be successful.
16826 (loop for i from 1 to 2 do ; twice, for end time as well
16827 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16828 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16829 (setq hour (string-to-number (match-string 1 ans))
16830 minute (if (match-end 3)
16831 (string-to-number (match-string 3 ans))
16833 pm (equal ?p
16834 (string-to-char (downcase (match-string 4 ans)))))
16835 (if (and (= hour 12) (not pm))
16836 (setq hour 0)
16837 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16838 (setq ans (replace-match (format "%02d:%02d" hour minute)
16839 t t ans))))
16841 ;; Check if a time range is given as a duration
16842 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16843 (setq hour (string-to-number (match-string 1 ans))
16844 h2 (+ hour (string-to-number (match-string 3 ans)))
16845 minute (string-to-number (match-string 2 ans))
16846 m2 (+ minute (if (match-end 5) (string-to-number
16847 (match-string 5 ans))0)))
16848 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16849 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16850 t t ans)))
16852 ;; Check if there is a time range
16853 (when (boundp 'org-end-time-was-given)
16854 (setq org-time-was-given nil)
16855 (when (and (string-match org-plain-time-of-day-regexp ans)
16856 (match-end 8))
16857 (setq org-end-time-was-given (match-string 8 ans))
16858 (setq ans (concat (substring ans 0 (match-beginning 7))
16859 (substring ans (match-end 7))))))
16861 (setq tl (parse-time-string ans)
16862 day (or (nth 3 tl) (nth 3 org-defdecode))
16863 month (or (nth 4 tl)
16864 (if (and org-read-date-prefer-future
16865 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16866 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16867 (nth 4 org-defdecode)))
16868 year (or (and (not kill-year) (nth 5 tl))
16869 (if (and org-read-date-prefer-future
16870 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16871 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16872 (nth 5 org-defdecode)))
16873 hour (or (nth 2 tl) (nth 2 org-defdecode))
16874 minute (or (nth 1 tl) (nth 1 org-defdecode))
16875 second (or (nth 0 tl) 0)
16876 wday (nth 6 tl))
16878 (when (and (eq org-read-date-prefer-future 'time)
16879 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16880 (equal day (nth 3 nowdecode))
16881 (equal month (nth 4 nowdecode))
16882 (equal year (nth 5 nowdecode))
16883 (nth 2 tl)
16884 (or (< (nth 2 tl) (nth 2 nowdecode))
16885 (and (= (nth 2 tl) (nth 2 nowdecode))
16886 (nth 1 tl)
16887 (< (nth 1 tl) (nth 1 nowdecode)))))
16888 (setq day (1+ day)
16889 futurep t))
16891 ;; Special date definitions below
16892 (cond
16893 (iso-week
16894 ;; There was an iso week
16895 (require 'cal-iso)
16896 (setq futurep nil)
16897 (setq year (or iso-year year)
16898 day (or iso-weekday wday 1)
16899 wday nil ; to make sure that the trigger below does not match
16900 iso-date (calendar-gregorian-from-absolute
16901 (calendar-absolute-from-iso
16902 (list iso-week day year))))
16903 ; FIXME: Should we also push ISO weeks into the future?
16904 ; (when (and org-read-date-prefer-future
16905 ; (not iso-year)
16906 ; (< (calendar-absolute-from-gregorian iso-date)
16907 ; (time-to-days (current-time))))
16908 ; (setq year (1+ year)
16909 ; iso-date (calendar-gregorian-from-absolute
16910 ; (calendar-absolute-from-iso
16911 ; (list iso-week day year)))))
16912 (setq month (car iso-date)
16913 year (nth 2 iso-date)
16914 day (nth 1 iso-date)))
16915 (deltan
16916 (setq futurep nil)
16917 (unless deltadef
16918 (let ((now (decode-time (current-time))))
16919 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16920 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16921 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16922 ((equal deltaw "m") (setq month (+ month deltan)))
16923 ((equal deltaw "y") (setq year (+ year deltan)))))
16924 ((and wday (not (nth 3 tl)))
16925 ;; Weekday was given, but no day, so pick that day in the week
16926 ;; on or after the derived date.
16927 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16928 (unless (equal wday wday1)
16929 (setq day (+ day (% (- wday wday1 -7) 7))))))
16930 (if (and (boundp 'org-time-was-given)
16931 (nth 2 tl))
16932 (setq org-time-was-given t))
16933 (if (< year 100) (setq year (+ 2000 year)))
16934 ;; Check of the date is representable
16935 (if org-read-date-force-compatible-dates
16936 (progn
16937 (if (< year 1970)
16938 (setq year 1970 org-read-date-analyze-forced-year t))
16939 (if (> year 2037)
16940 (setq year 2037 org-read-date-analyze-forced-year t)))
16941 (condition-case nil
16942 (ignore (encode-time second minute hour day month year))
16943 (error
16944 (setq year (nth 5 org-defdecode))
16945 (setq org-read-date-analyze-forced-year t))))
16946 (setq org-read-date-analyze-futurep futurep)
16947 (list second minute hour day month year)))
16949 (defvar parse-time-weekdays)
16950 (defun org-read-date-get-relative (s today default)
16951 "Check string S for special relative date string.
16952 TODAY and DEFAULT are internal times, for today and for a default.
16953 Return shift list (N what def-flag)
16954 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16955 N is the number of WHATs to shift.
16956 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16957 the DEFAULT date rather than TODAY."
16958 (require 'parse-time)
16959 (when (and
16960 (string-match
16961 (concat
16962 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16963 "\\([0-9]+\\)?"
16964 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16965 "\\([ \t]\\|$\\)") s)
16966 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16967 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16968 (string-to-char (substring (match-string 1 s) -1))
16969 ?+))
16970 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16971 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16972 (what (if (match-end 3) (match-string 3 s) "d"))
16973 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16974 (date (if rel default today))
16975 (wday (nth 6 (decode-time date)))
16976 delta)
16977 (if wday1
16978 (progn
16979 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16980 (if (= delta 0) (setq delta 7))
16981 (if (= dir ?-)
16982 (progn
16983 (setq delta (- delta 7))
16984 (if (= delta 0) (setq delta -7))))
16985 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16986 (list delta "d" rel))
16987 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16989 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16990 "Turn a user-specified date into the internal representation.
16991 The internal representation needed by the calendar is (month day year).
16992 This is a wrapper to handle the brain-dead convention in calendar that
16993 user function argument order change dependent on argument order."
16994 (if (boundp 'calendar-date-style)
16995 (cond
16996 ((eq calendar-date-style 'american)
16997 (list arg1 arg2 arg3))
16998 ((eq calendar-date-style 'european)
16999 (list arg2 arg1 arg3))
17000 ((eq calendar-date-style 'iso)
17001 (list arg2 arg3 arg1)))
17002 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17003 (if (org-bound-and-true-p european-calendar-style)
17004 (list arg2 arg1 arg3)
17005 (list arg1 arg2 arg3)))))
17007 (defun org-eval-in-calendar (form &optional keepdate)
17008 "Eval FORM in the calendar window and return to current window.
17009 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
17010 otherwise stick to the current value of `org-ans2'."
17011 (let ((sf (selected-frame))
17012 (sw (selected-window)))
17013 (select-window (get-buffer-window "*Calendar*" t))
17014 (eval form)
17015 (when (and (not keepdate) (calendar-cursor-to-date))
17016 (let* ((date (calendar-cursor-to-date))
17017 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17018 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17019 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17020 (select-window sw)
17021 (org-select-frame-set-input-focus sf)))
17023 (defun org-calendar-select ()
17024 "Return to `org-read-date' with the date currently selected.
17025 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17026 (interactive)
17027 (when (calendar-cursor-to-date)
17028 (let* ((date (calendar-cursor-to-date))
17029 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17030 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17031 (if (active-minibuffer-window) (exit-minibuffer))))
17033 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17034 "Insert a date stamp for the date given by the internal TIME.
17035 WITH-HM means use the stamp format that includes the time of the day.
17036 INACTIVE means use square brackets instead of angular ones, so that the
17037 stamp will not contribute to the agenda.
17038 PRE and POST are optional strings to be inserted before and after the
17039 stamp.
17040 The command returns the inserted time stamp."
17041 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17042 stamp)
17043 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17044 (insert-before-markers (or pre ""))
17045 (when (listp extra)
17046 (setq extra (car extra))
17047 (if (and (stringp extra)
17048 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17049 (setq extra (format "-%02d:%02d"
17050 (string-to-number (match-string 1 extra))
17051 (string-to-number (match-string 2 extra))))
17052 (setq extra nil)))
17053 (when extra
17054 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17055 (insert-before-markers (setq stamp (format-time-string fmt time)))
17056 (insert-before-markers (or post ""))
17057 (setq org-last-inserted-timestamp stamp)))
17059 (defun org-toggle-time-stamp-overlays ()
17060 "Toggle the use of custom time stamp formats."
17061 (interactive)
17062 (setq org-display-custom-times (not org-display-custom-times))
17063 (unless org-display-custom-times
17064 (let ((p (point-min)) (bmp (buffer-modified-p)))
17065 (while (setq p (next-single-property-change p 'display))
17066 (if (and (get-text-property p 'display)
17067 (eq (get-text-property p 'face) 'org-date))
17068 (remove-text-properties
17069 p (setq p (next-single-property-change p 'display))
17070 '(display t))))
17071 (set-buffer-modified-p bmp)))
17072 (if (featurep 'xemacs)
17073 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17074 (org-restart-font-lock)
17075 (setq org-table-may-need-update t)
17076 (if org-display-custom-times
17077 (message "Time stamps are overlaid with custom format")
17078 (message "Time stamp overlays removed")))
17080 (defun org-display-custom-time (beg end)
17081 "Overlay modified time stamp format over timestamp between BEG and END."
17082 (let* ((ts (buffer-substring beg end))
17083 t1 w1 with-hm tf time str w2 (off 0))
17084 (save-match-data
17085 (setq t1 (org-parse-time-string ts t))
17086 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17087 (setq off (- (match-end 0) (match-beginning 0)))))
17088 (setq end (- end off))
17089 (setq w1 (- end beg)
17090 with-hm (and (nth 1 t1) (nth 2 t1))
17091 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17092 time (org-fix-decoded-time t1)
17093 str (org-add-props
17094 (format-time-string
17095 (substring tf 1 -1) (apply 'encode-time time))
17096 nil 'mouse-face 'highlight)
17097 w2 (length str))
17098 (if (not (= w2 w1))
17099 (add-text-properties (1+ beg) (+ 2 beg)
17100 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17101 (if (featurep 'xemacs)
17102 (progn
17103 (put-text-property beg end 'invisible t)
17104 (put-text-property beg end 'end-glyph (make-glyph str)))
17105 (put-text-property beg end 'display str))))
17107 (defun org-translate-time (string)
17108 "Translate all timestamps in STRING to custom format.
17109 But do this only if the variable `org-display-custom-times' is set."
17110 (when org-display-custom-times
17111 (save-match-data
17112 (let* ((start 0)
17113 (re org-ts-regexp-both)
17114 t1 with-hm inactive tf time str beg end)
17115 (while (setq start (string-match re string start))
17116 (setq beg (match-beginning 0)
17117 end (match-end 0)
17118 t1 (save-match-data
17119 (org-parse-time-string (substring string beg end) t))
17120 with-hm (and (nth 1 t1) (nth 2 t1))
17121 inactive (equal (substring string beg (1+ beg)) "[")
17122 tf (funcall (if with-hm 'cdr 'car)
17123 org-time-stamp-custom-formats)
17124 time (org-fix-decoded-time t1)
17125 str (format-time-string
17126 (concat
17127 (if inactive "[" "<") (substring tf 1 -1)
17128 (if inactive "]" ">"))
17129 (apply 'encode-time time))
17130 string (replace-match str t t string)
17131 start (+ start (length str)))))))
17132 string)
17134 (defun org-fix-decoded-time (time)
17135 "Set 0 instead of nil for the first 6 elements of time.
17136 Don't touch the rest."
17137 (let ((n 0))
17138 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17140 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17142 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17143 "Difference between TIMESTAMP-STRING and now in days.
17144 If SECONDS is non-nil, return the difference in seconds."
17145 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17146 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17147 (funcall fdiff (current-time)))))
17149 (defun org-deadline-close (timestamp-string &optional ndays)
17150 "Is the time in TIMESTAMP-STRING close to the current date?"
17151 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17152 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17153 (not (org-entry-is-done-p))))
17155 (defun org-get-wdays (ts &optional delay zero-delay)
17156 "Get the deadline lead time appropriate for timestring TS.
17157 When DELAY is non-nil, get the delay time for scheduled items
17158 instead of the deadline lead time. When ZERO-DELAY is non-nil
17159 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17160 don't try to find the delay cookie in the scheduled timestamp."
17161 (let ((tv (if delay org-scheduled-delay-days
17162 org-deadline-warning-days)))
17163 (cond
17164 ((or (and delay (< tv 0))
17165 (and delay zero-delay (<= tv 0))
17166 (and (not delay) (<= tv 0)))
17167 ;; Enforce this value no matter what
17168 (- tv))
17169 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17170 ;; lead time is specified.
17171 (floor (* (string-to-number (match-string 1 ts))
17172 (cdr (assoc (match-string 2 ts)
17173 '(("d" . 1) ("w" . 7)
17174 ("m" . 30.4) ("y" . 365.25)
17175 ("h" . 0.041667)))))))
17176 ;; go for the default.
17177 (t tv))))
17179 (defun org-calendar-select-mouse (ev)
17180 "Return to `org-read-date' with the date currently selected.
17181 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17182 (interactive "e")
17183 (mouse-set-point ev)
17184 (when (calendar-cursor-to-date)
17185 (let* ((date (calendar-cursor-to-date))
17186 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17187 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17188 (if (active-minibuffer-window) (exit-minibuffer))))
17190 (defun org-check-deadlines (ndays)
17191 "Check if there are any deadlines due or past due.
17192 A deadline is considered due if it happens within `org-deadline-warning-days'
17193 days from today's date. If the deadline appears in an entry marked DONE,
17194 it is not shown. The prefix arg NDAYS can be used to test that many
17195 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17196 (interactive "P")
17197 (let* ((org-warn-days
17198 (cond
17199 ((equal ndays '(4)) 100000)
17200 (ndays (prefix-numeric-value ndays))
17201 (t (abs org-deadline-warning-days))))
17202 (case-fold-search nil)
17203 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17204 (callback
17205 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17207 (message "%d deadlines past-due or due within %d days"
17208 (org-occur regexp nil callback)
17209 org-warn-days)))
17211 (defsubst org-re-timestamp (type)
17212 "Return a regexp for timestamp TYPE.
17213 Allowed values for TYPE are:
17215 all: all timestamps
17216 active: only active timestamps (<...>)
17217 inactive: only inactive timestamps ([...])
17218 scheduled: only scheduled timestamps
17219 deadline: only deadline timestamps
17220 closed: only closed time-stamps
17222 When TYPE is nil, fall back on returning a regexp that matches
17223 both scheduled and deadline timestamps."
17224 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17225 ((eq type 'active) org-ts-regexp)
17226 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17227 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17228 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17229 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17230 ((eq type 'scheduled-or-deadline)
17231 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17233 (defun org-check-before-date (date)
17234 "Check if there are deadlines or scheduled entries before DATE."
17235 (interactive (list (org-read-date)))
17236 (let ((case-fold-search nil)
17237 (regexp (org-re-timestamp org-ts-type))
17238 (callback
17239 (lambda () (time-less-p
17240 (org-time-string-to-time (match-string 1))
17241 (org-time-string-to-time date)))))
17242 (message "%d entries before %s"
17243 (org-occur regexp nil callback) date)))
17245 (defun org-check-after-date (date)
17246 "Check if there are deadlines or scheduled entries after DATE."
17247 (interactive (list (org-read-date)))
17248 (let ((case-fold-search nil)
17249 (regexp (org-re-timestamp org-ts-type))
17250 (callback
17251 (lambda () (not
17252 (time-less-p
17253 (org-time-string-to-time (match-string 1))
17254 (org-time-string-to-time date))))))
17255 (message "%d entries after %s"
17256 (org-occur regexp nil callback) date)))
17258 (defun org-check-dates-range (start-date end-date)
17259 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17260 (interactive (list (org-read-date nil nil nil "Range starts")
17261 (org-read-date nil nil nil "Range end")))
17262 (let ((case-fold-search nil)
17263 (regexp (org-re-timestamp org-ts-type))
17264 (callback
17265 (lambda ()
17266 (let ((match (match-string 1)))
17267 (and
17268 (not (time-less-p
17269 (org-time-string-to-time match)
17270 (org-time-string-to-time start-date)))
17271 (time-less-p
17272 (org-time-string-to-time match)
17273 (org-time-string-to-time end-date)))))))
17274 (message "%d entries between %s and %s"
17275 (org-occur regexp nil callback) start-date end-date)))
17277 (defun org-evaluate-time-range (&optional to-buffer)
17278 "Evaluate a time range by computing the difference between start and end.
17279 Normally the result is just printed in the echo area, but with prefix arg
17280 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17281 If the time range is actually in a table, the result is inserted into the
17282 next column.
17283 For time difference computation, a year is assumed to be exactly 365
17284 days in order to avoid rounding problems."
17285 (interactive "P")
17287 (org-clock-update-time-maybe)
17288 (save-excursion
17289 (unless (org-at-date-range-p t)
17290 (goto-char (point-at-bol))
17291 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17292 (if (not (org-at-date-range-p t))
17293 (user-error "Not at a time-stamp range, and none found in current line")))
17294 (let* ((ts1 (match-string 1))
17295 (ts2 (match-string 2))
17296 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17297 (match-end (match-end 0))
17298 (time1 (org-time-string-to-time ts1))
17299 (time2 (org-time-string-to-time ts2))
17300 (t1 (org-float-time time1))
17301 (t2 (org-float-time time2))
17302 (diff (abs (- t2 t1)))
17303 (negative (< (- t2 t1) 0))
17304 ;; (ys (floor (* 365 24 60 60)))
17305 (ds (* 24 60 60))
17306 (hs (* 60 60))
17307 (fy "%dy %dd %02d:%02d")
17308 (fy1 "%dy %dd")
17309 (fd "%dd %02d:%02d")
17310 (fd1 "%dd")
17311 (fh "%02d:%02d")
17312 y d h m align)
17313 (if havetime
17314 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17316 d (floor (/ diff ds)) diff (mod diff ds)
17317 h (floor (/ diff hs)) diff (mod diff hs)
17318 m (floor (/ diff 60)))
17319 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17321 d (floor (+ (/ diff ds) 0.5))
17322 h 0 m 0))
17323 (if (not to-buffer)
17324 (message "%s" (org-make-tdiff-string y d h m))
17325 (if (org-at-table-p)
17326 (progn
17327 (goto-char match-end)
17328 (setq align t)
17329 (and (looking-at " *|") (goto-char (match-end 0))))
17330 (goto-char match-end))
17331 (if (looking-at
17332 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17333 (replace-match ""))
17334 (if negative (insert " -"))
17335 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17336 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17337 (insert " " (format fh h m))))
17338 (if align (org-table-align))
17339 (message "Time difference inserted")))))
17341 (defun org-make-tdiff-string (y d h m)
17342 (let ((fmt "")
17343 (l nil))
17344 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17345 l (push y l)))
17346 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17347 l (push d l)))
17348 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17349 l (push h l)))
17350 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17351 l (push m l)))
17352 (apply 'format fmt (nreverse l))))
17354 (defun org-time-string-to-time (s &optional buffer pos)
17355 "Convert a timestamp string into internal time."
17356 (condition-case errdata
17357 (apply 'encode-time (org-parse-time-string s))
17358 (error (error "Bad timestamp `%s'%s\nError was: %s"
17359 s (if (not (and buffer pos))
17361 (format " at %d in buffer `%s'" pos buffer))
17362 (cdr errdata)))))
17364 (defun org-time-string-to-seconds (s)
17365 "Convert a timestamp string to a number of seconds."
17366 (org-float-time (org-time-string-to-time s)))
17368 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17369 "Convert a time stamp to an absolute day number.
17370 If there is a specifier for a cyclic time stamp, get the closest
17371 date to DAYNR.
17372 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17373 The variable `date' is bound by the calendar when this is called."
17374 (cond
17375 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17376 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17377 daynr
17378 (+ daynr 1000)))
17379 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17380 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17381 (time-to-days (current-time))) (match-string 0 s)
17382 prefer show-all))
17383 (t (time-to-days
17384 (condition-case errdata
17385 (apply 'encode-time (org-parse-time-string s))
17386 (error (error "Bad timestamp `%s'%s\nError was: %s"
17387 s (if (not (and buffer pos))
17389 (format " at %d in buffer `%s'" pos buffer))
17390 (cdr errdata))))))))
17392 (defun org-days-to-iso-week (days)
17393 "Return the iso week number."
17394 (require 'cal-iso)
17395 (car (calendar-iso-from-absolute days)))
17397 (defun org-small-year-to-year (year)
17398 "Convert 2-digit years into 4-digit years.
17399 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17400 The year 2000 cannot be abbreviated. Any year larger than 99
17401 is returned unchanged."
17402 (if (< year 38)
17403 (setq year (+ 2000 year))
17404 (if (< year 100)
17405 (setq year (+ 1900 year))))
17406 year)
17408 (defun org-time-from-absolute (d)
17409 "Return the time corresponding to date D.
17410 D may be an absolute day number, or a calendar-type list (month day year)."
17411 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17412 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17414 (defun org-calendar-holiday ()
17415 "List of holidays, for Diary display in Org-mode."
17416 (require 'holidays)
17417 (let ((hl (funcall
17418 (if (fboundp 'calendar-check-holidays)
17419 'calendar-check-holidays 'check-calendar-holidays) date)))
17420 (if hl (mapconcat 'identity hl "; "))))
17422 (defun org-diary-sexp-entry (sexp entry date)
17423 "Process a SEXP diary ENTRY for DATE."
17424 (require 'diary-lib)
17425 (let ((result (if calendar-debug-sexp
17426 (let ((stack-trace-on-error t))
17427 (eval (car (read-from-string sexp))))
17428 (condition-case nil
17429 (eval (car (read-from-string sexp)))
17430 (error
17431 (beep)
17432 (message "Bad sexp at line %d in %s: %s"
17433 (org-current-line)
17434 (buffer-file-name) sexp)
17435 (sleep-for 2))))))
17436 (cond ((stringp result) (split-string result "; "))
17437 ((and (consp result)
17438 (not (consp (cdr result)))
17439 (stringp (cdr result))) (cdr result))
17440 ((and (consp result)
17441 (stringp (car result))) result)
17442 (result entry))))
17444 (defun org-diary-to-ical-string (frombuf)
17445 "Get iCalendar entries from diary entries in buffer FROMBUF.
17446 This uses the icalendar.el library."
17447 (let* ((tmpdir (if (featurep 'xemacs)
17448 (temp-directory)
17449 temporary-file-directory))
17450 (tmpfile (make-temp-name
17451 (expand-file-name "orgics" tmpdir)))
17452 buf rtn b e)
17453 (with-current-buffer frombuf
17454 (icalendar-export-region (point-min) (point-max) tmpfile)
17455 (setq buf (find-buffer-visiting tmpfile))
17456 (set-buffer buf)
17457 (goto-char (point-min))
17458 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17459 (setq b (match-beginning 0)))
17460 (goto-char (point-max))
17461 (if (re-search-backward "^END:VEVENT" nil t)
17462 (setq e (match-end 0)))
17463 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17464 (kill-buffer buf)
17465 (delete-file tmpfile)
17466 rtn))
17468 (defun org-closest-date (start current change prefer show-all)
17469 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17470 When PREFER is `past', return a date that is either CURRENT or past.
17471 When PREFER is `future', return a date that is either CURRENT or future.
17472 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17473 ;; Make the proper lists from the dates
17474 (catch 'exit
17475 (let ((a1 '(("h" . hour)
17476 ("d" . day)
17477 ("w" . week)
17478 ("m" . month)
17479 ("y" . year)))
17480 (shour (nth 2 (org-parse-time-string start)))
17481 dn dw sday cday n1 n2 n0
17482 d m y y1 y2 date1 date2 nmonths nm ny m2)
17484 (setq start (org-date-to-gregorian start)
17485 current (org-date-to-gregorian
17486 (if show-all
17487 current
17488 (time-to-days (current-time))))
17489 sday (calendar-absolute-from-gregorian start)
17490 cday (calendar-absolute-from-gregorian current))
17492 (if (<= cday sday) (throw 'exit sday))
17494 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17495 (setq dn (string-to-number (match-string 1 change))
17496 dw (cdr (assoc (match-string 2 change) a1)))
17497 (user-error "Invalid change specifier: %s" change))
17498 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17499 (cond
17500 ((eq dw 'hour)
17501 (let ((missing-hours
17502 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17503 dn)))
17504 (setq n1 (if (zerop missing-hours) cday
17505 (- cday (1+ (floor (/ missing-hours 24)))))
17506 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17507 ((eq dw 'day)
17508 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17509 n2 (+ n1 dn)))
17510 ((eq dw 'year)
17511 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17512 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17513 (setq date1 (list m d y1)
17514 n1 (calendar-absolute-from-gregorian date1)
17515 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17516 n2 (calendar-absolute-from-gregorian date2)))
17517 ((eq dw 'month)
17518 ;; approx number of month between the two dates
17519 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17520 ;; How often does dn fit in there?
17521 (setq d (nth 1 start) m (car start) y (nth 2 start)
17522 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17523 m (+ m nm)
17524 ny (floor (/ m 12))
17525 y (+ y ny)
17526 m (- m (* ny 12)))
17527 (while (> m 12) (setq m (- m 12) y (1+ y)))
17528 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17529 (setq m2 (+ m dn) y2 y)
17530 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17531 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17532 (while (<= n2 cday)
17533 (setq n1 n2 m m2 y y2)
17534 (setq m2 (+ m dn) y2 y)
17535 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17536 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17537 ;; Make sure n1 is the earlier date
17538 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17539 (if show-all
17540 (cond
17541 ((eq prefer 'past) (if (= cday n2) n2 n1))
17542 ((eq prefer 'future) (if (= cday n1) n1 n2))
17543 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17544 (cond
17545 ((eq prefer 'past) (if (= cday n2) n2 n1))
17546 ((eq prefer 'future) (if (= cday n1) n1 n2))
17547 (t (if (= cday n1) n1 n2)))))))
17549 (defun org-date-to-gregorian (date)
17550 "Turn any specification of DATE into a Gregorian date for the calendar."
17551 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17552 ((and (listp date) (= (length date) 3)) date)
17553 ((stringp date)
17554 (setq date (org-parse-time-string date))
17555 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17556 ((listp date)
17557 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17559 (defun org-parse-time-string (s &optional nodefault)
17560 "Parse the standard Org-mode time string.
17561 This should be a lot faster than the normal `parse-time-string'.
17562 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17563 hour and minute fields will be nil if not given."
17564 (cond ((string-match org-ts-regexp0 s)
17565 (list 0
17566 (if (or (match-beginning 8) (not nodefault))
17567 (string-to-number (or (match-string 8 s) "0")))
17568 (if (or (match-beginning 7) (not nodefault))
17569 (string-to-number (or (match-string 7 s) "0")))
17570 (string-to-number (match-string 4 s))
17571 (string-to-number (match-string 3 s))
17572 (string-to-number (match-string 2 s))
17573 nil nil nil))
17574 ((string-match "^<[^>]+>$" s)
17575 (decode-time (seconds-to-time (org-matcher-time s))))
17576 (t (error "Not a standard Org-mode time string: %s" s))))
17578 (defun org-timestamp-up (&optional arg)
17579 "Increase the date item at the cursor by one.
17580 If the cursor is on the year, change the year. If it is on the month,
17581 the day or the time, change that.
17582 With prefix ARG, change by that many units."
17583 (interactive "p")
17584 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17586 (defun org-timestamp-down (&optional arg)
17587 "Decrease the date item at the cursor by one.
17588 If the cursor is on the year, change the year. If it is on the month,
17589 the day or the time, change that.
17590 With prefix ARG, change by that many units."
17591 (interactive "p")
17592 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17594 (defun org-timestamp-up-day (&optional arg)
17595 "Increase the date in the time stamp by one day.
17596 With prefix ARG, change that many days."
17597 (interactive "p")
17598 (if (and (not (org-at-timestamp-p t))
17599 (org-at-heading-p))
17600 (org-todo 'up)
17601 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17603 (defun org-timestamp-down-day (&optional arg)
17604 "Decrease the date in the time stamp by one day.
17605 With prefix ARG, change that many days."
17606 (interactive "p")
17607 (if (and (not (org-at-timestamp-p t))
17608 (org-at-heading-p))
17609 (org-todo 'down)
17610 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17612 (defun org-at-timestamp-p (&optional inactive-ok)
17613 "Determine if the cursor is in or at a timestamp."
17614 (interactive)
17615 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17616 (pos (point))
17617 (ans (or (looking-at tsr)
17618 (save-excursion
17619 (skip-chars-backward "^[<\n\r\t")
17620 (if (> (point) (point-min)) (backward-char 1))
17621 (and (looking-at tsr)
17622 (> (- (match-end 0) pos) -1))))))
17623 (and ans
17624 (boundp 'org-ts-what)
17625 (setq org-ts-what
17626 (cond
17627 ((= pos (match-beginning 0)) 'bracket)
17628 ;; Point is considered to be "on the bracket" whether
17629 ;; it's really on it or right after it.
17630 ((= pos (1- (match-end 0))) 'bracket)
17631 ((= pos (match-end 0)) 'after)
17632 ((org-pos-in-match-range pos 2) 'year)
17633 ((org-pos-in-match-range pos 3) 'month)
17634 ((org-pos-in-match-range pos 7) 'hour)
17635 ((org-pos-in-match-range pos 8) 'minute)
17636 ((or (org-pos-in-match-range pos 4)
17637 (org-pos-in-match-range pos 5)) 'day)
17638 ((and (> pos (or (match-end 8) (match-end 5)))
17639 (< pos (match-end 0)))
17640 (- pos (or (match-end 8) (match-end 5))))
17641 (t 'day))))
17642 ans))
17644 (defun org-toggle-timestamp-type ()
17645 "Toggle the type (<active> or [inactive]) of a time stamp."
17646 (interactive)
17647 (when (org-at-timestamp-p t)
17648 (let ((beg (match-beginning 0)) (end (match-end 0))
17649 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17650 (save-excursion
17651 (goto-char beg)
17652 (while (re-search-forward "[][<>]" end t)
17653 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17654 t t)))
17655 (message "Timestamp is now %sactive"
17656 (if (equal (char-after beg) ?<) "" "in")))))
17658 (defun org-at-clock-log-p nil
17659 "Is the cursor on the clock log line?"
17660 (save-excursion
17661 (move-beginning-of-line 1)
17662 (looking-at org-clock-line-re)))
17664 (defvar org-clock-history) ; defined in org-clock.el
17665 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17666 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17667 "Change the date in the time stamp at point.
17668 The date will be changed by N times WHAT. WHAT can be `day', `month',
17669 `year', `minute', `second'. If WHAT is not given, the cursor position
17670 in the timestamp determines what will be changed.
17671 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17672 (let ((origin (point)) origin-cat
17673 with-hm inactive
17674 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17675 org-ts-what
17676 extra rem
17677 ts time time0 fixnext clrgx)
17678 (if (not (org-at-timestamp-p t))
17679 (user-error "Not at a timestamp"))
17680 (if (and (not what) (eq org-ts-what 'bracket))
17681 (org-toggle-timestamp-type)
17682 ;; Point isn't on brackets. Remember the part of the time-stamp
17683 ;; the point was in. Indeed, size of time-stamps may change,
17684 ;; but point must be kept in the same category nonetheless.
17685 (setq origin-cat org-ts-what)
17686 (if (and (not what) (not (eq org-ts-what 'day))
17687 org-display-custom-times
17688 (get-text-property (point) 'display)
17689 (not (get-text-property (1- (point)) 'display)))
17690 (setq org-ts-what 'day))
17691 (setq org-ts-what (or what org-ts-what)
17692 inactive (= (char-after (match-beginning 0)) ?\[)
17693 ts (match-string 0))
17694 (replace-match "")
17695 (when (string-match
17696 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17698 (setq extra (match-string 1 ts))
17699 (if suppress-tmp-delay
17700 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17701 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17702 (setq with-hm t))
17703 (setq time0 (org-parse-time-string ts))
17704 (when (and updown
17705 (eq org-ts-what 'minute)
17706 (not current-prefix-arg))
17707 ;; This looks like s-up and s-down. Change by one rounding step.
17708 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17709 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17710 (setcar (cdr time0) (+ (nth 1 time0)
17711 (if (> n 0) (- rem) (- dm rem))))))
17712 (setq time
17713 (encode-time (or (car time0) 0)
17714 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17715 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17716 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17717 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17718 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17719 (nthcdr 6 time0)))
17720 (when (and (member org-ts-what '(hour minute))
17721 extra
17722 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17723 (setq extra (org-modify-ts-extra
17724 extra
17725 (if (eq org-ts-what 'hour) 2 5)
17726 n dm)))
17727 (when (integerp org-ts-what)
17728 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17729 (if (eq what 'calendar)
17730 (let ((cal-date (org-get-date-from-calendar)))
17731 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17732 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17733 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17734 (setcar time0 (or (car time0) 0))
17735 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17736 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17737 (setq time (apply 'encode-time time0))))
17738 ;; Insert the new time-stamp, and ensure point stays in the same
17739 ;; category as before (i.e. not after the last position in that
17740 ;; category).
17741 (let ((pos (point)))
17742 ;; Stay before inserted string. `save-excursion' is of no use.
17743 (setq org-last-changed-timestamp
17744 (org-insert-time-stamp time with-hm inactive nil nil extra))
17745 (goto-char pos))
17746 (save-match-data
17747 (looking-at org-ts-regexp3)
17748 (goto-char (cond
17749 ;; `day' category ends before `hour' if any, or at
17750 ;; the end of the day name.
17751 ((eq origin-cat 'day)
17752 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17753 ((eq origin-cat 'hour) (min (match-end 7) origin))
17754 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17755 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17756 ;; `year' and `month' have both fixed size: point
17757 ;; couldn't have moved into another part.
17758 (t origin))))
17759 ;; Update clock if on a CLOCK line.
17760 (org-clock-update-time-maybe)
17761 ;; Maybe adjust the closest clock in `org-clock-history'
17762 (when org-clock-adjust-closest
17763 (if (not (and (org-at-clock-log-p)
17764 (< 1 (length (delq nil (mapcar 'marker-position
17765 org-clock-history))))))
17766 (message "No clock to adjust")
17767 (cond ((save-excursion ; fix previous clock?
17768 (re-search-backward org-ts-regexp0 nil t)
17769 (org-looking-back (concat org-clock-string " \\[")))
17770 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17771 ((save-excursion ; fix next clock?
17772 (re-search-backward org-ts-regexp0 nil t)
17773 (looking-at (concat org-ts-regexp0 "\\] =>")))
17774 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17775 (save-window-excursion
17776 ;; Find closest clock to point, adjust the previous/next one in history
17777 (let* ((p (save-excursion (org-back-to-heading t)))
17778 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17779 (clfixnth
17780 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17781 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17782 (if (not clfixpos)
17783 (message "No clock to adjust")
17784 (save-excursion
17785 (org-goto-marker-or-bmk clfixpos)
17786 (org-show-subtree)
17787 (when (re-search-forward clrgx nil t)
17788 (goto-char (match-beginning 1))
17789 (let (org-clock-adjust-closest)
17790 (org-timestamp-change n org-ts-what updown))
17791 (message "Clock adjusted in %s for heading: %s"
17792 (file-name-nondirectory (buffer-file-name))
17793 (org-get-heading t t)))))))))
17794 ;; Try to recenter the calendar window, if any.
17795 (if (and org-calendar-follow-timestamp-change
17796 (get-buffer-window "*Calendar*" t)
17797 (memq org-ts-what '(day month year)))
17798 (org-recenter-calendar (time-to-days time))))))
17800 (defun org-modify-ts-extra (s pos n dm)
17801 "Change the different parts of the lead-time and repeat fields in timestamp."
17802 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17803 ng h m new rem)
17804 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17805 (cond
17806 ((or (org-pos-in-match-range pos 2)
17807 (org-pos-in-match-range pos 3))
17808 (setq m (string-to-number (match-string 3 s))
17809 h (string-to-number (match-string 2 s)))
17810 (if (org-pos-in-match-range pos 2)
17811 (setq h (+ h n))
17812 (setq n (* dm (org-no-warnings (signum n))))
17813 (when (not (= 0 (setq rem (% m dm))))
17814 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17815 (setq m (+ m n)))
17816 (if (< m 0) (setq m (+ m 60) h (1- h)))
17817 (if (> m 59) (setq m (- m 60) h (1+ h)))
17818 (setq h (min 24 (max 0 h)))
17819 (setq ng 1 new (format "-%02d:%02d" h m)))
17820 ((org-pos-in-match-range pos 6)
17821 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17822 ((org-pos-in-match-range pos 5)
17823 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17825 ((org-pos-in-match-range pos 9)
17826 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17827 ((org-pos-in-match-range pos 8)
17828 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17830 (when ng
17831 (setq s (concat
17832 (substring s 0 (match-beginning ng))
17834 (substring s (match-end ng))))))
17837 (defun org-recenter-calendar (date)
17838 "If the calendar is visible, recenter it to DATE."
17839 (let ((cwin (get-buffer-window "*Calendar*" t)))
17840 (when cwin
17841 (let ((calendar-move-hook nil))
17842 (with-selected-window cwin
17843 (calendar-goto-date (if (listp date) date
17844 (calendar-gregorian-from-absolute date))))))))
17846 (defun org-goto-calendar (&optional arg)
17847 "Go to the Emacs calendar at the current date.
17848 If there is a time stamp in the current line, go to that date.
17849 A prefix ARG can be used to force the current date."
17850 (interactive "P")
17851 (let ((tsr org-ts-regexp) diff
17852 (calendar-move-hook nil)
17853 (calendar-view-holidays-initially-flag nil)
17854 (calendar-view-diary-initially-flag nil))
17855 (if (or (org-at-timestamp-p)
17856 (save-excursion
17857 (beginning-of-line 1)
17858 (looking-at (concat ".*" tsr))))
17859 (let ((d1 (time-to-days (current-time)))
17860 (d2 (time-to-days
17861 (org-time-string-to-time (match-string 1)))))
17862 (setq diff (- d2 d1))))
17863 (calendar)
17864 (calendar-goto-today)
17865 (if (and diff (not arg)) (calendar-forward-day diff))))
17867 (defun org-get-date-from-calendar ()
17868 "Return a list (month day year) of date at point in calendar."
17869 (with-current-buffer "*Calendar*"
17870 (save-match-data
17871 (calendar-cursor-to-date))))
17873 (defun org-date-from-calendar ()
17874 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17875 If there is already a time stamp at the cursor position, update it."
17876 (interactive)
17877 (if (org-at-timestamp-p t)
17878 (org-timestamp-change 0 'calendar)
17879 (let ((cal-date (org-get-date-from-calendar)))
17880 (org-insert-time-stamp
17881 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17883 (defcustom org-effort-durations
17884 `(("h" . 60)
17885 ("d" . ,(* 60 8))
17886 ("w" . ,(* 60 8 5))
17887 ("m" . ,(* 60 8 5 4))
17888 ("y" . ,(* 60 8 5 40)))
17889 "Conversion factor to minutes for an effort modifier.
17891 Each entry has the form (MODIFIER . MINUTES).
17893 In an effort string, a number followed by MODIFIER is multiplied
17894 by the specified number of MINUTES to obtain an effort in
17895 minutes.
17897 For example, if the value of this variable is ((\"hours\" . 60)), then an
17898 effort string \"2hours\" is equivalent to 120 minutes."
17899 :group 'org-agenda
17900 :version "24.1"
17901 :type '(alist :key-type (string :tag "Modifier")
17902 :value-type (number :tag "Minutes")))
17904 (defun org-minutes-to-clocksum-string (m)
17905 "Format number of minutes as a clocksum string.
17906 The format is determined by `org-time-clocksum-format',
17907 `org-time-clocksum-use-fractional' and
17908 `org-time-clocksum-fractional-format' and
17909 `org-time-clocksum-use-effort-durations'."
17910 (let ((clocksum "")
17911 (m (round m)) ; Don't allow fractions of minutes
17912 h d w mo y fmt n)
17913 (setq h (if org-time-clocksum-use-effort-durations
17914 (cdr (assoc "h" org-effort-durations)) 60)
17915 d (if org-time-clocksum-use-effort-durations
17916 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17917 w (if org-time-clocksum-use-effort-durations
17918 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17919 mo (if org-time-clocksum-use-effort-durations
17920 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17921 y (if org-time-clocksum-use-effort-durations
17922 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17923 ;; fractional format
17924 (if org-time-clocksum-use-fractional
17925 (cond
17926 ;; single format string
17927 ((stringp org-time-clocksum-fractional-format)
17928 (format org-time-clocksum-fractional-format (/ m (float h))))
17929 ;; choice of fractional formats for different time units
17930 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17931 (> (/ (truncate m) (* y d h)) 0))
17932 (format fmt (/ m (* y d (float h)))))
17933 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17934 (> (/ (truncate m) (* mo d h)) 0))
17935 (format fmt (/ m (* mo d (float h)))))
17936 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17937 (> (/ (truncate m) (* w d h)) 0))
17938 (format fmt (/ m (* w d (float h)))))
17939 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17940 (> (/ (truncate m) (* d h)) 0))
17941 (format fmt (/ m (* d (float h)))))
17942 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17943 (> (/ (truncate m) h) 0))
17944 (format fmt (/ m (float h))))
17945 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17946 (format fmt m))
17947 ;; fall back to smallest time unit with a format
17948 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17949 (format fmt (/ m (float h))))
17950 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17951 (format fmt (/ m (* d (float h)))))
17952 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17953 (format fmt (/ m (* w d (float h)))))
17954 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17955 (format fmt (/ m (* mo d (float h)))))
17956 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17957 (format fmt (/ m (* y d (float h))))))
17958 ;; standard (non-fractional) format, with single format string
17959 (if (stringp org-time-clocksum-format)
17960 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17961 ;; separate formats components
17962 (and (setq fmt (plist-get org-time-clocksum-format :years))
17963 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17964 (plist-get org-time-clocksum-format :require-years))
17965 (setq clocksum (concat clocksum (format fmt n))
17966 m (- m (* n y d h))))
17967 (and (setq fmt (plist-get org-time-clocksum-format :months))
17968 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17969 (plist-get org-time-clocksum-format :require-months))
17970 (setq clocksum (concat clocksum (format fmt n))
17971 m (- m (* n mo d h))))
17972 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17973 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17974 (plist-get org-time-clocksum-format :require-weeks))
17975 (setq clocksum (concat clocksum (format fmt n))
17976 m (- m (* n w d h))))
17977 (and (setq fmt (plist-get org-time-clocksum-format :days))
17978 (or (> (setq n (/ (truncate m) (* d h))) 0)
17979 (plist-get org-time-clocksum-format :require-days))
17980 (setq clocksum (concat clocksum (format fmt n))
17981 m (- m (* n d h))))
17982 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17983 (or (> (setq n (/ (truncate m) h)) 0)
17984 (plist-get org-time-clocksum-format :require-hours))
17985 (setq clocksum (concat clocksum (format fmt n))
17986 m (- m (* n h))))
17987 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17988 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17989 (setq clocksum (concat clocksum (format fmt m))))
17990 ;; return formatted time duration
17991 clocksum))))
17993 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17994 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17995 "Org mode version 8.0")
17997 (defun org-hours-to-clocksum-string (n)
17998 (org-minutes-to-clocksum-string (* n 60)))
18000 (defun org-hh:mm-string-to-minutes (s)
18001 "Convert a string H:MM to a number of minutes.
18002 If the string is just a number, interpret it as minutes.
18003 In fact, the first hh:mm or number in the string will be taken,
18004 there can be extra stuff in the string.
18005 If no number is found, the return value is 0."
18006 (cond
18007 ((integerp s) s)
18008 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18009 (+ (* (string-to-number (match-string 1 s)) 60)
18010 (string-to-number (match-string 2 s))))
18011 ((string-match "\\([0-9]+\\)" s)
18012 (string-to-number (match-string 1 s)))
18013 (t 0)))
18015 (defcustom org-image-actual-width t
18016 "Should we use the actual width of images when inlining them?
18018 When set to `t', always use the image width.
18020 When set to a number, use imagemagick (when available) to set
18021 the image's width to this value.
18023 When set to a number in a list, try to get the width from any
18024 #+ATTR.* keyword if it matches a width specification like
18026 #+ATTR_HTML: :width 300px
18028 and fall back on that number if none is found.
18030 When set to nil, try to get the width from an #+ATTR.* keyword
18031 and fall back on the original width if none is found.
18033 This requires Emacs >= 24.1, build with imagemagick support."
18034 :group 'org-appearance
18035 :version "24.4"
18036 :package-version '(Org . "8.0")
18037 :type '(choice
18038 (const :tag "Use the image width" t)
18039 (integer :tag "Use a number of pixels")
18040 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18041 (const :tag "Use #+ATTR* or don't resize" nil)))
18043 (defcustom org-agenda-inhibit-startup nil
18044 "Inhibit startup when preparing agenda buffers.
18045 When this variable is `t', the initialization of the Org agenda
18046 buffers is inhibited: e.g. the visibility state is not set, the
18047 tables are not re-aligned, etc."
18048 :type 'boolean
18049 :version "24.3"
18050 :group 'org-agenda)
18052 (define-obsolete-variable-alias
18053 'org-agenda-ignore-drawer-properties
18054 'org-agenda-ignore-properties "25.1")
18056 (defcustom org-agenda-ignore-properties nil
18057 "Avoid updating text properties when building the agenda.
18058 Properties are used to prepare buffers for effort estimates,
18059 appointments, statistics and subtree-local categories.
18060 If you don't use these in the agenda, you can add them to this
18061 list and agenda building will be a bit faster.
18062 The value is a list, with zero or more of the symbols `effort', `appt',
18063 `stats' or `category'."
18064 :type '(set :greedy t
18065 (const effort)
18066 (const appt)
18067 (const stats)
18068 (const category))
18069 :version "25.1"
18070 :package-version '(Org . "8.3")
18071 :group 'org-agenda)
18073 (defun org-duration-string-to-minutes (s &optional output-to-string)
18074 "Convert a duration string S to minutes.
18076 A bare number is interpreted as minutes, modifiers can be set by
18077 customizing `org-effort-durations' (which see).
18079 Entries containing a colon are interpreted as H:MM by
18080 `org-hh:mm-string-to-minutes'."
18081 (let ((result 0)
18082 (re (concat "\\([0-9.]+\\) *\\("
18083 (regexp-opt (mapcar 'car org-effort-durations))
18084 "\\)")))
18085 (while (string-match re s)
18086 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18087 (string-to-number (match-string 1 s))))
18088 (setq s (replace-match "" nil t s)))
18089 (setq result (floor result))
18090 (incf result (org-hh:mm-string-to-minutes s))
18091 (if output-to-string (number-to-string result) result)))
18093 ;;;; Files
18095 (defun org-save-all-org-buffers ()
18096 "Save all Org-mode buffers without user confirmation."
18097 (interactive)
18098 (message "Saving all Org-mode buffers...")
18099 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18100 (when (featurep 'org-id) (org-id-locations-save))
18101 (message "Saving all Org-mode buffers... done"))
18103 (defun org-revert-all-org-buffers ()
18104 "Revert all Org-mode buffers.
18105 Prompt for confirmation when there are unsaved changes.
18106 Be sure you know what you are doing before letting this function
18107 overwrite your changes.
18109 This function is useful in a setup where one tracks org files
18110 with a version control system, to revert on one machine after pulling
18111 changes from another. I believe the procedure must be like this:
18113 1. M-x org-save-all-org-buffers
18114 2. Pull changes from the other machine, resolve conflicts
18115 3. M-x org-revert-all-org-buffers"
18116 (interactive)
18117 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18118 (user-error "Abort"))
18119 (save-excursion
18120 (save-window-excursion
18121 (mapc
18122 (lambda (b)
18123 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18124 (with-current-buffer b buffer-file-name))
18125 (org-pop-to-buffer-same-window b)
18126 (revert-buffer t 'no-confirm)))
18127 (buffer-list))
18128 (when (and (featurep 'org-id) org-id-track-globally)
18129 (org-id-locations-load)))))
18131 ;;;; Agenda files
18133 ;;;###autoload
18134 (defun org-switchb (&optional arg)
18135 "Switch between Org buffers.
18136 With one prefix argument, restrict available buffers to files.
18137 With two prefix arguments, restrict available buffers to agenda files.
18139 Defaults to `iswitchb' for buffer name completion.
18140 Set `org-completion-use-ido' to make it use ido instead."
18141 (interactive "P")
18142 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18143 ((equal arg '(16)) (org-buffer-list 'agenda))
18144 (t (org-buffer-list))))
18145 (org-completion-use-iswitchb org-completion-use-iswitchb)
18146 (org-completion-use-ido org-completion-use-ido))
18147 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18148 (setq org-completion-use-iswitchb t))
18149 (org-pop-to-buffer-same-window
18150 (org-icompleting-read "Org buffer: "
18151 (mapcar 'list (mapcar 'buffer-name blist))
18152 nil t))))
18154 ;;; Define some older names previously used for this functionality
18155 ;;;###autoload
18156 (defalias 'org-ido-switchb 'org-switchb)
18157 ;;;###autoload
18158 (defalias 'org-iswitchb 'org-switchb)
18160 (defun org-buffer-list (&optional predicate exclude-tmp)
18161 "Return a list of Org buffers.
18162 PREDICATE can be `export', `files' or `agenda'.
18164 export restrict the list to Export buffers.
18165 files restrict the list to buffers visiting Org files.
18166 agenda restrict the list to buffers visiting agenda files.
18168 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18169 (let* ((bfn nil)
18170 (agenda-files (and (eq predicate 'agenda)
18171 (mapcar 'file-truename (org-agenda-files t))))
18172 (filter
18173 (cond
18174 ((eq predicate 'files)
18175 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18176 ((eq predicate 'export)
18177 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18178 ((eq predicate 'agenda)
18179 (lambda (b)
18180 (with-current-buffer b
18181 (and (derived-mode-p 'org-mode)
18182 (setq bfn (buffer-file-name b))
18183 (member (file-truename bfn) agenda-files)))))
18184 (t (lambda (b) (with-current-buffer b
18185 (or (derived-mode-p 'org-mode)
18186 (string-match "\*Org .*Export"
18187 (buffer-name b)))))))))
18188 (delq nil
18189 (mapcar
18190 (lambda(b)
18191 (if (and (funcall filter b)
18192 (or (not exclude-tmp)
18193 (not (string-match "tmp" (buffer-name b)))))
18195 nil))
18196 (buffer-list)))))
18198 (defun org-agenda-files (&optional unrestricted archives)
18199 "Get the list of agenda files.
18200 Optional UNRESTRICTED means return the full list even if a restriction
18201 is currently in place.
18202 When ARCHIVES is t, include all archive files that are really being
18203 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18204 `org-agenda-archives-mode' is t."
18205 (let ((files
18206 (cond
18207 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18208 ((stringp org-agenda-files) (org-read-agenda-file-list))
18209 ((listp org-agenda-files) org-agenda-files)
18210 (t (error "Invalid value of `org-agenda-files'")))))
18211 (setq files (apply 'append
18212 (mapcar (lambda (f)
18213 (if (file-directory-p f)
18214 (directory-files
18215 f t org-agenda-file-regexp)
18216 (list f)))
18217 files)))
18218 (when org-agenda-skip-unavailable-files
18219 (setq files (delq nil
18220 (mapcar (function
18221 (lambda (file)
18222 (and (file-readable-p file) file)))
18223 files))))
18224 (when (or (eq archives t)
18225 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18226 (setq files (org-add-archive-files files)))
18227 files))
18229 (defun org-agenda-file-p (&optional file)
18230 "Return non-nil, if FILE is an agenda file.
18231 If FILE is omitted, use the file associated with the current
18232 buffer."
18233 (let ((fname (or file (buffer-file-name))))
18234 (and fname
18235 (member (file-truename fname)
18236 (mapcar #'file-truename (org-agenda-files t))))))
18238 (defun org-edit-agenda-file-list ()
18239 "Edit the list of agenda files.
18240 Depending on setup, this either uses customize to edit the variable
18241 `org-agenda-files', or it visits the file that is holding the list. In the
18242 latter case, the buffer is set up in a way that saving it automatically kills
18243 the buffer and restores the previous window configuration."
18244 (interactive)
18245 (if (stringp org-agenda-files)
18246 (let ((cw (current-window-configuration)))
18247 (find-file org-agenda-files)
18248 (org-set-local 'org-window-configuration cw)
18249 (org-add-hook 'after-save-hook
18250 (lambda ()
18251 (set-window-configuration
18252 (prog1 org-window-configuration
18253 (kill-buffer (current-buffer))))
18254 (org-install-agenda-files-menu)
18255 (message "New agenda file list installed"))
18256 nil 'local)
18257 (message "%s" (substitute-command-keys
18258 "Edit list and finish with \\[save-buffer]")))
18259 (customize-variable 'org-agenda-files)))
18261 (defun org-store-new-agenda-file-list (list)
18262 "Set new value for the agenda file list and save it correctly."
18263 (if (stringp org-agenda-files)
18264 (let ((fe (org-read-agenda-file-list t)) b u)
18265 (while (setq b (find-buffer-visiting org-agenda-files))
18266 (kill-buffer b))
18267 (with-temp-file org-agenda-files
18268 (insert
18269 (mapconcat
18270 (lambda (f) ;; Keep un-expanded entries.
18271 (if (setq u (assoc f fe))
18272 (cdr u)
18274 list "\n")
18275 "\n")))
18276 (let ((org-mode-hook nil) (org-inhibit-startup t)
18277 (org-insert-mode-line-in-empty-file nil))
18278 (setq org-agenda-files list)
18279 (customize-save-variable 'org-agenda-files org-agenda-files))))
18281 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18282 "Read the list of agenda files from a file.
18283 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18284 filenames, used by `org-store-new-agenda-file-list' to write back
18285 un-expanded file names."
18286 (when (file-directory-p org-agenda-files)
18287 (error "`org-agenda-files' cannot be a single directory"))
18288 (when (stringp org-agenda-files)
18289 (with-temp-buffer
18290 (insert-file-contents org-agenda-files)
18291 (mapcar
18292 (lambda (f)
18293 (let ((e (expand-file-name (substitute-in-file-name f)
18294 org-directory)))
18295 (if pair-with-expansion
18296 (cons e f)
18297 e)))
18298 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18300 ;;;###autoload
18301 (defun org-cycle-agenda-files ()
18302 "Cycle through the files in `org-agenda-files'.
18303 If the current buffer visits an agenda file, find the next one in the list.
18304 If the current buffer does not, find the first agenda file."
18305 (interactive)
18306 (let* ((fs (org-agenda-files t))
18307 (files (append fs (list (car fs))))
18308 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18309 file)
18310 (unless files (user-error "No agenda files"))
18311 (catch 'exit
18312 (while (setq file (pop files))
18313 (if (equal (file-truename file) tcf)
18314 (when (car files)
18315 (find-file (car files))
18316 (throw 'exit t))))
18317 (find-file (car fs)))
18318 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18320 (defun org-agenda-file-to-front (&optional to-end)
18321 "Move/add the current file to the top of the agenda file list.
18322 If the file is not present in the list, it is added to the front. If it is
18323 present, it is moved there. With optional argument TO-END, add/move to the
18324 end of the list."
18325 (interactive "P")
18326 (let ((org-agenda-skip-unavailable-files nil)
18327 (file-alist (mapcar (lambda (x)
18328 (cons (file-truename x) x))
18329 (org-agenda-files t)))
18330 (ctf (file-truename
18331 (or buffer-file-name
18332 (user-error "Please save the current buffer to a file"))))
18333 x had)
18334 (setq x (assoc ctf file-alist) had x)
18336 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18337 (if to-end
18338 (setq file-alist (append (delq x file-alist) (list x)))
18339 (setq file-alist (cons x (delq x file-alist))))
18340 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18341 (org-install-agenda-files-menu)
18342 (message "File %s to %s of agenda file list"
18343 (if had "moved" "added") (if to-end "end" "front"))))
18345 (defun org-remove-file (&optional file)
18346 "Remove current file from the list of files in variable `org-agenda-files'.
18347 These are the files which are being checked for agenda entries.
18348 Optional argument FILE means use this file instead of the current."
18349 (interactive)
18350 (let* ((org-agenda-skip-unavailable-files nil)
18351 (file (or file buffer-file-name
18352 (user-error "Current buffer does not visit a file")))
18353 (true-file (file-truename file))
18354 (afile (abbreviate-file-name file))
18355 (files (delq nil (mapcar
18356 (lambda (x)
18357 (if (equal true-file
18358 (file-truename x))
18359 nil x))
18360 (org-agenda-files t)))))
18361 (if (not (= (length files) (length (org-agenda-files t))))
18362 (progn
18363 (org-store-new-agenda-file-list files)
18364 (org-install-agenda-files-menu)
18365 (message "Removed file: %s" afile))
18366 (message "File was not in list: %s (not removed)" afile))))
18368 (defun org-file-menu-entry (file)
18369 (vector file (list 'find-file file) t))
18371 (defun org-check-agenda-file (file)
18372 "Make sure FILE exists. If not, ask user what to do."
18373 (when (not (file-exists-p file))
18374 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18375 (abbreviate-file-name file))
18376 (let ((r (downcase (read-char-exclusive))))
18377 (cond
18378 ((equal r ?r)
18379 (org-remove-file file)
18380 (throw 'nextfile t))
18381 (t (user-error "Abort"))))))
18383 (defun org-get-agenda-file-buffer (file)
18384 "Get an agenda buffer visiting FILE.
18385 If the buffer needs to be created, add it to the list of buffers
18386 which might be released later."
18387 (let ((buf (org-find-base-buffer-visiting file)))
18388 (if buf
18389 buf ; just return it
18390 ;; Make a new buffer and remember it
18391 (setq buf (find-file-noselect file))
18392 (if buf (push buf org-agenda-new-buffers))
18393 buf)))
18395 (defun org-release-buffers (blist)
18396 "Release all buffers in list, asking the user for confirmation when needed.
18397 When a buffer is unmodified, it is just killed. When modified, it is saved
18398 \(if the user agrees) and then killed."
18399 (let (buf file)
18400 (while (setq buf (pop blist))
18401 (setq file (buffer-file-name buf))
18402 (when (and (buffer-modified-p buf)
18403 file
18404 (y-or-n-p (format "Save file %s? " file)))
18405 (with-current-buffer buf (save-buffer)))
18406 (kill-buffer buf))))
18408 (defun org-agenda-prepare-buffers (files)
18409 "Create buffers for all agenda files, protect archived trees and comments."
18410 (interactive)
18411 (let ((pa '(:org-archived t))
18412 (pc '(:org-comment t))
18413 (pall '(:org-archived t :org-comment t))
18414 (inhibit-read-only t)
18415 (org-inhibit-startup org-agenda-inhibit-startup)
18416 (rea (concat ":" org-archive-tag ":"))
18417 file re pos)
18418 (setq org-tag-alist-for-agenda nil
18419 org-tag-groups-alist-for-agenda nil)
18420 (save-excursion
18421 (save-restriction
18422 (while (setq file (pop files))
18423 (catch 'nextfile
18424 (if (bufferp file)
18425 (set-buffer file)
18426 (org-check-agenda-file file)
18427 (set-buffer (org-get-agenda-file-buffer file)))
18428 (widen)
18429 (org-set-regexps-and-options 'tags-only)
18430 (setq pos (point))
18431 (or (memq 'category org-agenda-ignore-properties)
18432 (org-refresh-category-properties))
18433 (or (memq 'stats org-agenda-ignore-properties)
18434 (org-refresh-stats-properties))
18435 (or (memq 'effort org-agenda-ignore-properties)
18436 (org-refresh-effort-properties))
18437 (or (memq 'appt org-agenda-ignore-properties)
18438 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18439 (setq org-todo-keywords-for-agenda
18440 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18441 (setq org-done-keywords-for-agenda
18442 (append org-done-keywords-for-agenda org-done-keywords))
18443 (setq org-todo-keyword-alist-for-agenda
18444 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18445 (setq org-tag-alist-for-agenda
18446 (org-uniquify
18447 (append org-tag-alist-for-agenda
18448 org-tag-alist
18449 org-tag-persistent-alist)))
18450 (if org-group-tags
18451 (setq org-tag-groups-alist-for-agenda
18452 (org-uniquify-alist
18453 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18454 (org-with-silent-modifications
18455 (save-excursion
18456 (remove-text-properties (point-min) (point-max) pall)
18457 (when org-agenda-skip-archived-trees
18458 (goto-char (point-min))
18459 (while (re-search-forward rea nil t)
18460 (if (org-at-heading-p t)
18461 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18462 (goto-char (point-min))
18463 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18464 (while (re-search-forward re nil t)
18465 (when (save-match-data (org-in-commented-heading-p t))
18466 (add-text-properties
18467 (match-beginning 0) (org-end-of-subtree t) pc)))))
18468 (goto-char pos)))))
18469 (setq org-todo-keywords-for-agenda
18470 (org-uniquify org-todo-keywords-for-agenda))
18471 (setq org-todo-keyword-alist-for-agenda
18472 (org-uniquify org-todo-keyword-alist-for-agenda))))
18475 ;;;; CDLaTeX minor mode
18477 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18478 "Keymap for the minor `org-cdlatex-mode'.")
18480 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18481 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18482 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18483 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18484 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18486 (defvar org-cdlatex-texmathp-advice-is-done nil
18487 "Flag remembering if we have applied the advice to texmathp already.")
18489 (define-minor-mode org-cdlatex-mode
18490 "Toggle the minor `org-cdlatex-mode'.
18491 This mode supports entering LaTeX environment and math in LaTeX fragments
18492 in Org-mode.
18493 \\{org-cdlatex-mode-map}"
18494 nil " OCDL" nil
18495 (when org-cdlatex-mode
18496 (require 'cdlatex)
18497 (run-hooks 'cdlatex-mode-hook)
18498 (cdlatex-compute-tables))
18499 (unless org-cdlatex-texmathp-advice-is-done
18500 (setq org-cdlatex-texmathp-advice-is-done t)
18501 (defadvice texmathp (around org-math-always-on activate)
18502 "Always return t in org-mode buffers.
18503 This is because we want to insert math symbols without dollars even outside
18504 the LaTeX math segments. If Orgmode thinks that point is actually inside
18505 an embedded LaTeX fragment, let texmathp do its job.
18506 \\[org-cdlatex-mode-map]"
18507 (interactive)
18508 (let (p)
18509 (cond
18510 ((not (derived-mode-p 'org-mode)) ad-do-it)
18511 ((eq this-command 'cdlatex-math-symbol)
18512 (setq ad-return-value t
18513 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18515 (let ((p (org-inside-LaTeX-fragment-p)))
18516 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18517 (setq ad-return-value t
18518 texmathp-why '("Org-mode embedded math" . 0))
18519 (if p ad-do-it)))))))))
18521 (defun turn-on-org-cdlatex ()
18522 "Unconditionally turn on `org-cdlatex-mode'."
18523 (org-cdlatex-mode 1))
18525 (defun org-try-cdlatex-tab ()
18526 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18527 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18528 - inside a LaTeX fragment, or
18529 - after the first word in a line, where an abbreviation expansion could
18530 insert a LaTeX environment."
18531 (when org-cdlatex-mode
18532 (cond
18533 ;; Before any word on the line: No expansion possible.
18534 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18535 ;; Just after first word on the line: Expand it. Make sure it
18536 ;; cannot happen on headlines, though.
18537 ((save-excursion
18538 (skip-chars-backward "a-zA-Z0-9*")
18539 (skip-chars-backward " \t")
18540 (and (bolp) (not (org-at-heading-p))))
18541 (cdlatex-tab) t)
18542 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18544 (defun org-cdlatex-underscore-caret (&optional arg)
18545 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18546 Revert to the normal definition outside of these fragments."
18547 (interactive "P")
18548 (if (org-inside-LaTeX-fragment-p)
18549 (call-interactively 'cdlatex-sub-superscript)
18550 (let (org-cdlatex-mode)
18551 (call-interactively (key-binding (vector last-input-event))))))
18553 (defun org-cdlatex-math-modify (&optional arg)
18554 "Execute `cdlatex-math-modify' in LaTeX fragments.
18555 Revert to the normal definition outside of these fragments."
18556 (interactive "P")
18557 (if (org-inside-LaTeX-fragment-p)
18558 (call-interactively 'cdlatex-math-modify)
18559 (let (org-cdlatex-mode)
18560 (call-interactively (key-binding (vector last-input-event))))))
18562 (defun org-cdlatex-environment-indent (&optional environment item)
18563 "Execute `cdlatex-environment' and indent the inserted environment."
18564 (interactive)
18565 (cdlatex-environment environment item)
18566 (let ((element (org-element-at-point)))
18567 (org-indent-region (org-element-property :begin element)
18568 (org-element-property :end element))))
18571 ;;;; LaTeX fragments
18573 (defun org-inside-LaTeX-fragment-p ()
18574 "Test if point is inside a LaTeX fragment.
18575 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18576 sequence appearing also before point.
18577 Even though the matchers for math are configurable, this function assumes
18578 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18579 delimiters are skipped when they have been removed by customization.
18580 The return value is nil, or a cons cell with the delimiter and the
18581 position of this delimiter.
18583 This function does a reasonably good job, but can locally be fooled by
18584 for example currency specifications. For example it will assume being in
18585 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18586 fragments that are properly closed, but during editing, we have to live
18587 with the uncertainty caused by missing closing delimiters. This function
18588 looks only before point, not after."
18589 (catch 'exit
18590 (let ((pos (point))
18591 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18592 (lim (progn
18593 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18594 (point)))
18595 dd-on str (start 0) m re)
18596 (goto-char pos)
18597 (when dodollar
18598 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18599 re (nth 1 (assoc "$" org-latex-regexps)))
18600 (while (string-match re str start)
18601 (cond
18602 ((= (match-end 0) (length str))
18603 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18604 ((= (match-end 0) (- (length str) 5))
18605 (throw 'exit nil))
18606 (t (setq start (match-end 0))))))
18607 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18608 (goto-char pos)
18609 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18610 (and (match-beginning 2) (throw 'exit nil))
18611 ;; count $$
18612 (while (re-search-backward "\\$\\$" lim t)
18613 (setq dd-on (not dd-on)))
18614 (goto-char pos)
18615 (if dd-on (cons "$$" m))))))
18617 (defun org-inside-latex-macro-p ()
18618 "Is point inside a LaTeX macro or its arguments?"
18619 (save-match-data
18620 (org-in-regexp
18621 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18623 (defvar org-latex-fragment-image-overlays nil
18624 "List of overlays carrying the images of latex fragments.")
18625 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18627 (defun org-remove-latex-fragment-image-overlays ()
18628 "Remove all overlays with LaTeX fragment images in current buffer."
18629 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18630 (setq org-latex-fragment-image-overlays nil))
18632 (define-obsolete-function-alias
18633 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18634 (defun org-toggle-latex-fragment (&optional subtree)
18635 "Preview the LaTeX fragment at point, or all locally or globally.
18636 If the cursor is in a LaTeX fragment, create the image and overlay
18637 it over the source code. If there is no fragment at point, display
18638 all fragments in the current text, from one headline to the next. With
18639 prefix SUBTREE, display all fragments in the current subtree. With a
18640 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18641 the cursor is before the first headline,
18642 display all fragments in the buffer.
18643 The images can be removed again with \\[org-toggle-latex-fragment]."
18644 (interactive "P")
18645 (unless buffer-file-name
18646 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18647 (if org-latex-fragment-image-overlays
18648 (progn (org-remove-latex-fragment-image-overlays)
18649 (message "LaTeX fragments images removed"))
18650 (when (display-graphic-p)
18651 (org-remove-latex-fragment-image-overlays)
18652 (save-excursion
18653 (save-restriction
18654 (let (beg end at msg)
18655 (cond
18656 ((or (equal subtree '(16))
18657 (not (save-excursion
18658 (re-search-backward org-outline-regexp-bol nil t))))
18659 (setq beg (point-min) end (point-max)
18660 msg "Creating images for buffer...%s"))
18661 ((equal subtree '(4))
18662 (org-back-to-heading)
18663 (setq beg (point) end (org-end-of-subtree t)
18664 msg "Creating images for subtree...%s"))
18666 (if (setq at (org-inside-LaTeX-fragment-p))
18667 (goto-char (max (point-min) (- (cdr at) 2)))
18668 (org-back-to-heading))
18669 (setq beg (point) end (progn (outline-next-heading) (point))
18670 msg (if at "Creating image...%s"
18671 "Creating images for entry...%s"))))
18672 (message msg "")
18673 (narrow-to-region beg end)
18674 (goto-char beg)
18675 (org-format-latex
18676 (concat org-latex-preview-ltxpng-directory
18677 (file-name-sans-extension
18678 (file-name-nondirectory buffer-file-name)))
18679 default-directory 'overlays msg at 'forbuffer
18680 org-latex-create-formula-image-program)
18681 (message msg "done. Use `C-c C-x C-l' to remove images.")))))))
18683 (defun org-format-latex (prefix &optional dir overlays msg at
18684 forbuffer processing-type)
18685 "Replace LaTeX fragments with links to an image, and produce images.
18686 Some of the options can be changed using the variable
18687 `org-format-latex-options'."
18688 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18689 (let* ((prefixnodir (file-name-nondirectory prefix))
18690 (absprefix (expand-file-name prefix dir))
18691 (todir (file-name-directory absprefix))
18692 (opt org-format-latex-options)
18693 (optnew org-format-latex-options)
18694 (matchers (plist-get opt :matchers))
18695 (re-list org-latex-regexps)
18696 (cnt 0) txt hash link beg end re e checkdir
18697 string
18698 m n block-type block linkfile movefile ov)
18699 ;; Check the different regular expressions
18700 (while (setq e (pop re-list))
18701 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18702 block (if block-type "\n\n" ""))
18703 (when (member m matchers)
18704 (goto-char (point-min))
18705 (while (re-search-forward re nil t)
18706 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18707 (or (not overlays)
18708 (not (eq (get-char-property (match-beginning n)
18709 'org-overlay-type)
18710 'org-latex-overlay))))
18711 (cond
18712 ((eq processing-type 'verbatim))
18713 ((eq processing-type 'mathjax)
18714 ;; Prepare for MathJax processing.
18715 (setq string (match-string n))
18716 (when (member m '("$" "$1"))
18717 (save-excursion
18718 (delete-region (match-beginning n) (match-end n))
18719 (goto-char (match-beginning n))
18720 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18721 ((or (eq processing-type 'dvipng)
18722 (eq processing-type 'imagemagick))
18723 ;; Process to an image.
18724 (setq txt (match-string n)
18725 beg (match-beginning n) end (match-end n)
18726 cnt (1+ cnt))
18727 (let ((face (face-at-point))
18728 (fg (plist-get opt :foreground))
18729 (bg (plist-get opt :background))
18730 ;; Ensure full list is printed.
18731 print-length print-level)
18732 (when forbuffer
18733 ;; Get the colors from the face at point.
18734 (goto-char beg)
18735 (when (eq fg 'auto)
18736 (setq fg (face-attribute face :foreground nil 'default)))
18737 (when (eq bg 'auto)
18738 (setq bg (face-attribute face :background nil 'default)))
18739 (setq optnew (copy-sequence opt))
18740 (plist-put optnew :foreground fg)
18741 (plist-put optnew :background bg))
18742 (setq hash (sha1 (prin1-to-string
18743 (list org-format-latex-header
18744 org-latex-default-packages-alist
18745 org-latex-packages-alist
18746 org-format-latex-options
18747 forbuffer txt fg bg)))
18748 linkfile (format "%s_%s.png" prefix hash)
18749 movefile (format "%s_%s.png" absprefix hash)))
18750 (setq link (concat block "[[file:" linkfile "]]" block))
18751 (if msg (message msg cnt))
18752 (goto-char beg)
18753 (unless checkdir ; Ensure the directory exists.
18754 (setq checkdir t)
18755 (or (file-directory-p todir) (make-directory todir t)))
18756 (unless (file-exists-p movefile)
18757 (org-create-formula-image
18758 txt movefile optnew forbuffer processing-type))
18759 (if overlays
18760 (progn
18761 (mapc (lambda (o)
18762 (if (eq (overlay-get o 'org-overlay-type)
18763 'org-latex-overlay)
18764 (delete-overlay o)))
18765 (overlays-in beg end))
18766 (setq ov (make-overlay beg end))
18767 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18768 (if (featurep 'xemacs)
18769 (progn
18770 (overlay-put ov 'invisible t)
18771 (overlay-put
18772 ov 'end-glyph
18773 (make-glyph (vector 'png :file movefile))))
18774 (overlay-put
18775 ov 'display
18776 (list 'image :type 'png :file movefile :ascent 'center)))
18777 (push ov org-latex-fragment-image-overlays)
18778 (goto-char end))
18779 (delete-region beg end)
18780 (insert (org-add-props link
18781 (list 'org-latex-src
18782 (replace-regexp-in-string
18783 "\"" "" txt)
18784 'org-latex-src-embed-type
18785 (if block-type 'paragraph 'character))))))
18786 ((eq processing-type 'mathml)
18787 ;; Process to MathML
18788 (unless (save-match-data (org-format-latex-mathml-available-p))
18789 (user-error "LaTeX to MathML converter not configured"))
18790 (setq txt (match-string n)
18791 beg (match-beginning n) end (match-end n)
18792 cnt (1+ cnt))
18793 (if msg (message msg cnt))
18794 (goto-char beg)
18795 (delete-region beg end)
18796 (insert (org-format-latex-as-mathml
18797 txt block-type prefix dir)))
18799 (error "Unknown conversion type %s for LaTeX fragments"
18800 processing-type)))))))))
18802 (defun org-create-math-formula (latex-frag &optional mathml-file)
18803 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18804 Use `org-latex-to-mathml-convert-command'. If the conversion is
18805 sucessful, return the portion between \"<math...> </math>\"
18806 elements otherwise return nil. When MATHML-FILE is specified,
18807 write the results in to that file. When invoked as an
18808 interactive command, prompt for LATEX-FRAG, with initial value
18809 set to the current active region and echo the results for user
18810 inspection."
18811 (interactive (list (let ((frag (when (org-region-active-p)
18812 (buffer-substring-no-properties
18813 (region-beginning) (region-end)))))
18814 (read-string "LaTeX Fragment: " frag nil frag))))
18815 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18816 (let* ((tmp-in-file (file-relative-name
18817 (make-temp-name (expand-file-name "ltxmathml-in"))))
18818 (ignore (write-region latex-frag nil tmp-in-file))
18819 (tmp-out-file (file-relative-name
18820 (make-temp-name (expand-file-name "ltxmathml-out"))))
18821 (cmd (format-spec
18822 org-latex-to-mathml-convert-command
18823 `((?j . ,(shell-quote-argument
18824 (expand-file-name org-latex-to-mathml-jar-file)))
18825 (?I . ,(shell-quote-argument tmp-in-file))
18826 (?o . ,(shell-quote-argument tmp-out-file)))))
18827 mathml shell-command-output)
18828 (when (org-called-interactively-p 'any)
18829 (unless (org-format-latex-mathml-available-p)
18830 (user-error "LaTeX to MathML converter not configured")))
18831 (message "Running %s" cmd)
18832 (setq shell-command-output (shell-command-to-string cmd))
18833 (setq mathml
18834 (when (file-readable-p tmp-out-file)
18835 (with-current-buffer (find-file-noselect tmp-out-file t)
18836 (goto-char (point-min))
18837 (when (re-search-forward
18838 (concat
18839 (regexp-quote
18840 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18841 "\\(.\\|\n\\)*"
18842 (regexp-quote "</math>")) nil t)
18843 (prog1 (match-string 0) (kill-buffer))))))
18844 (cond
18845 (mathml
18846 (setq mathml
18847 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18848 (when mathml-file
18849 (write-region mathml nil mathml-file))
18850 (when (org-called-interactively-p 'any)
18851 (message mathml)))
18852 ((message "LaTeX to MathML conversion failed")
18853 (message shell-command-output)))
18854 (delete-file tmp-in-file)
18855 (when (file-exists-p tmp-out-file)
18856 (delete-file tmp-out-file))
18857 mathml))
18859 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18860 prefix &optional dir)
18861 "Use `org-create-math-formula' but check local cache first."
18862 (let* ((absprefix (expand-file-name prefix dir))
18863 (print-length nil) (print-level nil)
18864 (formula-id (concat
18865 "formula-"
18866 (sha1
18867 (prin1-to-string
18868 (list latex-frag
18869 org-latex-to-mathml-convert-command)))))
18870 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18871 (formula-cache-dir (file-name-directory formula-cache)))
18873 (unless (file-directory-p formula-cache-dir)
18874 (make-directory formula-cache-dir t))
18876 (unless (file-exists-p formula-cache)
18877 (org-create-math-formula latex-frag formula-cache))
18879 (if (file-exists-p formula-cache)
18880 ;; Successful conversion. Return the link to MathML file.
18881 (org-add-props
18882 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18883 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18884 'org-latex-src-embed-type (if latex-frag-type
18885 'paragraph 'character)))
18886 ;; Failed conversion. Return the LaTeX fragment verbatim
18887 latex-frag)))
18889 (defun org-create-formula-image (string tofile options buffer &optional type)
18890 "Create an image from LaTeX source using dvipng or convert.
18891 This function calls either `org-create-formula-image-with-dvipng'
18892 or `org-create-formula-image-with-imagemagick' depending on the
18893 value of `org-latex-create-formula-image-program' or on the value
18894 of the optional TYPE variable.
18896 Note: ultimately these two function should be combined as they
18897 share a good deal of logic."
18898 (org-check-external-command
18899 "latex" "needed to convert LaTeX fragments to images")
18900 (funcall
18901 (case (or type org-latex-create-formula-image-program)
18902 ('dvipng
18903 (org-check-external-command
18904 "dvipng" "needed to convert LaTeX fragments to images")
18905 'org-create-formula-image-with-dvipng)
18906 ('imagemagick
18907 (org-check-external-command
18908 "convert" "you need to install imagemagick")
18909 'org-create-formula-image-with-imagemagick)
18910 (t (error
18911 "Invalid value of `org-latex-create-formula-image-program'")))
18912 string tofile options buffer))
18914 (declare-function org-export-get-backend "ox" (name))
18915 (declare-function org-export--get-global-options "ox" (&optional backend))
18916 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18917 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18918 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18919 (defun org-create-formula--latex-header ()
18920 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18921 (let ((info (org-combine-plists (org-export--get-global-options
18922 (org-export-get-backend 'latex))
18923 (org-export--get-inbuffer-options
18924 (org-export-get-backend 'latex)))))
18925 (org-latex-guess-babel-language
18926 (org-latex-guess-inputenc
18927 (org-splice-latex-header
18928 org-format-latex-header
18929 org-latex-default-packages-alist
18930 org-latex-packages-alist t
18931 (plist-get info :latex-header)))
18932 info)))
18934 ;; This function borrows from Ganesh Swami's latex2png.el
18935 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18936 "This calls dvipng."
18937 (require 'ox-latex)
18938 (let* ((tmpdir (if (featurep 'xemacs)
18939 (temp-directory)
18940 temporary-file-directory))
18941 (texfilebase (make-temp-name
18942 (expand-file-name "orgtex" tmpdir)))
18943 (texfile (concat texfilebase ".tex"))
18944 (dvifile (concat texfilebase ".dvi"))
18945 (pngfile (concat texfilebase ".png"))
18946 (fnh (if (featurep 'xemacs)
18947 (font-height (face-font 'default))
18948 (face-attribute 'default :height nil)))
18949 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18950 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18951 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18952 "Black"))
18953 (bg (or (plist-get options (if buffer :background :html-background))
18954 "Transparent")))
18955 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18956 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18957 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18958 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18959 (let ((latex-header (org-create-formula--latex-header)))
18960 (with-temp-file texfile
18961 (insert latex-header)
18962 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18963 (let ((dir default-directory))
18964 (ignore-errors
18965 (cd tmpdir)
18966 (call-process "latex" nil nil nil texfile))
18967 (cd dir))
18968 (if (not (file-exists-p dvifile))
18969 (progn (message "Failed to create dvi file from %s" texfile) nil)
18970 (ignore-errors
18971 (if (featurep 'xemacs)
18972 (call-process "dvipng" nil nil nil
18973 "-fg" fg "-bg" bg
18974 "-T" "tight"
18975 "-o" pngfile
18976 dvifile)
18977 (call-process "dvipng" nil nil nil
18978 "-fg" fg "-bg" bg
18979 "-D" dpi
18980 ;;"-x" scale "-y" scale
18981 "-T" "tight"
18982 "-o" pngfile
18983 dvifile)))
18984 (if (not (file-exists-p pngfile))
18985 (if org-format-latex-signal-error
18986 (error "Failed to create png file from %s" texfile)
18987 (message "Failed to create png file from %s" texfile)
18988 nil)
18989 ;; Use the requested file name and clean up
18990 (copy-file pngfile tofile 'replace)
18991 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18992 (if (file-exists-p (concat texfilebase e))
18993 (delete-file (concat texfilebase e))))
18994 pngfile))))
18996 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18997 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18998 "This calls convert, which is included into imagemagick."
18999 (require 'ox-latex)
19000 (let* ((tmpdir (if (featurep 'xemacs)
19001 (temp-directory)
19002 temporary-file-directory))
19003 (texfilebase (make-temp-name
19004 (expand-file-name "orgtex" tmpdir)))
19005 (texfile (concat texfilebase ".tex"))
19006 (pdffile (concat texfilebase ".pdf"))
19007 (pngfile (concat texfilebase ".png"))
19008 (fnh (if (featurep 'xemacs)
19009 (font-height (face-font 'default))
19010 (face-attribute 'default :height nil)))
19011 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19012 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
19013 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19014 "black"))
19015 (bg (or (plist-get options (if buffer :background :html-background))
19016 "white")))
19017 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19018 (setq fg (org-latex-color-format fg)))
19019 (if (eq bg 'default) (setq bg (org-latex-color :background))
19020 (setq bg (org-latex-color-format
19021 (if (string= bg "Transparent") "white" bg))))
19022 (let ((latex-header (org-create-formula--latex-header)))
19023 (with-temp-file texfile
19024 (insert latex-header)
19025 (insert "\n\\begin{document}\n"
19026 "\\definecolor{fg}{rgb}{" fg "}\n"
19027 "\\definecolor{bg}{rgb}{" bg "}\n"
19028 "\n\\pagecolor{bg}\n"
19029 "\n{\\color{fg}\n"
19030 string
19031 "\n}\n"
19032 "\n\\end{document}\n")))
19033 (org-latex-compile texfile t)
19034 (if (not (file-exists-p pdffile))
19035 (progn (message "Failed to create pdf file from %s" texfile) nil)
19036 (ignore-errors
19037 (if (featurep 'xemacs)
19038 (call-process "convert" nil nil nil
19039 "-density" "96"
19040 "-trim"
19041 "-antialias"
19042 pdffile
19043 "-quality" "100"
19044 ;; "-sharpen" "0x1.0"
19045 pngfile)
19046 (call-process "convert" nil nil nil
19047 "-density" dpi
19048 "-trim"
19049 "-antialias"
19050 pdffile
19051 "-quality" "100"
19052 ;; "-sharpen" "0x1.0"
19053 pngfile)))
19054 (if (not (file-exists-p pngfile))
19055 (if org-format-latex-signal-error
19056 (error "Failed to create png file from %s" texfile)
19057 (message "Failed to create png file from %s" texfile)
19058 nil)
19059 ;; Use the requested file name and clean up
19060 (copy-file pngfile tofile 'replace)
19061 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19062 (if (file-exists-p (concat texfilebase e))
19063 (delete-file (concat texfilebase e))))
19064 pngfile))))
19066 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19067 "Fill a LaTeX header template TPL.
19068 In the template, the following place holders will be recognized:
19070 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19071 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19072 [PACKAGES] \\usepackage statements for PKG
19073 [NO-PACKAGES] do not include PKG
19074 [EXTRA] the string EXTRA
19075 [NO-EXTRA] do not include EXTRA
19077 For backward compatibility, if both the positive and the negative place
19078 holder is missing, the positive one (without the \"NO-\") will be
19079 assumed to be present at the end of the template.
19080 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19081 EXTRA is a string.
19082 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19083 (let (rpl (end ""))
19084 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19085 (setq rpl (if (or (match-end 1) (not def-pkg))
19086 "" (org-latex-packages-to-string def-pkg snippets-p t))
19087 tpl (replace-match rpl t t tpl))
19088 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19090 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19091 (setq rpl (if (or (match-end 1) (not pkg))
19092 "" (org-latex-packages-to-string pkg snippets-p t))
19093 tpl (replace-match rpl t t tpl))
19094 (if pkg (setq end
19095 (concat end "\n"
19096 (org-latex-packages-to-string pkg snippets-p)))))
19098 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19099 (setq rpl (if (or (match-end 1) (not extra))
19100 "" (concat extra "\n"))
19101 tpl (replace-match rpl t t tpl))
19102 (if (and extra (string-match "\\S-" extra))
19103 (setq end (concat end "\n" extra))))
19105 (if (string-match "\\S-" end)
19106 (concat tpl "\n" end)
19107 tpl)))
19109 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19110 "Turn an alist of packages into a string with the \\usepackage macros."
19111 (setq pkg (mapconcat (lambda(p)
19112 (cond
19113 ((stringp p) p)
19114 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19115 (format "%% Package %s omitted" (cadr p)))
19116 ((equal "" (car p))
19117 (format "\\usepackage{%s}" (cadr p)))
19119 (format "\\usepackage[%s]{%s}"
19120 (car p) (cadr p)))))
19122 "\n"))
19123 (if newline (concat pkg "\n") pkg))
19125 (defun org-dvipng-color (attr)
19126 "Return a RGB color specification for dvipng."
19127 (apply 'format "rgb %s %s %s"
19128 (mapcar 'org-normalize-color
19129 (if (featurep 'xemacs)
19130 (color-rgb-components
19131 (face-property 'default
19132 (cond ((eq attr :foreground) 'foreground)
19133 ((eq attr :background) 'background))))
19134 (color-values (face-attribute 'default attr nil))))))
19136 (defun org-dvipng-color-format (color-name)
19137 "Convert COLOR-NAME to a RGB color value for dvipng."
19138 (apply 'format "rgb %s %s %s"
19139 (mapcar 'org-normalize-color
19140 (color-values color-name))))
19142 (defun org-latex-color (attr)
19143 "Return a RGB color for the LaTeX color package."
19144 (apply 'format "%s,%s,%s"
19145 (mapcar 'org-normalize-color
19146 (if (featurep 'xemacs)
19147 (color-rgb-components
19148 (face-property 'default
19149 (cond ((eq attr :foreground) 'foreground)
19150 ((eq attr :background) 'background))))
19151 (color-values (face-attribute 'default attr nil))))))
19153 (defun org-latex-color-format (color-name)
19154 "Convert COLOR-NAME to a RGB color value."
19155 (apply 'format "%s,%s,%s"
19156 (mapcar 'org-normalize-color
19157 (color-values color-name))))
19159 (defun org-normalize-color (value)
19160 "Return string to be used as color value for an RGB component."
19161 (format "%g" (/ value 65535.0)))
19165 ;; Image display
19167 (defvar org-inline-image-overlays nil)
19168 (make-variable-buffer-local 'org-inline-image-overlays)
19170 (defun org-toggle-inline-images (&optional include-linked)
19171 "Toggle the display of inline images.
19172 INCLUDE-LINKED is passed to `org-display-inline-images'."
19173 (interactive "P")
19174 (if org-inline-image-overlays
19175 (progn
19176 (org-remove-inline-images)
19177 (message "Inline image display turned off"))
19178 (org-display-inline-images include-linked)
19179 (if (and (org-called-interactively-p)
19180 org-inline-image-overlays)
19181 (message "%d images displayed inline"
19182 (length org-inline-image-overlays))
19183 (message "No images to display inline"))))
19185 (defun org-redisplay-inline-images ()
19186 "Refresh the display of inline images."
19187 (interactive)
19188 (if (not org-inline-image-overlays)
19189 (org-toggle-inline-images)
19190 (org-toggle-inline-images)
19191 (org-toggle-inline-images)))
19193 (defun org-display-inline-images (&optional include-linked refresh beg end)
19194 "Display inline images.
19196 An inline image is a link which follows either of these
19197 conventions:
19199 1. Its path is a file with an extension matching return value
19200 from `image-file-name-regexp' and it has no contents.
19202 2. Its description consists in a single link of the previous
19203 type.
19205 When optional argument INCLUDE-LINKED is non-nil, also links with
19206 a text description part will be inlined. This can be nice for
19207 a quick look at those images, but it does not reflect what
19208 exported files will look like.
19210 When optional argument REFRESH is non-nil, refresh existing
19211 images between BEG and END. This will create new image displays
19212 only if necessary. BEG and END default to the buffer
19213 boundaries."
19214 (interactive "P")
19215 (when (display-graphic-p)
19216 (unless refresh
19217 (org-remove-inline-images)
19218 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19219 (org-with-wide-buffer
19220 (goto-char (or beg (point-min)))
19221 (let ((case-fold-search t)
19222 (file-extension-re (org-image-file-name-regexp)))
19223 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19224 (let ((link (save-match-data (org-element-context))))
19225 ;; Check if we're at an inline image.
19226 (when (and (equal (org-element-property :type link) "file")
19227 (or include-linked
19228 (not (org-element-property :contents-begin link)))
19229 (let ((parent (org-element-property :parent link)))
19230 (or (not (eq (org-element-type parent) 'link))
19231 (not (cdr (org-element-contents parent)))))
19232 (org-string-match-p file-extension-re
19233 (org-element-property :path link)))
19234 (let ((file (expand-file-name (org-element-property :path link))))
19235 (when (file-exists-p file)
19236 (let ((width
19237 ;; Apply `org-image-actual-width' specifications.
19238 (cond
19239 ((not (image-type-available-p 'imagemagick)) nil)
19240 ((eq org-image-actual-width t) nil)
19241 ((listp org-image-actual-width)
19243 ;; First try to find a width among
19244 ;; attributes associated to the paragraph
19245 ;; containing link.
19246 (let ((paragraph
19247 (let ((e link))
19248 (while (and (setq e (org-element-property
19249 :parent e))
19250 (not (eq (org-element-type e)
19251 'paragraph))))
19252 e)))
19253 (when paragraph
19254 (save-excursion
19255 (goto-char (org-element-property :begin paragraph))
19256 (when
19257 (re-search-forward
19258 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19259 (org-element-property
19260 :post-affiliated paragraph)
19262 (string-to-number (match-string 1))))))
19263 ;; Otherwise, fall-back to provided number.
19264 (car org-image-actual-width)))
19265 ((numberp org-image-actual-width)
19266 org-image-actual-width)))
19267 (old (get-char-property-and-overlay
19268 (org-element-property :begin link)
19269 'org-image-overlay)))
19270 (if (and (car-safe old) refresh)
19271 (image-refresh (overlay-get (cdr old) 'display))
19272 (let ((image (create-image file
19273 (and width 'imagemagick)
19275 :width width)))
19276 (when image
19277 (let* ((link
19278 ;; If inline image is the description
19279 ;; of another link, be sure to
19280 ;; consider the latter as the one to
19281 ;; apply the overlay on.
19282 (let ((parent
19283 (org-element-property :parent link)))
19284 (if (eq (org-element-type parent) 'link)
19285 parent
19286 link)))
19287 (ov (make-overlay
19288 (org-element-property :begin link)
19289 (progn
19290 (goto-char
19291 (org-element-property :end link))
19292 (skip-chars-backward " \t")
19293 (point)))))
19294 (overlay-put ov 'display image)
19295 (overlay-put ov 'face 'default)
19296 (overlay-put ov 'org-image-overlay t)
19297 (overlay-put
19298 ov 'modification-hooks
19299 (list 'org-display-inline-remove-overlay))
19300 (push ov org-inline-image-overlays)))))))))))))))
19302 (define-obsolete-function-alias
19303 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19305 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19306 "Remove inline-display overlay if a corresponding region is modified."
19307 (let ((inhibit-modification-hooks t))
19308 (when (and ov after)
19309 (delete ov org-inline-image-overlays)
19310 (delete-overlay ov))))
19312 (defun org-remove-inline-images ()
19313 "Remove inline display of images."
19314 (interactive)
19315 (mapc 'delete-overlay org-inline-image-overlays)
19316 (setq org-inline-image-overlays nil))
19318 ;;;; Key bindings
19320 ;; Outline functions from `outline-mode-prefix-map'
19321 ;; that can be remapped in Org:
19322 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19323 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19324 (define-key org-mode-map [remap outline-forward-same-level]
19325 'org-forward-heading-same-level)
19326 (define-key org-mode-map [remap outline-backward-same-level]
19327 'org-backward-heading-same-level)
19328 (define-key org-mode-map [remap show-branches]
19329 'org-kill-note-or-show-branches)
19330 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19331 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19332 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19334 ;; Outline functions from `outline-mode-prefix-map' that can not
19335 ;; be remapped in Org:
19337 ;; - the column "key binding" shows whether the Outline function is still
19338 ;; available in Org mode on the same key that it has been bound to in
19339 ;; Outline mode:
19340 ;; - "overridden": key used for a different functionality in Org mode
19341 ;; - else: key still bound to the same Outline function in Org mode
19343 ;; | Outline function | key binding | Org replacement |
19344 ;; |------------------------------------+-------------+-----------------------|
19345 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19346 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19347 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19348 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19349 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19350 ;; | `show-entry' | overridden | no replacement |
19351 ;; | `show-children' | `C-c C-i' | visibility cycling |
19352 ;; | `show-branches' | `C-c C-k' | still same function |
19353 ;; | `show-subtree' | overridden | visibility cycling |
19354 ;; | `show-all' | overridden | no replacement |
19355 ;; | `hide-subtree' | overridden | visibility cycling |
19356 ;; | `hide-body' | overridden | no replacement |
19357 ;; | `hide-entry' | overridden | visibility cycling |
19358 ;; | `hide-leaves' | overridden | no replacement |
19359 ;; | `hide-sublevels' | overridden | no replacement |
19360 ;; | `hide-other' | overridden | no replacement |
19362 ;; Make `C-c C-x' a prefix key
19363 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19365 ;; TAB key with modifiers
19366 (org-defkey org-mode-map "\C-i" 'org-cycle)
19367 (org-defkey org-mode-map [(tab)] 'org-cycle)
19368 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19369 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19370 ;; The following line is necessary under Suse GNU/Linux
19371 (unless (featurep 'xemacs)
19372 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19373 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19374 (define-key org-mode-map [backtab] 'org-shifttab)
19376 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19377 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19378 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19380 ;; Cursor keys with modifiers
19381 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19382 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19383 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19384 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19386 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19387 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19388 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19389 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19390 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19391 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19393 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19394 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19395 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19396 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19398 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19399 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19400 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19401 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19403 ;; Babel keys
19404 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19405 (mapc (lambda (pair)
19406 (define-key org-babel-map (car pair) (cdr pair)))
19407 org-babel-key-bindings)
19409 ;;; Extra keys for tty access.
19410 ;; We only set them when really needed because otherwise the
19411 ;; menus don't show the simple keys
19413 (when (or org-use-extra-keys
19414 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19415 (not window-system))
19416 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19417 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19418 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19419 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19420 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19421 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19422 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19423 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19424 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19425 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19426 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19427 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19428 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19429 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19430 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19431 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19432 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19433 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19434 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19435 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19436 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19437 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19438 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19439 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19440 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19441 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19442 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19443 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19445 ;; All the other keys
19447 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19448 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19449 (if (boundp 'narrow-map)
19450 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19451 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19452 (if (boundp 'narrow-map)
19453 (org-defkey narrow-map "b" 'org-narrow-to-block)
19454 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19455 (if (boundp 'narrow-map)
19456 (org-defkey narrow-map "e" 'org-narrow-to-element)
19457 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19458 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19459 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19460 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19461 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19462 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19463 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19464 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19465 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19466 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19467 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19468 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19469 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19470 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19471 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19472 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19473 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19474 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19475 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19476 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19477 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19478 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19479 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19480 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19481 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19482 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19483 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19484 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19485 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19486 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19487 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19488 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19489 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19490 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19491 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19492 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19493 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19494 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19495 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19496 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19497 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19498 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19499 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19500 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19501 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19502 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19503 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19504 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19505 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19506 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19507 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19508 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19509 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19510 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19511 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19512 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19513 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19514 (org-defkey org-mode-map "\C-c^" 'org-sort)
19515 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19516 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19517 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19518 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19519 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19520 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19521 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19522 (org-defkey org-mode-map "\C-m" 'org-return)
19523 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19524 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19525 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19526 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19527 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19528 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19529 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19530 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19531 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19532 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19533 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19534 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19535 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19536 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19537 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19538 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19539 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19540 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19541 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19542 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19543 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19544 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19545 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19546 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19547 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19549 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19550 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19551 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19553 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19554 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19555 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19556 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19557 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19558 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19559 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19560 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19561 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19562 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19563 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19564 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19565 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19566 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19567 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19568 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19569 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19570 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19571 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19572 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19573 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19574 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19575 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19577 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19578 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19579 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19580 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19581 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19583 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19585 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19587 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19588 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19590 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19593 (when (featurep 'xemacs)
19594 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19597 (defconst org-speed-commands-default
19599 ("Outline Navigation")
19600 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19601 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19602 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19603 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19604 ("F" . org-next-block)
19605 ("B" . org-previous-block)
19606 ("u" . (org-speed-move-safe 'outline-up-heading))
19607 ("j" . org-goto)
19608 ("g" . (org-refile t))
19609 ("Outline Visibility")
19610 ("c" . org-cycle)
19611 ("C" . org-shifttab)
19612 (" " . org-display-outline-path)
19613 ("s" . org-narrow-to-subtree)
19614 ("=" . org-columns)
19615 ("Outline Structure Editing")
19616 ("U" . org-metaup)
19617 ("D" . org-metadown)
19618 ("r" . org-metaright)
19619 ("l" . org-metaleft)
19620 ("R" . org-shiftmetaright)
19621 ("L" . org-shiftmetaleft)
19622 ("i" . (progn (forward-char 1) (call-interactively
19623 'org-insert-heading-respect-content)))
19624 ("^" . org-sort)
19625 ("w" . org-refile)
19626 ("a" . org-archive-subtree-default-with-confirmation)
19627 ("@" . org-mark-subtree)
19628 ("#" . org-toggle-comment)
19629 ("Clock Commands")
19630 ("I" . org-clock-in)
19631 ("O" . org-clock-out)
19632 ("Meta Data Editing")
19633 ("t" . org-todo)
19634 ("," . (org-priority))
19635 ("0" . (org-priority ?\ ))
19636 ("1" . (org-priority ?A))
19637 ("2" . (org-priority ?B))
19638 ("3" . (org-priority ?C))
19639 (":" . org-set-tags-command)
19640 ("e" . org-set-effort)
19641 ("E" . org-inc-effort)
19642 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19643 (org-entry-put (point) "APPT_WARNTIME" m)))
19644 ("Agenda Views etc")
19645 ("v" . org-agenda)
19646 ("/" . org-sparse-tree)
19647 ("Misc")
19648 ("o" . org-open-at-point)
19649 ("?" . org-speed-command-help)
19650 ("<" . (org-agenda-set-restriction-lock 'subtree))
19651 (">" . (org-agenda-remove-restriction-lock))
19653 "The default speed commands.")
19655 (defun org-print-speed-command (e)
19656 (if (> (length (car e)) 1)
19657 (progn
19658 (princ "\n")
19659 (princ (car e))
19660 (princ "\n")
19661 (princ (make-string (length (car e)) ?-))
19662 (princ "\n"))
19663 (princ (car e))
19664 (princ " ")
19665 (if (symbolp (cdr e))
19666 (princ (symbol-name (cdr e)))
19667 (prin1 (cdr e)))
19668 (princ "\n")))
19670 (defun org-speed-command-help ()
19671 "Show the available speed commands."
19672 (interactive)
19673 (if (not org-use-speed-commands)
19674 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19675 (with-output-to-temp-buffer "*Help*"
19676 (princ "User-defined Speed commands\n===========================\n")
19677 (mapc 'org-print-speed-command org-speed-commands-user)
19678 (princ "\n")
19679 (princ "Built-in Speed commands\n=======================\n")
19680 (mapc 'org-print-speed-command org-speed-commands-default))
19681 (with-current-buffer "*Help*"
19682 (setq truncate-lines t))))
19684 (defun org-speed-move-safe (cmd)
19685 "Execute CMD, but make sure that the cursor always ends up in a headline.
19686 If not, return to the original position and throw an error."
19687 (interactive)
19688 (let ((pos (point)))
19689 (call-interactively cmd)
19690 (unless (and (bolp) (org-at-heading-p))
19691 (goto-char pos)
19692 (error "Boundary reached while executing %s" cmd))))
19694 (defvar org-self-insert-command-undo-counter 0)
19696 (defvar org-table-auto-blank-field) ; defined in org-table.el
19697 (defvar org-speed-command nil)
19699 (define-obsolete-function-alias
19700 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19702 (defun org-speed-command-activate (keys)
19703 "Hook for activating single-letter speed commands.
19704 `org-speed-commands-default' specifies a minimal command set.
19705 Use `org-speed-commands-user' for further customization."
19706 (when (or (and (bolp) (looking-at org-outline-regexp))
19707 (and (functionp org-use-speed-commands)
19708 (funcall org-use-speed-commands)))
19709 (cdr (assoc keys (append org-speed-commands-user
19710 org-speed-commands-default)))))
19712 (define-obsolete-function-alias
19713 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19715 (defun org-babel-speed-command-activate (keys)
19716 "Hook for activating single-letter code block commands."
19717 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19718 (cdr (assoc keys org-babel-key-bindings))))
19720 (defcustom org-speed-command-hook
19721 '(org-speed-command-default-hook org-babel-speed-command-hook)
19722 "Hook for activating speed commands at strategic locations.
19723 Hook functions are called in sequence until a valid handler is
19724 found.
19726 Each hook takes a single argument, a user-pressed command key
19727 which is also a `self-insert-command' from the global map.
19729 Within the hook, examine the cursor position and the command key
19730 and return nil or a valid handler as appropriate. Handler could
19731 be one of an interactive command, a function, or a form.
19733 Set `org-use-speed-commands' to non-nil value to enable this
19734 hook. The default setting is `org-speed-command-activate'."
19735 :group 'org-structure
19736 :version "24.1"
19737 :type 'hook)
19739 (defun org-self-insert-command (N)
19740 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19741 If the cursor is in a table looking at whitespace, the whitespace is
19742 overwritten, and the table is not marked as requiring realignment."
19743 (interactive "p")
19744 (org-check-before-invisible-edit 'insert)
19745 (cond
19746 ((and org-use-speed-commands
19747 (let ((kv (this-command-keys-vector)))
19748 (setq org-speed-command
19749 (run-hook-with-args-until-success
19750 'org-speed-command-hook
19751 (make-string 1 (aref kv (1- (length kv))))))))
19752 (cond
19753 ((commandp org-speed-command)
19754 (setq this-command org-speed-command)
19755 (call-interactively org-speed-command))
19756 ((functionp org-speed-command)
19757 (funcall org-speed-command))
19758 ((and org-speed-command (listp org-speed-command))
19759 (eval org-speed-command))
19760 (t (let (org-use-speed-commands)
19761 (call-interactively 'org-self-insert-command)))))
19762 ((and
19763 (org-table-p)
19764 (progn
19765 ;; check if we blank the field, and if that triggers align
19766 (and (featurep 'org-table) org-table-auto-blank-field
19767 (member last-command
19768 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas-expand))
19769 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19770 ;; got extra space, this field does not determine column width
19771 (let (org-table-may-need-update) (org-table-blank-field))
19772 ;; no extra space, this field may determine column width
19773 (org-table-blank-field)))
19775 (eq N 1)
19776 (looking-at "[^|\n]* |"))
19777 (let (org-table-may-need-update)
19778 (goto-char (1- (match-end 0)))
19779 (backward-delete-char 1)
19780 (goto-char (match-beginning 0))
19781 (self-insert-command N)))
19783 (setq org-table-may-need-update t)
19784 (self-insert-command N)
19785 (org-fix-tags-on-the-fly)
19786 (if org-self-insert-cluster-for-undo
19787 (if (not (eq last-command 'org-self-insert-command))
19788 (setq org-self-insert-command-undo-counter 1)
19789 (if (>= org-self-insert-command-undo-counter 20)
19790 (setq org-self-insert-command-undo-counter 1)
19791 (and (> org-self-insert-command-undo-counter 0)
19792 buffer-undo-list (listp buffer-undo-list)
19793 (not (cadr buffer-undo-list)) ; remove nil entry
19794 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19795 (setq org-self-insert-command-undo-counter
19796 (1+ org-self-insert-command-undo-counter))))))))
19798 (defun org-check-before-invisible-edit (kind)
19799 "Check is editing if kind KIND would be dangerous with invisible text around.
19800 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19801 ;; First, try to get out of here as quickly as possible, to reduce overhead
19802 (if (and org-catch-invisible-edits
19803 (or (not (boundp 'visible-mode)) (not visible-mode))
19804 (or (get-char-property (point) 'invisible)
19805 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19806 ;; OK, we need to take a closer look
19807 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19808 (invisible-before-point (if (bobp) nil (get-char-property
19809 (1- (point)) 'invisible)))
19810 (border-and-ok-direction
19812 ;; Check if we are acting predictably before invisible text
19813 (and invisible-at-point (not invisible-before-point)
19814 (memq kind '(insert delete-backward)))
19815 ;; Check if we are acting predictably after invisible text
19816 ;; This works not well, and I have turned it off. It seems
19817 ;; better to always show and stop after invisible text.
19818 ;; (and (not invisible-at-point) invisible-before-point
19819 ;; (memq kind '(insert delete)))
19821 (when (or (memq invisible-at-point '(outline org-hide-block t))
19822 (memq invisible-before-point '(outline org-hide-block t)))
19823 (if (eq org-catch-invisible-edits 'error)
19824 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19825 (if (and org-custom-properties-overlays
19826 (y-or-n-p "Display invisible properties in this buffer? "))
19827 (org-toggle-custom-properties-visibility)
19828 ;; Make the area visible
19829 (save-excursion
19830 (if invisible-before-point
19831 (goto-char (previous-single-char-property-change
19832 (point) 'invisible)))
19833 (show-subtree))
19834 (cond
19835 ((eq org-catch-invisible-edits 'show)
19836 ;; That's it, we do the edit after showing
19837 (message
19838 "Unfolding invisible region around point before editing")
19839 (sit-for 1))
19840 ((and (eq org-catch-invisible-edits 'smart)
19841 border-and-ok-direction)
19842 (message "Unfolding invisible region around point before editing"))
19844 ;; Don't do the edit, make the user repeat it in full visibility
19845 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19847 (defun org-fix-tags-on-the-fly ()
19848 (when (and (equal (char-after (point-at-bol)) ?*)
19849 (org-at-heading-p))
19850 (org-align-tags-here org-tags-column)))
19852 (defun org-delete-backward-char (N)
19853 "Like `delete-backward-char', insert whitespace at field end in tables.
19854 When deleting backwards, in tables this function will insert whitespace in
19855 front of the next \"|\" separator, to keep the table aligned. The table will
19856 still be marked for re-alignment if the field did fill the entire column,
19857 because, in this case the deletion might narrow the column."
19858 (interactive "p")
19859 (save-match-data
19860 (org-check-before-invisible-edit 'delete-backward)
19861 (if (and (org-table-p)
19862 (eq N 1)
19863 (string-match "|" (buffer-substring (point-at-bol) (point)))
19864 (looking-at ".*?|"))
19865 (let ((pos (point))
19866 (noalign (looking-at "[^|\n\r]* |"))
19867 (c org-table-may-need-update))
19868 (backward-delete-char N)
19869 (if (not overwrite-mode)
19870 (progn
19871 (skip-chars-forward "^|")
19872 (insert " ")
19873 (goto-char (1- pos))))
19874 ;; noalign: if there were two spaces at the end, this field
19875 ;; does not determine the width of the column.
19876 (if noalign (setq org-table-may-need-update c)))
19877 (backward-delete-char N)
19878 (org-fix-tags-on-the-fly))))
19880 (defun org-delete-char (N)
19881 "Like `delete-char', but insert whitespace at field end in tables.
19882 When deleting characters, in tables this function will insert whitespace in
19883 front of the next \"|\" separator, to keep the table aligned. The table will
19884 still be marked for re-alignment if the field did fill the entire column,
19885 because, in this case the deletion might narrow the column."
19886 (interactive "p")
19887 (save-match-data
19888 (org-check-before-invisible-edit 'delete)
19889 (if (and (org-table-p)
19890 (not (bolp))
19891 (not (= (char-after) ?|))
19892 (eq N 1))
19893 (if (looking-at ".*?|")
19894 (let ((pos (point))
19895 (noalign (looking-at "[^|\n\r]* |"))
19896 (c org-table-may-need-update))
19897 (replace-match
19898 (concat (substring (match-string 0) 1 -1) " |") nil t)
19899 (goto-char pos)
19900 ;; noalign: if there were two spaces at the end, this field
19901 ;; does not determine the width of the column.
19902 (if noalign (setq org-table-may-need-update c)))
19903 (delete-char N))
19904 (delete-char N)
19905 (org-fix-tags-on-the-fly))))
19907 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19908 (put 'org-self-insert-command 'delete-selection
19909 (lambda ()
19910 (not (run-hook-with-args-until-success
19911 'self-insert-uses-region-functions))))
19912 (put 'orgtbl-self-insert-command 'delete-selection
19913 (lambda ()
19914 (not (run-hook-with-args-until-success
19915 'self-insert-uses-region-functions))))
19916 (put 'org-delete-char 'delete-selection 'supersede)
19917 (put 'org-delete-backward-char 'delete-selection 'supersede)
19918 (put 'org-yank 'delete-selection 'yank)
19920 ;; Make `flyspell-mode' delay after some commands
19921 (put 'org-self-insert-command 'flyspell-delayed t)
19922 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19923 (put 'org-delete-char 'flyspell-delayed t)
19924 (put 'org-delete-backward-char 'flyspell-delayed t)
19926 ;; Make pabbrev-mode expand after org-mode commands
19927 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19928 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19930 (defun org-remap (map &rest commands)
19931 "In MAP, remap the functions given in COMMANDS.
19932 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19933 (let (new old)
19934 (while commands
19935 (setq old (pop commands) new (pop commands))
19936 (if (fboundp 'command-remapping)
19937 (org-defkey map (vector 'remap old) new)
19938 (substitute-key-definition old new map global-map)))))
19940 (defun org-transpose-words ()
19941 "Transpose words for Org.
19942 This uses the `org-mode-transpose-word-syntax-table' syntax
19943 table, which interprets characters in `org-emphasis-alist' as
19944 word constituents."
19945 (interactive)
19946 (with-syntax-table org-mode-transpose-word-syntax-table
19947 (call-interactively 'transpose-words)))
19948 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19950 (when (eq org-enable-table-editor 'optimized)
19951 ;; If the user wants maximum table support, we need to hijack
19952 ;; some standard editing functions
19953 (org-remap org-mode-map
19954 'self-insert-command 'org-self-insert-command
19955 'delete-char 'org-delete-char
19956 'delete-backward-char 'org-delete-backward-char)
19957 (org-defkey org-mode-map "|" 'org-force-self-insert))
19959 (defvar org-ctrl-c-ctrl-c-hook nil
19960 "Hook for functions attaching themselves to `C-c C-c'.
19962 This can be used to add additional functionality to the C-c C-c
19963 key which executes context-dependent commands. This hook is run
19964 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19965 run after the last test.
19967 Each function will be called with no arguments. The function
19968 must check if the context is appropriate for it to act. If yes,
19969 it should do its thing and then return a non-nil value. If the
19970 context is wrong, just do nothing and return nil.")
19972 (defvar org-ctrl-c-ctrl-c-final-hook nil
19973 "Hook for functions attaching themselves to `C-c C-c'.
19975 This can be used to add additional functionality to the C-c C-c
19976 key which executes context-dependent commands. This hook is run
19977 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19978 before the first test.
19980 Each function will be called with no arguments. The function
19981 must check if the context is appropriate for it to act. If yes,
19982 it should do its thing and then return a non-nil value. If the
19983 context is wrong, just do nothing and return nil.")
19985 (defvar org-tab-first-hook nil
19986 "Hook for functions to attach themselves to TAB.
19987 See `org-ctrl-c-ctrl-c-hook' for more information.
19988 This hook runs as the first action when TAB is pressed, even before
19989 `org-cycle' messes around with the `outline-regexp' to cater for
19990 inline tasks and plain list item folding.
19991 If any function in this hook returns t, any other actions that
19992 would have been caused by TAB (such as table field motion or visibility
19993 cycling) will not occur.")
19995 (defvar org-tab-after-check-for-table-hook nil
19996 "Hook for functions to attach themselves to TAB.
19997 See `org-ctrl-c-ctrl-c-hook' for more information.
19998 This hook runs after it has been established that the cursor is not in a
19999 table, but before checking if the cursor is in a headline or if global cycling
20000 should be done.
20001 If any function in this hook returns t, not other actions like visibility
20002 cycling will be done.")
20004 (defvar org-tab-after-check-for-cycling-hook nil
20005 "Hook for functions to attach themselves to TAB.
20006 See `org-ctrl-c-ctrl-c-hook' for more information.
20007 This hook runs after it has been established that not table field motion and
20008 not visibility should be done because of current context. This is probably
20009 the place where a package like yasnippets can hook in.")
20011 (defvar org-tab-before-tab-emulation-hook nil
20012 "Hook for functions to attach themselves to TAB.
20013 See `org-ctrl-c-ctrl-c-hook' for more information.
20014 This hook runs after every other options for TAB have been exhausted, but
20015 before indentation and \t insertion takes place.")
20017 (defvar org-metaleft-hook nil
20018 "Hook for functions attaching themselves to `M-left'.
20019 See `org-ctrl-c-ctrl-c-hook' for more information.")
20020 (defvar org-metaright-hook nil
20021 "Hook for functions attaching themselves to `M-right'.
20022 See `org-ctrl-c-ctrl-c-hook' for more information.")
20023 (defvar org-metaup-hook nil
20024 "Hook for functions attaching themselves to `M-up'.
20025 See `org-ctrl-c-ctrl-c-hook' for more information.")
20026 (defvar org-metadown-hook nil
20027 "Hook for functions attaching themselves to `M-down'.
20028 See `org-ctrl-c-ctrl-c-hook' for more information.")
20029 (defvar org-shiftmetaleft-hook nil
20030 "Hook for functions attaching themselves to `M-S-left'.
20031 See `org-ctrl-c-ctrl-c-hook' for more information.")
20032 (defvar org-shiftmetaright-hook nil
20033 "Hook for functions attaching themselves to `M-S-right'.
20034 See `org-ctrl-c-ctrl-c-hook' for more information.")
20035 (defvar org-shiftmetaup-hook nil
20036 "Hook for functions attaching themselves to `M-S-up'.
20037 See `org-ctrl-c-ctrl-c-hook' for more information.")
20038 (defvar org-shiftmetadown-hook nil
20039 "Hook for functions attaching themselves to `M-S-down'.
20040 See `org-ctrl-c-ctrl-c-hook' for more information.")
20041 (defvar org-metareturn-hook nil
20042 "Hook for functions attaching themselves to `M-RET'.
20043 See `org-ctrl-c-ctrl-c-hook' for more information.")
20044 (defvar org-shiftup-hook nil
20045 "Hook for functions attaching themselves to `S-up'.
20046 See `org-ctrl-c-ctrl-c-hook' for more information.")
20047 (defvar org-shiftup-final-hook nil
20048 "Hook for functions attaching themselves to `S-up'.
20049 This one runs after all other options except shift-select have been excluded.
20050 See `org-ctrl-c-ctrl-c-hook' for more information.")
20051 (defvar org-shiftdown-hook nil
20052 "Hook for functions attaching themselves to `S-down'.
20053 See `org-ctrl-c-ctrl-c-hook' for more information.")
20054 (defvar org-shiftdown-final-hook nil
20055 "Hook for functions attaching themselves to `S-down'.
20056 This one runs after all other options except shift-select have been excluded.
20057 See `org-ctrl-c-ctrl-c-hook' for more information.")
20058 (defvar org-shiftleft-hook nil
20059 "Hook for functions attaching themselves to `S-left'.
20060 See `org-ctrl-c-ctrl-c-hook' for more information.")
20061 (defvar org-shiftleft-final-hook nil
20062 "Hook for functions attaching themselves to `S-left'.
20063 This one runs after all other options except shift-select have been excluded.
20064 See `org-ctrl-c-ctrl-c-hook' for more information.")
20065 (defvar org-shiftright-hook nil
20066 "Hook for functions attaching themselves to `S-right'.
20067 See `org-ctrl-c-ctrl-c-hook' for more information.")
20068 (defvar org-shiftright-final-hook nil
20069 "Hook for functions attaching themselves to `S-right'.
20070 This one runs after all other options except shift-select have been excluded.
20071 See `org-ctrl-c-ctrl-c-hook' for more information.")
20073 (defun org-modifier-cursor-error ()
20074 "Throw an error, a modified cursor command was applied in wrong context."
20075 (user-error "This command is active in special context like tables, headlines or items"))
20077 (defun org-shiftselect-error ()
20078 "Throw an error because Shift-Cursor command was applied in wrong context."
20079 (if (and (boundp 'shift-select-mode) shift-select-mode)
20080 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20081 (user-error "This command works only in special context like headlines or timestamps")))
20083 (defun org-call-for-shift-select (cmd)
20084 (let ((this-command-keys-shift-translated t))
20085 (call-interactively cmd)))
20087 (defun org-shifttab (&optional arg)
20088 "Global visibility cycling or move to previous table field.
20089 Call `org-table-previous-field' within a table.
20090 When ARG is nil, cycle globally through visibility states.
20091 When ARG is a numeric prefix, show contents of this level."
20092 (interactive "P")
20093 (cond
20094 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20095 ((integerp arg)
20096 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20097 (message "Content view to level: %d" arg)
20098 (org-content (prefix-numeric-value arg2))
20099 (org-cycle-show-empty-lines t)
20100 (setq org-cycle-global-status 'overview)))
20101 (t (call-interactively 'org-global-cycle))))
20103 (defun org-shiftmetaleft ()
20104 "Promote subtree or delete table column.
20105 Calls `org-promote-subtree', `org-outdent-item-tree', or
20106 `org-table-delete-column', depending on context. See the
20107 individual commands for more information."
20108 (interactive)
20109 (cond
20110 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20111 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20112 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20113 ((if (not (org-region-active-p)) (org-at-item-p)
20114 (save-excursion (goto-char (region-beginning))
20115 (org-at-item-p)))
20116 (call-interactively 'org-outdent-item-tree))
20117 (t (org-modifier-cursor-error))))
20119 (defun org-shiftmetaright ()
20120 "Demote subtree or insert table column.
20121 Calls `org-demote-subtree', `org-indent-item-tree', or
20122 `org-table-insert-column', depending on context. See the
20123 individual commands for more information."
20124 (interactive)
20125 (cond
20126 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20127 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20128 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20129 ((if (not (org-region-active-p)) (org-at-item-p)
20130 (save-excursion (goto-char (region-beginning))
20131 (org-at-item-p)))
20132 (call-interactively 'org-indent-item-tree))
20133 (t (org-modifier-cursor-error))))
20135 (defun org-shiftmetaup (&optional arg)
20136 "Drag the line at point up.
20137 In a table, kill the current row.
20138 On a clock timestamp, update the value of the timestamp like `S-<up>'
20139 but also adjust the previous clocked item in the clock history.
20140 Everywhere else, drag the line at point up."
20141 (interactive "P")
20142 (cond
20143 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20144 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20145 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20146 (call-interactively 'org-timestamp-up)))
20147 (t (call-interactively 'org-drag-line-backward))))
20149 (defun org-shiftmetadown (&optional arg)
20150 "Drag the line at point down.
20151 In a table, insert an empty row at the current line.
20152 On a clock timestamp, update the value of the timestamp like `S-<down>'
20153 but also adjust the previous clocked item in the clock history.
20154 Everywhere else, drag the line at point down."
20155 (interactive "P")
20156 (cond
20157 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20158 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20159 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20160 (call-interactively 'org-timestamp-down)))
20161 (t (call-interactively 'org-drag-line-forward))))
20163 (defsubst org-hidden-tree-error ()
20164 (user-error
20165 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20167 (defun org-metaleft (&optional arg)
20168 "Promote heading or move table column to left.
20169 Calls `org-do-promote' or `org-table-move-column', depending on context.
20170 With no specific context, calls the Emacs default `backward-word'.
20171 See the individual commands for more information."
20172 (interactive "P")
20173 (cond
20174 ((run-hook-with-args-until-success 'org-metaleft-hook))
20175 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20176 ((org-with-limited-levels
20177 (or (org-at-heading-p)
20178 (and (org-region-active-p)
20179 (save-excursion
20180 (goto-char (region-beginning))
20181 (org-at-heading-p)))))
20182 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20183 (call-interactively 'org-do-promote))
20184 ;; At an inline task.
20185 ((org-at-heading-p)
20186 (call-interactively 'org-inlinetask-promote))
20187 ((or (org-at-item-p)
20188 (and (org-region-active-p)
20189 (save-excursion
20190 (goto-char (region-beginning))
20191 (org-at-item-p))))
20192 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20193 (call-interactively 'org-outdent-item))
20194 (t (call-interactively 'backward-word))))
20196 (defun org-metaright (&optional arg)
20197 "Demote a subtree, a list item or move table column to right.
20198 In front of a drawer or a block keyword, indent it correctly.
20199 With no specific context, calls the Emacs default `forward-word'.
20200 See the individual commands for more information."
20201 (interactive "P")
20202 (cond
20203 ((run-hook-with-args-until-success 'org-metaright-hook))
20204 ((org-at-table-p) (call-interactively 'org-table-move-column))
20205 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20206 ((org-at-block-p) (call-interactively 'org-indent-block))
20207 ((org-with-limited-levels
20208 (or (org-at-heading-p)
20209 (and (org-region-active-p)
20210 (save-excursion
20211 (goto-char (region-beginning))
20212 (org-at-heading-p)))))
20213 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20214 (call-interactively 'org-do-demote))
20215 ;; At an inline task.
20216 ((org-at-heading-p)
20217 (call-interactively 'org-inlinetask-demote))
20218 ((or (org-at-item-p)
20219 (and (org-region-active-p)
20220 (save-excursion
20221 (goto-char (region-beginning))
20222 (org-at-item-p))))
20223 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20224 (call-interactively 'org-indent-item))
20225 (t (call-interactively 'forward-word))))
20227 (defun org-check-for-hidden (what)
20228 "Check if there are hidden headlines/items in the current visual line.
20229 WHAT can be either `headlines' or `items'. If the current line is
20230 an outline or item heading and it has a folded subtree below it,
20231 this function returns t, nil otherwise."
20232 (let ((re (cond
20233 ((eq what 'headlines) org-outline-regexp-bol)
20234 ((eq what 'items) (org-item-beginning-re))
20235 (t (error "This should not happen"))))
20236 beg end)
20237 (save-excursion
20238 (catch 'exit
20239 (unless (org-region-active-p)
20240 (setq beg (point-at-bol))
20241 (beginning-of-line 2)
20242 (while (and (not (eobp)) ;; this is like `next-line'
20243 (get-char-property (1- (point)) 'invisible))
20244 (beginning-of-line 2))
20245 (setq end (point))
20246 (goto-char beg)
20247 (goto-char (point-at-eol))
20248 (setq end (max end (point)))
20249 (while (re-search-forward re end t)
20250 (if (get-char-property (match-beginning 0) 'invisible)
20251 (throw 'exit t))))
20252 nil))))
20254 (defun org-metaup (&optional arg)
20255 "Move subtree up or move table row up.
20256 Calls `org-move-subtree-up' or `org-table-move-row' or
20257 `org-move-item-up', depending on context. See the individual commands
20258 for more information."
20259 (interactive "P")
20260 (cond
20261 ((run-hook-with-args-until-success 'org-metaup-hook))
20262 ((org-region-active-p)
20263 (let* ((a (min (region-beginning) (region-end)))
20264 (b (1- (max (region-beginning) (region-end))))
20265 (c (save-excursion (goto-char a)
20266 (move-beginning-of-line 0)))
20267 (d (save-excursion (goto-char a)
20268 (move-end-of-line 0) (point))))
20269 (transpose-regions a b c d)
20270 (goto-char c)))
20271 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20272 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20273 ((org-at-item-p) (call-interactively 'org-move-item-up))
20274 (t (org-drag-element-backward))))
20276 (defun org-metadown (&optional arg)
20277 "Move subtree down or move table row down.
20278 Calls `org-move-subtree-down' or `org-table-move-row' or
20279 `org-move-item-down', depending on context. See the individual
20280 commands for more information."
20281 (interactive "P")
20282 (cond
20283 ((run-hook-with-args-until-success 'org-metadown-hook))
20284 ((org-region-active-p)
20285 (let* ((a (min (region-beginning) (region-end)))
20286 (b (max (region-beginning) (region-end)))
20287 (c (save-excursion (goto-char b)
20288 (move-beginning-of-line 1)))
20289 (d (save-excursion (goto-char b)
20290 (move-end-of-line 1) (1+ (point)))))
20291 (transpose-regions a b c d)
20292 (goto-char d)))
20293 ((org-at-table-p) (call-interactively 'org-table-move-row))
20294 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20295 ((org-at-item-p) (call-interactively 'org-move-item-down))
20296 (t (org-drag-element-forward))))
20298 (defun org-shiftup (&optional arg)
20299 "Increase item in timestamp or increase priority of current headline.
20300 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20301 depending on context. See the individual commands for more information."
20302 (interactive "P")
20303 (cond
20304 ((run-hook-with-args-until-success 'org-shiftup-hook))
20305 ((and org-support-shift-select (org-region-active-p))
20306 (org-call-for-shift-select 'previous-line))
20307 ((org-at-timestamp-p t)
20308 (call-interactively (if org-edit-timestamp-down-means-later
20309 'org-timestamp-down 'org-timestamp-up)))
20310 ((and (not (eq org-support-shift-select 'always))
20311 org-enable-priority-commands
20312 (org-at-heading-p))
20313 (call-interactively 'org-priority-up))
20314 ((and (not org-support-shift-select) (org-at-item-p))
20315 (call-interactively 'org-previous-item))
20316 ((org-clocktable-try-shift 'up arg))
20317 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20318 (org-support-shift-select
20319 (org-call-for-shift-select 'previous-line))
20320 (t (org-shiftselect-error))))
20322 (defun org-shiftdown (&optional arg)
20323 "Decrease item in timestamp or decrease priority of current headline.
20324 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20325 depending on context. See the individual commands for more information."
20326 (interactive "P")
20327 (cond
20328 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20329 ((and org-support-shift-select (org-region-active-p))
20330 (org-call-for-shift-select 'next-line))
20331 ((org-at-timestamp-p t)
20332 (call-interactively (if org-edit-timestamp-down-means-later
20333 'org-timestamp-up 'org-timestamp-down)))
20334 ((and (not (eq org-support-shift-select 'always))
20335 org-enable-priority-commands
20336 (org-at-heading-p))
20337 (call-interactively 'org-priority-down))
20338 ((and (not org-support-shift-select) (org-at-item-p))
20339 (call-interactively 'org-next-item))
20340 ((org-clocktable-try-shift 'down arg))
20341 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20342 (org-support-shift-select
20343 (org-call-for-shift-select 'next-line))
20344 (t (org-shiftselect-error))))
20346 (defun org-shiftright (&optional arg)
20347 "Cycle the thing at point or in the current line, depending on context.
20348 Depending on context, this does one of the following:
20350 - switch a timestamp at point one day into the future
20351 - on a headline, switch to the next TODO keyword.
20352 - on an item, switch entire list to the next bullet type
20353 - on a property line, switch to the next allowed value
20354 - on a clocktable definition line, move time block into the future"
20355 (interactive "P")
20356 (cond
20357 ((run-hook-with-args-until-success 'org-shiftright-hook))
20358 ((and org-support-shift-select (org-region-active-p))
20359 (org-call-for-shift-select 'forward-char))
20360 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20361 ((and (not (eq org-support-shift-select 'always))
20362 (org-at-heading-p))
20363 (let ((org-inhibit-logging
20364 (not org-treat-S-cursor-todo-selection-as-state-change))
20365 (org-inhibit-blocking
20366 (not org-treat-S-cursor-todo-selection-as-state-change)))
20367 (org-call-with-arg 'org-todo 'right)))
20368 ((or (and org-support-shift-select
20369 (not (eq org-support-shift-select 'always))
20370 (org-at-item-bullet-p))
20371 (and (not org-support-shift-select) (org-at-item-p)))
20372 (org-call-with-arg 'org-cycle-list-bullet nil))
20373 ((and (not (eq org-support-shift-select 'always))
20374 (org-at-property-p))
20375 (call-interactively 'org-property-next-allowed-value))
20376 ((org-clocktable-try-shift 'right arg))
20377 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20378 (org-support-shift-select
20379 (org-call-for-shift-select 'forward-char))
20380 (t (org-shiftselect-error))))
20382 (defun org-shiftleft (&optional arg)
20383 "Cycle the thing at point or in the current line, depending on context.
20384 Depending on context, this does one of the following:
20386 - switch a timestamp at point one day into the past
20387 - on a headline, switch to the previous TODO keyword.
20388 - on an item, switch entire list to the previous bullet type
20389 - on a property line, switch to the previous allowed value
20390 - on a clocktable definition line, move time block into the past"
20391 (interactive "P")
20392 (cond
20393 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20394 ((and org-support-shift-select (org-region-active-p))
20395 (org-call-for-shift-select 'backward-char))
20396 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20397 ((and (not (eq org-support-shift-select 'always))
20398 (org-at-heading-p))
20399 (let ((org-inhibit-logging
20400 (not org-treat-S-cursor-todo-selection-as-state-change))
20401 (org-inhibit-blocking
20402 (not org-treat-S-cursor-todo-selection-as-state-change)))
20403 (org-call-with-arg 'org-todo 'left)))
20404 ((or (and org-support-shift-select
20405 (not (eq org-support-shift-select 'always))
20406 (org-at-item-bullet-p))
20407 (and (not org-support-shift-select) (org-at-item-p)))
20408 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20409 ((and (not (eq org-support-shift-select 'always))
20410 (org-at-property-p))
20411 (call-interactively 'org-property-previous-allowed-value))
20412 ((org-clocktable-try-shift 'left arg))
20413 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20414 (org-support-shift-select
20415 (org-call-for-shift-select 'backward-char))
20416 (t (org-shiftselect-error))))
20418 (defun org-shiftcontrolright ()
20419 "Switch to next TODO set."
20420 (interactive)
20421 (cond
20422 ((and org-support-shift-select (org-region-active-p))
20423 (org-call-for-shift-select 'forward-word))
20424 ((and (not (eq org-support-shift-select 'always))
20425 (org-at-heading-p))
20426 (org-call-with-arg 'org-todo 'nextset))
20427 (org-support-shift-select
20428 (org-call-for-shift-select 'forward-word))
20429 (t (org-shiftselect-error))))
20431 (defun org-shiftcontrolleft ()
20432 "Switch to previous TODO set."
20433 (interactive)
20434 (cond
20435 ((and org-support-shift-select (org-region-active-p))
20436 (org-call-for-shift-select 'backward-word))
20437 ((and (not (eq org-support-shift-select 'always))
20438 (org-at-heading-p))
20439 (org-call-with-arg 'org-todo 'previousset))
20440 (org-support-shift-select
20441 (org-call-for-shift-select 'backward-word))
20442 (t (org-shiftselect-error))))
20444 (defun org-shiftcontrolup (&optional n)
20445 "Change timestamps synchronously up in CLOCK log lines.
20446 Optional argument N tells to change by that many units."
20447 (interactive "P")
20448 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20449 (let (org-support-shift-select)
20450 (org-clock-timestamps-up n))
20451 (user-error "Not at a clock log")))
20453 (defun org-shiftcontroldown (&optional n)
20454 "Change timestamps synchronously down in CLOCK log lines.
20455 Optional argument N tells to change by that many units."
20456 (interactive "P")
20457 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20458 (let (org-support-shift-select)
20459 (org-clock-timestamps-down n))
20460 (user-error "Not at a clock log")))
20462 (defun org-increase-number-at-point (&optional inc)
20463 "Increment the number at point.
20464 With an optional prefix numeric argument INC, increment using
20465 this numeric value."
20466 (interactive "p")
20467 (if (not (number-at-point))
20468 (user-error "Not on a number")
20469 (unless inc (setq inc 1))
20470 (let ((pos (point))
20471 (beg (skip-chars-backward "-+^/*0-9eE."))
20472 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20473 (setq nap (buffer-substring-no-properties
20474 (+ pos beg) (+ pos beg end)))
20475 (delete-region (+ pos beg) (+ pos beg end))
20476 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20477 (when (org-at-table-p)
20478 (org-table-align)
20479 (org-table-end-of-field 1))))
20481 (defun org-decrease-number-at-point (&optional inc)
20482 "Decrement the number at point.
20483 With an optional prefix numeric argument INC, decrement using
20484 this numeric value."
20485 (interactive "p")
20486 (org-increase-number-at-point (- inc)))
20488 (defun org-ctrl-c-ret ()
20489 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20490 (interactive)
20491 (cond
20492 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20493 (t (call-interactively 'org-insert-heading))))
20495 (defun org-find-visible ()
20496 (let ((s (point)))
20497 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20498 (get-char-property s 'invisible)))
20500 (defun org-find-invisible ()
20501 (let ((s (point)))
20502 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20503 (not (get-char-property s 'invisible))))
20506 (defun org-copy-visible (beg end)
20507 "Copy the visible parts of the region."
20508 (interactive "r")
20509 (let (snippets s)
20510 (save-excursion
20511 (save-restriction
20512 (narrow-to-region beg end)
20513 (setq s (goto-char (point-min)))
20514 (while (not (= (point) (point-max)))
20515 (goto-char (org-find-invisible))
20516 (push (buffer-substring s (point)) snippets)
20517 (setq s (goto-char (org-find-visible))))))
20518 (kill-new (apply 'concat (nreverse snippets)))))
20520 (defun org-copy-special ()
20521 "Copy region in table or copy current subtree.
20522 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20523 See the individual commands for more information."
20524 (interactive)
20525 (call-interactively
20526 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20528 (defun org-cut-special ()
20529 "Cut region in table or cut current subtree.
20530 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20531 See the individual commands for more information."
20532 (interactive)
20533 (call-interactively
20534 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20536 (defun org-paste-special (arg)
20537 "Paste rectangular region into table, or past subtree relative to level.
20538 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20539 See the individual commands for more information."
20540 (interactive "P")
20541 (if (org-at-table-p)
20542 (org-table-paste-rectangle)
20543 (org-paste-subtree arg)))
20545 (defsubst org-in-fixed-width-region-p ()
20546 "Is point in a fixed-width region?"
20547 (save-match-data
20548 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20550 (defun org-edit-special (&optional arg)
20551 "Call a special editor for the element at point.
20552 When at a table, call the formula editor with `org-table-edit-formulas'.
20553 When in a source code block, call `org-edit-src-code'.
20554 When in a fixed-width region, call `org-edit-fixed-width-region'.
20555 When at an #+INCLUDE keyword, visit the included file.
20556 On a link, call `ffap' to visit the link at point.
20557 Otherwise, return a user error."
20558 (interactive "P")
20559 (let ((element (org-element-at-point)))
20560 (assert (not buffer-read-only) nil
20561 "Buffer is read-only: %s" (buffer-name))
20562 (case (org-element-type element)
20563 (src-block
20564 (if (not arg) (org-edit-src-code)
20565 (let* ((info (org-babel-get-src-block-info))
20566 (lang (nth 0 info))
20567 (params (nth 2 info))
20568 (session (cdr (assq :session params))))
20569 (if (not session) (org-edit-src-code)
20570 ;; At a src-block with a session and function called with
20571 ;; an ARG: switch to the buffer related to the inferior
20572 ;; process.
20573 (switch-to-buffer
20574 (funcall (intern (concat "org-babel-prep-session:" lang))
20575 session params))))))
20576 (keyword
20577 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20578 (org-open-link-from-string
20579 (format "[[%s]]"
20580 (expand-file-name
20581 (let ((value (org-element-property :value element)))
20582 (cond ((not (org-string-nw-p value))
20583 (user-error "No file to edit"))
20584 ((string-match "\\`\"\\(.*?\\)\"" value)
20585 (match-string 1 value))
20586 ((string-match "\\`[^ \t\"]\\S-*" value)
20587 (match-string 0 value))
20588 (t (user-error "No valid file specified")))))))
20589 (user-error "No special environment to edit here")))
20590 (table
20591 (if (eq (org-element-property :type element) 'table.el)
20592 (org-edit-src-code)
20593 (call-interactively 'org-table-edit-formulas)))
20594 ;; Only Org tables contain `table-row' type elements.
20595 (table-row (call-interactively 'org-table-edit-formulas))
20596 ((example-block export-block) (org-edit-src-code))
20597 (fixed-width (org-edit-fixed-width-region))
20598 (otherwise
20599 ;; No notable element at point. Though, we may be at a link,
20600 ;; which is an object. Thus, scan deeper.
20601 (if (eq (org-element-type (org-element-context element)) 'link)
20602 (call-interactively 'ffap)
20603 (user-error "No special environment to edit here"))))))
20605 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20606 (defun org-ctrl-c-ctrl-c (&optional arg)
20607 "Set tags in headline, or update according to changed information at point.
20609 This command does many different things, depending on context:
20611 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20612 this is what we do.
20614 - If the cursor is on a statistics cookie, update it.
20616 - If the cursor is in a headline, prompt for tags and insert them
20617 into the current line, aligned to `org-tags-column'. When called
20618 with prefix arg, realign all tags in the current buffer.
20620 - If the cursor is in one of the special #+KEYWORD lines, this
20621 triggers scanning the buffer for these lines and updating the
20622 information.
20624 - If the cursor is inside a table, realign the table. This command
20625 works even if the automatic table editor has been turned off.
20627 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20628 the entire table.
20630 - If the cursor is at a footnote reference or definition, jump to
20631 the corresponding definition or references, respectively.
20633 - If the cursor is a the beginning of a dynamic block, update it.
20635 - If the current buffer is a capture buffer, close note and file it.
20637 - If the cursor is on a <<<target>>>, update radio targets and
20638 corresponding links in this buffer.
20640 - If the cursor is on a numbered item in a plain list, renumber the
20641 ordered list.
20643 - If the cursor is on a checkbox, toggle it.
20645 - If the cursor is on a code block, evaluate it. The variable
20646 `org-confirm-babel-evaluate' can be used to control prompting
20647 before code block evaluation, by default every code block
20648 evaluation requires confirmation. Code block evaluation can be
20649 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20650 (interactive "P")
20651 (cond
20652 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20653 org-occur-highlights)
20654 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20655 (org-remove-occur-highlights)
20656 (message "Temporary highlights/overlays removed from current buffer"))
20657 ((and (local-variable-p 'org-finish-function (current-buffer))
20658 (fboundp org-finish-function))
20659 (funcall org-finish-function))
20660 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20662 (let* ((context (org-element-context)) (type (org-element-type context)))
20663 ;; Test if point is within a blank line.
20664 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20665 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20666 (user-error "C-c C-c can do nothing useful at this location"))
20667 (case type
20668 ;; When at a link, act according to the parent instead.
20669 (link (setq context (org-element-property :parent context))
20670 (setq type (org-element-type context)))
20671 ;; Unsupported object types: refer to the first supported
20672 ;; element or object containing it.
20673 ((bold code entity export-snippet inline-babel-call inline-src-block
20674 italic latex-fragment line-break macro strike-through subscript
20675 superscript underline verbatim)
20676 (while (and (setq context (org-element-property :parent context))
20677 (not (memq (setq type (org-element-type context))
20678 '(radio-target paragraph verse-block
20679 table-cell)))))))
20680 ;; For convenience: at the first line of a paragraph on the
20681 ;; same line as an item, apply function on that item instead.
20682 (when (eq type 'paragraph)
20683 (let ((parent (org-element-property :parent context)))
20684 (when (and (eq (org-element-type parent) 'item)
20685 (= (point-at-bol) (org-element-property :begin parent)))
20686 (setq context parent type 'item))))
20687 ;; Act according to type of element or object at point.
20688 (case type
20689 (clock (org-clock-update-time-maybe))
20690 (dynamic-block
20691 (save-excursion
20692 (goto-char (org-element-property :post-affiliated context))
20693 (org-update-dblock)))
20694 (footnote-definition
20695 (goto-char (org-element-property :post-affiliated context))
20696 (call-interactively 'org-footnote-action))
20697 (footnote-reference (call-interactively 'org-footnote-action))
20698 ((headline inlinetask)
20699 (save-excursion (goto-char (org-element-property :begin context))
20700 (call-interactively 'org-set-tags)))
20701 (item
20702 ;; At an item: a double C-u set checkbox to "[-]"
20703 ;; unconditionally, whereas a single one will toggle its
20704 ;; presence. Without an universal argument, if the item
20705 ;; has a checkbox, toggle it. Otherwise repair the list.
20706 (let* ((box (org-element-property :checkbox context))
20707 (struct (org-element-property :structure context))
20708 (old-struct (copy-tree struct))
20709 (parents (org-list-parents-alist struct))
20710 (prevs (org-list-prevs-alist struct))
20711 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20712 (org-list-set-checkbox
20713 (org-element-property :begin context) struct
20714 (cond ((equal arg '(16)) "[-]")
20715 ((and (not box) (equal arg '(4))) "[ ]")
20716 ((or (not box) (equal arg '(4))) nil)
20717 ((eq box 'on) "[ ]")
20718 (t "[X]")))
20719 ;; Mimic `org-list-write-struct' but with grabbing
20720 ;; a return value from `org-list-struct-fix-box'.
20721 (org-list-struct-fix-ind struct parents 2)
20722 (org-list-struct-fix-item-end struct)
20723 (org-list-struct-fix-bul struct prevs)
20724 (org-list-struct-fix-ind struct parents)
20725 (let ((block-item
20726 (org-list-struct-fix-box struct parents prevs orderedp)))
20727 (if (and box (equal struct old-struct))
20728 (if (equal arg '(16))
20729 (message "Checkboxes already reset")
20730 (user-error "Cannot toggle this checkbox: %s"
20731 (if (eq box 'on)
20732 "all subitems checked"
20733 "unchecked subitems")))
20734 (org-list-struct-apply-struct struct old-struct)
20735 (org-update-checkbox-count-maybe))
20736 (when block-item
20737 (message "Checkboxes were removed due to empty box at line %d"
20738 (org-current-line block-item))))))
20739 (keyword
20740 (let ((org-inhibit-startup-visibility-stuff t)
20741 (org-startup-align-all-tables nil))
20742 (when (boundp 'org-table-coordinate-overlays)
20743 (mapc 'delete-overlay org-table-coordinate-overlays)
20744 (setq org-table-coordinate-overlays nil))
20745 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20746 (message "Local setup has been refreshed"))
20747 (plain-list
20748 ;; At a plain list, with a double C-u argument, set
20749 ;; checkboxes of each item to "[-]", whereas a single one
20750 ;; will toggle their presence according to the state of the
20751 ;; first item in the list. Without an argument, repair the
20752 ;; list.
20753 (let* ((begin (org-element-property :contents-begin context))
20754 (beginm (move-marker (make-marker) begin))
20755 (struct (org-element-property :structure context))
20756 (old-struct (copy-tree struct))
20757 (first-box (save-excursion
20758 (goto-char begin)
20759 (looking-at org-list-full-item-re)
20760 (match-string-no-properties 3)))
20761 (new-box (cond ((equal arg '(16)) "[-]")
20762 ((equal arg '(4)) (unless first-box "[ ]"))
20763 ((equal first-box "[X]") "[ ]")
20764 (t "[X]"))))
20765 (cond
20766 (arg
20767 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20768 (org-list-get-all-items
20769 begin struct (org-list-prevs-alist struct))))
20770 ((and first-box (eq (point) begin))
20771 ;; For convenience, when point is at bol on the first
20772 ;; item of the list and no argument is provided, simply
20773 ;; toggle checkbox of that item, if any.
20774 (org-list-set-checkbox begin struct new-box)))
20775 (org-list-write-struct
20776 struct (org-list-parents-alist struct) old-struct)
20777 (org-update-checkbox-count-maybe)
20778 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20779 ((property-drawer node-property)
20780 (call-interactively 'org-property-action))
20781 ((radio-target target)
20782 (call-interactively 'org-update-radio-target-regexp))
20783 (statistics-cookie
20784 (call-interactively 'org-update-statistics-cookies))
20785 ((table table-cell table-row)
20786 ;; At a table, recalculate every field and align it. Also
20787 ;; send the table if necessary. If the table has
20788 ;; a `table.el' type, just give up. At a table row or
20789 ;; cell, maybe recalculate line but always align table.
20790 (if (eq (org-element-property :type context) 'table.el)
20791 (message "Use C-c ' to edit table.el tables")
20792 (let ((org-enable-table-editor t))
20793 (if (or (eq type 'table)
20794 ;; Check if point is at a TBLFM line.
20795 (and (eq type 'table-row)
20796 (= (point) (org-element-property :end context))))
20797 (save-excursion
20798 (if (org-at-TBLFM-p)
20799 (progn (require 'org-table)
20800 (org-table-calc-current-TBLFM))
20801 (goto-char (org-element-property :contents-begin context))
20802 (org-call-with-arg 'org-table-recalculate (or arg t))
20803 (orgtbl-send-table 'maybe)))
20804 (org-table-maybe-eval-formula)
20805 (cond (arg (call-interactively 'org-table-recalculate))
20806 ((org-table-maybe-recalculate-line))
20807 (t (org-table-align)))))))
20808 (timestamp (org-timestamp-change 0 'day))
20809 (otherwise
20810 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20811 (user-error
20812 "C-c C-c can do nothing useful at this location")))))))))
20814 (defun org-mode-restart ()
20815 (interactive)
20816 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20817 (funcall major-mode)
20818 (hack-local-variables)
20819 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20820 (org-indent-mode -1)))
20821 (message "%s restarted" major-mode))
20823 (defun org-kill-note-or-show-branches ()
20824 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20825 (interactive)
20826 (if (not org-finish-function)
20827 (progn
20828 (hide-subtree)
20829 (call-interactively 'show-branches))
20830 (let ((org-note-abort t))
20831 (funcall org-finish-function))))
20833 (defun org-open-line (n)
20834 "Insert a new row in tables, call `open-line' elsewhere.
20835 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20836 (interactive "*p")
20837 (cond
20838 ((not org-special-ctrl-o)
20839 (open-line n))
20840 ((org-at-table-p)
20841 (org-table-insert-row))
20843 (open-line n))))
20845 (defun org-return (&optional indent)
20846 "Goto next table row or insert a newline.
20847 Calls `org-table-next-row' or `newline', depending on context.
20848 See the individual commands for more information."
20849 (interactive)
20850 (let (org-ts-what)
20851 (cond
20852 ((or (bobp) (org-in-src-block-p))
20853 (if indent (newline-and-indent) (newline)))
20854 ((org-at-table-p)
20855 (org-table-justify-field-maybe)
20856 (call-interactively 'org-table-next-row))
20857 ;; when `newline-and-indent' is called within a list, make sure
20858 ;; text moved stays inside the item.
20859 ((and (org-in-item-p) indent)
20860 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20861 (progn
20862 (save-match-data (newline))
20863 (org-indent-line-to (length (match-string 0))))
20864 (let ((ind (org-get-indentation)))
20865 (newline)
20866 (if (org-looking-back org-list-end-re)
20867 (org-indent-line)
20868 (org-indent-line-to ind)))))
20869 ((and org-return-follows-link
20870 (org-at-timestamp-p t)
20871 (not (eq org-ts-what 'after)))
20872 (org-follow-timestamp-link))
20873 ((and org-return-follows-link
20874 (let ((tprop (get-text-property (point) 'face)))
20875 (or (eq tprop 'org-link)
20876 (and (listp tprop) (memq 'org-link tprop)))))
20877 (call-interactively 'org-open-at-point))
20878 ((and (org-at-heading-p)
20879 (looking-at
20880 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20881 (org-show-entry)
20882 (end-of-line 1)
20883 (newline))
20884 (t (if indent (newline-and-indent) (newline))))))
20886 (defun org-return-indent ()
20887 "Goto next table row or insert a newline and indent.
20888 Calls `org-table-next-row' or `newline-and-indent', depending on
20889 context. See the individual commands for more information."
20890 (interactive)
20891 (org-return t))
20893 (defun org-ctrl-c-star ()
20894 "Compute table, or change heading status of lines.
20895 Calls `org-table-recalculate' or `org-toggle-heading',
20896 depending on context."
20897 (interactive)
20898 (cond
20899 ((org-at-table-p)
20900 (call-interactively 'org-table-recalculate))
20902 ;; Convert all lines in region to list items
20903 (call-interactively 'org-toggle-heading))))
20905 (defun org-ctrl-c-minus ()
20906 "Insert separator line in table or modify bullet status of line.
20907 Also turns a plain line or a region of lines into list items.
20908 Calls `org-table-insert-hline', `org-toggle-item', or
20909 `org-cycle-list-bullet', depending on context."
20910 (interactive)
20911 (cond
20912 ((org-at-table-p)
20913 (call-interactively 'org-table-insert-hline))
20914 ((org-region-active-p)
20915 (call-interactively 'org-toggle-item))
20916 ((org-in-item-p)
20917 (call-interactively 'org-cycle-list-bullet))
20919 (call-interactively 'org-toggle-item))))
20921 (defun org-toggle-item (arg)
20922 "Convert headings or normal lines to items, items to normal lines.
20923 If there is no active region, only the current line is considered.
20925 If the first non blank line in the region is a headline, convert
20926 all headlines to items, shifting text accordingly.
20928 If it is an item, convert all items to normal lines.
20930 If it is normal text, change region into a list of items.
20931 With a prefix argument ARG, change the region in a single item."
20932 (interactive "P")
20933 (let ((shift-text
20934 (function
20935 ;; Shift text in current section to IND, from point to END.
20936 ;; The function leaves point to END line.
20937 (lambda (ind end)
20938 (let ((min-i 1000) (end (copy-marker end)))
20939 ;; First determine the minimum indentation (MIN-I) of
20940 ;; the text.
20941 (save-excursion
20942 (catch 'exit
20943 (while (< (point) end)
20944 (let ((i (org-get-indentation)))
20945 (cond
20946 ;; Skip blank lines and inline tasks.
20947 ((looking-at "^[ \t]*$"))
20948 ((looking-at org-outline-regexp-bol))
20949 ;; We can't find less than 0 indentation.
20950 ((zerop i) (throw 'exit (setq min-i 0)))
20951 ((< i min-i) (setq min-i i))))
20952 (forward-line))))
20953 ;; Then indent each line so that a line indented to
20954 ;; MIN-I becomes indented to IND. Ignore blank lines
20955 ;; and inline tasks in the process.
20956 (let ((delta (- ind min-i)))
20957 (while (< (point) end)
20958 (unless (or (looking-at "^[ \t]*$")
20959 (looking-at org-outline-regexp-bol))
20960 (org-indent-line-to (+ (org-get-indentation) delta)))
20961 (forward-line)))))))
20962 (skip-blanks
20963 (function
20964 ;; Return beginning of first non-blank line, starting from
20965 ;; line at POS.
20966 (lambda (pos)
20967 (save-excursion
20968 (goto-char pos)
20969 (skip-chars-forward " \r\t\n")
20970 (point-at-bol)))))
20971 beg end)
20972 ;; Determine boundaries of changes.
20973 (if (org-region-active-p)
20974 (setq beg (funcall skip-blanks (region-beginning))
20975 end (copy-marker (region-end)))
20976 (setq beg (funcall skip-blanks (point-at-bol))
20977 end (copy-marker (point-at-eol))))
20978 ;; Depending on the starting line, choose an action on the text
20979 ;; between BEG and END.
20980 (org-with-limited-levels
20981 (save-excursion
20982 (goto-char beg)
20983 (cond
20984 ;; Case 1. Start at an item: de-itemize. Note that it only
20985 ;; happens when a region is active: `org-ctrl-c-minus'
20986 ;; would call `org-cycle-list-bullet' otherwise.
20987 ((org-at-item-p)
20988 (while (< (point) end)
20989 (when (org-at-item-p)
20990 (skip-chars-forward " \t")
20991 (delete-region (point) (match-end 0)))
20992 (forward-line)))
20993 ;; Case 2. Start at an heading: convert to items.
20994 ((org-at-heading-p)
20995 (let* ((bul (org-list-bullet-string "-"))
20996 (bul-len (length bul))
20997 (done (org-entry-is-done-p))
20998 (todo (org-entry-is-todo-p))
20999 ;; Indentation of the first heading. It should be
21000 ;; relative to the indentation of its parent, if any.
21001 (start-ind (save-excursion
21002 (cond
21003 ((not org-adapt-indentation) 0)
21004 ((not (outline-previous-heading)) 0)
21005 (t (length (match-string 0))))))
21006 ;; Level of first heading. Further headings will be
21007 ;; compared to it to determine hierarchy in the list.
21008 (ref-level (org-reduced-level (org-outline-level))))
21009 (when (or done todo) (org-todo ""))
21010 (while (< (point) end)
21011 (let* ((level (org-reduced-level (org-outline-level)))
21012 (delta (max 0 (- level ref-level))))
21013 ;; If current headline is less indented than the first
21014 ;; one, set it as reference, in order to preserve
21015 ;; subtrees.
21016 (when (< level ref-level) (setq ref-level level))
21017 (replace-match bul t t)
21018 (org-indent-line-to (+ start-ind (* delta bul-len)))
21019 (when (or done todo)
21020 (let* ((struct (org-list-struct))
21021 (old (copy-tree struct)))
21022 (org-list-set-checkbox (line-beginning-position)
21023 struct
21024 (if done "[X]" "[ ]"))
21025 (org-list-write-struct struct
21026 (org-list-parents-alist struct)
21027 old)))
21028 ;; Ensure all text down to END (or SECTION-END) belongs
21029 ;; to the newly created item.
21030 (let ((section-end (save-excursion
21031 (or (outline-next-heading) (point)))))
21032 (forward-line)
21033 (funcall shift-text
21034 (+ start-ind (* (1+ delta) bul-len))
21035 (min end section-end)))))))
21036 ;; Case 3. Normal line with ARG: make the first line of region
21037 ;; an item, and shift indentation of others lines to
21038 ;; set them as item's body.
21039 (arg (let* ((bul (org-list-bullet-string "-"))
21040 (bul-len (length bul))
21041 (ref-ind (org-get-indentation)))
21042 (skip-chars-forward " \t")
21043 (insert bul)
21044 (forward-line)
21045 (while (< (point) end)
21046 ;; Ensure that lines less indented than first one
21047 ;; still get included in item body.
21048 (funcall shift-text
21049 (+ ref-ind bul-len)
21050 (min end (save-excursion (or (outline-next-heading)
21051 (point)))))
21052 (forward-line))))
21053 ;; Case 4. Normal line without ARG: turn each non-item line
21054 ;; into an item.
21056 (while (< (point) end)
21057 (unless (or (org-at-heading-p) (org-at-item-p))
21058 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21059 (replace-match
21060 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21061 (forward-line))))))))
21063 (defun org-toggle-heading (&optional nstars)
21064 "Convert headings to normal text, or items or text to headings.
21065 If there is no active region, only convert the current line.
21067 With a \\[universal-argument] prefix, convert the whole list at
21068 point into heading.
21070 In a region:
21072 - If the first non blank line is a headline, remove the stars
21073 from all headlines in the region.
21075 - If it is a normal line, turn each and every normal line (i.e.,
21076 not an heading or an item) in the region into headings. If you
21077 want to convert only the first line of this region, use one
21078 universal prefix argument.
21080 - If it is a plain list item, turn all plain list items into headings.
21082 When converting a line into a heading, the number of stars is chosen
21083 such that the lines become children of the current entry. However,
21084 when a numeric prefix argument is given, its value determines the
21085 number of stars to add."
21086 (interactive "P")
21087 (let ((skip-blanks
21088 (function
21089 ;; Return beginning of first non-blank line, starting from
21090 ;; line at POS.
21091 (lambda (pos)
21092 (save-excursion
21093 (goto-char pos)
21094 (while (org-at-comment-p) (forward-line))
21095 (skip-chars-forward " \r\t\n")
21096 (point-at-bol)))))
21097 beg end toggled)
21098 ;; Determine boundaries of changes. If a universal prefix has
21099 ;; been given, put the list in a region. If region ends at a bol,
21100 ;; do not consider the last line to be in the region.
21102 (when (and current-prefix-arg (org-at-item-p))
21103 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21104 (org-mark-element))
21106 (if (org-region-active-p)
21107 (setq beg (funcall skip-blanks (region-beginning))
21108 end (copy-marker (save-excursion
21109 (goto-char (region-end))
21110 (if (bolp) (point) (point-at-eol)))))
21111 (setq beg (funcall skip-blanks (point-at-bol))
21112 end (copy-marker (point-at-eol))))
21113 ;; Ensure inline tasks don't count as headings.
21114 (org-with-limited-levels
21115 (save-excursion
21116 (goto-char beg)
21117 (cond
21118 ;; Case 1. Started at an heading: de-star headings.
21119 ((org-at-heading-p)
21120 (while (< (point) end)
21121 (when (org-at-heading-p t)
21122 (looking-at org-outline-regexp) (replace-match "")
21123 (setq toggled t))
21124 (forward-line)))
21125 ;; Case 2. Started at an item: change items into headlines.
21126 ;; One star will be added by `org-list-to-subtree'.
21127 ((org-at-item-p)
21128 (let* ((stars (make-string
21129 ;; subtract the star that will be added again by
21130 ;; `org-list-to-subtree'
21131 (if (numberp nstars) (1- nstars)
21132 (or (org-current-level) 0))
21133 ?*))
21134 (add-stars
21135 (cond (nstars "") ; stars from prefix only
21136 ((equal stars "") "") ; before first heading
21137 (org-odd-levels-only "*") ; inside heading, odd
21138 (t "")))) ; inside heading, oddeven
21139 (while (< (point) end)
21140 (when (org-at-item-p)
21141 ;; Pay attention to cases when region ends before list.
21142 (let* ((struct (org-list-struct))
21143 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21144 (save-restriction
21145 (narrow-to-region (point) list-end)
21146 (insert
21147 (org-list-to-subtree
21148 (org-list-parse-list t)
21149 '(:istart (concat stars add-stars (funcall get-stars depth))
21150 :icount (concat stars add-stars (funcall get-stars depth)))))))
21151 (setq toggled t))
21152 (forward-line))))
21153 ;; Case 3. Started at normal text: make every line an heading,
21154 ;; skipping headlines and items.
21155 (t (let* ((stars
21156 (make-string
21157 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21158 (add-stars
21159 (cond (nstars "") ; stars from prefix only
21160 ((equal stars "") "*") ; before first heading
21161 (org-odd-levels-only "**") ; inside heading, odd
21162 (t "*"))) ; inside heading, oddeven
21163 (rpl (concat stars add-stars " "))
21164 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21165 (while (< (point) (if (equal nstars '(4)) lend end))
21166 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21167 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21168 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21169 (forward-line)))))))
21170 (unless toggled (message "Cannot toggle heading from here"))))
21172 (defun org-meta-return (&optional arg)
21173 "Insert a new heading or wrap a region in a table.
21174 Calls `org-insert-heading' or `org-table-wrap-region', depending
21175 on context. See the individual commands for more information."
21176 (interactive "P")
21177 (org-check-before-invisible-edit 'insert)
21178 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21179 (let* ((element (org-element-at-point))
21180 (type (org-element-type element)))
21181 (when (eq type 'table-row)
21182 (setq element (org-element-property :parent element))
21183 (setq type 'table))
21184 (if (and (eq type 'table)
21185 (eq (org-element-property :type element) 'org)
21186 (>= (point) (org-element-property :contents-begin element))
21187 (< (point) (org-element-property :contents-end element)))
21188 (call-interactively 'org-table-wrap-region)
21189 (call-interactively 'org-insert-heading)))))
21191 ;;; Menu entries
21193 (defsubst org-in-subtree-not-table-p ()
21194 "Are we in a subtree and not in a table?"
21195 (and (not (org-before-first-heading-p))
21196 (not (org-at-table-p))))
21198 ;; Define the Org-mode menus
21199 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21200 '("Tbl"
21201 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21202 ["Next Field" org-cycle (org-at-table-p)]
21203 ["Previous Field" org-shifttab (org-at-table-p)]
21204 ["Next Row" org-return (org-at-table-p)]
21205 "--"
21206 ["Blank Field" org-table-blank-field (org-at-table-p)]
21207 ["Edit Field" org-table-edit-field (org-at-table-p)]
21208 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21209 "--"
21210 ("Column"
21211 ["Move Column Left" org-metaleft (org-at-table-p)]
21212 ["Move Column Right" org-metaright (org-at-table-p)]
21213 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21214 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21215 ("Row"
21216 ["Move Row Up" org-metaup (org-at-table-p)]
21217 ["Move Row Down" org-metadown (org-at-table-p)]
21218 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21219 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21220 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21221 "--"
21222 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21223 ("Rectangle"
21224 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21225 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21226 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21227 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21228 "--"
21229 ("Calculate"
21230 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21231 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21232 ["Edit Formulas" org-edit-special (org-at-table-p)]
21233 "--"
21234 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21235 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21236 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21237 "--"
21238 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21239 "--"
21240 ["Sum Column/Rectangle" org-table-sum
21241 (or (org-at-table-p) (org-region-active-p))]
21242 ["Which Column?" org-table-current-column (org-at-table-p)])
21243 ["Debug Formulas"
21244 org-table-toggle-formula-debugger
21245 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21246 ["Show Col/Row Numbers"
21247 org-table-toggle-coordinate-overlays
21248 :style toggle
21249 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21250 "--"
21251 ["Create" org-table-create (and (not (org-at-table-p))
21252 org-enable-table-editor)]
21253 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21254 ["Import from File" org-table-import (not (org-at-table-p))]
21255 ["Export to File" org-table-export (org-at-table-p)]
21256 "--"
21257 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21258 "--"
21259 ("Plot"
21260 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21261 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21263 (easy-menu-define org-org-menu org-mode-map "Org menu"
21264 '("Org"
21265 ("Show/Hide"
21266 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21267 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21268 ["Sparse Tree..." org-sparse-tree t]
21269 ["Reveal Context" org-reveal t]
21270 ["Show All" show-all t]
21271 "--"
21272 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21273 "--"
21274 ["New Heading" org-insert-heading t]
21275 ("Navigate Headings"
21276 ["Up" outline-up-heading t]
21277 ["Next" outline-next-visible-heading t]
21278 ["Previous" outline-previous-visible-heading t]
21279 ["Next Same Level" outline-forward-same-level t]
21280 ["Previous Same Level" outline-backward-same-level t]
21281 "--"
21282 ["Jump" org-goto t])
21283 ("Edit Structure"
21284 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21285 "--"
21286 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21287 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21288 "--"
21289 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21290 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21291 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21292 "--"
21293 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21294 "--"
21295 ["Copy visible text" org-copy-visible t]
21296 "--"
21297 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21298 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21299 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21300 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21301 "--"
21302 ["Sort Region/Children" org-sort t]
21303 "--"
21304 ["Convert to odd levels" org-convert-to-odd-levels t]
21305 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21306 ("Editing"
21307 ["Emphasis..." org-emphasize t]
21308 ["Edit Source Example" org-edit-special t]
21309 "--"
21310 ["Footnote new/jump" org-footnote-action t]
21311 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21312 ("Archive"
21313 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21314 "--"
21315 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21316 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21317 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21319 "--"
21320 ("Hyperlinks"
21321 ["Store Link (Global)" org-store-link t]
21322 ["Find existing link to here" org-occur-link-in-agenda-files t]
21323 ["Insert Link" org-insert-link t]
21324 ["Follow Link" org-open-at-point t]
21325 "--"
21326 ["Next link" org-next-link t]
21327 ["Previous link" org-previous-link t]
21328 "--"
21329 ["Descriptive Links"
21330 org-toggle-link-display
21331 :style radio
21332 :selected org-descriptive-links
21334 ["Literal Links"
21335 org-toggle-link-display
21336 :style radio
21337 :selected (not org-descriptive-links)])
21338 "--"
21339 ("TODO Lists"
21340 ["TODO/DONE/-" org-todo t]
21341 ("Select keyword"
21342 ["Next keyword" org-shiftright (org-at-heading-p)]
21343 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21344 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21345 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21346 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21347 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21348 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21349 "--"
21350 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21351 :selected org-enforce-todo-dependencies :style toggle :active t]
21352 "Settings for tree at point"
21353 ["Do Children sequentially" org-toggle-ordered-property :style radio
21354 :selected (org-entry-get nil "ORDERED")
21355 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21356 ["Do Children parallel" org-toggle-ordered-property :style radio
21357 :selected (not (org-entry-get nil "ORDERED"))
21358 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21359 "--"
21360 ["Set Priority" org-priority t]
21361 ["Priority Up" org-shiftup t]
21362 ["Priority Down" org-shiftdown t]
21363 "--"
21364 ["Get news from all feeds" org-feed-update-all t]
21365 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21366 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21367 ("TAGS and Properties"
21368 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21369 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21370 "--"
21371 ["Set property" org-set-property (not (org-before-first-heading-p))]
21372 ["Column view of properties" org-columns t]
21373 ["Insert Column View DBlock" org-insert-columns-dblock t])
21374 ("Dates and Scheduling"
21375 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21376 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21377 ("Change Date"
21378 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21379 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21380 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21381 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21382 ["Compute Time Range" org-evaluate-time-range t]
21383 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21384 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21385 "--"
21386 ["Custom time format" org-toggle-time-stamp-overlays
21387 :style radio :selected org-display-custom-times]
21388 "--"
21389 ["Goto Calendar" org-goto-calendar t]
21390 ["Date from Calendar" org-date-from-calendar t]
21391 "--"
21392 ["Start/Restart Timer" org-timer-start t]
21393 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21394 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21395 ["Insert Timer String" org-timer t]
21396 ["Insert Timer Item" org-timer-item t])
21397 ("Logging work"
21398 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21399 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21400 ["Clock out" org-clock-out t]
21401 ["Clock cancel" org-clock-cancel t]
21402 "--"
21403 ["Mark as default task" org-clock-mark-default-task t]
21404 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21405 ["Goto running clock" org-clock-goto t]
21406 "--"
21407 ["Display times" org-clock-display t]
21408 ["Create clock table" org-clock-report t]
21409 "--"
21410 ["Record DONE time"
21411 (progn (setq org-log-done (not org-log-done))
21412 (message "Switching to %s will %s record a timestamp"
21413 (car org-done-keywords)
21414 (if org-log-done "automatically" "not")))
21415 :style toggle :selected org-log-done])
21416 "--"
21417 ["Agenda Command..." org-agenda t]
21418 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21419 ("File List for Agenda")
21420 ("Special views current file"
21421 ["TODO Tree" org-show-todo-tree t]
21422 ["Check Deadlines" org-check-deadlines t]
21423 ["Timeline" org-timeline t]
21424 ["Tags/Property tree" org-match-sparse-tree t])
21425 "--"
21426 ["Export/Publish..." org-export-dispatch t]
21427 ("LaTeX"
21428 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21429 :selected org-cdlatex-mode]
21430 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21431 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21432 ["Modify math symbol" org-cdlatex-math-modify
21433 (org-inside-LaTeX-fragment-p)]
21434 ["Insert citation" org-reftex-citation t]
21435 "--"
21436 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21437 "--"
21438 ("MobileOrg"
21439 ["Push Files and Views" org-mobile-push t]
21440 ["Get Captured and Flagged" org-mobile-pull t]
21441 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21442 "--"
21443 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21444 "--"
21445 ("Documentation"
21446 ["Show Version" org-version t]
21447 ["Info Documentation" org-info t])
21448 ("Customize"
21449 ["Browse Org Group" org-customize t]
21450 "--"
21451 ["Expand This Menu" org-create-customize-menu
21452 (fboundp 'customize-menu-create)])
21453 ["Send bug report" org-submit-bug-report t]
21454 "--"
21455 ("Refresh/Reload"
21456 ["Refresh setup current buffer" org-mode-restart t]
21457 ["Reload Org (after update)" org-reload t]
21458 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21461 (defun org-info (&optional node)
21462 "Read documentation for Org-mode in the info system.
21463 With optional NODE, go directly to that node."
21464 (interactive)
21465 (info (format "(org)%s" (or node ""))))
21467 ;;;###autoload
21468 (defun org-submit-bug-report ()
21469 "Submit a bug report on Org-mode via mail.
21471 Don't hesitate to report any problems or inaccurate documentation.
21473 If you don't have setup sending mail from (X)Emacs, please copy the
21474 output buffer into your mail program, as it gives us important
21475 information about your Org-mode version and configuration."
21476 (interactive)
21477 (require 'reporter)
21478 (org-load-modules-maybe)
21479 (org-require-autoloaded-modules)
21480 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21481 (reporter-submit-bug-report
21482 "emacs-orgmode@gnu.org"
21483 (org-version nil 'full)
21484 (let (list)
21485 (save-window-excursion
21486 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21487 (delete-other-windows)
21488 (erase-buffer)
21489 (insert "You are about to submit a bug report to the Org-mode mailing list.
21491 We would like to add your full Org-mode and Outline configuration to the
21492 bug report. This greatly simplifies the work of the maintainer and
21493 other experts on the mailing list.
21495 HOWEVER, some variables you have customized may contain private
21496 information. The names of customers, colleagues, or friends, might
21497 appear in the form of file names, tags, todo states, or search strings.
21498 If you answer yes to the prompt, you might want to check and remove
21499 such private information before sending the email.")
21500 (add-text-properties (point-min) (point-max) '(face org-warning))
21501 (when (yes-or-no-p "Include your Org-mode configuration ")
21502 (mapatoms
21503 (lambda (v)
21504 (and (boundp v)
21505 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21506 (or (and (symbol-value v)
21507 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21508 (and
21509 (get v 'custom-type) (get v 'standard-value)
21510 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21511 (push v list)))))
21512 (kill-buffer (get-buffer "*Warn about privacy*"))
21513 list))
21514 nil nil
21515 "Remember to cover the basics, that is, what you expected to happen and
21516 what in fact did happen. You don't know how to make a good report? See
21518 http://orgmode.org/manual/Feedback.html#Feedback
21520 Your bug report will be posted to the Org-mode mailing list.
21521 ------------------------------------------------------------------------")
21522 (save-excursion
21523 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21524 (replace-match "\\1Bug: \\3 [\\2]")))))
21527 (defun org-install-agenda-files-menu ()
21528 (let ((bl (buffer-list)))
21529 (save-excursion
21530 (while bl
21531 (set-buffer (pop bl))
21532 (if (derived-mode-p 'org-mode) (setq bl nil)))
21533 (when (derived-mode-p 'org-mode)
21534 (easy-menu-change
21535 '("Org") "File List for Agenda"
21536 (append
21537 (list
21538 ["Edit File List" (org-edit-agenda-file-list) t]
21539 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21540 ["Remove Current File from List" org-remove-file t]
21541 ["Cycle through agenda files" org-cycle-agenda-files t]
21542 ["Occur in all agenda files" org-occur-in-agenda-files t]
21543 "--")
21544 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21546 ;;;; Documentation
21548 (defun org-require-autoloaded-modules ()
21549 (interactive)
21550 (mapc 'require
21551 '(org-agenda org-archive org-attach org-clock org-colview org-id
21552 org-table org-timer)))
21554 ;;;###autoload
21555 (defun org-reload (&optional uncompiled)
21556 "Reload all org lisp files.
21557 With prefix arg UNCOMPILED, load the uncompiled versions."
21558 (interactive "P")
21559 (require 'loadhist)
21560 (let* ((org-dir (org-find-library-dir "org"))
21561 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21562 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21563 (remove-re (mapconcat 'identity
21564 (mapcar (lambda (f) (concat "^" f "$"))
21565 (list (if (featurep 'xemacs)
21566 "org-colview"
21567 "org-colview-xemacs")
21568 "org" "org-loaddefs" "org-version"))
21569 "\\|"))
21570 (feats (delete-dups
21571 (mapcar 'file-name-sans-extension
21572 (mapcar 'file-name-nondirectory
21573 (delq nil
21574 (mapcar 'feature-file
21575 features))))))
21576 (lfeat (append
21577 (sort
21578 (setq feats
21579 (delq nil (mapcar
21580 (lambda (f)
21581 (if (and (string-match feature-re f)
21582 (not (string-match remove-re f)))
21583 f nil))
21584 feats)))
21585 'string-lessp)
21586 (list "org-version" "org")))
21587 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21588 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21589 load-uncore load-misses)
21590 (setq load-misses
21591 (delq 't
21592 (mapcar (lambda (f)
21593 (or (org-load-noerror-mustsuffix (concat org-dir f))
21594 (and (string= org-dir contrib-dir)
21595 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21596 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21597 (add-to-list 'load-uncore f 'append)
21600 lfeat)))
21601 (if load-uncore
21602 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21603 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21604 (if load-misses
21605 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21606 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21607 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21609 ;;;###autoload
21610 (defun org-customize ()
21611 "Call the customize function with org as argument."
21612 (interactive)
21613 (org-load-modules-maybe)
21614 (org-require-autoloaded-modules)
21615 (customize-browse 'org))
21617 (defun org-create-customize-menu ()
21618 "Create a full customization menu for Org-mode, insert it into the menu."
21619 (interactive)
21620 (org-load-modules-maybe)
21621 (org-require-autoloaded-modules)
21622 (if (fboundp 'customize-menu-create)
21623 (progn
21624 (easy-menu-change
21625 '("Org") "Customize"
21626 `(["Browse Org group" org-customize t]
21627 "--"
21628 ,(customize-menu-create 'org)
21629 ["Set" Custom-set t]
21630 ["Save" Custom-save t]
21631 ["Reset to Current" Custom-reset-current t]
21632 ["Reset to Saved" Custom-reset-saved t]
21633 ["Reset to Standard Settings" Custom-reset-standard t]))
21634 (message "\"Org\"-menu now contains full customization menu"))
21635 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21637 ;;;; Miscellaneous stuff
21639 ;;; Generally useful functions
21641 (defsubst org-get-at-eol (property n)
21642 "Get text property PROPERTY at the end of line less N characters."
21643 (get-text-property (- (point-at-eol) n) property))
21645 (defun org-find-text-property-in-string (prop s)
21646 "Return the first non-nil value of property PROP in string S."
21647 (or (get-text-property 0 prop s)
21648 (get-text-property (or (next-single-property-change 0 prop s) 0)
21649 prop s)))
21651 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21652 "Display the given MESSAGE as a warning."
21653 (if (fboundp 'display-warning)
21654 (display-warning 'org message
21655 (if (featurep 'xemacs) 'warning :warning))
21656 (let ((buf (get-buffer-create "*Org warnings*")))
21657 (with-current-buffer buf
21658 (goto-char (point-max))
21659 (insert "Warning (Org): " message)
21660 (unless (bolp)
21661 (newline)))
21662 (display-buffer buf)
21663 (sit-for 0))))
21665 (defun org-eval (form)
21666 "Eval FORM and return result."
21667 (condition-case error
21668 (eval form)
21669 (error (format "%%![Error: %s]" error))))
21671 (defun org-in-clocktable-p ()
21672 "Check if the cursor is in a clocktable."
21673 (let ((pos (point)) start)
21674 (save-excursion
21675 (end-of-line 1)
21676 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21677 (setq start (match-beginning 0))
21678 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21679 (>= (match-end 0) pos)
21680 start))))
21682 (defun org-in-verbatim-emphasis ()
21683 (save-match-data
21684 (and (org-in-regexp org-emph-re 2)
21685 (>= (point) (match-beginning 3))
21686 (<= (point) (match-end 4))
21687 (member (match-string 3) '("=" "~")))))
21689 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21690 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21691 (if (and marker (marker-buffer marker)
21692 (buffer-live-p (marker-buffer marker)))
21693 (progn
21694 (org-pop-to-buffer-same-window (marker-buffer marker))
21695 (if (or (> marker (point-max)) (< marker (point-min)))
21696 (widen))
21697 (goto-char marker)
21698 (org-show-context 'org-goto))
21699 (if bookmark
21700 (bookmark-jump bookmark)
21701 (error "Cannot find location"))))
21703 (defun org-quote-csv-field (s)
21704 "Quote field for inclusion in CSV material."
21705 (if (string-match "[\",]" s)
21706 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21709 (defun org-force-self-insert (N)
21710 "Needed to enforce self-insert under remapping."
21711 (interactive "p")
21712 (self-insert-command N))
21714 (defun org-string-width (s)
21715 "Compute width of string, ignoring invisible characters.
21716 This ignores character with invisibility property `org-link', and also
21717 characters with property `org-cwidth', because these will become invisible
21718 upon the next fontification round."
21719 (let (b l)
21720 (when (or (eq t buffer-invisibility-spec)
21721 (assq 'org-link buffer-invisibility-spec))
21722 (while (setq b (text-property-any 0 (length s)
21723 'invisible 'org-link s))
21724 (setq s (concat (substring s 0 b)
21725 (substring s (or (next-single-property-change
21726 b 'invisible s) (length s)))))))
21727 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21728 (setq s (concat (substring s 0 b)
21729 (substring s (or (next-single-property-change
21730 b 'org-cwidth s) (length s))))))
21731 (setq l (string-width s) b -1)
21732 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21733 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21736 (defun org-shorten-string (s maxlength)
21737 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21738 If the string is shorter or has length MAXLENGTH, just return the
21739 original string. If it is longer, the functions finds a space in the
21740 string, breaks this string off at that locations and adds three dots
21741 as ellipsis. Including the ellipsis, the string will not be longer
21742 than MAXLENGTH. If finding a good breaking point in the string does
21743 not work, the string is just chopped off in the middle of a word
21744 if necessary."
21745 (if (<= (length s) maxlength)
21747 (let* ((n (max (- maxlength 4) 1))
21748 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21749 (if (string-match re s)
21750 (concat (match-string 1 s) "...")
21751 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21753 (defun org-get-indentation (&optional line)
21754 "Get the indentation of the current line, interpreting tabs.
21755 When LINE is given, assume it represents a line and compute its indentation."
21756 (if line
21757 (if (string-match "^ *" (org-remove-tabs line))
21758 (match-end 0))
21759 (save-excursion
21760 (beginning-of-line 1)
21761 (skip-chars-forward " \t")
21762 (current-column))))
21764 (defun org-get-string-indentation (s)
21765 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21766 (let ((n -1) (i 0) (w tab-width) c)
21767 (catch 'exit
21768 (while (< (setq n (1+ n)) (length s))
21769 (setq c (aref s n))
21770 (cond ((= c ?\ ) (setq i (1+ i)))
21771 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21772 (t (throw 'exit t)))))
21775 (defun org-remove-tabs (s &optional width)
21776 "Replace tabulators in S with spaces.
21777 Assumes that s is a single line, starting in column 0."
21778 (setq width (or width tab-width))
21779 (while (string-match "\t" s)
21780 (setq s (replace-match
21781 (make-string
21782 (- (* width (/ (+ (match-beginning 0) width) width))
21783 (match-beginning 0)) ?\ )
21784 t t s)))
21787 (defun org-fix-indentation (line ind)
21788 "Fix indentation in LINE.
21789 IND is a cons cell with target and minimum indentation.
21790 If the current indentation in LINE is smaller than the minimum,
21791 leave it alone. If it is larger than ind, set it to the target."
21792 (let* ((l (org-remove-tabs line))
21793 (i (org-get-indentation l))
21794 (i1 (car ind)) (i2 (cdr ind)))
21795 (if (>= i i2) (setq l (substring line i2)))
21796 (if (> i1 0)
21797 (concat (make-string i1 ?\ ) l)
21798 l)))
21800 (defun org-remove-indentation (code &optional n)
21801 "Remove the maximum common indentation from the lines in CODE.
21802 N may optionally be the number of spaces to remove."
21803 (with-temp-buffer
21804 (insert code)
21805 (org-do-remove-indentation n)
21806 (buffer-string)))
21808 (defun org-do-remove-indentation (&optional n)
21809 "Remove the maximum common indentation from the buffer."
21810 (untabify (point-min) (point-max))
21811 (let ((min 10000) re)
21812 (if n
21813 (setq min n)
21814 (goto-char (point-min))
21815 (while (re-search-forward "^ *[^ \n]" nil t)
21816 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21817 (unless (or (= min 0) (= min 10000))
21818 (setq re (format "^ \\{%d\\}" min))
21819 (goto-char (point-min))
21820 (while (re-search-forward re nil t)
21821 (replace-match "")
21822 (end-of-line 1))
21823 min)))
21825 (defun org-fill-template (template alist)
21826 "Find each %key of ALIST in TEMPLATE and replace it."
21827 (let ((case-fold-search nil)
21828 entry key value)
21829 (setq alist (sort (copy-sequence alist)
21830 (lambda (a b) (< (length (car a)) (length (car b))))))
21831 (while (setq entry (pop alist))
21832 (setq template
21833 (replace-regexp-in-string
21834 (concat "%" (regexp-quote (car entry)))
21835 (or (cdr entry) "") template t t)))
21836 template))
21838 (defun org-base-buffer (buffer)
21839 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21840 (if (not buffer)
21841 buffer
21842 (or (buffer-base-buffer buffer)
21843 buffer)))
21845 (defun org-wrap (string &optional width lines)
21846 "Wrap string to either a number of lines, or a width in characters.
21847 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21848 that costs. If there is a word longer than WIDTH, the text is actually
21849 wrapped to the length of that word.
21850 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21851 many lines, whatever width that takes.
21852 The return value is a list of lines, without newlines at the end."
21853 (let* ((words (org-split-string string "[ \t\n]+"))
21854 (maxword (apply 'max (mapcar 'org-string-width words)))
21855 w ll)
21856 (cond (width
21857 (org-do-wrap words (max maxword width)))
21858 (lines
21859 (setq w maxword)
21860 (setq ll (org-do-wrap words maxword))
21861 (if (<= (length ll) lines)
21863 (setq ll words)
21864 (while (> (length ll) lines)
21865 (setq w (1+ w))
21866 (setq ll (org-do-wrap words w)))
21867 ll))
21868 (t (error "Cannot wrap this")))))
21870 (defun org-do-wrap (words width)
21871 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21872 (let (lines line)
21873 (while words
21874 (setq line (pop words))
21875 (while (and words (< (+ (length line) (length (car words))) width))
21876 (setq line (concat line " " (pop words))))
21877 (setq lines (push line lines)))
21878 (nreverse lines)))
21880 (defun org-split-string (string &optional separators)
21881 "Splits STRING into substrings at SEPARATORS.
21882 No empty strings are returned if there are matches at the beginning
21883 and end of string."
21884 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21885 (start 0)
21886 notfirst
21887 (list nil))
21888 (while (and (string-match rexp string
21889 (if (and notfirst
21890 (= start (match-beginning 0))
21891 (< start (length string)))
21892 (1+ start) start))
21893 (< (match-beginning 0) (length string)))
21894 (setq notfirst t)
21895 (or (eq (match-beginning 0) 0)
21896 (and (eq (match-beginning 0) (match-end 0))
21897 (eq (match-beginning 0) start))
21898 (setq list
21899 (cons (substring string start (match-beginning 0))
21900 list)))
21901 (setq start (match-end 0)))
21902 (or (eq start (length string))
21903 (setq list
21904 (cons (substring string start)
21905 list)))
21906 (nreverse list)))
21908 (defun org-quote-vert (s)
21909 "Replace \"|\" with \"\\vert\"."
21910 (while (string-match "|" s)
21911 (setq s (replace-match "\\vert" t t s)))
21914 (defun org-uuidgen-p (s)
21915 "Is S an ID created by UUIDGEN?"
21916 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21918 (defun org-in-src-block-p (&optional inside)
21919 "Whether point is in a code source block.
21920 When INSIDE is non-nil, don't consider we are within a src block
21921 when point is at #+BEGIN_SRC or #+END_SRC."
21922 (let ((case-fold-search t) ov)
21923 (or (and (eq (get-char-property (point) 'src-block) t))
21924 (and (not inside)
21925 (save-match-data
21926 (save-excursion
21927 (beginning-of-line)
21928 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21930 (defun org-context ()
21931 "Return a list of contexts of the current cursor position.
21932 If several contexts apply, all are returned.
21933 Each context entry is a list with a symbol naming the context, and
21934 two positions indicating start and end of the context. Possible
21935 contexts are:
21937 :headline anywhere in a headline
21938 :headline-stars on the leading stars in a headline
21939 :todo-keyword on a TODO keyword (including DONE) in a headline
21940 :tags on the TAGS in a headline
21941 :priority on the priority cookie in a headline
21942 :item on the first line of a plain list item
21943 :item-bullet on the bullet/number of a plain list item
21944 :checkbox on the checkbox in a plain list item
21945 :table in an org-mode table
21946 :table-special on a special filed in a table
21947 :table-table in a table.el table
21948 :clocktable in a clocktable
21949 :src-block in a source block
21950 :link on a hyperlink
21951 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21952 :target on a <<target>>
21953 :radio-target on a <<<radio-target>>>
21954 :latex-fragment on a LaTeX fragment
21955 :latex-preview on a LaTeX fragment with overlaid preview image
21957 This function expects the position to be visible because it uses font-lock
21958 faces as a help to recognize the following contexts: :table-special, :link,
21959 and :keyword."
21960 (let* ((f (get-text-property (point) 'face))
21961 (faces (if (listp f) f (list f)))
21962 (case-fold-search t)
21963 (p (point)) clist o)
21964 ;; First the large context
21965 (cond
21966 ((org-at-heading-p t)
21967 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21968 (when (progn
21969 (beginning-of-line 1)
21970 (looking-at org-todo-line-tags-regexp))
21971 (push (org-point-in-group p 1 :headline-stars) clist)
21972 (push (org-point-in-group p 2 :todo-keyword) clist)
21973 (push (org-point-in-group p 4 :tags) clist))
21974 (goto-char p)
21975 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21976 (if (looking-at "\\[#[A-Z0-9]\\]")
21977 (push (org-point-in-group p 0 :priority) clist)))
21979 ((org-at-item-p)
21980 (push (org-point-in-group p 2 :item-bullet) clist)
21981 (push (list :item (point-at-bol)
21982 (save-excursion (org-end-of-item) (point)))
21983 clist)
21984 (and (org-at-item-checkbox-p)
21985 (push (org-point-in-group p 0 :checkbox) clist)))
21987 ((org-at-table-p)
21988 (push (list :table (org-table-begin) (org-table-end)) clist)
21989 (if (memq 'org-formula faces)
21990 (push (list :table-special
21991 (previous-single-property-change p 'face)
21992 (next-single-property-change p 'face)) clist)))
21993 ((org-at-table-p 'any)
21994 (push (list :table-table) clist)))
21995 (goto-char p)
21997 (let ((case-fold-search t))
21998 ;; New the "medium" contexts: clocktables, source blocks
21999 (cond ((org-in-clocktable-p)
22000 (push (list :clocktable
22001 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22002 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22003 (match-beginning 1))
22004 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22005 (match-end 0))) clist))
22006 ((org-in-src-block-p)
22007 (push (list :src-block
22008 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22009 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22010 (match-beginning 1))
22011 (and (search-forward "#+END_SRC" nil t)
22012 (match-beginning 0))) clist))))
22013 (goto-char p)
22015 ;; Now the small context
22016 (cond
22017 ((org-at-timestamp-p)
22018 (push (org-point-in-group p 0 :timestamp) clist))
22019 ((memq 'org-link faces)
22020 (push (list :link
22021 (previous-single-property-change p 'face)
22022 (next-single-property-change p 'face)) clist))
22023 ((memq 'org-special-keyword faces)
22024 (push (list :keyword
22025 (previous-single-property-change p 'face)
22026 (next-single-property-change p 'face)) clist))
22027 ((org-at-target-p)
22028 (push (org-point-in-group p 0 :target) clist)
22029 (goto-char (1- (match-beginning 0)))
22030 (if (looking-at org-radio-target-regexp)
22031 (push (org-point-in-group p 0 :radio-target) clist))
22032 (goto-char p))
22033 ((setq o (car (delq nil
22034 (mapcar
22035 (lambda (x)
22036 (if (memq x org-latex-fragment-image-overlays) x))
22037 (overlays-at (point))))))
22038 (push (list :latex-fragment
22039 (overlay-start o) (overlay-end o)) clist)
22040 (push (list :latex-preview
22041 (overlay-start o) (overlay-end o)) clist))
22042 ((org-inside-LaTeX-fragment-p)
22043 ;; FIXME: positions wrong.
22044 (push (list :latex-fragment (point) (point)) clist)))
22046 (setq clist (nreverse (delq nil clist)))
22047 clist))
22049 ;; FIXME: Compare with at-regexp-p Do we need both?
22050 (defun org-in-regexp (re &optional nlines visually)
22051 "Check if point is inside a match of regexp.
22052 Normally only the current line is checked, but you can include NLINES extra
22053 lines both before and after point into the search.
22054 If VISUALLY is set, require that the cursor is not after the match but
22055 really on, so that the block visually is on the match."
22056 (catch 'exit
22057 (let ((pos (point))
22058 (eol (point-at-eol (+ 1 (or nlines 0))))
22059 (inc (if visually 1 0)))
22060 (save-excursion
22061 (beginning-of-line (- 1 (or nlines 0)))
22062 (while (re-search-forward re eol t)
22063 (if (and (<= (match-beginning 0) pos)
22064 (>= (+ inc (match-end 0)) pos))
22065 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
22067 (defun org-at-regexp-p (regexp)
22068 "Is point inside a match of REGEXP in the current line?"
22069 (catch 'exit
22070 (save-excursion
22071 (let ((pos (point)) (end (point-at-eol)))
22072 (beginning-of-line 1)
22073 (while (re-search-forward regexp end t)
22074 (if (and (<= (match-beginning 0) pos)
22075 (>= (match-end 0) pos))
22076 (throw 'exit t)))
22077 nil))))
22079 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22080 "Non-nil when point is between matches of START-RE and END-RE.
22082 Also return a non-nil value when point is on one of the matches.
22084 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22085 buffer positions. Default values are the positions of headlines
22086 surrounding the point.
22088 The functions returns a cons cell whose car (resp. cdr) is the
22089 position before START-RE (resp. after END-RE)."
22090 (save-match-data
22091 (let ((pos (point))
22092 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22093 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22094 beg end)
22095 (save-excursion
22096 ;; Point is on a block when on START-RE or if START-RE can be
22097 ;; found before it...
22098 (and (or (org-at-regexp-p start-re)
22099 (re-search-backward start-re limit-up t))
22100 (setq beg (match-beginning 0))
22101 ;; ... and END-RE after it...
22102 (goto-char (match-end 0))
22103 (re-search-forward end-re limit-down t)
22104 (> (setq end (match-end 0)) pos)
22105 ;; ... without another START-RE in-between.
22106 (goto-char (match-beginning 0))
22107 (not (re-search-backward start-re (1+ beg) t))
22108 ;; Return value.
22109 (cons beg end))))))
22111 (defun org-in-block-p (names)
22112 "Non-nil when point belongs to a block whose name belongs to NAMES.
22114 NAMES is a list of strings containing names of blocks.
22116 Return first block name matched, or nil. Beware that in case of
22117 nested blocks, the returned name may not belong to the closest
22118 block from point."
22119 (save-match-data
22120 (catch 'exit
22121 (let ((case-fold-search t)
22122 (lim-up (save-excursion (outline-previous-heading)))
22123 (lim-down (save-excursion (outline-next-heading))))
22124 (mapc (lambda (name)
22125 (let ((n (regexp-quote name)))
22126 (when (org-between-regexps-p
22127 (concat "^[ \t]*#\\+begin_" n)
22128 (concat "^[ \t]*#\\+end_" n)
22129 lim-up lim-down)
22130 (throw 'exit n))))
22131 names))
22132 nil)))
22134 (defun org-in-drawer-p ()
22135 "Non-nil if point is within a drawer.
22136 If point is within a drawer, return it, as parsed data."
22137 (let ((element (save-match-data (org-element-at-point))))
22138 (while (and element (not (memq (org-element-type element)
22139 '(drawer property-drawer))))
22140 (setq element (org-element-property :parent element)))
22141 element))
22143 (defun org-occur-in-agenda-files (regexp &optional nlines)
22144 "Call `multi-occur' with buffers for all agenda files."
22145 (interactive "sOrg-files matching: \np")
22146 (let* ((files (org-agenda-files))
22147 (tnames (mapcar 'file-truename files))
22148 (extra org-agenda-text-search-extra-files)
22150 (when (eq (car extra) 'agenda-archives)
22151 (setq extra (cdr extra))
22152 (setq files (org-add-archive-files files)))
22153 (while (setq f (pop extra))
22154 (unless (member (file-truename f) tnames)
22155 (add-to-list 'files f 'append)
22156 (add-to-list 'tnames (file-truename f) 'append)))
22157 (multi-occur
22158 (mapcar (lambda (x)
22159 (with-current-buffer
22160 (or (get-file-buffer x) (find-file-noselect x))
22161 (widen)
22162 (current-buffer)))
22163 files)
22164 regexp)))
22166 (if (boundp 'occur-mode-find-occurrence-hook)
22167 ;; Emacs 23
22168 (add-hook 'occur-mode-find-occurrence-hook
22169 (lambda ()
22170 (when (derived-mode-p 'org-mode)
22171 (org-reveal))))
22172 ;; Emacs 22
22173 (defadvice occur-mode-goto-occurrence
22174 (after org-occur-reveal activate)
22175 (and (derived-mode-p 'org-mode) (org-reveal)))
22176 (defadvice occur-mode-goto-occurrence-other-window
22177 (after org-occur-reveal activate)
22178 (and (derived-mode-p 'org-mode) (org-reveal)))
22179 (defadvice occur-mode-display-occurrence
22180 (after org-occur-reveal activate)
22181 (when (derived-mode-p 'org-mode)
22182 (let ((pos (occur-mode-find-occurrence)))
22183 (with-current-buffer (marker-buffer pos)
22184 (save-excursion
22185 (goto-char pos)
22186 (org-reveal)))))))
22188 (defun org-occur-link-in-agenda-files ()
22189 "Create a link and search for it in the agendas.
22190 The link is not stored in `org-stored-links', it is just created
22191 for the search purpose."
22192 (interactive)
22193 (let ((link (condition-case nil
22194 (org-store-link nil)
22195 (error "Unable to create a link to here"))))
22196 (org-occur-in-agenda-files (regexp-quote link))))
22198 (defun org-reverse-string (string)
22199 "Return the reverse of STRING."
22200 (apply 'string (reverse (string-to-list string))))
22202 ;; defsubst org-uniquify must be defined before first use
22204 (defun org-uniquify-alist (alist)
22205 "Merge elements of ALIST with the same key.
22207 For example, in this alist:
22209 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22210 => '((a 1 3) (b 2))
22212 merge (a 1) and (a 3) into (a 1 3).
22214 The function returns the new ALIST."
22215 (let (rtn)
22216 (mapc
22217 (lambda (e)
22218 (let (n)
22219 (if (not (assoc (car e) rtn))
22220 (push e rtn)
22221 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22222 (setq rtn (assq-delete-all (car e) rtn))
22223 (push n rtn))))
22224 alist)
22225 rtn))
22227 (defun org-delete-all (elts list)
22228 "Remove all elements in ELTS from LIST."
22229 (while elts
22230 (setq list (delete (pop elts) list)))
22231 list)
22233 (defun org-count (cl-item cl-seq)
22234 "Count the number of occurrences of ITEM in SEQ.
22235 Taken from `count' in cl-seq.el with all keyword arguments removed."
22236 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22237 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22238 (while (< cl-start cl-end)
22239 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22240 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22241 (setq cl-start (1+ cl-start)))
22242 cl-count))
22244 (defun org-remove-if (predicate seq)
22245 "Remove everything from SEQ that fulfills PREDICATE."
22246 (let (res e)
22247 (while seq
22248 (setq e (pop seq))
22249 (if (not (funcall predicate e)) (push e res)))
22250 (nreverse res)))
22252 (defun org-remove-if-not (predicate seq)
22253 "Remove everything from SEQ that does not fulfill PREDICATE."
22254 (let (res e)
22255 (while seq
22256 (setq e (pop seq))
22257 (if (funcall predicate e) (push e res)))
22258 (nreverse res)))
22260 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22261 "Reduce two-argument FUNCTION across SEQ.
22262 Taken from `reduce' in cl-seq.el with all keyword arguments but
22263 \":initial-value\" removed."
22264 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22265 (cadr (memq :initial-value cl-keys)))
22266 (cl-seq (pop cl-seq))
22267 (t (funcall cl-func)))))
22268 (while cl-seq
22269 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22270 cl-accum))
22272 (defun org-every (pred seq)
22273 "Return true if PREDICATE is true of every element of SEQ.
22274 Adapted from `every' in cl.el."
22275 (catch 'org-every
22276 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22279 (defun org-some (pred seq)
22280 "Return true if PREDICATE is true of any element of SEQ.
22281 Adapted from `some' in cl.el."
22282 (catch 'org-some
22283 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22284 nil))
22286 (defun org-back-over-empty-lines ()
22287 "Move backwards over whitespace, to the beginning of the first empty line.
22288 Returns the number of empty lines passed."
22289 (let ((pos (point)))
22290 (if (cdr (assoc 'heading org-blank-before-new-entry))
22291 (skip-chars-backward " \t\n\r")
22292 (unless (eobp)
22293 (forward-line -1)))
22294 (beginning-of-line 2)
22295 (goto-char (min (point) pos))
22296 (count-lines (point) pos)))
22298 (defun org-skip-whitespace ()
22299 (skip-chars-forward " \t\n\r"))
22301 (defun org-point-in-group (point group &optional context)
22302 "Check if POINT is in match-group GROUP.
22303 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22304 match. If the match group does not exist or point is not inside it,
22305 return nil."
22306 (and (match-beginning group)
22307 (>= point (match-beginning group))
22308 (<= point (match-end group))
22309 (if context
22310 (list context (match-beginning group) (match-end group))
22311 t)))
22313 (defun org-switch-to-buffer-other-window (&rest args)
22314 "Switch to buffer in a second window on the current frame.
22315 In particular, do not allow pop-up frames.
22316 Returns the newly created buffer."
22317 (org-no-popups
22318 (apply 'switch-to-buffer-other-window args)))
22320 (defun org-combine-plists (&rest plists)
22321 "Create a single property list from all plists in PLISTS.
22322 The process starts by copying the first list, and then setting properties
22323 from the other lists. Settings in the last list are the most significant
22324 ones and overrule settings in the other lists."
22325 (let ((rtn (copy-sequence (pop plists)))
22326 p v ls)
22327 (while plists
22328 (setq ls (pop plists))
22329 (while ls
22330 (setq p (pop ls) v (pop ls))
22331 (setq rtn (plist-put rtn p v))))
22332 rtn))
22334 (defun org-replace-escapes (string table)
22335 "Replace %-escapes in STRING with values in TABLE.
22336 TABLE is an association list with keys like \"%a\" and string values.
22337 The sequences in STRING may contain normal field width and padding information,
22338 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22339 so values can contain further %-escapes if they are define later in TABLE."
22340 (let ((tbl (copy-alist table))
22341 (case-fold-search nil)
22342 (pchg 0)
22343 e re rpl)
22344 (while (setq e (pop tbl))
22345 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22346 (when (and (cdr e) (string-match re (cdr e)))
22347 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22348 (safe "SREF"))
22349 (add-text-properties 0 3 (list 'sref sref) safe)
22350 (setcdr e (replace-match safe t t (cdr e)))))
22351 (while (string-match re string)
22352 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22353 (cdr e)))
22354 (setq string (replace-match rpl t t string))))
22355 (while (setq pchg (next-property-change pchg string))
22356 (let ((sref (get-text-property pchg 'sref string)))
22357 (when (and sref (string-match "SREF" string pchg))
22358 (setq string (replace-match sref t t string)))))
22359 string))
22361 (defun org-sublist (list start end)
22362 "Return a section of LIST, from START to END.
22363 Counting starts at 1."
22364 (let (rtn (c start))
22365 (setq list (nthcdr (1- start) list))
22366 (while (and list (<= c end))
22367 (push (pop list) rtn)
22368 (setq c (1+ c)))
22369 (nreverse rtn)))
22371 (defun org-find-base-buffer-visiting (file)
22372 "Like `find-buffer-visiting' but always return the base buffer and
22373 not an indirect buffer."
22374 (let ((buf (or (get-file-buffer file)
22375 (find-buffer-visiting file))))
22376 (if buf
22377 (or (buffer-base-buffer buf) buf)
22378 nil)))
22380 (defun org-image-file-name-regexp (&optional extensions)
22381 "Return regexp matching the file names of images.
22382 If EXTENSIONS is given, only match these."
22383 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22384 (image-file-name-regexp)
22385 (let ((image-file-name-extensions
22386 (or extensions
22387 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22388 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22389 (concat "\\."
22390 (regexp-opt (nconc (mapcar 'upcase
22391 image-file-name-extensions)
22392 image-file-name-extensions)
22394 "\\'"))))
22396 (defun org-file-image-p (file &optional extensions)
22397 "Return non-nil if FILE is an image."
22398 (save-match-data
22399 (string-match (org-image-file-name-regexp extensions) file)))
22401 (defun org-get-cursor-date (&optional with-time)
22402 "Return the date at cursor in as a time.
22403 This works in the calendar and in the agenda, anywhere else it just
22404 returns the current time.
22405 If WITH-TIME is non-nil, returns the time of the event at point (in
22406 the agenda) or the current time of the day."
22407 (let (date day defd tp tm hod mod)
22408 (when with-time
22409 (setq tp (get-text-property (point) 'time))
22410 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22411 (setq hod (string-to-number (match-string 1 tp))
22412 mod (string-to-number (match-string 2 tp))))
22413 (or tp (setq hod (nth 2 (decode-time (current-time)))
22414 mod (nth 1 (decode-time (current-time))))))
22415 (cond
22416 ((eq major-mode 'calendar-mode)
22417 (setq date (calendar-cursor-to-date)
22418 defd (encode-time 0 (or mod 0) (or hod 0)
22419 (nth 1 date) (nth 0 date) (nth 2 date))))
22420 ((eq major-mode 'org-agenda-mode)
22421 (setq day (get-text-property (point) 'day))
22422 (if day
22423 (setq date (calendar-gregorian-from-absolute day)
22424 defd (encode-time 0 (or mod 0) (or hod 0)
22425 (nth 1 date) (nth 0 date) (nth 2 date))))))
22426 (or defd (current-time))))
22428 (defun org-mark-subtree (&optional up)
22429 "Mark the current subtree.
22430 This puts point at the start of the current subtree, and mark at
22431 the end. If a numeric prefix UP is given, move up into the
22432 hierarchy of headlines by UP levels before marking the subtree."
22433 (interactive "P")
22434 (org-with-limited-levels
22435 (cond ((org-at-heading-p) (beginning-of-line))
22436 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22437 (t (outline-previous-visible-heading 1))))
22438 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22439 (if (org-called-interactively-p 'any)
22440 (call-interactively 'org-mark-element)
22441 (org-mark-element)))
22444 ;;; Indentation
22446 (defun org--get-expected-indentation (element contentsp)
22447 "Expected indentation column for current line, according to ELEMENT.
22448 ELEMENT is an element containing point. CONTENTSP is non-nil
22449 when indentation is to be computed according to contents of
22450 ELEMENT."
22451 (let ((type (org-element-type element))
22452 (start (org-element-property :begin element)))
22453 (org-with-wide-buffer
22454 (cond
22455 (contentsp
22456 (case type
22457 (footnote-definition 0)
22458 ((headline inlinetask nil)
22459 (if (not org-adapt-indentation) 0
22460 (let ((level (org-current-level)))
22461 (if level (1+ level) 0))))
22462 (item
22463 (org-list-item-body-column
22464 (org-element-property :post-affiliated element)))
22465 (plain-list
22466 (save-excursion
22467 (goto-char (org-element-property :post-affiliated element))
22468 (org-get-indentation)))
22469 (otherwise
22470 (goto-char start)
22471 (org-get-indentation))))
22472 ((memq type '(headline inlinetask nil))
22473 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22474 (org--get-expected-indentation element t)
22476 ((eq type 'footnote-definition) 0)
22477 ;; First paragraph of a footnote definition or an item.
22478 ;; Indent like parent.
22479 ((< (line-beginning-position) start)
22480 (org--get-expected-indentation
22481 (org-element-property :parent element) t))
22482 ;; At first line: indent according to previous sibling, if any,
22483 ;; ignoring footnote definitions and inline tasks, or parent's
22484 ;; contents.
22485 ((= (line-beginning-position) start)
22486 (catch 'exit
22487 (while t
22488 (if (= (point-min) start) (throw 'exit 0)
22489 (goto-char (1- start))
22490 (let* ((previous (org-element-at-point))
22491 (parent previous))
22492 (while (and parent (<= (org-element-property :end parent) start))
22493 (setq previous parent
22494 parent (org-element-property :parent parent)))
22495 (cond
22496 ((not previous) (throw 'exit 0))
22497 ((> (org-element-property :end previous) start)
22498 (throw 'exit (org--get-expected-indentation previous t)))
22499 ((memq (org-element-type previous)
22500 '(footnote-definition inlinetask))
22501 (setq start (org-element-property :begin previous)))
22502 (t (goto-char (org-element-property :begin previous))
22503 (throw 'exit
22504 (if (bolp) (org-get-indentation)
22505 ;; At first paragraph in an item or
22506 ;; a footnote definition.
22507 (org--get-expected-indentation
22508 (org-element-property :parent previous) t))))))))))
22509 ;; Otherwise, move to the first non-blank line above.
22511 (beginning-of-line)
22512 (let ((pos (point)))
22513 (skip-chars-backward " \r\t\n")
22514 (cond
22515 ;; Two blank lines end a footnote definition or a plain
22516 ;; list. When we indent an empty line after them, the
22517 ;; containing list or footnote definition is over, so it
22518 ;; qualifies as a previous sibling. Therefore, we indent
22519 ;; like its first line.
22520 ((and (memq type '(footnote-definition plain-list))
22521 (> (count-lines (point) pos) 2))
22522 (goto-char start)
22523 (org-get-indentation))
22524 ;; Line above is the first one of a paragraph at the
22525 ;; beginning of an item or a footnote definition. Indent
22526 ;; like parent.
22527 ((< (line-beginning-position) start)
22528 (org--get-expected-indentation
22529 (org-element-property :parent element) t))
22530 ;; POS is after contents in a greater element. Indent like
22531 ;; the beginning of the element.
22533 ;; As a special case, if point is at the end of a footnote
22534 ;; definition or an item, indent like the very last element
22535 ;; within.
22536 ((let ((cend (org-element-property :contents-end element)))
22537 (and cend (<= cend pos)))
22538 (if (memq type '(footnote-definition item plain-list))
22539 (org--get-expected-indentation (org-element-at-point) nil)
22540 (goto-char start)
22541 (org-get-indentation)))
22542 ;; In any other case, indent like the current line.
22543 (t (org-get-indentation)))))))))
22545 (defun org--align-node-property ()
22546 "Align node property at point.
22547 Alignment is done according to `org-property-format', which see."
22548 (when (save-excursion
22549 (beginning-of-line)
22550 (looking-at org-property-re))
22551 (replace-match
22552 (concat (match-string 4)
22553 (org-trim
22554 (format org-property-format (match-string 1) (match-string 3))))
22555 t t)))
22557 (defun org-indent-line ()
22558 "Indent line depending on context.
22560 Indentation is done according to the following rules:
22562 - Footnote definitions, headlines and inline tasks have to
22563 start at column 0.
22565 - On the very first line of an element, consider, in order, the
22566 next rules until one matches:
22568 1. If there's a sibling element before, ignoring footnote
22569 definitions and inline tasks, indent like its first line.
22571 2. If element has a parent, indent like its contents. More
22572 precisely, if parent is an item, indent after the
22573 description part, if any, or the bullet (see
22574 ``org-list-description-max-indent'). Else, indent like
22575 parent's first line.
22577 3. Otherwise, indent relatively to current level, if
22578 `org-adapt-indentation' is non-nil, or to left margin.
22580 - On a blank line at the end of a plain list, an item, or
22581 a footnote definition, indent like the very last element
22582 within.
22584 - In the code part of a source block, use language major mode
22585 to indent current line if `org-src-tab-acts-natively' is
22586 non-nil. If it is nil, do nothing.
22588 - Otherwise, indent like the first non-blank line above.
22590 The function doesn't indent an item as it could break the whole
22591 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22592 \\[org-shiftmetaright].
22594 Also align node properties according to `org-property-format'."
22595 (interactive)
22596 (cond
22597 (orgstruct-is-++
22598 (let ((indent-line-function
22599 (cadadr (assq 'indent-line-function org-fb-vars))))
22600 (indent-according-to-mode)))
22601 ((org-at-heading-p) 'noindent)
22603 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22604 (type (org-element-type element)))
22605 (cond ((and (memq type '(plain-list item))
22606 (= (line-beginning-position)
22607 (org-element-property :post-affiliated element)))
22608 'noindent)
22609 ((and (eq type 'src-block)
22610 org-src-tab-acts-natively
22611 (> (line-beginning-position)
22612 (org-element-property :post-affiliated element))
22613 (< (line-beginning-position)
22614 (org-with-wide-buffer
22615 (goto-char (org-element-property :end element))
22616 (skip-chars-backward " \r\t\n")
22617 (line-beginning-position))))
22618 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22619 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))))
22621 (let ((column (org--get-expected-indentation element nil)))
22622 ;; Preserve current column.
22623 (if (<= (current-column) (current-indentation))
22624 (org-indent-line-to column)
22625 (save-excursion (org-indent-line-to column))))
22626 ;; Align node property. Also preserve current column.
22627 (when (eq type 'node-property)
22628 (let ((column (current-column)))
22629 (org--align-node-property)
22630 (org-move-to-column column)))))))))
22632 (defun org-indent-region (start end)
22633 "Indent each non-blank line in the region.
22634 Called from a program, START and END specify the region to
22635 indent. The function will not indent contents of example blocks,
22636 verse blocks and export blocks as leading white spaces are
22637 assumed to be significant there."
22638 (interactive "r")
22639 (save-excursion
22640 (goto-char start)
22641 (skip-chars-forward " \r\t\n")
22642 (unless (eobp) (beginning-of-line))
22643 (let ((indent-to
22644 (lambda (ind pos)
22645 ;; Set IND as indentation for all lines between point and
22646 ;; POS or END, whichever comes first. Blank lines are
22647 ;; ignored. Leave point after POS once done.
22648 (let ((limit (copy-marker (min end pos))))
22649 (while (< (point) limit)
22650 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22651 (forward-line))
22652 (set-marker limit nil))))
22653 (end (copy-marker end)))
22654 (while (< (point) end)
22655 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22656 (let* ((element (org-element-at-point))
22657 (type (org-element-type element))
22658 (element-end (copy-marker (org-element-property :end element)))
22659 (ind (org--get-expected-indentation element nil)))
22660 (cond
22661 ((or (memq type '(paragraph table table-row))
22662 (not (or (org-element-property :contents-begin element)
22663 (memq type
22664 '(example-block export-block src-block)))))
22665 ;; Elements here are indented as a single block. Also
22666 ;; align node properties.
22667 (when (eq type 'node-property)
22668 (org--align-node-property)
22669 (beginning-of-line))
22670 (funcall indent-to ind element-end))
22672 ;; Elements in this category consist of three parts:
22673 ;; before the contents, the contents, and after the
22674 ;; contents. The contents are treated specially,
22675 ;; according to the element type, or not indented at
22676 ;; all. Other parts are indented as a single block.
22677 (let* ((post (copy-marker
22678 (org-element-property :post-affiliated element)))
22679 (cbeg
22680 (copy-marker
22681 (cond
22682 ((not (org-element-property :contents-begin element))
22683 ;; Fake contents for source blocks.
22684 (org-with-wide-buffer
22685 (goto-char post)
22686 (forward-line)
22687 (point)))
22688 ((memq type '(footnote-definition item plain-list))
22689 ;; Contents in these elements could start on
22690 ;; the same line as the beginning of the
22691 ;; element. Make sure we start indenting
22692 ;; from the second line.
22693 (org-with-wide-buffer
22694 (goto-char post)
22695 (end-of-line)
22696 (skip-chars-forward " \r\t\n")
22697 (if (eobp) (point) (line-beginning-position))))
22698 (t (org-element-property :contents-begin element)))))
22699 (cend (copy-marker
22700 (or (org-element-property :contents-end element)
22701 ;; Fake contents for source blocks.
22702 (org-with-wide-buffer
22703 (goto-char element-end)
22704 (skip-chars-backward " \r\t\n")
22705 (line-beginning-position))))))
22706 ;; Do not change items indentation individually as it
22707 ;; might break the list as a whole. On the other
22708 ;; hand, when at a plain list, indent it as a whole.
22709 (cond ((eq type 'plain-list)
22710 (let ((offset (- ind (org-get-indentation))))
22711 (unless (zerop offset)
22712 (indent-rigidly (org-element-property :begin element)
22713 (org-element-property :end element)
22714 offset))
22715 (goto-char cbeg)))
22716 ((eq type 'item) (goto-char cbeg))
22717 (t (funcall indent-to ind cbeg)))
22718 (when (< (point) end)
22719 (case type
22720 ((example-block export-block verse-block))
22721 (src-block
22722 ;; In a source block, indent source code
22723 ;; according to language major mode, but only if
22724 ;; `org-src-tab-acts-natively' is non-nil.
22725 (when (and (< (point) end) org-src-tab-acts-natively)
22726 (ignore-errors
22727 (let (org-src-strip-leading-and-trailing-blank-lines
22728 ;; Region boundaries in edit buffer.
22729 (start (1+ (- (point) cbeg)))
22730 (end (- (min cend end) cbeg)))
22731 (org-babel-do-in-edit-buffer
22732 (indent-region start end))))))
22733 (t (org-indent-region (point) (min cend end))))
22734 (goto-char (min cend end))
22735 (when (< (point) end) (funcall indent-to ind element-end)))
22736 (set-marker post nil)
22737 (set-marker cbeg nil)
22738 (set-marker cend nil))))
22739 (set-marker element-end nil))))
22740 (set-marker end nil))))
22742 (defun org-indent-drawer ()
22743 "Indent the drawer at point."
22744 (interactive)
22745 (unless (save-excursion
22746 (beginning-of-line)
22747 (org-looking-at-p org-drawer-regexp))
22748 (user-error "Not at a drawer"))
22749 (let ((element (org-element-at-point)))
22750 (unless (memq (org-element-type element) '(drawer property-drawer))
22751 (user-error "Not at a drawer"))
22752 (org-with-wide-buffer
22753 (org-indent-region (org-element-property :begin element)
22754 (org-element-property :end element))))
22755 (message "Drawer at point indented"))
22757 (defun org-indent-block ()
22758 "Indent the block at point."
22759 (interactive)
22760 (unless (save-excursion
22761 (beginning-of-line)
22762 (let ((case-fold-search t))
22763 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22764 (user-error "Not at a block"))
22765 (let ((element (org-element-at-point)))
22766 (unless (memq (org-element-type element)
22767 '(comment-block center-block dynamic-block example-block
22768 export-block quote-block special-block
22769 src-block verse-block))
22770 (user-error "Not at a block"))
22771 (org-with-wide-buffer
22772 (org-indent-region (org-element-property :begin element)
22773 (org-element-property :end element))))
22774 (message "Block at point indented"))
22777 ;;; Filling
22779 ;; We use our own fill-paragraph and auto-fill functions.
22781 ;; `org-fill-paragraph' relies on adaptive filling and context
22782 ;; checking. Appropriate `fill-prefix' is computed with
22783 ;; `org-adaptive-fill-function'.
22785 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22786 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22787 ;; `org-adaptive-fill-function' value. Internally,
22788 ;; `org-comment-line-break-function' breaks the line.
22790 ;; `org-setup-filling' installs filling and auto-filling related
22791 ;; variables during `org-mode' initialization.
22793 (defvar org-element-paragraph-separate) ; org-element.el
22794 (defun org-setup-filling ()
22795 (require 'org-element)
22796 ;; Prevent auto-fill from inserting unwanted new items.
22797 (when (boundp 'fill-nobreak-predicate)
22798 (org-set-local
22799 'fill-nobreak-predicate
22800 (org-uniquify
22801 (append fill-nobreak-predicate
22802 '(org-fill-line-break-nobreak-p
22803 org-fill-paragraph-with-timestamp-nobreak-p)))))
22804 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22805 (org-set-local 'paragraph-start paragraph-ending)
22806 (org-set-local 'paragraph-separate paragraph-ending))
22807 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22808 (org-set-local 'auto-fill-inhibit-regexp nil)
22809 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22810 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22811 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22813 (defun org-fill-line-break-nobreak-p ()
22814 "Non-nil when a new line at point would create an Org line break."
22815 (save-excursion
22816 (skip-chars-backward "[ \t]")
22817 (skip-chars-backward "\\\\")
22818 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22820 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22821 "Non-nil when a new line at point would split a timestamp."
22822 (and (org-at-timestamp-p t)
22823 (not (looking-at org-ts-regexp-both))))
22825 (declare-function message-in-body-p "message" ())
22826 (defvar orgtbl-line-start-regexp) ; From org-table.el
22827 (defun org-adaptive-fill-function ()
22828 "Compute a fill prefix for the current line.
22829 Return fill prefix, as a string, or nil if current line isn't
22830 meant to be filled. For convenience, if `adaptive-fill-regexp'
22831 matches in paragraphs or comments, use it."
22832 (catch 'exit
22833 (when (derived-mode-p 'message-mode)
22834 (save-excursion
22835 (beginning-of-line)
22836 (cond ((or (not (message-in-body-p))
22837 (looking-at orgtbl-line-start-regexp))
22838 (throw 'exit nil))
22839 ((looking-at message-cite-prefix-regexp)
22840 (throw 'exit (match-string-no-properties 0)))
22841 ((looking-at org-outline-regexp)
22842 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22843 (org-with-wide-buffer
22844 (unless (org-at-heading-p)
22845 (let* ((p (line-beginning-position))
22846 (element (save-excursion
22847 (beginning-of-line)
22848 (org-element-at-point)))
22849 (type (org-element-type element))
22850 (post-affiliated (org-element-property :post-affiliated element)))
22851 (unless (< p post-affiliated)
22852 (case type
22853 (comment
22854 (save-excursion
22855 (beginning-of-line)
22856 (looking-at "[ \t]*")
22857 (concat (match-string 0) "# ")))
22858 (footnote-definition "")
22859 ((item plain-list)
22860 (make-string (org-list-item-body-column post-affiliated) ?\s))
22861 (paragraph
22862 ;; Fill prefix is usually the same as the current line,
22863 ;; unless the paragraph is at the beginning of an item.
22864 (let ((parent (org-element-property :parent element)))
22865 (save-excursion
22866 (beginning-of-line)
22867 (cond ((eq (org-element-type parent) 'item)
22868 (make-string (org-list-item-body-column
22869 (org-element-property :begin parent))
22870 ?\s))
22871 ((and adaptive-fill-regexp
22872 ;; Locally disable
22873 ;; `adaptive-fill-function' to let
22874 ;; `fill-context-prefix' handle
22875 ;; `adaptive-fill-regexp' variable.
22876 (let (adaptive-fill-function)
22877 (fill-context-prefix
22878 post-affiliated
22879 (org-element-property :end element)))))
22880 ((looking-at "[ \t]+") (match-string 0))
22881 (t "")))))
22882 (comment-block
22883 ;; Only fill contents if P is within block boundaries.
22884 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22885 (forward-line)
22886 (point)))
22887 (cend (save-excursion
22888 (goto-char (org-element-property :end element))
22889 (skip-chars-backward " \r\t\n")
22890 (line-beginning-position))))
22891 (when (and (>= p cbeg) (< p cend))
22892 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22893 (match-string 0)
22894 "")))))))))))
22896 (declare-function message-goto-body "message" ())
22897 (defvar message-cite-prefix-regexp) ; From message.el
22898 (defun org-fill-paragraph (&optional justify)
22899 "Fill element at point, when applicable.
22901 This function only applies to comment blocks, comments, example
22902 blocks and paragraphs. Also, as a special case, re-align table
22903 when point is at one.
22905 If JUSTIFY is non-nil (interactively, with prefix argument),
22906 justify as well. If `sentence-end-double-space' is non-nil, then
22907 period followed by one space does not end a sentence, so don't
22908 break a line there. The variable `fill-column' controls the
22909 width for filling.
22911 For convenience, when point is at a plain list, an item or
22912 a footnote definition, try to fill the first paragraph within."
22913 (interactive)
22914 (if (and (derived-mode-p 'message-mode)
22915 (or (not (message-in-body-p))
22916 (save-excursion (move-beginning-of-line 1)
22917 (looking-at message-cite-prefix-regexp))))
22918 ;; First ensure filling is correct in message-mode.
22919 (let ((fill-paragraph-function
22920 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22921 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22922 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22923 (paragraph-separate
22924 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22925 (fill-paragraph nil))
22926 (with-syntax-table org-mode-transpose-word-syntax-table
22927 ;; Move to end of line in order to get the first paragraph
22928 ;; within a plain list or a footnote definition.
22929 (let ((element (save-excursion
22930 (end-of-line)
22931 (or (ignore-errors (org-element-at-point))
22932 (user-error "An element cannot be parsed line %d"
22933 (line-number-at-pos (point)))))))
22934 ;; First check if point is in a blank line at the beginning of
22935 ;; the buffer. In that case, ignore filling.
22936 (case (org-element-type element)
22937 ;; Use major mode filling function is src blocks.
22938 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22939 ;; Align Org tables, leave table.el tables as-is.
22940 (table-row (org-table-align) t)
22941 (table
22942 (when (eq (org-element-property :type element) 'org)
22943 (save-excursion
22944 (goto-char (org-element-property :post-affiliated element))
22945 (org-table-align)))
22947 (paragraph
22948 ;; Paragraphs may contain `line-break' type objects.
22949 (let ((beg (max (point-min)
22950 (org-element-property :contents-begin element)))
22951 (end (min (point-max)
22952 (org-element-property :contents-end element))))
22953 ;; Do nothing if point is at an affiliated keyword.
22954 (if (< (line-end-position) beg) t
22955 (when (derived-mode-p 'message-mode)
22956 ;; In `message-mode', do not fill following citation
22957 ;; in current paragraph nor text before message body.
22958 (let ((body-start (save-excursion (message-goto-body))))
22959 (when body-start (setq beg (max body-start beg))))
22960 (when (save-excursion
22961 (re-search-forward
22962 (concat "^" message-cite-prefix-regexp) end t))
22963 (setq end (match-beginning 0))))
22964 ;; Fill paragraph, taking line breaks into account.
22965 (save-excursion
22966 (goto-char beg)
22967 (let ((cuts (list beg)))
22968 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22969 (when (eq 'line-break
22970 (org-element-type
22971 (save-excursion (backward-char)
22972 (org-element-context))))
22973 (push (point) cuts)))
22974 (dolist (c (delq end cuts))
22975 (fill-region-as-paragraph c end justify)
22976 (setq end c))))
22977 t)))
22978 ;; Contents of `comment-block' type elements should be
22979 ;; filled as plain text, but only if point is within block
22980 ;; markers.
22981 (comment-block
22982 (let* ((case-fold-search t)
22983 (beg (save-excursion
22984 (goto-char (org-element-property :begin element))
22985 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22986 (forward-line)
22987 (point)))
22988 (end (save-excursion
22989 (goto-char (org-element-property :end element))
22990 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22991 (line-beginning-position))))
22992 (if (or (< (point) beg) (> (point) end)) t
22993 (fill-region-as-paragraph
22994 (save-excursion (end-of-line)
22995 (re-search-backward "^[ \t]*$" beg 'move)
22996 (line-beginning-position))
22997 (save-excursion (beginning-of-line)
22998 (re-search-forward "^[ \t]*$" end 'move)
22999 (line-beginning-position))
23000 justify))))
23001 ;; Fill comments.
23002 (comment
23003 (let ((begin (org-element-property :post-affiliated element))
23004 (end (org-element-property :end element)))
23005 (when (and (>= (point) begin) (<= (point) end))
23006 (let ((begin (save-excursion
23007 (end-of-line)
23008 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23009 (progn (forward-line) (point))
23010 begin)))
23011 (end (save-excursion
23012 (end-of-line)
23013 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23014 (1- (line-beginning-position))
23015 (skip-chars-backward " \r\t\n")
23016 (line-end-position)))))
23017 ;; Do not fill comments when at a blank line.
23018 (when (> end begin)
23019 (let ((fill-prefix
23020 (save-excursion
23021 (beginning-of-line)
23022 (looking-at "[ \t]*#")
23023 (let ((comment-prefix (match-string 0)))
23024 (goto-char (match-end 0))
23025 (if (looking-at adaptive-fill-regexp)
23026 (concat comment-prefix (match-string 0))
23027 (concat comment-prefix " "))))))
23028 (save-excursion
23029 (fill-region-as-paragraph begin end justify))))))
23031 ;; Ignore every other element.
23032 (otherwise t))))))
23034 (defun org-auto-fill-function ()
23035 "Auto-fill function."
23036 ;; Check if auto-filling is meaningful.
23037 (let ((fc (current-fill-column)))
23038 (when (and fc (> (current-column) fc))
23039 (let* ((fill-prefix (org-adaptive-fill-function))
23040 ;; Enforce empty fill prefix, if required. Otherwise, it
23041 ;; will be computed again.
23042 (adaptive-fill-mode (not (equal fill-prefix ""))))
23043 (when fill-prefix (do-auto-fill))))))
23045 (defun org-comment-line-break-function (&optional soft)
23046 "Break line at point and indent, continuing comment if within one.
23047 The inserted newline is marked hard if variable
23048 `use-hard-newlines' is true, unless optional argument SOFT is
23049 non-nil."
23050 (if soft (insert-and-inherit ?\n) (newline 1))
23051 (save-excursion (forward-char -1) (delete-horizontal-space))
23052 (delete-horizontal-space)
23053 (indent-to-left-margin)
23054 (insert-before-markers-and-inherit fill-prefix))
23057 ;;; Fixed Width Areas
23059 (defun org-toggle-fixed-width ()
23060 "Toggle fixed-width markup.
23062 Add or remove fixed-width markup on current line, whenever it
23063 makes sense. Return an error otherwise.
23065 If a region is active and if it contains only fixed-width areas
23066 or blank lines, remove all fixed-width markup in it. If the
23067 region contains anything else, convert all non-fixed-width lines
23068 to fixed-width ones.
23070 Blank lines at the end of the region are ignored unless the
23071 region only contains such lines."
23072 (interactive)
23073 (if (not (org-region-active-p))
23074 ;; No region:
23076 ;; Remove fixed width marker only in a fixed-with element.
23078 ;; Add fixed width maker in paragraphs, in blank lines after
23079 ;; elements or at the beginning of a headline or an inlinetask,
23080 ;; and before any one-line elements (e.g., a clock).
23081 (progn
23082 (beginning-of-line)
23083 (let* ((element (org-element-at-point))
23084 (type (org-element-type element)))
23085 (cond
23086 ((and (eq type 'fixed-width)
23087 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23088 (replace-match
23089 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23090 ((and (memq type '(babel-call clock comment diary-sexp headline
23091 horizontal-rule keyword paragraph
23092 planning))
23093 (<= (org-element-property :post-affiliated element) (point)))
23094 (skip-chars-forward " \t")
23095 (insert ": "))
23096 ((and (org-looking-at-p "[ \t]*$")
23097 (or (eq type 'inlinetask)
23098 (save-excursion
23099 (skip-chars-forward " \r\t\n")
23100 (<= (org-element-property :end element) (point)))))
23101 (delete-region (point) (line-end-position))
23102 (org-indent-line)
23103 (insert ": "))
23104 (t (user-error "Cannot insert a fixed-width line here")))))
23105 ;; Region active.
23106 (let* ((begin (save-excursion
23107 (goto-char (region-beginning))
23108 (line-beginning-position)))
23109 (end (copy-marker
23110 (save-excursion
23111 (goto-char (region-end))
23112 (unless (eolp) (beginning-of-line))
23113 (if (save-excursion (re-search-backward "\\S-" begin t))
23114 (progn (skip-chars-backward " \r\t\n") (point))
23115 (point)))))
23116 (all-fixed-width-p
23117 (catch 'not-all-p
23118 (save-excursion
23119 (goto-char begin)
23120 (skip-chars-forward " \r\t\n")
23121 (when (eobp) (throw 'not-all-p nil))
23122 (while (< (point) end)
23123 (let ((element (org-element-at-point)))
23124 (if (eq (org-element-type element) 'fixed-width)
23125 (goto-char (org-element-property :end element))
23126 (throw 'not-all-p nil))))
23127 t))))
23128 (if all-fixed-width-p
23129 (save-excursion
23130 (goto-char begin)
23131 (while (< (point) end)
23132 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23133 (replace-match
23134 "" nil nil nil
23135 (if (= (line-end-position) (match-end 0)) 0 1)))
23136 (forward-line)))
23137 (let ((min-ind (point-max)))
23138 ;; Find minimum indentation across all lines.
23139 (save-excursion
23140 (goto-char begin)
23141 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23142 (setq min-ind 0)
23143 (catch 'zerop
23144 (while (< (point) end)
23145 (unless (org-looking-at-p "[ \t]*$")
23146 (let ((ind (org-get-indentation)))
23147 (setq min-ind (min min-ind ind))
23148 (when (zerop ind) (throw 'zerop t))))
23149 (forward-line)))))
23150 ;; Loop over all lines and add fixed-width markup everywhere
23151 ;; but in fixed-width lines.
23152 (save-excursion
23153 (goto-char begin)
23154 (while (< (point) end)
23155 (cond
23156 ((org-at-heading-p)
23157 (insert ": ")
23158 (forward-line)
23159 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23160 (insert ":")
23161 (forward-line)))
23162 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23163 (let* ((element (org-element-at-point))
23164 (element-end (org-element-property :end element)))
23165 (if (eq (org-element-type element) 'fixed-width)
23166 (progn (goto-char element-end)
23167 (skip-chars-backward " \r\t\n")
23168 (forward-line))
23169 (let ((limit (min end element-end)))
23170 (while (< (point) limit)
23171 (org-move-to-column min-ind t)
23172 (insert ": ")
23173 (forward-line))))))
23175 (org-move-to-column min-ind t)
23176 (insert ": ")
23177 (forward-line)))))))
23178 (set-marker end nil))))
23181 ;;; Comments
23183 ;; Org comments syntax is quite complex. It requires the entire line
23184 ;; to be just a comment. Also, even with the right syntax at the
23185 ;; beginning of line, some some elements (i.e. verse-block or
23186 ;; example-block) don't accept comments. Usual Emacs comment commands
23187 ;; cannot cope with those requirements. Therefore, Org replaces them.
23189 ;; Org still relies on `comment-dwim', but cannot trust
23190 ;; `comment-only-p'. So, `comment-region-function' and
23191 ;; `uncomment-region-function' both point
23192 ;; to`org-comment-or-uncomment-region'. Eventually,
23193 ;; `org-insert-comment' takes care of insertion of comments at the
23194 ;; beginning of line.
23196 ;; `org-setup-comments-handling' install comments related variables
23197 ;; during `org-mode' initialization.
23199 (defun org-setup-comments-handling ()
23200 (interactive)
23201 (org-set-local 'comment-use-syntax nil)
23202 (org-set-local 'comment-start "# ")
23203 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23204 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23205 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23206 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23208 (defun org-insert-comment ()
23209 "Insert an empty comment above current line.
23210 If the line is empty, insert comment at its beginning. When
23211 point is within a source block, comment according to the related
23212 major mode."
23213 (if (let ((element (org-element-at-point)))
23214 (and (eq (org-element-type element) 'src-block)
23215 (< (save-excursion
23216 (goto-char (org-element-property :post-affiliated element))
23217 (line-end-position))
23218 (point))
23219 (> (save-excursion
23220 (goto-char (org-element-property :end element))
23221 (skip-chars-backward " \r\t\n")
23222 (line-beginning-position))
23223 (point))))
23224 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23225 (beginning-of-line)
23226 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23227 (open-line 1))
23228 (org-indent-line)
23229 (insert "# ")))
23231 (defvar comment-empty-lines) ; From newcomment.el.
23232 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23233 "Comment or uncomment each non-blank line in the region.
23234 Uncomment each non-blank line between BEG and END if it only
23235 contains commented lines. Otherwise, comment them. If region is
23236 strictly within a source block, use appropriate comment syntax."
23237 (if (let ((element (org-element-at-point)))
23238 (and (eq (org-element-type element) 'src-block)
23239 (< (save-excursion
23240 (goto-char (org-element-property :post-affiliated element))
23241 (line-end-position))
23242 beg)
23243 (>= (save-excursion
23244 (goto-char (org-element-property :end element))
23245 (skip-chars-backward " \r\t\n")
23246 (line-beginning-position))
23247 end)))
23248 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23249 (save-restriction
23250 ;; Restrict region
23251 (narrow-to-region (save-excursion (goto-char beg)
23252 (skip-chars-forward " \r\t\n" end)
23253 (line-beginning-position))
23254 (save-excursion (goto-char end)
23255 (skip-chars-backward " \r\t\n" beg)
23256 (line-end-position)))
23257 (let ((uncommentp
23258 ;; UNCOMMENTP is non-nil when every non blank line between
23259 ;; BEG and END is a comment.
23260 (save-excursion
23261 (goto-char (point-min))
23262 (while (and (not (eobp))
23263 (let ((element (org-element-at-point)))
23264 (and (eq (org-element-type element) 'comment)
23265 (goto-char (min (point-max)
23266 (org-element-property
23267 :end element)))))))
23268 (eobp))))
23269 (if uncommentp
23270 ;; Only blank lines and comments in region: uncomment it.
23271 (save-excursion
23272 (goto-char (point-min))
23273 (while (not (eobp))
23274 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23275 (replace-match "" nil nil nil 1))
23276 (forward-line)))
23277 ;; Comment each line in region.
23278 (let ((min-indent (point-max)))
23279 ;; First find the minimum indentation across all lines.
23280 (save-excursion
23281 (goto-char (point-min))
23282 (while (and (not (eobp)) (not (zerop min-indent)))
23283 (unless (looking-at "[ \t]*$")
23284 (setq min-indent (min min-indent (current-indentation))))
23285 (forward-line)))
23286 ;; Then loop over all lines.
23287 (save-excursion
23288 (goto-char (point-min))
23289 (while (not (eobp))
23290 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23291 ;; Don't get fooled by invisible text (e.g. link path)
23292 ;; when moving to column MIN-INDENT.
23293 (let ((buffer-invisibility-spec nil))
23294 (org-move-to-column min-indent t))
23295 (insert comment-start))
23296 (forward-line)))))))))
23298 (defun org-comment-dwim (arg)
23299 "Call `comment-dwim' within a source edit buffer if needed."
23300 (interactive "*P")
23301 (if (org-in-src-block-p)
23302 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23303 (call-interactively 'comment-dwim)))
23306 ;;; Planning
23308 ;; This section contains tools to operate on timestamp objects, as
23309 ;; returned by, e.g. `org-element-context'.
23311 (defun org-timestamp-has-time-p (timestamp)
23312 "Non-nil when TIMESTAMP has a time specified."
23313 (org-element-property :hour-start timestamp))
23315 (defun org-timestamp-format (timestamp format &optional end utc)
23316 "Format a TIMESTAMP element into a string.
23318 FORMAT is a format specifier to be passed to
23319 `format-time-string'.
23321 When optional argument END is non-nil, use end of date-range or
23322 time-range, if possible.
23324 When optional argument UTC is non-nil, time will be expressed as
23325 Universal Time."
23326 (format-time-string
23327 format
23328 (apply 'encode-time
23329 (cons 0
23330 (mapcar
23331 (lambda (prop) (or (org-element-property prop timestamp) 0))
23332 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23333 '(:minute-start :hour-start :day-start :month-start
23334 :year-start)))))
23335 utc))
23337 (defun org-timestamp-split-range (timestamp &optional end)
23338 "Extract a timestamp object from a date or time range.
23340 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23341 the end of the range. Otherwise, extract its start.
23343 Return a new timestamp object sharing the same parent as
23344 TIMESTAMP."
23345 (let ((type (org-element-property :type timestamp)))
23346 (if (memq type '(active inactive diary)) timestamp
23347 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23348 ;; Set new type.
23349 (org-element-put-property
23350 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23351 ;; Copy start properties over end properties if END is
23352 ;; non-nil. Otherwise, copy end properties over `start' ones.
23353 (let ((p-alist '((:minute-start . :minute-end)
23354 (:hour-start . :hour-end)
23355 (:day-start . :day-end)
23356 (:month-start . :month-end)
23357 (:year-start . :year-end))))
23358 (dolist (p-cell p-alist)
23359 (org-element-put-property
23360 split-ts
23361 (funcall (if end 'car 'cdr) p-cell)
23362 (org-element-property
23363 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23364 ;; Eventually refresh `:raw-value'.
23365 (org-element-put-property split-ts :raw-value nil)
23366 (org-element-put-property
23367 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23369 (defun org-timestamp-translate (timestamp &optional boundary)
23370 "Apply `org-translate-time' on a TIMESTAMP object.
23371 When optional argument BOUNDARY is non-nil, it is either the
23372 symbol `start' or `end'. In this case, only translate the
23373 starting or ending part of TIMESTAMP if it is a date or time
23374 range. Otherwise, translate both parts."
23375 (if (and (not boundary)
23376 (memq (org-element-property :type timestamp)
23377 '(active-range inactive-range)))
23378 (concat
23379 (org-translate-time
23380 (org-element-property :raw-value
23381 (org-timestamp-split-range timestamp)))
23382 "--"
23383 (org-translate-time
23384 (org-element-property :raw-value
23385 (org-timestamp-split-range timestamp t))))
23386 (org-translate-time
23387 (org-element-property
23388 :raw-value
23389 (if (not boundary) timestamp
23390 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23394 ;;; Other stuff.
23396 (defun org-reftex-citation ()
23397 "Use reftex-citation to insert a citation into the buffer.
23398 This looks for a line like
23400 #+BIBLIOGRAPHY: foo plain option:-d
23402 and derives from it that foo.bib is the bibliography file relevant
23403 for this document. It then installs the necessary environment for RefTeX
23404 to work in this buffer and calls `reftex-citation' to insert a citation
23405 into the buffer.
23407 Export of such citations to both LaTeX and HTML is handled by the contributed
23408 package ox-bibtex by Taru Karttunen."
23409 (interactive)
23410 (let ((reftex-docstruct-symbol 'rds)
23411 (reftex-cite-format "\\cite{%l}")
23412 rds bib)
23413 (save-excursion
23414 (save-restriction
23415 (widen)
23416 (let ((case-fold-search t)
23417 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23418 (if (not (save-excursion
23419 (or (re-search-forward re nil t)
23420 (re-search-backward re nil t))))
23421 (user-error "No bibliography defined in file")
23422 (setq bib (concat (match-string 1) ".bib")
23423 rds (list (list 'bib bib)))))))
23424 (call-interactively 'reftex-citation)))
23426 ;;;; Functions extending outline functionality
23428 (defun org-beginning-of-line (&optional arg)
23429 "Go to the beginning of the current line. If that is invisible, continue
23430 to a visible line beginning. This makes the function of C-a more intuitive.
23431 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23432 first attempt, and only move to after the tags when the cursor is already
23433 beyond the end of the headline."
23434 (interactive "P")
23435 (let ((pos (point))
23436 (special (if (consp org-special-ctrl-a/e)
23437 (car org-special-ctrl-a/e)
23438 org-special-ctrl-a/e))
23439 deactivate-mark refpos)
23440 (if (org-bound-and-true-p visual-line-mode)
23441 (beginning-of-visual-line 1)
23442 (beginning-of-line 1))
23443 (if (and arg (fboundp 'move-beginning-of-line))
23444 (call-interactively 'move-beginning-of-line)
23445 (if (bobp)
23447 (backward-char 1)
23448 (if (org-truely-invisible-p)
23449 (while (and (not (bobp)) (org-truely-invisible-p))
23450 (backward-char 1)
23451 (beginning-of-line 1))
23452 (forward-char 1))))
23453 (when special
23454 (cond
23455 ((and (looking-at org-complex-heading-regexp)
23456 (= (char-after (match-end 1)) ?\ ))
23457 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23458 (point-at-eol)))
23459 (goto-char
23460 (if (eq special t)
23461 (cond ((> pos refpos) refpos)
23462 ((= pos (point)) refpos)
23463 (t (point)))
23464 (cond ((> pos (point)) (point))
23465 ((not (eq last-command this-command)) (point))
23466 (t refpos)))))
23467 ((org-at-item-p)
23468 ;; Being at an item and not looking at an the item means point
23469 ;; was previously moved to beginning of a visual line, which
23470 ;; doesn't contain the item. Therefore, do nothing special,
23471 ;; just stay here.
23472 (when (looking-at org-list-full-item-re)
23473 ;; Set special position at first white space character after
23474 ;; bullet, and check-box, if any.
23475 (let ((after-bullet
23476 (let ((box (match-end 3)))
23477 (if (not box) (match-end 1)
23478 (let ((after (char-after box)))
23479 (if (and after (= after ? )) (1+ box) box))))))
23480 ;; Special case: Move point to special position when
23481 ;; currently after it or at beginning of line.
23482 (if (eq special t)
23483 (when (or (> pos after-bullet) (= (point) pos))
23484 (goto-char after-bullet))
23485 ;; Reversed case: Move point to special position when
23486 ;; point was already at beginning of line and command is
23487 ;; repeated.
23488 (when (and (= (point) pos) (eq last-command this-command))
23489 (goto-char after-bullet))))))))
23490 (org-no-warnings
23491 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23492 (setq disable-point-adjustment
23493 (or (not (invisible-p (point)))
23494 (not (invisible-p (max (point-min) (1- (point))))))))
23496 (defun org-end-of-line (&optional arg)
23497 "Go to the end of the line.
23498 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23499 tags on the first attempt, and only move to after the tags when
23500 the cursor is already beyond the end of the headline."
23501 (interactive "P")
23502 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23503 org-special-ctrl-a/e))
23504 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23505 'end-of-visual-line)
23506 ((fboundp 'move-end-of-line) 'move-end-of-line)
23507 (t 'end-of-line)))
23508 deactivate-mark)
23509 (if (or (not special) arg) (call-interactively move-fun)
23510 (let* ((element (save-excursion (beginning-of-line)
23511 (org-element-at-point)))
23512 (type (org-element-type element)))
23513 (cond
23514 ((memq type '(headline inlinetask))
23515 (let ((pos (point)))
23516 (beginning-of-line 1)
23517 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23518 (if (eq special t)
23519 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23520 (goto-char (match-beginning 1))
23521 (goto-char (match-end 0)))
23522 (if (or (< pos (match-end 0))
23523 (not (eq this-command last-command)))
23524 (goto-char (match-end 0))
23525 (goto-char (match-beginning 1))))
23526 (call-interactively move-fun))))
23527 ((outline-invisible-p (line-end-position))
23528 ;; If element is hidden, `move-end-of-line' would put point
23529 ;; after it. Use `end-of-line' to stay on current line.
23530 (call-interactively 'end-of-line))
23531 (t (call-interactively move-fun)))))
23532 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23533 (setq disable-point-adjustment
23534 (or (not (invisible-p (point)))
23535 (not (invisible-p (max (point-min) (1- (point))))))))
23537 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23538 (define-key org-mode-map "\C-e" 'org-end-of-line)
23540 (defun org-backward-sentence (&optional arg)
23541 "Go to beginning of sentence, or beginning of table field.
23542 This will call `backward-sentence' or `org-table-beginning-of-field',
23543 depending on context."
23544 (interactive "P")
23545 (cond
23546 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23547 (t (call-interactively 'backward-sentence))))
23549 (defun org-forward-sentence (&optional arg)
23550 "Go to end of sentence, or end of table field.
23551 This will call `forward-sentence' or `org-table-end-of-field',
23552 depending on context."
23553 (interactive "P")
23554 (cond
23555 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23556 (t (call-interactively 'forward-sentence))))
23558 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23559 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23561 (defun org-kill-line (&optional arg)
23562 "Kill line, to tags or end of line."
23563 (interactive "P")
23564 (cond
23565 ((or (not org-special-ctrl-k)
23566 (bolp)
23567 (not (org-at-heading-p)))
23568 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23569 org-ctrl-k-protect-subtree)
23570 (if (or (eq org-ctrl-k-protect-subtree 'error)
23571 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23572 (user-error "C-k aborted as it would kill a hidden subtree")))
23573 (call-interactively
23574 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23575 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23576 (kill-region (point) (match-beginning 1))
23577 (org-set-tags nil t))
23578 (t (kill-region (point) (point-at-eol)))))
23580 (define-key org-mode-map "\C-k" 'org-kill-line)
23582 (defun org-yank (&optional arg)
23583 "Yank. If the kill is a subtree, treat it specially.
23584 This command will look at the current kill and check if is a single
23585 subtree, or a series of subtrees[1]. If it passes the test, and if the
23586 cursor is at the beginning of a line or after the stars of a currently
23587 empty headline, then the yank is handled specially. How exactly depends
23588 on the value of the following variables, both set by default.
23590 `org-yank-folded-subtrees'
23591 When set, the subtree(s) will be folded after insertion, but only
23592 if doing so would now swallow text after the yanked text.
23594 `org-yank-adjusted-subtrees'
23595 When set, the subtree will be promoted or demoted in order to
23596 fit into the local outline tree structure, which means that the
23597 level will be adjusted so that it becomes the smaller one of the
23598 two *visible* surrounding headings.
23600 Any prefix to this command will cause `yank' to be called directly with
23601 no special treatment. In particular, a simple \\[universal-argument] prefix \
23602 will just
23603 plainly yank the text as it is.
23605 \[1] The test checks if the first non-white line is a heading
23606 and if there are no other headings with fewer stars."
23607 (interactive "P")
23608 (org-yank-generic 'yank arg))
23610 (defun org-yank-generic (command arg)
23611 "Perform some yank-like command.
23613 This function implements the behavior described in the `org-yank'
23614 documentation. However, it has been generalized to work for any
23615 interactive command with similar behavior."
23617 ;; pretend to be command COMMAND
23618 (setq this-command command)
23620 (if arg
23621 (call-interactively command)
23623 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23624 (and (org-kill-is-subtree-p)
23625 (or (bolp)
23626 (and (looking-at "[ \t]*$")
23627 (string-match
23628 "\\`\\*+\\'"
23629 (buffer-substring (point-at-bol) (point)))))))
23630 swallowp)
23631 (cond
23632 ((and subtreep org-yank-folded-subtrees)
23633 (let ((beg (point))
23634 end)
23635 (if (and subtreep org-yank-adjusted-subtrees)
23636 (org-paste-subtree nil nil 'for-yank)
23637 (call-interactively command))
23639 (setq end (point))
23640 (goto-char beg)
23641 (when (and (bolp) subtreep
23642 (not (setq swallowp
23643 (org-yank-folding-would-swallow-text beg end))))
23644 (org-with-limited-levels
23645 (or (looking-at org-outline-regexp)
23646 (re-search-forward org-outline-regexp-bol end t))
23647 (while (and (< (point) end) (looking-at org-outline-regexp))
23648 (hide-subtree)
23649 (org-cycle-show-empty-lines 'folded)
23650 (condition-case nil
23651 (outline-forward-same-level 1)
23652 (error (goto-char end))))))
23653 (when swallowp
23654 (message
23655 "Inserted text not folded because that would swallow text"))
23657 (goto-char end)
23658 (skip-chars-forward " \t\n\r")
23659 (beginning-of-line 1)
23660 (push-mark beg 'nomsg)))
23661 ((and subtreep org-yank-adjusted-subtrees)
23662 (let ((beg (point-at-bol)))
23663 (org-paste-subtree nil nil 'for-yank)
23664 (push-mark beg 'nomsg)))
23666 (call-interactively command))))))
23668 (defun org-yank-folding-would-swallow-text (beg end)
23669 "Would hide-subtree at BEG swallow any text after END?"
23670 (let (level)
23671 (org-with-limited-levels
23672 (save-excursion
23673 (goto-char beg)
23674 (when (or (looking-at org-outline-regexp)
23675 (re-search-forward org-outline-regexp-bol end t))
23676 (setq level (org-outline-level)))
23677 (goto-char end)
23678 (skip-chars-forward " \t\r\n\v\f")
23679 (if (or (eobp)
23680 (and (bolp) (looking-at org-outline-regexp)
23681 (<= (org-outline-level) level)))
23682 nil ; Nothing would be swallowed
23683 t))))) ; something would swallow
23685 (define-key org-mode-map "\C-y" 'org-yank)
23687 (defun org-truely-invisible-p ()
23688 "Check if point is at a character currently not visible.
23689 This version does not only check the character property, but also
23690 `visible-mode'."
23691 ;; Early versions of noutline don't have `outline-invisible-p'.
23692 (if (org-bound-and-true-p visible-mode)
23694 (outline-invisible-p)))
23696 (defun org-invisible-p2 ()
23697 "Check if point is at a character currently not visible."
23698 (save-excursion
23699 (if (and (eolp) (not (bobp))) (backward-char 1))
23700 ;; Early versions of noutline don't have `outline-invisible-p'.
23701 (outline-invisible-p)))
23703 (defun org-back-to-heading (&optional invisible-ok)
23704 "Call `outline-back-to-heading', but provide a better error message."
23705 (condition-case nil
23706 (outline-back-to-heading invisible-ok)
23707 (error (error "Before first headline at position %d in buffer %s"
23708 (point) (current-buffer)))))
23710 (defun org-before-first-heading-p ()
23711 "Before first heading?"
23712 (save-excursion
23713 (end-of-line)
23714 (null (re-search-backward org-outline-regexp-bol nil t))))
23716 (defun org-at-heading-p (&optional ignored)
23717 (outline-on-heading-p t))
23718 ;; Compatibility alias with Org versions < 7.8.03
23719 (defalias 'org-on-heading-p 'org-at-heading-p)
23721 (defun org-in-commented-heading-p (&optional no-inheritance)
23722 "Non-nil if point is under a commented heading.
23723 This function also checks ancestors of the current headline,
23724 unless optional argument NO-INHERITANCE is non-nil."
23725 (cond
23726 ((org-before-first-heading-p) nil)
23727 ((let ((headline (nth 4 (org-heading-components))))
23728 (and headline
23729 (let ((case-fold-search nil))
23730 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23731 headline)))))
23732 (no-inheritance nil)
23734 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23736 (defun org-at-comment-p nil
23737 "Is cursor in a commented line?"
23738 (save-excursion
23739 (save-match-data
23740 (beginning-of-line)
23741 (looking-at "^[ \t]*# "))))
23743 (defun org-at-drawer-p nil
23744 "Is cursor at a drawer keyword?"
23745 (save-excursion
23746 (move-beginning-of-line 1)
23747 (looking-at org-drawer-regexp)))
23749 (defun org-at-block-p nil
23750 "Is cursor at a block keyword?"
23751 (save-excursion
23752 (move-beginning-of-line 1)
23753 (looking-at org-block-regexp)))
23755 (defun org-point-at-end-of-empty-headline ()
23756 "If point is at the end of an empty headline, return t, else nil.
23757 If the heading only contains a TODO keyword, it is still still considered
23758 empty."
23759 (and (looking-at "[ \t]*$")
23760 (when org-todo-line-regexp
23761 (save-excursion
23762 (beginning-of-line 1)
23763 (let ((case-fold-search nil))
23764 (looking-at org-todo-line-regexp)
23765 (string= (match-string 3) ""))))))
23767 (defun org-at-heading-or-item-p ()
23768 (or (org-at-heading-p) (org-at-item-p)))
23770 (defun org-at-target-p ()
23771 (or (org-in-regexp org-radio-target-regexp)
23772 (org-in-regexp org-target-regexp)))
23773 ;; Compatibility alias with Org versions < 7.8.03
23774 (defalias 'org-on-target-p 'org-at-target-p)
23776 (defun org-up-heading-all (arg)
23777 "Move to the heading line of which the present line is a subheading.
23778 This function considers both visible and invisible heading lines.
23779 With argument, move up ARG levels."
23780 (if (fboundp 'outline-up-heading-all)
23781 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23782 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23784 (defun org-up-heading-safe ()
23785 "Move to the heading line of which the present line is a subheading.
23786 This version will not throw an error. It will return the level of the
23787 headline found, or nil if no higher level is found.
23789 Also, this function will be a lot faster than `outline-up-heading',
23790 because it relies on stars being the outline starters. This can really
23791 make a significant difference in outlines with very many siblings."
23792 (when (ignore-errors (org-back-to-heading t))
23793 (let ((level-up (1- (funcall outline-level))))
23794 (and (> level-up 0)
23795 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23796 (funcall outline-level)))))
23798 (defun org-first-sibling-p ()
23799 "Is this heading the first child of its parents?"
23800 (interactive)
23801 (let ((re org-outline-regexp-bol)
23802 level l)
23803 (unless (org-at-heading-p t)
23804 (user-error "Not at a heading"))
23805 (setq level (funcall outline-level))
23806 (save-excursion
23807 (if (not (re-search-backward re nil t))
23809 (setq l (funcall outline-level))
23810 (< l level)))))
23812 (defun org-goto-sibling (&optional previous)
23813 "Goto the next sibling, even if it is invisible.
23814 When PREVIOUS is set, go to the previous sibling instead. Returns t
23815 when a sibling was found. When none is found, return nil and don't
23816 move point."
23817 (let ((fun (if previous 're-search-backward 're-search-forward))
23818 (pos (point))
23819 (re org-outline-regexp-bol)
23820 level l)
23821 (when (ignore-errors (org-back-to-heading t))
23822 (setq level (funcall outline-level))
23823 (catch 'exit
23824 (or previous (forward-char 1))
23825 (while (funcall fun re nil t)
23826 (setq l (funcall outline-level))
23827 (when (< l level) (goto-char pos) (throw 'exit nil))
23828 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23829 (goto-char pos)
23830 nil))))
23832 (defun org-show-siblings ()
23833 "Show all siblings of the current headline."
23834 (save-excursion
23835 (while (org-goto-sibling) (org-flag-heading nil)))
23836 (save-excursion
23837 (while (org-goto-sibling 'previous)
23838 (org-flag-heading nil))))
23840 (defun org-goto-first-child ()
23841 "Goto the first child, even if it is invisible.
23842 Return t when a child was found. Otherwise don't move point and
23843 return nil."
23844 (let (level (pos (point)) (re org-outline-regexp-bol))
23845 (when (ignore-errors (org-back-to-heading t))
23846 (setq level (outline-level))
23847 (forward-char 1)
23848 (if (and (re-search-forward re nil t) (> (outline-level) level))
23849 (progn (goto-char (match-beginning 0)) t)
23850 (goto-char pos) nil))))
23852 (defun org-show-hidden-entry ()
23853 "Show an entry where even the heading is hidden."
23854 (save-excursion
23855 (org-show-entry)))
23857 (defun org-flag-heading (flag &optional entry)
23858 "Flag the current heading. FLAG non-nil means make invisible.
23859 When ENTRY is non-nil, show the entire entry."
23860 (save-excursion
23861 (org-back-to-heading t)
23862 ;; Check if we should show the entire entry
23863 (if entry
23864 (progn
23865 (org-show-entry)
23866 (save-excursion
23867 (and (outline-next-heading)
23868 (org-flag-heading nil))))
23869 (outline-flag-region (max (point-min) (1- (point)))
23870 (save-excursion (outline-end-of-heading) (point))
23871 flag))))
23873 (defun org-get-next-sibling ()
23874 "Move to next heading of the same level, and return point.
23875 If there is no such heading, return nil.
23876 This is like outline-next-sibling, but invisible headings are ok."
23877 (let ((level (funcall outline-level)))
23878 (outline-next-heading)
23879 (while (and (not (eobp)) (> (funcall outline-level) level))
23880 (outline-next-heading))
23881 (if (or (eobp) (< (funcall outline-level) level))
23883 (point))))
23885 (defun org-get-last-sibling ()
23886 "Move to previous heading of the same level, and return point.
23887 If there is no such heading, return nil."
23888 (let ((opoint (point))
23889 (level (funcall outline-level)))
23890 (outline-previous-heading)
23891 (when (and (/= (point) opoint) (outline-on-heading-p t))
23892 (while (and (> (funcall outline-level) level)
23893 (not (bobp)))
23894 (outline-previous-heading))
23895 (if (< (funcall outline-level) level)
23897 (point)))))
23899 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23900 "Goto to the end of a subtree."
23901 ;; This contains an exact copy of the original function, but it uses
23902 ;; `org-back-to-heading', to make it work also in invisible
23903 ;; trees. And is uses an invisible-ok argument.
23904 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23905 ;; Furthermore, when used inside Org, finding the end of a large subtree
23906 ;; with many children and grandchildren etc, this can be much faster
23907 ;; than the outline version.
23908 (org-back-to-heading invisible-ok)
23909 (let ((first t)
23910 (level (funcall outline-level)))
23911 (if (and (derived-mode-p 'org-mode) (< level 1000))
23912 ;; A true heading (not a plain list item), in Org-mode
23913 ;; This means we can easily find the end by looking
23914 ;; only for the right number of stars. Using a regexp to do
23915 ;; this is so much faster than using a Lisp loop.
23916 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23917 (forward-char 1)
23918 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23919 ;; something else, do it the slow way
23920 (while (and (not (eobp))
23921 (or first (> (funcall outline-level) level)))
23922 (setq first nil)
23923 (outline-next-heading)))
23924 (unless to-heading
23925 (if (memq (preceding-char) '(?\n ?\^M))
23926 (progn
23927 ;; Go to end of line before heading
23928 (forward-char -1)
23929 (if (memq (preceding-char) '(?\n ?\^M))
23930 ;; leave blank line before heading
23931 (forward-char -1))))))
23932 (point))
23934 (defun org-end-of-meta-data-and-drawers ()
23935 "Jump to the first text after meta data and drawers in the current entry.
23936 This will move over empty lines, lines with planning time stamps,
23937 clocking lines, and drawers."
23938 (org-back-to-heading t)
23939 (let ((end (save-excursion (outline-next-heading) (point)))
23940 (re (concat "\\(" org-drawer-regexp "\\)"
23941 "\\|" "[ \t]*" org-keyword-time-regexp)))
23942 (forward-line 1)
23943 (while (re-search-forward re end t)
23944 (if (not (match-end 1))
23945 ;; empty or planning line
23946 (forward-line 1)
23947 ;; a drawer, find the end
23948 (re-search-forward "^[ \t]*:END:" end 'move)
23949 (forward-line 1)))
23950 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23951 (point)))
23953 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23954 "Move forward to the ARG'th subheading at same level as this one.
23955 Stop at the first and last subheadings of a superior heading.
23956 Normally this only looks at visible headings, but when INVISIBLE-OK is
23957 non-nil it will also look at invisible ones."
23958 (interactive "p")
23959 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23960 (if (and arg (< arg 0))
23961 (goto-char (point-min))
23962 (outline-next-heading))
23963 (org-at-heading-p)
23964 (let ((level (- (match-end 0) (match-beginning 0) 1))
23965 (f (if (and arg (< arg 0))
23966 're-search-backward
23967 're-search-forward))
23968 (count (if arg (abs arg) 1))
23969 (result (point)))
23970 (while (and (prog1 (> count 0)
23971 (forward-char (if (and arg (< arg 0)) -1 1)))
23972 (funcall f org-outline-regexp-bol nil 'move))
23973 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23974 (cond ((< l level) (setq count 0))
23975 ((and (= l level)
23976 (or invisible-ok
23977 (progn
23978 (goto-char (line-beginning-position))
23979 (not (outline-invisible-p)))))
23980 (setq count (1- count))
23981 (when (eq l level)
23982 (setq result (point)))))))
23983 (goto-char result))
23984 (beginning-of-line 1)))
23986 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23987 "Move backward to the ARG'th subheading at same level as this one.
23988 Stop at the first and last subheadings of a superior heading."
23989 (interactive "p")
23990 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23992 (defun org-next-block (arg &optional backward block-regexp)
23993 "Jump to the next block.
23994 With a prefix argument ARG, jump forward ARG many source blocks.
23995 When BACKWARD is non-nil, jump to the previous block.
23996 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23997 (interactive "p")
23998 (let ((re (or block-regexp org-block-regexp))
23999 (re-search-fn (or (and backward 're-search-backward)
24000 're-search-forward)))
24001 (if (looking-at re) (forward-char 1))
24002 (condition-case nil
24003 (funcall re-search-fn re nil nil arg)
24004 (error (user-error "No %s code blocks"
24005 (if backward "previous" "further" ))))
24006 (goto-char (match-beginning 0)) (org-show-context)))
24008 (defun org-previous-block (arg &optional block-regexp)
24009 "Jump to the previous block.
24010 With a prefix argument ARG, jump backward ARG many source blocks.
24011 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24012 (interactive "p")
24013 (org-next-block arg t block-regexp))
24015 (defun org-forward-paragraph ()
24016 "Move forward to beginning of next paragraph or equivalent.
24018 The function moves point to the beginning of the next visible
24019 structural element, which can be a paragraph, a table, a list
24020 item, etc. It also provides some special moves for convenience:
24022 - On an affiliated keyword, jump to the beginning of the
24023 relative element.
24024 - On an item or a footnote definition, move to the second
24025 element inside, if any.
24026 - On a table or a property drawer, jump after it.
24027 - On a verse or source block, stop after blank lines."
24028 (interactive)
24029 (when (eobp) (user-error "Cannot move further down"))
24030 (let* ((deactivate-mark nil)
24031 (element (org-element-at-point))
24032 (type (org-element-type element))
24033 (post-affiliated (org-element-property :post-affiliated element))
24034 (contents-begin (org-element-property :contents-begin element))
24035 (contents-end (org-element-property :contents-end element))
24036 (end (let ((end (org-element-property :end element)) (parent element))
24037 (while (and (setq parent (org-element-property :parent parent))
24038 (= (org-element-property :contents-end parent) end))
24039 (setq end (org-element-property :end parent)))
24040 end)))
24041 (cond ((not element)
24042 (skip-chars-forward " \r\t\n")
24043 (or (eobp) (beginning-of-line)))
24044 ;; On affiliated keywords, move to element's beginning.
24045 ((< (point) post-affiliated)
24046 (goto-char post-affiliated))
24047 ;; At a table row, move to the end of the table. Similarly,
24048 ;; at a node property, move to the end of the property
24049 ;; drawer.
24050 ((memq type '(node-property table-row))
24051 (goto-char (org-element-property
24052 :end (org-element-property :parent element))))
24053 ((memq type '(property-drawer table)) (goto-char end))
24054 ;; Consider blank lines as separators in verse and source
24055 ;; blocks to ease editing.
24056 ((memq type '(src-block verse-block))
24057 (when (eq type 'src-block)
24058 (setq contents-end
24059 (save-excursion (goto-char end)
24060 (skip-chars-backward " \r\t\n")
24061 (line-beginning-position))))
24062 (beginning-of-line)
24063 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24064 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24065 (goto-char end)
24066 (skip-chars-forward " \r\t\n")
24067 (if (= (point) contents-end) (goto-char end)
24068 (beginning-of-line))))
24069 ;; With no contents, just skip element.
24070 ((not contents-begin) (goto-char end))
24071 ;; If contents are invisible, skip the element altogether.
24072 ((outline-invisible-p (line-end-position))
24073 (case type
24074 (headline
24075 (org-with-limited-levels (outline-next-visible-heading 1)))
24076 ;; At a plain list, make sure we move to the next item
24077 ;; instead of skipping the whole list.
24078 (plain-list (forward-char)
24079 (org-forward-paragraph))
24080 (otherwise (goto-char end))))
24081 ((>= (point) contents-end) (goto-char end))
24082 ((>= (point) contents-begin)
24083 ;; This can only happen on paragraphs and plain lists.
24084 (case type
24085 (paragraph (goto-char end))
24086 ;; At a plain list, try to move to second element in
24087 ;; first item, if possible.
24088 (plain-list (end-of-line)
24089 (org-forward-paragraph))))
24090 ;; When contents start on the middle of a line (e.g. in
24091 ;; items and footnote definitions), try to reach first
24092 ;; element starting after current line.
24093 ((> (line-end-position) contents-begin)
24094 (end-of-line)
24095 (org-forward-paragraph))
24096 (t (goto-char contents-begin)))))
24098 (defun org-backward-paragraph ()
24099 "Move backward to start of previous paragraph or equivalent.
24101 The function moves point to the beginning of the current
24102 structural element, which can be a paragraph, a table, a list
24103 item, etc., or to the beginning of the previous visible one if
24104 point is already there. It also provides some special moves for
24105 convenience:
24107 - On an affiliated keyword, jump to the first one.
24108 - On a table or a property drawer, move to its beginning.
24109 - On a verse or source block, stop before blank lines."
24110 (interactive)
24111 (when (bobp) (user-error "Cannot move further up"))
24112 (let* ((deactivate-mark nil)
24113 (element (org-element-at-point))
24114 (type (org-element-type element))
24115 (contents-begin (org-element-property :contents-begin element))
24116 (contents-end (org-element-property :contents-end element))
24117 (post-affiliated (org-element-property :post-affiliated element))
24118 (begin (org-element-property :begin element)))
24119 (cond
24120 ((not element) (goto-char (point-min)))
24121 ((= (point) begin)
24122 (backward-char)
24123 (org-backward-paragraph))
24124 ((<= (point) post-affiliated) (goto-char begin))
24125 ((memq type '(node-property table-row))
24126 (goto-char (org-element-property
24127 :post-affiliated (org-element-property :parent element))))
24128 ((memq type '(property-drawer table)) (goto-char begin))
24129 ((memq type '(src-block verse-block))
24130 (when (eq type 'src-block)
24131 (setq contents-begin
24132 (save-excursion (goto-char begin) (forward-line) (point))))
24133 (if (= (point) contents-begin) (goto-char post-affiliated)
24134 ;; Inside a verse block, see blank lines as paragraph
24135 ;; separators.
24136 (let ((origin (point)))
24137 (skip-chars-backward " \r\t\n" contents-begin)
24138 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24139 (skip-chars-forward " \r\t\n" origin)
24140 (if (= (point) origin) (goto-char contents-begin)
24141 (beginning-of-line))))))
24142 ((not contents-begin) (goto-char (or post-affiliated begin)))
24143 ((eq type 'paragraph)
24144 (goto-char contents-begin)
24145 ;; When at first paragraph in an item or a footnote definition,
24146 ;; move directly to beginning of line.
24147 (let ((parent-contents
24148 (org-element-property
24149 :contents-begin (org-element-property :parent element))))
24150 (when (and parent-contents (= parent-contents contents-begin))
24151 (beginning-of-line))))
24152 ;; At the end of a greater element, move to the beginning of the
24153 ;; last element within.
24154 ((>= (point) contents-end)
24155 (goto-char (1- contents-end))
24156 (org-backward-paragraph))
24157 (t (goto-char (or post-affiliated begin))))
24158 ;; Ensure we never leave point invisible.
24159 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24161 (defun org-forward-element ()
24162 "Move forward by one element.
24163 Move to the next element at the same level, when possible."
24164 (interactive)
24165 (cond ((eobp) (user-error "Cannot move further down"))
24166 ((org-with-limited-levels (org-at-heading-p))
24167 (let ((origin (point)))
24168 (goto-char (org-end-of-subtree nil t))
24169 (unless (org-with-limited-levels (org-at-heading-p))
24170 (goto-char origin)
24171 (user-error "Cannot move further down"))))
24173 (let* ((elem (org-element-at-point))
24174 (end (org-element-property :end elem))
24175 (parent (org-element-property :parent elem)))
24176 (cond ((and parent (= (org-element-property :contents-end parent) end))
24177 (goto-char (org-element-property :end parent)))
24178 ((integer-or-marker-p end) (goto-char end))
24179 (t (message "No element at point")))))))
24181 (defun org-backward-element ()
24182 "Move backward by one element.
24183 Move to the previous element at the same level, when possible."
24184 (interactive)
24185 (cond ((bobp) (user-error "Cannot move further up"))
24186 ((org-with-limited-levels (org-at-heading-p))
24187 ;; At a headline, move to the previous one, if any, or stay
24188 ;; here.
24189 (let ((origin (point)))
24190 (org-with-limited-levels (org-backward-heading-same-level 1))
24191 ;; When current headline has no sibling above, move to its
24192 ;; parent.
24193 (when (= (point) origin)
24194 (or (org-with-limited-levels (org-up-heading-safe))
24195 (progn (goto-char origin)
24196 (user-error "Cannot move further up"))))))
24198 (let* ((elem (org-element-at-point))
24199 (beg (org-element-property :begin elem)))
24200 (cond
24201 ;; Move to beginning of current element if point isn't
24202 ;; there already.
24203 ((null beg) (message "No element at point"))
24204 ((/= (point) beg) (goto-char beg))
24205 (t (goto-char beg)
24206 (skip-chars-backward " \r\t\n")
24207 (unless (bobp)
24208 (let ((prev (org-element-at-point)))
24209 (goto-char (org-element-property :begin prev))
24210 (while (and (setq prev (org-element-property :parent prev))
24211 (<= (org-element-property :end prev) beg))
24212 (goto-char (org-element-property :begin prev)))))))))))
24214 (defun org-up-element ()
24215 "Move to upper element."
24216 (interactive)
24217 (if (org-with-limited-levels (org-at-heading-p))
24218 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24219 (let* ((elem (org-element-at-point))
24220 (parent (org-element-property :parent elem)))
24221 (if parent (goto-char (org-element-property :begin parent))
24222 (if (org-with-limited-levels (org-before-first-heading-p))
24223 (user-error "No surrounding element")
24224 (org-with-limited-levels (org-back-to-heading)))))))
24226 (defvar org-element-greater-elements)
24227 (defun org-down-element ()
24228 "Move to inner element."
24229 (interactive)
24230 (let ((element (org-element-at-point)))
24231 (cond
24232 ((memq (org-element-type element) '(plain-list table))
24233 (goto-char (org-element-property :contents-begin element))
24234 (forward-char))
24235 ((memq (org-element-type element) org-element-greater-elements)
24236 ;; If contents are hidden, first disclose them.
24237 (when (outline-invisible-p (line-end-position)) (org-cycle))
24238 (goto-char (or (org-element-property :contents-begin element)
24239 (user-error "No content for this element"))))
24240 (t (user-error "No inner element")))))
24242 (defun org-drag-element-backward ()
24243 "Move backward element at point."
24244 (interactive)
24245 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24246 (let* ((elem (org-element-at-point))
24247 (prev-elem
24248 (save-excursion
24249 (goto-char (org-element-property :begin elem))
24250 (skip-chars-backward " \r\t\n")
24251 (unless (bobp)
24252 (let* ((beg (org-element-property :begin elem))
24253 (prev (org-element-at-point))
24254 (up prev))
24255 (while (and (setq up (org-element-property :parent up))
24256 (<= (org-element-property :end up) beg))
24257 (setq prev up))
24258 prev)))))
24259 ;; Error out if no previous element or previous element is
24260 ;; a parent of the current one.
24261 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24262 (user-error "Cannot drag element backward")
24263 (let ((pos (point)))
24264 (org-element-swap-A-B prev-elem elem)
24265 (goto-char (+ (org-element-property :begin prev-elem)
24266 (- pos (org-element-property :begin elem)))))))))
24268 (defun org-drag-element-forward ()
24269 "Move forward element at point."
24270 (interactive)
24271 (let* ((pos (point))
24272 (elem (org-element-at-point)))
24273 (when (= (point-max) (org-element-property :end elem))
24274 (user-error "Cannot drag element forward"))
24275 (goto-char (org-element-property :end elem))
24276 (let ((next-elem (org-element-at-point)))
24277 (when (or (org-element-nested-p elem next-elem)
24278 (and (eq (org-element-type next-elem) 'headline)
24279 (not (eq (org-element-type elem) 'headline))))
24280 (goto-char pos)
24281 (user-error "Cannot drag element forward"))
24282 ;; Compute new position of point: it's shifted by NEXT-ELEM
24283 ;; body's length (without final blanks) and by the length of
24284 ;; blanks between ELEM and NEXT-ELEM.
24285 (let ((size-next (- (save-excursion
24286 (goto-char (org-element-property :end next-elem))
24287 (skip-chars-backward " \r\t\n")
24288 (forward-line)
24289 ;; Small correction if buffer doesn't end
24290 ;; with a newline character.
24291 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24292 (org-element-property :begin next-elem)))
24293 (size-blank (- (org-element-property :end elem)
24294 (save-excursion
24295 (goto-char (org-element-property :end elem))
24296 (skip-chars-backward " \r\t\n")
24297 (forward-line)
24298 (point)))))
24299 (org-element-swap-A-B elem next-elem)
24300 (goto-char (+ pos size-next size-blank))))))
24302 (defun org-drag-line-forward (arg)
24303 "Drag the line at point ARG lines forward."
24304 (interactive "p")
24305 (dotimes (n (abs arg))
24306 (let ((c (current-column)))
24307 (if (< 0 arg)
24308 (progn
24309 (beginning-of-line 2)
24310 (transpose-lines 1)
24311 (beginning-of-line 0))
24312 (transpose-lines 1)
24313 (beginning-of-line -1))
24314 (org-move-to-column c))))
24316 (defun org-drag-line-backward (arg)
24317 "Drag the line at point ARG lines backward."
24318 (interactive "p")
24319 (org-drag-line-forward (- arg)))
24321 (defun org-mark-element ()
24322 "Put point at beginning of this element, mark at end.
24324 Interactively, if this command is repeated or (in Transient Mark
24325 mode) if the mark is active, it marks the next element after the
24326 ones already marked."
24327 (interactive)
24328 (let (deactivate-mark)
24329 (if (and (org-called-interactively-p 'any)
24330 (or (and (eq last-command this-command) (mark t))
24331 (and transient-mark-mode mark-active)))
24332 (set-mark
24333 (save-excursion
24334 (goto-char (mark))
24335 (goto-char (org-element-property :end (org-element-at-point)))))
24336 (let ((element (org-element-at-point)))
24337 (end-of-line)
24338 (push-mark (org-element-property :end element) t t)
24339 (goto-char (org-element-property :begin element))))))
24341 (defun org-narrow-to-element ()
24342 "Narrow buffer to current element."
24343 (interactive)
24344 (let ((elem (org-element-at-point)))
24345 (cond
24346 ((eq (car elem) 'headline)
24347 (narrow-to-region
24348 (org-element-property :begin elem)
24349 (org-element-property :end elem)))
24350 ((memq (car elem) org-element-greater-elements)
24351 (narrow-to-region
24352 (org-element-property :contents-begin elem)
24353 (org-element-property :contents-end elem)))
24355 (narrow-to-region
24356 (org-element-property :begin elem)
24357 (org-element-property :end elem))))))
24359 (defun org-transpose-element ()
24360 "Transpose current and previous elements, keeping blank lines between.
24361 Point is moved after both elements."
24362 (interactive)
24363 (org-skip-whitespace)
24364 (let ((end (org-element-property :end (org-element-at-point))))
24365 (org-drag-element-backward)
24366 (goto-char end)))
24368 (defun org-unindent-buffer ()
24369 "Un-indent the visible part of the buffer.
24370 Relative indentation (between items, inside blocks, etc.) isn't
24371 modified."
24372 (interactive)
24373 (unless (eq major-mode 'org-mode)
24374 (user-error "Cannot un-indent a buffer not in Org mode"))
24375 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24376 unindent-tree ; For byte-compiler.
24377 (unindent-tree
24378 (function
24379 (lambda (contents)
24380 (mapc
24381 (lambda (element)
24382 (if (memq (org-element-type element) '(headline section))
24383 (funcall unindent-tree (org-element-contents element))
24384 (save-excursion
24385 (save-restriction
24386 (narrow-to-region
24387 (org-element-property :begin element)
24388 (org-element-property :end element))
24389 (org-do-remove-indentation)))))
24390 (reverse contents))))))
24391 (funcall unindent-tree (org-element-contents parse-tree))))
24393 (defun org-show-subtree ()
24394 "Show everything after this heading at deeper levels."
24395 (interactive)
24396 (outline-flag-region
24397 (point)
24398 (save-excursion
24399 (org-end-of-subtree t t))
24400 nil))
24402 (defun org-show-entry ()
24403 "Show the body directly following this heading.
24404 Show the heading too, if it is currently invisible."
24405 (interactive)
24406 (save-excursion
24407 (ignore-errors
24408 (org-back-to-heading t)
24409 (outline-flag-region
24410 (max (point-min) (1- (point)))
24411 (save-excursion
24412 (if (re-search-forward
24413 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24414 (match-beginning 1)
24415 (point-max)))
24416 nil)
24417 (org-cycle-hide-drawers 'children))))
24419 (defun org-make-options-regexp (kwds &optional extra)
24420 "Make a regular expression for keyword lines.
24421 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24422 when non-nil, is a regexp matching keywords names."
24423 (concat "^[ \t]*#\\+\\("
24424 (regexp-opt kwds)
24425 (and extra (concat (and kwds "\\|") extra))
24426 "\\):[ \t]*\\(.*\\)"))
24428 ;; Make isearch reveal the necessary context
24429 (defun org-isearch-end ()
24430 "Reveal context after isearch exits."
24431 (when isearch-success ; only if search was successful
24432 (if (featurep 'xemacs)
24433 ;; Under XEmacs, the hook is run in the correct place,
24434 ;; we directly show the context.
24435 (org-show-context 'isearch)
24436 ;; In Emacs the hook runs *before* restoring the overlays.
24437 ;; So we have to use a one-time post-command-hook to do this.
24438 ;; (Emacs 22 has a special variable, see function `org-mode')
24439 (unless (and (boundp 'isearch-mode-end-hook-quit)
24440 isearch-mode-end-hook-quit)
24441 ;; Only when the isearch was not quitted.
24442 (org-add-hook 'post-command-hook 'org-isearch-post-command
24443 'append 'local)))))
24445 (defun org-isearch-post-command ()
24446 "Remove self from hook, and show context."
24447 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24448 (org-show-context 'isearch))
24451 ;;;; Integration with and fixes for other packages
24453 ;;; Imenu support
24455 (defvar org-imenu-markers nil
24456 "All markers currently used by Imenu.")
24457 (make-variable-buffer-local 'org-imenu-markers)
24459 (defun org-imenu-new-marker (&optional pos)
24460 "Return a new marker for use by Imenu, and remember the marker."
24461 (let ((m (make-marker)))
24462 (move-marker m (or pos (point)))
24463 (push m org-imenu-markers)
24466 (defun org-imenu-get-tree ()
24467 "Produce the index for Imenu."
24468 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24469 (setq org-imenu-markers nil)
24470 (let* ((n org-imenu-depth)
24471 (re (concat "^" (org-get-limited-outline-regexp)))
24472 (subs (make-vector (1+ n) nil))
24473 (last-level 0)
24474 m level head0 head)
24475 (save-excursion
24476 (save-restriction
24477 (widen)
24478 (goto-char (point-max))
24479 (while (re-search-backward re nil t)
24480 (setq level (org-reduced-level (funcall outline-level)))
24481 (when (and (<= level n)
24482 (looking-at org-complex-heading-regexp)
24483 (setq head0 (org-match-string-no-properties 4)))
24484 (setq head (org-link-display-format head0)
24485 m (org-imenu-new-marker))
24486 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24487 (if (>= level last-level)
24488 (push (cons head m) (aref subs level))
24489 (push (cons head (aref subs (1+ level))) (aref subs level))
24490 (loop for i from (1+ level) to n do (aset subs i nil)))
24491 (setq last-level level)))))
24492 (aref subs 1)))
24494 (eval-after-load "imenu"
24495 '(progn
24496 (add-hook 'imenu-after-jump-hook
24497 (lambda ()
24498 (if (derived-mode-p 'org-mode)
24499 (org-show-context 'org-goto))))))
24501 (defun org-link-display-format (link)
24502 "Replace a link with its the description.
24503 If there is no description, use the link target."
24504 (save-match-data
24505 (if (string-match org-bracket-link-analytic-regexp link)
24506 (replace-match (if (match-end 5)
24507 (match-string 5 link)
24508 (concat (match-string 1 link)
24509 (match-string 3 link)))
24510 nil t link)
24511 link)))
24513 (defun org-toggle-link-display ()
24514 "Toggle the literal or descriptive display of links."
24515 (interactive)
24516 (if org-descriptive-links
24517 (progn (org-remove-from-invisibility-spec '(org-link))
24518 (org-restart-font-lock)
24519 (setq org-descriptive-links nil))
24520 (progn (add-to-invisibility-spec '(org-link))
24521 (org-restart-font-lock)
24522 (setq org-descriptive-links t))))
24524 ;; Speedbar support
24526 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24527 "Overlay marking the agenda restriction line in speedbar.")
24528 (overlay-put org-speedbar-restriction-lock-overlay
24529 'face 'org-agenda-restriction-lock)
24530 (overlay-put org-speedbar-restriction-lock-overlay
24531 'help-echo "Agendas are currently limited to this item.")
24532 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24534 (defun org-speedbar-set-agenda-restriction ()
24535 "Restrict future agenda commands to the location at point in speedbar.
24536 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24537 (interactive)
24538 (require 'org-agenda)
24539 (let (p m tp np dir txt)
24540 (cond
24541 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24542 'org-imenu t))
24543 (setq m (get-text-property p 'org-imenu-marker))
24544 (with-current-buffer (marker-buffer m)
24545 (goto-char m)
24546 (org-agenda-set-restriction-lock 'subtree)))
24547 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24548 'speedbar-function 'speedbar-find-file))
24549 (setq tp (previous-single-property-change
24550 (1+ p) 'speedbar-function)
24551 np (next-single-property-change
24552 tp 'speedbar-function)
24553 dir (speedbar-line-directory)
24554 txt (buffer-substring-no-properties (or tp (point-min))
24555 (or np (point-max))))
24556 (with-current-buffer (find-file-noselect
24557 (let ((default-directory dir))
24558 (expand-file-name txt)))
24559 (unless (derived-mode-p 'org-mode)
24560 (user-error "Cannot restrict to non-Org-mode file"))
24561 (org-agenda-set-restriction-lock 'file)))
24562 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24563 (move-overlay org-speedbar-restriction-lock-overlay
24564 (point-at-bol) (point-at-eol))
24565 (setq current-prefix-arg nil)
24566 (org-agenda-maybe-redo)))
24568 (defvar speedbar-file-key-map)
24569 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24570 (eval-after-load "speedbar"
24571 '(progn
24572 (speedbar-add-supported-extension ".org")
24573 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24574 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24575 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24576 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24577 (add-hook 'speedbar-visiting-tag-hook
24578 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24580 ;;; Fixes and Hacks for problems with other packages
24582 (defun org--flyspell-object-check-p (element)
24583 "Non-nil when Flyspell can check object at point.
24584 ELEMENT is the element at point."
24585 (let ((object (save-excursion
24586 (when (org-looking-at-p "\\>") (backward-char))
24587 (org-element-context element))))
24588 (case (org-element-type object)
24589 ;; Prevent checks in links due to keybinding conflict with
24590 ;; Flyspell.
24591 ((code entity export-snippet inline-babel-call
24592 inline-src-block line-break latex-fragment link macro
24593 statistics-cookie target timestamp verbatim)
24594 nil)
24595 (footnote-reference
24596 ;; Only in inline footnotes, within the definition.
24597 (and (eq (org-element-property :type object) 'inline)
24598 (< (save-excursion
24599 (goto-char (org-element-property :begin object))
24600 (search-forward ":" nil t 2))
24601 (point))))
24602 (otherwise t))))
24604 (defun org-mode-flyspell-verify ()
24605 "Function used for `flyspell-generic-check-word-predicate'."
24606 (if (org-at-heading-p)
24607 ;; At a headline or an inlinetask, check title only. This is
24608 ;; faster than relying on `org-element-at-point'.
24609 (and (save-excursion (beginning-of-line)
24610 (and (let ((case-fold-search t))
24611 (not (looking-at "\\*+ END[ \t]*$")))
24612 (looking-at org-complex-heading-regexp)))
24613 (match-beginning 4)
24614 (>= (point) (match-beginning 4))
24615 (or (not (match-beginning 5))
24616 (< (point) (match-beginning 5))))
24617 (let* ((element (org-element-at-point))
24618 (post-affiliated (org-element-property :post-affiliated element)))
24619 (cond
24620 ;; Ignore checks in all affiliated keywords but captions.
24621 ((< (point) post-affiliated)
24622 (and (save-excursion
24623 (beginning-of-line)
24624 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24625 (> (point) (match-end 0))
24626 (org--flyspell-object-check-p element)))
24627 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24628 ((and org-log-into-drawer
24629 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24630 (parent element))
24631 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24632 (setq parent (org-element-property :parent parent)))
24633 (and parent
24634 (eq (compare-strings
24635 log nil nil
24636 (org-element-property :drawer-name parent) nil nil t)
24637 t))))
24638 nil)
24640 (case (org-element-type element)
24641 ((comment quote-section) t)
24642 (comment-block
24643 ;; Allow checks between block markers, not on them.
24644 (and (> (line-beginning-position) post-affiliated)
24645 (save-excursion
24646 (end-of-line)
24647 (skip-chars-forward " \r\t\n")
24648 (< (point) (org-element-property :end element)))))
24649 ;; Arbitrary list of keywords where checks are meaningful.
24650 ;; Make sure point is on the value part of the element.
24651 (keyword
24652 (and (member (org-element-property :key element)
24653 '("DESCRIPTION" "TITLE"))
24654 (< (save-excursion
24655 (beginning-of-line) (search-forward ":") (point))
24656 (point))))
24657 ;; Check is globally allowed in paragraphs verse blocks and
24658 ;; table rows (after affiliated keywords) but some objects
24659 ;; must not be affected.
24660 ((paragraph table-row verse-block)
24661 (let ((cbeg (org-element-property :contents-begin element))
24662 (cend (org-element-property :contents-end element)))
24663 (and cbeg (>= (point) cbeg) (< (point) cend)
24664 (org--flyspell-object-check-p element))))))))))
24665 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24667 (defun org-remove-flyspell-overlays-in (beg end)
24668 "Remove flyspell overlays in region."
24669 (and (org-bound-and-true-p flyspell-mode)
24670 (fboundp 'flyspell-delete-region-overlays)
24671 (flyspell-delete-region-overlays beg end)))
24673 (defvar flyspell-delayed-commands)
24674 (eval-after-load "flyspell"
24675 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24677 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24678 (eval-after-load "bookmark"
24679 '(if (boundp 'bookmark-after-jump-hook)
24680 ;; We can use the hook
24681 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24682 ;; Hook not available, use advice
24683 (defadvice bookmark-jump (after org-make-visible activate)
24684 "Make the position visible."
24685 (org-bookmark-jump-unhide))))
24687 ;; Make sure saveplace shows the location if it was hidden
24688 (eval-after-load "saveplace"
24689 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24690 "Make the position visible."
24691 (org-bookmark-jump-unhide)))
24693 ;; Make sure ecb shows the location if it was hidden
24694 (eval-after-load "ecb"
24695 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24696 "Make hierarchy visible when jumping into location from ECB tree buffer."
24697 (if (derived-mode-p 'org-mode)
24698 (org-show-context))))
24700 (defun org-bookmark-jump-unhide ()
24701 "Unhide the current position, to show the bookmark location."
24702 (and (derived-mode-p 'org-mode)
24703 (or (outline-invisible-p)
24704 (save-excursion (goto-char (max (point-min) (1- (point))))
24705 (outline-invisible-p)))
24706 (org-show-context 'bookmark-jump)))
24708 (defun org-mark-jump-unhide ()
24709 "Make the point visible with `org-show-context' after jumping to the mark."
24710 (when (and (derived-mode-p 'org-mode)
24711 (outline-invisible-p))
24712 (org-show-context 'mark-goto)))
24714 (eval-after-load "simple"
24715 '(defadvice pop-to-mark-command (after org-make-visible activate)
24716 "Make the point visible with `org-show-context'."
24717 (org-mark-jump-unhide)))
24719 (eval-after-load "simple"
24720 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24721 "Make the point visible with `org-show-context'."
24722 (org-mark-jump-unhide)))
24724 (eval-after-load "simple"
24725 '(defadvice pop-global-mark (after org-make-visible activate)
24726 "Make the point visible with `org-show-context'."
24727 (org-mark-jump-unhide)))
24729 ;; Make session.el ignore our circular variable
24730 (defvar session-globals-exclude)
24731 (eval-after-load "session"
24732 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24734 ;;;; Finish up
24736 (provide 'org)
24738 (run-hooks 'org-load-hook)
24740 ;;; org.el ends here