Update `org-get-property-block'
[org-mode.git] / lisp / org.el
blob4d2ec9bf9efeeebf7f9eac2191018180ca0d11e6
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-planning-line-re
393 (concat "^[ \t]*"
394 (regexp-opt
395 (list org-closed-string org-deadline-string org-scheduled-string)
397 "Matches a line with planning info.
398 Matched keyword is in group 1.")
400 (defconst org-clock-line-re
401 (concat "^[ \t]*" org-clock-string)
402 "Matches a line with clock info.")
404 ;;;; Drawer
406 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
407 "Matches first or last line of a hidden block.
408 Group 1 contains drawer's name or \"END\".")
410 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
411 "Regular expression matching the first line of a property drawer.")
413 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
414 "Regular expression matching the last line of a property drawer.")
416 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
417 "Regular expression matching the first line of a clock drawer.")
419 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
420 "Regular expression matching the last line of a clock drawer.")
422 (defconst org-property-drawer-re
423 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
424 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*"
425 "[ \t]*:END:[ \t]*$")
426 "Matches an entire property drawer.")
428 (defconst org-clock-drawer-re
429 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
430 org-clock-drawer-end-re "\\)\n?")
431 "Matches an entire clock drawer.")
433 ;;;; Headline
435 (defconst org-heading-keyword-regexp-format
436 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
437 "Printf format for a regexp matching a headline with some keyword.
438 This regexp will match the headline of any node which has the
439 exact keyword that is put into the format. The keyword isn't in
440 any group by default, but the stars and the body are.")
442 (defconst org-heading-keyword-maybe-regexp-format
443 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
444 "Printf format for a regexp matching a headline, possibly with some keyword.
445 This regexp can match any headline with the specified keyword, or
446 without a keyword. The keyword isn't in any group by default,
447 but the stars and the body are.")
449 (defconst org-archive-tag "ARCHIVE"
450 "The tag that marks a subtree as archived.
451 An archived subtree does not open during visibility cycling, and does
452 not contribute to the agenda listings.")
454 (defconst org-comment-string "COMMENT"
455 "Entries starting with this keyword will never be exported.
456 An entry can be toggled between COMMENT and normal with
457 \\[org-toggle-comment].")
460 ;;;; LaTeX Environments and Fragments
462 (defconst org-latex-regexps
463 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
464 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
465 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
466 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
467 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
468 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
469 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
470 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
471 "Regular expressions for matching embedded LaTeX.")
473 ;;;; Node Property
475 (defconst org-effort-property "Effort"
476 "The property that is being used to keep track of effort estimates.
477 Effort estimates given in this property need to have the format H:MM.")
479 ;;;; Table
481 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
482 "Detect an org-type or table-type table.")
484 (defconst org-table-line-regexp "^[ \t]*|"
485 "Detect an org-type table line.")
487 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
488 "Detect an org-type table line.")
490 (defconst org-table-hline-regexp "^[ \t]*|-"
491 "Detect an org-type table hline.")
493 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
494 "Detect a table-type table hline.")
496 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
497 "Detect the first line outside a table when searching from within it.
498 This works for both table types.")
500 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
501 "Detect a #+TBLFM line.")
503 ;;;; Timestamp
505 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
506 "Regular expression for fast time stamp matching.")
508 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
509 "Regular expression for fast time stamp matching.")
511 (defconst org-ts-regexp0
512 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
513 "Regular expression matching time strings for analysis.
514 This one does not require the space after the date, so it can be used
515 on a string that terminates immediately after the date.")
517 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
518 "Regular expression matching time strings for analysis.")
520 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
521 "Regular expression matching time stamps, with groups.")
523 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
524 "Regular expression matching time stamps (also [..]), with groups.")
526 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
527 "Regular expression matching a time stamp range.")
529 (defconst org-tr-regexp-both
530 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
531 "Regular expression matching a time stamp range.")
533 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
534 org-ts-regexp "\\)?")
535 "Regular expression matching a time stamp or time stamp range.")
537 (defconst org-tsr-regexp-both
538 (concat org-ts-regexp-both "\\(--?-?"
539 org-ts-regexp-both "\\)?")
540 "Regular expression matching a time stamp or time stamp range.
541 The time stamps may be either active or inactive.")
543 (defconst org-repeat-re
544 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
545 "Regular expression for specifying repeated events.
546 After a match, group 1 contains the repeat expression.")
548 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
549 "Formats for `format-time-string' which are used for time stamps.")
552 ;;; The custom variables
554 (defgroup org nil
555 "Outline-based notes management and organizer."
556 :tag "Org"
557 :group 'outlines
558 :group 'calendar)
560 (defcustom org-mode-hook nil
561 "Mode hook for Org-mode, run after the mode was turned on."
562 :group 'org
563 :type 'hook)
565 (defcustom org-load-hook nil
566 "Hook that is run after org.el has been loaded."
567 :group 'org
568 :type 'hook)
570 (defcustom org-log-buffer-setup-hook nil
571 "Hook that is run after an Org log buffer is created."
572 :group 'org
573 :version "24.1"
574 :type 'hook)
576 (defvar org-modules) ; defined below
577 (defvar org-modules-loaded nil
578 "Have the modules been loaded already?")
580 (defun org-load-modules-maybe (&optional force)
581 "Load all extensions listed in `org-modules'."
582 (when (or force (not org-modules-loaded))
583 (mapc (lambda (ext)
584 (condition-case nil (require ext)
585 (error (message "Problems while trying to load feature `%s'" ext))))
586 org-modules)
587 (setq org-modules-loaded t)))
589 (defun org-set-modules (var value)
590 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
591 (set var value)
592 (when (featurep 'org)
593 (org-load-modules-maybe 'force)
594 (org-element-cache-reset 'all)))
596 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
597 "Modules that should always be loaded together with org.el.
599 If a description starts with <C>, the file is not part of Emacs
600 and loading it will require that you have downloaded and properly
601 installed the Org mode distribution.
603 You can also use this system to load external packages (i.e. neither Org
604 core modules, nor modules from the CONTRIB directory). Just add symbols
605 to the end of the list. If the package is called org-xyz.el, then you need
606 to add the symbol `xyz', and the package must have a call to:
608 \(provide 'org-xyz)
610 For export specific modules, see also `org-export-backends'."
611 :group 'org
612 :set 'org-set-modules
613 :version "24.4"
614 :package-version '(Org . "8.0")
615 :type
616 '(set :greedy t
617 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
618 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
619 (const :tag " crypt: Encryption of subtrees" org-crypt)
620 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
621 (const :tag " docview: Links to doc-view buffers" org-docview)
622 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
623 (const :tag " habit: Track your consistency with habits" org-habit)
624 (const :tag " id: Global IDs for identifying entries" org-id)
625 (const :tag " info: Links to Info nodes" org-info)
626 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
627 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
628 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
629 (const :tag " mouse: Additional mouse support" org-mouse)
630 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
631 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
632 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
634 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
635 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
636 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
637 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
638 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
639 (const :tag "C collector: Collect properties into tables" org-collector)
640 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
641 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
642 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
643 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
644 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
645 (const :tag "C eval: Include command output as text" org-eval)
646 (const :tag "C eww: Store link to url of eww" org-eww)
647 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
648 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
649 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
650 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
651 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
652 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
653 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
654 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
655 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
656 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
657 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
658 (const :tag "C mew: Links to Mew folders/messages" org-mew)
659 (const :tag "C mtags: Support for muse-like tags" org-mtags)
660 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
661 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
662 (const :tag "C registry: A registry for Org-mode links" org-registry)
663 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
664 (const :tag "C secretary: Team management with org-mode" org-secretary)
665 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
666 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
667 (const :tag "C track: Keep up with Org-mode development" org-track)
668 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
669 (const :tag "C vm: Links to VM folders/messages" org-vm)
670 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
671 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
672 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
674 (defvar org-export--registered-backends) ; From ox.el.
675 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
676 (declare-function org-export-backend-name "ox" (backend))
677 (defcustom org-export-backends '(ascii html icalendar latex)
678 "List of export back-ends that should be always available.
680 If a description starts with <C>, the file is not part of Emacs
681 and loading it will require that you have downloaded and properly
682 installed the Org mode distribution.
684 Unlike to `org-modules', libraries in this list will not be
685 loaded along with Org, but only once the export framework is
686 needed.
688 This variable needs to be set before org.el is loaded. If you
689 need to make a change while Emacs is running, use the customize
690 interface or run the following code, where VAL stands for the new
691 value of the variable, after updating it:
693 \(progn
694 \(setq org-export--registered-backends
695 \(org-remove-if-not
696 \(lambda (backend)
697 \(let ((name (org-export-backend-name backend)))
698 \(or (memq name val)
699 \(catch 'parentp
700 \(dolist (b val)
701 \(and (org-export-derived-backend-p b name)
702 \(throw 'parentp t)))))))
703 org-export--registered-backends))
704 \(let ((new-list (mapcar 'org-export-backend-name
705 org-export--registered-backends)))
706 \(dolist (backend val)
707 \(cond
708 \((not (load (format \"ox-%s\" backend) t t))
709 \(message \"Problems while trying to load export back-end `%s'\"
710 backend))
711 \((not (memq backend new-list)) (push backend new-list))))
712 \(set-default 'org-export-backends new-list)))
714 Adding a back-end to this list will also pull the back-end it
715 depends on, if any."
716 :group 'org
717 :group 'org-export
718 :version "24.4"
719 :package-version '(Org . "8.0")
720 :initialize 'custom-initialize-set
721 :set (lambda (var val)
722 (if (not (featurep 'ox)) (set-default var val)
723 ;; Any back-end not required anymore (not present in VAL and not
724 ;; a parent of any back-end in the new value) is removed from the
725 ;; list of registered back-ends.
726 (setq org-export--registered-backends
727 (org-remove-if-not
728 (lambda (backend)
729 (let ((name (org-export-backend-name backend)))
730 (or (memq name val)
731 (catch 'parentp
732 (dolist (b val)
733 (and (org-export-derived-backend-p b name)
734 (throw 'parentp t)))))))
735 org-export--registered-backends))
736 ;; Now build NEW-LIST of both new back-ends and required
737 ;; parents.
738 (let ((new-list (mapcar 'org-export-backend-name
739 org-export--registered-backends)))
740 (dolist (backend val)
741 (cond
742 ((not (load (format "ox-%s" backend) t t))
743 (message "Problems while trying to load export back-end `%s'"
744 backend))
745 ((not (memq backend new-list)) (push backend new-list))))
746 ;; Set VAR to that list with fixed dependencies.
747 (set-default var new-list))))
748 :type '(set :greedy t
749 (const :tag " ascii Export buffer to ASCII format" ascii)
750 (const :tag " beamer Export buffer to Beamer presentation" beamer)
751 (const :tag " html Export buffer to HTML format" html)
752 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
753 (const :tag " latex Export buffer to LaTeX format" latex)
754 (const :tag " man Export buffer to MAN format" man)
755 (const :tag " md Export buffer to Markdown format" md)
756 (const :tag " odt Export buffer to ODT format" odt)
757 (const :tag " org Export buffer to Org format" org)
758 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
759 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
760 (const :tag "C deck Export buffer to deck.js presentations" deck)
761 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
762 (const :tag "C groff Export buffer to Groff format" groff)
763 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
764 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
765 (const :tag "C s5 Export buffer to s5 presentations" s5)
766 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
768 (eval-after-load 'ox
769 '(mapc
770 (lambda (backend)
771 (condition-case nil (require (intern (format "ox-%s" backend)))
772 (error (message "Problems while trying to load export back-end `%s'"
773 backend))))
774 org-export-backends))
776 (defcustom org-support-shift-select nil
777 "Non-nil means make shift-cursor commands select text when possible.
779 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
780 start selecting a region, or enlarge regions started in this way.
781 In Org-mode, in special contexts, these same keys are used for
782 other purposes, important enough to compete with shift selection.
783 Org tries to balance these needs by supporting `shift-select-mode'
784 outside these special contexts, under control of this variable.
786 The default of this variable is nil, to avoid confusing behavior. Shifted
787 cursor keys will then execute Org commands in the following contexts:
788 - on a headline, changing TODO state (left/right) and priority (up/down)
789 - on a time stamp, changing the time
790 - in a plain list item, changing the bullet type
791 - in a property definition line, switching between allowed values
792 - in the BEGIN line of a clock table (changing the time block).
793 Outside these contexts, the commands will throw an error.
795 When this variable is t and the cursor is not in a special
796 context, Org-mode will support shift-selection for making and
797 enlarging regions. To make this more effective, the bullet
798 cycling will no longer happen anywhere in an item line, but only
799 if the cursor is exactly on the bullet.
801 If you set this variable to the symbol `always', then the keys
802 will not be special in headlines, property lines, and item lines,
803 to make shift selection work there as well. If this is what you
804 want, you can use the following alternative commands: `C-c C-t'
805 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
806 can be used to switch TODO sets, `C-c -' to cycle item bullet
807 types, and properties can be edited by hand or in column view.
809 However, when the cursor is on a timestamp, shift-cursor commands
810 will still edit the time stamp - this is just too good to give up.
812 XEmacs user should have this variable set to nil, because
813 `shift-select-mode' is in Emacs 23 or later only."
814 :group 'org
815 :type '(choice
816 (const :tag "Never" nil)
817 (const :tag "When outside special context" t)
818 (const :tag "Everywhere except timestamps" always)))
820 (defcustom org-loop-over-headlines-in-active-region nil
821 "Shall some commands act upon headlines in the active region?
823 When set to `t', some commands will be performed in all headlines
824 within the active region.
826 When set to `start-level', some commands will be performed in all
827 headlines within the active region, provided that these headlines
828 are of the same level than the first one.
830 When set to a string, those commands will be performed on the
831 matching headlines within the active region. Such string must be
832 a tags/property/todo match as it is used in the agenda tags view.
834 The list of commands is: `org-schedule', `org-deadline',
835 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
836 `org-archive-to-archive-sibling'. The archiving commands skip
837 already archived entries."
838 :type '(choice (const :tag "Don't loop" nil)
839 (const :tag "All headlines in active region" t)
840 (const :tag "In active region, headlines at the same level than the first one" start-level)
841 (string :tag "Tags/Property/Todo matcher"))
842 :version "24.1"
843 :group 'org-todo
844 :group 'org-archive)
846 (defgroup org-startup nil
847 "Options concerning startup of Org-mode."
848 :tag "Org Startup"
849 :group 'org)
851 (defcustom org-startup-folded t
852 "Non-nil means entering Org-mode will switch to OVERVIEW.
853 This can also be configured on a per-file basis by adding one of
854 the following lines anywhere in the buffer:
856 #+STARTUP: fold (or `overview', this is equivalent)
857 #+STARTUP: nofold (or `showall', this is equivalent)
858 #+STARTUP: content
859 #+STARTUP: showeverything
861 By default, this option is ignored when Org opens agenda files
862 for the first time. If you want the agenda to honor the startup
863 option, set `org-agenda-inhibit-startup' to nil."
864 :group 'org-startup
865 :type '(choice
866 (const :tag "nofold: show all" nil)
867 (const :tag "fold: overview" t)
868 (const :tag "content: all headlines" content)
869 (const :tag "show everything, even drawers" showeverything)))
871 (defcustom org-startup-truncated t
872 "Non-nil means entering Org-mode will set `truncate-lines'.
873 This is useful since some lines containing links can be very long and
874 uninteresting. Also tables look terrible when wrapped."
875 :group 'org-startup
876 :type 'boolean)
878 (defcustom org-startup-indented nil
879 "Non-nil means turn on `org-indent-mode' on startup.
880 This can also be configured on a per-file basis by adding one of
881 the following lines anywhere in the buffer:
883 #+STARTUP: indent
884 #+STARTUP: noindent"
885 :group 'org-structure
886 :type '(choice
887 (const :tag "Not" nil)
888 (const :tag "Globally (slow on startup in large files)" t)))
890 (defcustom org-use-sub-superscripts t
891 "Non-nil means interpret \"_\" and \"^\" for display.
893 If you want to control how Org exports those characters, see
894 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
895 used to be an alias for `org-export-with-sub-superscripts' in
896 Org <8.0, it is not anymore.
898 When this option is turned on, you can use TeX-like syntax for
899 sub- and superscripts within the buffer. Several characters after
900 \"_\" or \"^\" will be considered as a single item - so grouping
901 with {} is normally not needed. For example, the following things
902 will be parsed as single sub- or superscripts:
904 10^24 or 10^tau several digits will be considered 1 item.
905 10^-12 or 10^-tau a leading sign with digits or a word
906 x^2-y^3 will be read as x^2 - y^3, because items are
907 terminated by almost any nonword/nondigit char.
908 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
910 Still, ambiguity is possible. So when in doubt, use {} to enclose
911 the sub/superscript. If you set this variable to the symbol `{}',
912 the braces are *required* in order to trigger interpretations as
913 sub/superscript. This can be helpful in documents that need \"_\"
914 frequently in plain text."
915 :group 'org-startup
916 :version "24.4"
917 :package-version '(Org . "8.0")
918 :type '(choice
919 (const :tag "Always interpret" t)
920 (const :tag "Only with braces" {})
921 (const :tag "Never interpret" nil)))
923 (defcustom org-startup-with-beamer-mode nil
924 "Non-nil means turn on `org-beamer-mode' on startup.
925 This can also be configured on a per-file basis by adding one of
926 the following lines anywhere in the buffer:
928 #+STARTUP: beamer"
929 :group 'org-startup
930 :version "24.1"
931 :type 'boolean)
933 (defcustom org-startup-align-all-tables nil
934 "Non-nil means align all tables when visiting a file.
935 This is useful when the column width in tables is forced with <N> cookies
936 in table fields. Such tables will look correct only after the first re-align.
937 This can also be configured on a per-file basis by adding one of
938 the following lines anywhere in the buffer:
939 #+STARTUP: align
940 #+STARTUP: noalign"
941 :group 'org-startup
942 :type 'boolean)
944 (defcustom org-startup-with-inline-images nil
945 "Non-nil means show inline images when loading a new Org file.
946 This can also be configured on a per-file basis by adding one of
947 the following lines anywhere in the buffer:
948 #+STARTUP: inlineimages
949 #+STARTUP: noinlineimages"
950 :group 'org-startup
951 :version "24.1"
952 :type 'boolean)
954 (defcustom org-startup-with-latex-preview nil
955 "Non-nil means preview LaTeX fragments when loading a new Org file.
957 This can also be configured on a per-file basis by adding one of
958 the following lines anywhere in the buffer:
959 #+STARTUP: latexpreview
960 #+STARTUP: nolatexpreview"
961 :group 'org-startup
962 :version "24.4"
963 :package-version '(Org . "8.0")
964 :type 'boolean)
966 (defcustom org-insert-mode-line-in-empty-file nil
967 "Non-nil means insert the first line setting Org-mode in empty files.
968 When the function `org-mode' is called interactively in an empty file, this
969 normally means that the file name does not automatically trigger Org-mode.
970 To ensure that the file will always be in Org-mode in the future, a
971 line enforcing Org-mode will be inserted into the buffer, if this option
972 has been set."
973 :group 'org-startup
974 :type 'boolean)
976 (defcustom org-replace-disputed-keys nil
977 "Non-nil means use alternative key bindings for some keys.
978 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
979 These keys are also used by other packages like shift-selection-mode'
980 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
981 If you want to use Org-mode together with one of these other modes,
982 or more generally if you would like to move some Org-mode commands to
983 other keys, set this variable and configure the keys with the variable
984 `org-disputed-keys'.
986 This option is only relevant at load-time of Org-mode, and must be set
987 *before* org.el is loaded. Changing it requires a restart of Emacs to
988 become effective."
989 :group 'org-startup
990 :type 'boolean)
992 (defcustom org-use-extra-keys nil
993 "Non-nil means use extra key sequence definitions for certain commands.
994 This happens automatically if you run XEmacs or if `window-system'
995 is nil. This variable lets you do the same manually. You must
996 set it before loading org.
998 Example: on Carbon Emacs 22 running graphically, with an external
999 keyboard on a Powerbook, the default way of setting M-left might
1000 not work for either Alt or ESC. Setting this variable will make
1001 it work for ESC."
1002 :group 'org-startup
1003 :type 'boolean)
1005 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1007 (defcustom org-disputed-keys
1008 '(([(shift up)] . [(meta p)])
1009 ([(shift down)] . [(meta n)])
1010 ([(shift left)] . [(meta -)])
1011 ([(shift right)] . [(meta +)])
1012 ([(control shift right)] . [(meta shift +)])
1013 ([(control shift left)] . [(meta shift -)]))
1014 "Keys for which Org-mode and other modes compete.
1015 This is an alist, cars are the default keys, second element specifies
1016 the alternative to use when `org-replace-disputed-keys' is t.
1018 Keys can be specified in any syntax supported by `define-key'.
1019 The value of this option takes effect only at Org-mode's startup,
1020 therefore you'll have to restart Emacs to apply it after changing."
1021 :group 'org-startup
1022 :type 'alist)
1024 (defun org-key (key)
1025 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1026 Or return the original if not disputed.
1027 Also apply the translations defined in `org-xemacs-key-equivalents'."
1028 (when org-replace-disputed-keys
1029 (let* ((nkey (key-description key))
1030 (x (org-find-if (lambda (x)
1031 (equal (key-description (car x)) nkey))
1032 org-disputed-keys)))
1033 (setq key (if x (cdr x) key))))
1034 (when (featurep 'xemacs)
1035 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1036 key)
1038 (defun org-find-if (predicate seq)
1039 (catch 'exit
1040 (while seq
1041 (if (funcall predicate (car seq))
1042 (throw 'exit (car seq))
1043 (pop seq)))))
1045 (defun org-defkey (keymap key def)
1046 "Define a key, possibly translated, as returned by `org-key'."
1047 (define-key keymap (org-key key) def))
1049 (defcustom org-ellipsis nil
1050 "The ellipsis to use in the Org-mode outline.
1051 When nil, just use the standard three dots.
1052 When a string, use that string instead.
1053 When a face, use the standard 3 dots, but with the specified face.
1054 The change affects only Org-mode (which will then use its own display table).
1055 Changing this requires executing \\[org-mode] in a buffer to become
1056 effective."
1057 :group 'org-startup
1058 :type '(choice (const :tag "Default" nil)
1059 (face :tag "Face" :value org-warning)
1060 (string :tag "String" :value "...#")))
1062 (defvar org-display-table nil
1063 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1065 (defgroup org-keywords nil
1066 "Keywords in Org-mode."
1067 :tag "Org Keywords"
1068 :group 'org)
1070 (defcustom org-closed-keep-when-no-todo nil
1071 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1072 :group 'org-todo
1073 :group 'org-keywords
1074 :version "24.4"
1075 :package-version '(Org . "8.0")
1076 :type 'boolean)
1078 (defgroup org-structure nil
1079 "Options concerning the general structure of Org-mode files."
1080 :tag "Org Structure"
1081 :group 'org)
1083 (defgroup org-reveal-location nil
1084 "Options about how to make context of a location visible."
1085 :tag "Org Reveal Location"
1086 :group 'org-structure)
1088 (defconst org-context-choice
1089 '(choice
1090 (const :tag "Always" t)
1091 (const :tag "Never" nil)
1092 (repeat :greedy t :tag "Individual contexts"
1093 (cons
1094 (choice :tag "Context"
1095 (const agenda)
1096 (const org-goto)
1097 (const occur-tree)
1098 (const tags-tree)
1099 (const link-search)
1100 (const mark-goto)
1101 (const bookmark-jump)
1102 (const isearch)
1103 (const default))
1104 (boolean))))
1105 "Contexts for the reveal options.")
1107 (defcustom org-show-hierarchy-above '((default . t))
1108 "Non-nil means show full hierarchy when revealing a location.
1109 Org-mode often shows locations in an org-mode file which might have
1110 been invisible before. When this is set, the hierarchy of headings
1111 above the exposed location is shown.
1112 Turning this off for example for sparse trees makes them very compact.
1113 Instead of t, this can also be an alist specifying this option for different
1114 contexts. Valid contexts are
1115 agenda when exposing an entry from the agenda
1116 org-goto when using the command `org-goto' on key C-c C-j
1117 occur-tree when using the command `org-occur' on key C-c /
1118 tags-tree when constructing a sparse tree based on tags matches
1119 link-search when exposing search matches associated with a link
1120 mark-goto when exposing the jump goal of a mark
1121 bookmark-jump when exposing a bookmark location
1122 isearch when exiting from an incremental search
1123 default default for all contexts not set explicitly"
1124 :group 'org-reveal-location
1125 :type org-context-choice)
1127 (defcustom org-show-following-heading '((default . nil))
1128 "Non-nil means show following heading when revealing a location.
1129 Org-mode often shows locations in an org-mode file which might have
1130 been invisible before. When this is set, the heading following the
1131 match is shown.
1132 Turning this off for example for sparse trees makes them very compact,
1133 but makes it harder to edit the location of the match. In such a case,
1134 use the command \\[org-reveal] to show more context.
1135 Instead of t, this can also be an alist specifying this option for different
1136 contexts. See `org-show-hierarchy-above' for valid contexts."
1137 :group 'org-reveal-location
1138 :type org-context-choice)
1140 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1141 "Non-nil means show all sibling heading when revealing a location.
1142 Org-mode often shows locations in an org-mode file which might have
1143 been invisible before. When this is set, the sibling of the current entry
1144 heading are all made visible. If `org-show-hierarchy-above' is t,
1145 the same happens on each level of the hierarchy above the current entry.
1147 By default this is on for the isearch context, off for all other contexts.
1148 Turning this off for example for sparse trees makes them very compact,
1149 but makes it harder to edit the location of the match. In such a case,
1150 use the command \\[org-reveal] to show more context.
1151 Instead of t, this can also be an alist specifying this option for different
1152 contexts. See `org-show-hierarchy-above' for valid contexts."
1153 :group 'org-reveal-location
1154 :type org-context-choice
1155 :version "24.4"
1156 :package-version '(Org . "8.0"))
1158 (defcustom org-show-entry-below '((default . nil))
1159 "Non-nil means show the entry below a headline when revealing a location.
1160 Org-mode often shows locations in an org-mode file which might have
1161 been invisible before. When this is set, the text below the headline that is
1162 exposed is also shown.
1164 By default this is off for all contexts.
1165 Instead of t, this can also be an alist specifying this option for different
1166 contexts. See `org-show-hierarchy-above' for valid contexts."
1167 :group 'org-reveal-location
1168 :type org-context-choice)
1170 (defcustom org-indirect-buffer-display 'other-window
1171 "How should indirect tree buffers be displayed?
1172 This applies to indirect buffers created with the commands
1173 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1174 Valid values are:
1175 current-window Display in the current window
1176 other-window Just display in another window.
1177 dedicated-frame Create one new frame, and re-use it each time.
1178 new-frame Make a new frame each time. Note that in this case
1179 previously-made indirect buffers are kept, and you need to
1180 kill these buffers yourself."
1181 :group 'org-structure
1182 :group 'org-agenda-windows
1183 :type '(choice
1184 (const :tag "In current window" current-window)
1185 (const :tag "In current frame, other window" other-window)
1186 (const :tag "Each time a new frame" new-frame)
1187 (const :tag "One dedicated frame" dedicated-frame)))
1189 (defcustom org-use-speed-commands nil
1190 "Non-nil means activate single letter commands at beginning of a headline.
1191 This may also be a function to test for appropriate locations where speed
1192 commands should be active.
1194 For example, to activate speed commands when the point is on any
1195 star at the beginning of the headline, you can do this:
1197 (setq org-use-speed-commands
1198 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1199 :group 'org-structure
1200 :type '(choice
1201 (const :tag "Never" nil)
1202 (const :tag "At beginning of headline stars" t)
1203 (function)))
1205 (defcustom org-speed-commands-user nil
1206 "Alist of additional speed commands.
1207 This list will be checked before `org-speed-commands-default'
1208 when the variable `org-use-speed-commands' is non-nil
1209 and when the cursor is at the beginning of a headline.
1210 The car if each entry is a string with a single letter, which must
1211 be assigned to `self-insert-command' in the global map.
1212 The cdr is either a command to be called interactively, a function
1213 to be called, or a form to be evaluated.
1214 An entry that is just a list with a single string will be interpreted
1215 as a descriptive headline that will be added when listing the speed
1216 commands in the Help buffer using the `?' speed command."
1217 :group 'org-structure
1218 :type '(repeat :value ("k" . ignore)
1219 (choice :value ("k" . ignore)
1220 (list :tag "Descriptive Headline" (string :tag "Headline"))
1221 (cons :tag "Letter and Command"
1222 (string :tag "Command letter")
1223 (choice
1224 (function)
1225 (sexp))))))
1227 (defcustom org-bookmark-names-plist
1228 '(:last-capture "org-capture-last-stored"
1229 :last-refile "org-refile-last-stored"
1230 :last-capture-marker "org-capture-last-stored-marker")
1231 "Names for bookmarks automatically set by some Org commands.
1232 This can provide strings as names for a number of bookmarks Org sets
1233 automatically. The following keys are currently implemented:
1234 :last-capture
1235 :last-capture-marker
1236 :last-refile
1237 When a key does not show up in the property list, the corresponding bookmark
1238 is not set."
1239 :group 'org-structure
1240 :type 'plist)
1242 (defgroup org-cycle nil
1243 "Options concerning visibility cycling in Org-mode."
1244 :tag "Org Cycle"
1245 :group 'org-structure)
1247 (defcustom org-cycle-skip-children-state-if-no-children t
1248 "Non-nil means skip CHILDREN state in entries that don't have any."
1249 :group 'org-cycle
1250 :type 'boolean)
1252 (defcustom org-cycle-max-level nil
1253 "Maximum level which should still be subject to visibility cycling.
1254 Levels higher than this will, for cycling, be treated as text, not a headline.
1255 When `org-odd-levels-only' is set, a value of N in this variable actually
1256 means 2N-1 stars as the limiting headline.
1257 When nil, cycle all levels.
1258 Note that the limiting level of cycling is also influenced by
1259 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1260 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1261 than its value."
1262 :group 'org-cycle
1263 :type '(choice
1264 (const :tag "No limit" nil)
1265 (integer :tag "Maximum level")))
1267 (defcustom org-hide-block-startup nil
1268 "Non-nil means entering Org-mode will fold all blocks.
1269 This can also be set in on a per-file basis with
1271 #+STARTUP: hideblocks
1272 #+STARTUP: showblocks"
1273 :group 'org-startup
1274 :group 'org-cycle
1275 :type 'boolean)
1277 (defcustom org-cycle-global-at-bob nil
1278 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1279 This makes it possible to do global cycling without having to use S-TAB or
1280 \\[universal-argument] TAB. For this special case to work, the first line
1281 of the buffer must not be a headline -- it may be empty or some other text.
1282 When used in this way, `org-cycle-hook' is disabled temporarily to make
1283 sure the cursor stays at the beginning of the buffer. When this option is
1284 nil, don't do anything special at the beginning of the buffer."
1285 :group 'org-cycle
1286 :type 'boolean)
1288 (defcustom org-cycle-level-after-item/entry-creation t
1289 "Non-nil means cycle entry level or item indentation in new empty entries.
1291 When the cursor is at the end of an empty headline, i.e., with only stars
1292 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1293 and then all possible ancestor states, before returning to the original state.
1294 This makes data entry extremely fast: M-RET to create a new headline,
1295 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1297 When the cursor is at the end of an empty plain list item, one TAB will
1298 make it a subitem, two or more tabs will back up to make this an item
1299 higher up in the item hierarchy."
1300 :group 'org-cycle
1301 :type 'boolean)
1303 (defcustom org-cycle-emulate-tab t
1304 "Where should `org-cycle' emulate TAB.
1305 nil Never
1306 white Only in completely white lines
1307 whitestart Only at the beginning of lines, before the first non-white char
1308 t Everywhere except in headlines
1309 exc-hl-bol Everywhere except at the start of a headline
1310 If TAB is used in a place where it does not emulate TAB, the current subtree
1311 visibility is cycled."
1312 :group 'org-cycle
1313 :type '(choice (const :tag "Never" nil)
1314 (const :tag "Only in completely white lines" white)
1315 (const :tag "Before first char in a line" whitestart)
1316 (const :tag "Everywhere except in headlines" t)
1317 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1319 (defcustom org-cycle-separator-lines 2
1320 "Number of empty lines needed to keep an empty line between collapsed trees.
1321 If you leave an empty line between the end of a subtree and the following
1322 headline, this empty line is hidden when the subtree is folded.
1323 Org-mode will leave (exactly) one empty line visible if the number of
1324 empty lines is equal or larger to the number given in this variable.
1325 So the default 2 means at least 2 empty lines after the end of a subtree
1326 are needed to produce free space between a collapsed subtree and the
1327 following headline.
1329 If the number is negative, and the number of empty lines is at least -N,
1330 all empty lines are shown.
1332 Special case: when 0, never leave empty lines in collapsed view."
1333 :group 'org-cycle
1334 :type 'integer)
1335 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1337 (defcustom org-pre-cycle-hook nil
1338 "Hook that is run before visibility cycling is happening.
1339 The function(s) in this hook must accept a single argument which indicates
1340 the new state that will be set right after running this hook. The
1341 argument is a symbol. Before a global state change, it can have the values
1342 `overview', `content', or `all'. Before a local state change, it can have
1343 the values `folded', `children', or `subtree'."
1344 :group 'org-cycle
1345 :type 'hook)
1347 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1348 org-cycle-hide-drawers
1349 org-cycle-hide-inline-tasks
1350 org-cycle-show-empty-lines
1351 org-optimize-window-after-visibility-change)
1352 "Hook that is run after `org-cycle' has changed the buffer visibility.
1353 The function(s) in this hook must accept a single argument which indicates
1354 the new state that was set by the most recent `org-cycle' command. The
1355 argument is a symbol. After a global state change, it can have the values
1356 `overview', `contents', or `all'. After a local state change, it can have
1357 the values `folded', `children', or `subtree'."
1358 :group 'org-cycle
1359 :type 'hook)
1361 (defgroup org-edit-structure nil
1362 "Options concerning structure editing in Org-mode."
1363 :tag "Org Edit Structure"
1364 :group 'org-structure)
1366 (defcustom org-odd-levels-only nil
1367 "Non-nil means skip even levels and only use odd levels for the outline.
1368 This has the effect that two stars are being added/taken away in
1369 promotion/demotion commands. It also influences how levels are
1370 handled by the exporters.
1371 Changing it requires restart of `font-lock-mode' to become effective
1372 for fontification also in regions already fontified.
1373 You may also set this on a per-file basis by adding one of the following
1374 lines to the buffer:
1376 #+STARTUP: odd
1377 #+STARTUP: oddeven"
1378 :group 'org-edit-structure
1379 :group 'org-appearance
1380 :type 'boolean)
1382 (defcustom org-adapt-indentation t
1383 "Non-nil means adapt indentation to outline node level.
1385 When this variable is set, Org assumes that you write outlines by
1386 indenting text in each node to align with the headline (after the stars).
1387 The following issues are influenced by this variable:
1389 - When this is set and the *entire* text in an entry is indented, the
1390 indentation is increased by one space in a demotion command, and
1391 decreased by one in a promotion command. If any line in the entry
1392 body starts with text at column 0, indentation is not changed at all.
1394 - Property drawers and planning information is inserted indented when
1395 this variable s set. When nil, they will not be indented.
1397 - TAB indents a line relative to context. The lines below a headline
1398 will be indented when this variable is set.
1400 Note that this is all about true indentation, by adding and removing
1401 space characters. See also `org-indent.el' which does level-dependent
1402 indentation in a virtual way, i.e. at display time in Emacs."
1403 :group 'org-edit-structure
1404 :type 'boolean)
1406 (defcustom org-special-ctrl-a/e nil
1407 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1409 When t, `C-a' will bring back the cursor to the beginning of the
1410 headline text, i.e. after the stars and after a possible TODO
1411 keyword. In an item, this will be the position after bullet and
1412 check-box, if any. When the cursor is already at that position,
1413 another `C-a' will bring it to the beginning of the line.
1415 `C-e' will jump to the end of the headline, ignoring the presence
1416 of tags in the headline. A second `C-e' will then jump to the
1417 true end of the line, after any tags. This also means that, when
1418 this variable is non-nil, `C-e' also will never jump beyond the
1419 end of the heading of a folded section, i.e. not after the
1420 ellipses.
1422 When set to the symbol `reversed', the first `C-a' or `C-e' works
1423 normally, going to the true line boundary first. Only a directly
1424 following, identical keypress will bring the cursor to the
1425 special positions.
1427 This may also be a cons cell where the behavior for `C-a' and
1428 `C-e' is set separately."
1429 :group 'org-edit-structure
1430 :type '(choice
1431 (const :tag "off" nil)
1432 (const :tag "on: after stars/bullet and before tags first" t)
1433 (const :tag "reversed: true line boundary first" reversed)
1434 (cons :tag "Set C-a and C-e separately"
1435 (choice :tag "Special C-a"
1436 (const :tag "off" nil)
1437 (const :tag "on: after stars/bullet first" t)
1438 (const :tag "reversed: before stars/bullet first" reversed))
1439 (choice :tag "Special C-e"
1440 (const :tag "off" nil)
1441 (const :tag "on: before tags first" t)
1442 (const :tag "reversed: after tags first" reversed)))))
1443 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1445 (defcustom org-special-ctrl-k nil
1446 "Non-nil means `C-k' will behave specially in headlines.
1447 When nil, `C-k' will call the default `kill-line' command.
1448 When t, the following will happen while the cursor is in the headline:
1450 - When the cursor is at the beginning of a headline, kill the entire
1451 line and possible the folded subtree below the line.
1452 - When in the middle of the headline text, kill the headline up to the tags.
1453 - When after the headline text, kill the tags."
1454 :group 'org-edit-structure
1455 :type 'boolean)
1457 (defcustom org-ctrl-k-protect-subtree nil
1458 "Non-nil means, do not delete a hidden subtree with C-k.
1459 When set to the symbol `error', simply throw an error when C-k is
1460 used to kill (part-of) a headline that has hidden text behind it.
1461 Any other non-nil value will result in a query to the user, if it is
1462 OK to kill that hidden subtree. When nil, kill without remorse."
1463 :group 'org-edit-structure
1464 :version "24.1"
1465 :type '(choice
1466 (const :tag "Do not protect hidden subtrees" nil)
1467 (const :tag "Protect hidden subtrees with a security query" t)
1468 (const :tag "Never kill a hidden subtree with C-k" error)))
1470 (defcustom org-special-ctrl-o t
1471 "Non-nil means, make `C-o' insert a row in tables."
1472 :group 'org-edit-structure
1473 :type 'boolean)
1475 (defcustom org-catch-invisible-edits nil
1476 "Check if in invisible region before inserting or deleting a character.
1477 Valid values are:
1479 nil Do not check, so just do invisible edits.
1480 error Throw an error and do nothing.
1481 show Make point visible, and do the requested edit.
1482 show-and-error Make point visible, then throw an error and abort the edit.
1483 smart Make point visible, and do insertion/deletion if it is
1484 adjacent to visible text and the change feels predictable.
1485 Never delete a previously invisible character or add in the
1486 middle or right after an invisible region. Basically, this
1487 allows insertion and backward-delete right before ellipses.
1488 FIXME: maybe in this case we should not even show?"
1489 :group 'org-edit-structure
1490 :version "24.1"
1491 :type '(choice
1492 (const :tag "Do not check" nil)
1493 (const :tag "Throw error when trying to edit" error)
1494 (const :tag "Unhide, but do not do the edit" show-and-error)
1495 (const :tag "Show invisible part and do the edit" show)
1496 (const :tag "Be smart and do the right thing" smart)))
1498 (defcustom org-yank-folded-subtrees t
1499 "Non-nil means when yanking subtrees, fold them.
1500 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1501 it starts with a heading and all other headings in it are either children
1502 or siblings, then fold all the subtrees. However, do this only if no
1503 text after the yank would be swallowed into a folded tree by this action."
1504 :group 'org-edit-structure
1505 :type 'boolean)
1507 (defcustom org-yank-adjusted-subtrees nil
1508 "Non-nil means when yanking subtrees, adjust the level.
1509 With this setting, `org-paste-subtree' is used to insert the subtree, see
1510 this function for details."
1511 :group 'org-edit-structure
1512 :type 'boolean)
1514 (defcustom org-M-RET-may-split-line '((default . t))
1515 "Non-nil means M-RET will split the line at the cursor position.
1516 When nil, it will go to the end of the line before making a
1517 new line.
1518 You may also set this option in a different way for different
1519 contexts. Valid contexts are:
1521 headline when creating a new headline
1522 item when creating a new item
1523 table in a table field
1524 default the value to be used for all contexts not explicitly
1525 customized"
1526 :group 'org-structure
1527 :group 'org-table
1528 :type '(choice
1529 (const :tag "Always" t)
1530 (const :tag "Never" nil)
1531 (repeat :greedy t :tag "Individual contexts"
1532 (cons
1533 (choice :tag "Context"
1534 (const headline)
1535 (const item)
1536 (const table)
1537 (const default))
1538 (boolean)))))
1541 (defcustom org-insert-heading-respect-content nil
1542 "Non-nil means insert new headings after the current subtree.
1543 When nil, the new heading is created directly after the current line.
1544 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1545 this variable on for the duration of the command."
1546 :group 'org-structure
1547 :type 'boolean)
1549 (defcustom org-blank-before-new-entry '((heading . auto)
1550 (plain-list-item . auto))
1551 "Should `org-insert-heading' leave a blank line before new heading/item?
1552 The value is an alist, with `heading' and `plain-list-item' as CAR,
1553 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1554 which case Org will look at the surrounding headings/items and try to
1555 make an intelligent decision whether to insert a blank line or not.
1557 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1558 the setting here is ignored and no empty line is inserted to avoid breaking
1559 the list structure."
1560 :group 'org-edit-structure
1561 :type '(list
1562 (cons (const heading)
1563 (choice (const :tag "Never" nil)
1564 (const :tag "Always" t)
1565 (const :tag "Auto" auto)))
1566 (cons (const plain-list-item)
1567 (choice (const :tag "Never" nil)
1568 (const :tag "Always" t)
1569 (const :tag "Auto" auto)))))
1571 (defcustom org-insert-heading-hook nil
1572 "Hook being run after inserting a new heading."
1573 :group 'org-edit-structure
1574 :type 'hook)
1576 (defcustom org-enable-fixed-width-editor t
1577 "Non-nil means lines starting with \":\" are treated as fixed-width.
1578 This currently only means they are never auto-wrapped.
1579 When nil, such lines will be treated like ordinary lines."
1580 :group 'org-edit-structure
1581 :type 'boolean)
1583 (defcustom org-goto-auto-isearch t
1584 "Non-nil means typing characters in `org-goto' starts incremental search.
1585 When nil, you can use these keybindings to navigate the buffer:
1587 q Quit the org-goto interface
1588 n Go to the next visible heading
1589 p Go to the previous visible heading
1590 f Go one heading forward on same level
1591 b Go one heading backward on same level
1592 u Go one heading up"
1593 :group 'org-edit-structure
1594 :type 'boolean)
1596 (defgroup org-sparse-trees nil
1597 "Options concerning sparse trees in Org-mode."
1598 :tag "Org Sparse Trees"
1599 :group 'org-structure)
1601 (defcustom org-highlight-sparse-tree-matches t
1602 "Non-nil means highlight all matches that define a sparse tree.
1603 The highlights will automatically disappear the next time the buffer is
1604 changed by an edit command."
1605 :group 'org-sparse-trees
1606 :type 'boolean)
1608 (defcustom org-remove-highlights-with-change t
1609 "Non-nil means any change to the buffer will remove temporary highlights.
1610 Such highlights are created by `org-occur' and `org-clock-display'.
1611 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1612 The highlights created by `org-toggle-latex-fragment' always need
1613 `C-c C-x C-l' to be removed."
1614 :group 'org-sparse-trees
1615 :group 'org-time
1616 :type 'boolean)
1619 (defcustom org-occur-hook '(org-first-headline-recenter)
1620 "Hook that is run after `org-occur' has constructed a sparse tree.
1621 This can be used to recenter the window to show as much of the structure
1622 as possible."
1623 :group 'org-sparse-trees
1624 :type 'hook)
1626 (defgroup org-imenu-and-speedbar nil
1627 "Options concerning imenu and speedbar in Org-mode."
1628 :tag "Org Imenu and Speedbar"
1629 :group 'org-structure)
1631 (defcustom org-imenu-depth 2
1632 "The maximum level for Imenu access to Org-mode headlines.
1633 This also applied for speedbar access."
1634 :group 'org-imenu-and-speedbar
1635 :type 'integer)
1637 (defgroup org-table nil
1638 "Options concerning tables in Org-mode."
1639 :tag "Org Table"
1640 :group 'org)
1642 (defcustom org-enable-table-editor 'optimized
1643 "Non-nil means lines starting with \"|\" are handled by the table editor.
1644 When nil, such lines will be treated like ordinary lines.
1646 When equal to the symbol `optimized', the table editor will be optimized to
1647 do the following:
1648 - Automatic overwrite mode in front of whitespace in table fields.
1649 This makes the structure of the table stay in tact as long as the edited
1650 field does not exceed the column width.
1651 - Minimize the number of realigns. Normally, the table is aligned each time
1652 TAB or RET are pressed to move to another field. With optimization this
1653 happens only if changes to a field might have changed the column width.
1654 Optimization requires replacing the functions `self-insert-command',
1655 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1656 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1657 very good at guessing when a re-align will be necessary, but you can always
1658 force one with \\[org-ctrl-c-ctrl-c].
1660 If you would like to use the optimized version in Org-mode, but the
1661 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1663 This variable can be used to turn on and off the table editor during a session,
1664 but in order to toggle optimization, a restart is required.
1666 See also the variable `org-table-auto-blank-field'."
1667 :group 'org-table
1668 :type '(choice
1669 (const :tag "off" nil)
1670 (const :tag "on" t)
1671 (const :tag "on, optimized" optimized)))
1673 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1674 (version<= emacs-version "24.1"))
1675 "Non-nil means cluster self-insert commands for undo when possible.
1676 If this is set, then, like in the Emacs command loop, 20 consecutive
1677 characters will be undone together.
1678 This is configurable, because there is some impact on typing performance."
1679 :group 'org-table
1680 :type 'boolean)
1682 (defcustom org-table-tab-recognizes-table.el t
1683 "Non-nil means TAB will automatically notice a table.el table.
1684 When it sees such a table, it moves point into it and - if necessary -
1685 calls `table-recognize-table'."
1686 :group 'org-table-editing
1687 :type 'boolean)
1689 (defgroup org-link nil
1690 "Options concerning links in Org-mode."
1691 :tag "Org Link"
1692 :group 'org)
1694 (defvar org-link-abbrev-alist-local nil
1695 "Buffer-local version of `org-link-abbrev-alist', which see.
1696 The value of this is taken from the #+LINK lines.")
1697 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1699 (defcustom org-link-abbrev-alist nil
1700 "Alist of link abbreviations.
1701 The car of each element is a string, to be replaced at the start of a link.
1702 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1703 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1705 [[linkkey:tag][description]]
1707 The 'linkkey' must be a word word, starting with a letter, followed
1708 by letters, numbers, '-' or '_'.
1710 If REPLACE is a string, the tag will simply be appended to create the link.
1711 If the string contains \"%s\", the tag will be inserted there. If the string
1712 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1713 at that point (see the function `url-hexify-string'). If the string contains
1714 the specifier \"%(my-function)\", then the custom function `my-function' will
1715 be invoked: this function takes the tag as its only argument and must return
1716 a string.
1718 REPLACE may also be a function that will be called with the tag as the
1719 only argument to create the link, which should be returned as a string.
1721 See the manual for examples."
1722 :group 'org-link
1723 :type '(repeat
1724 (cons
1725 (string :tag "Protocol")
1726 (choice
1727 (string :tag "Format")
1728 (function)))))
1730 (defcustom org-descriptive-links t
1731 "Non-nil means Org will display descriptive links.
1732 E.g. [[http://orgmode.org][Org website]] will be displayed as
1733 \"Org Website\", hiding the link itself and just displaying its
1734 description. When set to `nil', Org will display the full links
1735 literally.
1737 You can interactively set the value of this variable by calling
1738 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1739 :group 'org-link
1740 :type 'boolean)
1742 (defcustom org-link-file-path-type 'adaptive
1743 "How the path name in file links should be stored.
1744 Valid values are:
1746 relative Relative to the current directory, i.e. the directory of the file
1747 into which the link is being inserted.
1748 absolute Absolute path, if possible with ~ for home directory.
1749 noabbrev Absolute path, no abbreviation of home directory.
1750 adaptive Use relative path for files in the current directory and sub-
1751 directories of it. For other files, use an absolute path."
1752 :group 'org-link
1753 :type '(choice
1754 (const relative)
1755 (const absolute)
1756 (const noabbrev)
1757 (const adaptive)))
1759 (defvaralias 'org-activate-links 'org-highlight-links)
1760 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1761 "Types of links that should be highlighted in Org-mode files.
1763 This is a list of symbols, each one of them leading to the
1764 highlighting of a certain link type.
1766 You can still open links that are not highlighted.
1768 In principle, it does not hurt to turn on highlighting for all
1769 link types. There may be a small gain when turning off unused
1770 link types. The types are:
1772 bracket The recommended [[link][description]] or [[link]] links with hiding.
1773 angle Links in angular brackets that may contain whitespace like
1774 <bbdb:Carsten Dominik>.
1775 plain Plain links in normal text, no whitespace, like http://google.com.
1776 radio Text that is matched by a radio target, see manual for details.
1777 tag Tag settings in a headline (link to tag search).
1778 date Time stamps (link to calendar).
1779 footnote Footnote labels.
1781 If you set this variable during an Emacs session, use `org-mode-restart'
1782 in the Org buffer so that the change takes effect."
1783 :group 'org-link
1784 :group 'org-appearance
1785 :type '(set :greedy t
1786 (const :tag "Double bracket links" bracket)
1787 (const :tag "Angular bracket links" angle)
1788 (const :tag "Plain text links" plain)
1789 (const :tag "Radio target matches" radio)
1790 (const :tag "Tags" tag)
1791 (const :tag "Timestamps" date)
1792 (const :tag "Footnotes" footnote)))
1794 (defcustom org-make-link-description-function nil
1795 "Function to use for generating link descriptions from links.
1796 When nil, the link location will be used. This function must take
1797 two parameters: the first one is the link, the second one is the
1798 description generated by `org-insert-link'. The function should
1799 return the description to use."
1800 :group 'org-link
1801 :type '(choice (const nil) (function)))
1803 (defgroup org-link-store nil
1804 "Options concerning storing links in Org-mode."
1805 :tag "Org Store Link"
1806 :group 'org-link)
1808 (defcustom org-url-hexify-p t
1809 "When non-nil, hexify URL when creating a link."
1810 :type 'boolean
1811 :version "24.3"
1812 :group 'org-link-store)
1814 (defcustom org-email-link-description-format "Email %c: %.30s"
1815 "Format of the description part of a link to an email or usenet message.
1816 The following %-escapes will be replaced by corresponding information:
1818 %F full \"From\" field
1819 %f name, taken from \"From\" field, address if no name
1820 %T full \"To\" field
1821 %t first name in \"To\" field, address if no name
1822 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1823 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1824 %s subject
1825 %d date
1826 %m message-id.
1828 You may use normal field width specification between the % and the letter.
1829 This is for example useful to limit the length of the subject.
1831 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1832 :group 'org-link-store
1833 :type 'string)
1835 (defcustom org-from-is-user-regexp
1836 (let (r1 r2)
1837 (when (and user-mail-address (not (string= user-mail-address "")))
1838 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1839 (when (and user-full-name (not (string= user-full-name "")))
1840 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1841 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1842 "Regexp matched against the \"From:\" header of an email or usenet message.
1843 It should match if the message is from the user him/herself."
1844 :group 'org-link-store
1845 :type 'regexp)
1847 (defcustom org-context-in-file-links t
1848 "Non-nil means file links from `org-store-link' contain context.
1849 A search string will be added to the file name with :: as separator and
1850 used to find the context when the link is activated by the command
1851 `org-open-at-point'. When this option is t, the entire active region
1852 will be placed in the search string of the file link. If set to a
1853 positive integer, only the first n lines of context will be stored.
1855 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1856 negates this setting for the duration of the command."
1857 :group 'org-link-store
1858 :type '(choice boolean integer))
1860 (defcustom org-keep-stored-link-after-insertion nil
1861 "Non-nil means keep link in list for entire session.
1863 The command `org-store-link' adds a link pointing to the current
1864 location to an internal list. These links accumulate during a session.
1865 The command `org-insert-link' can be used to insert links into any
1866 Org-mode file (offering completion for all stored links). When this
1867 option is nil, every link which has been inserted once using \\[org-insert-link]
1868 will be removed from the list, to make completing the unused links
1869 more efficient."
1870 :group 'org-link-store
1871 :type 'boolean)
1873 (defgroup org-link-follow nil
1874 "Options concerning following links in Org-mode."
1875 :tag "Org Follow Link"
1876 :group 'org-link)
1878 (defcustom org-link-translation-function nil
1879 "Function to translate links with different syntax to Org syntax.
1880 This can be used to translate links created for example by the Planner
1881 or emacs-wiki packages to Org syntax.
1882 The function must accept two parameters, a TYPE containing the link
1883 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1884 which is everything after the link protocol. It should return a cons
1885 with possibly modified values of type and path.
1886 Org contains a function for this, so if you set this variable to
1887 `org-translate-link-from-planner', you should be able follow many
1888 links created by planner."
1889 :group 'org-link-follow
1890 :type '(choice (const nil) (function)))
1892 (defcustom org-follow-link-hook nil
1893 "Hook that is run after a link has been followed."
1894 :group 'org-link-follow
1895 :type 'hook)
1897 (defcustom org-tab-follows-link nil
1898 "Non-nil means on links TAB will follow the link.
1899 Needs to be set before org.el is loaded.
1900 This really should not be used, it does not make sense, and the
1901 implementation is bad."
1902 :group 'org-link-follow
1903 :type 'boolean)
1905 (defcustom org-return-follows-link nil
1906 "Non-nil means on links RET will follow the link.
1907 In tables, the special behavior of RET has precedence."
1908 :group 'org-link-follow
1909 :type 'boolean)
1911 (defcustom org-mouse-1-follows-link
1912 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1913 "Non-nil means mouse-1 on a link will follow the link.
1914 A longer mouse click will still set point. Does not work on XEmacs.
1915 Needs to be set before org.el is loaded."
1916 :group 'org-link-follow
1917 :version "24.4"
1918 :package-version '(Org . "8.3")
1919 :type '(choice
1920 (const :tag "A double click follows the link" double)
1921 (const :tag "Unconditionally follow the link with mouse-1" t)
1922 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1924 (defcustom org-mark-ring-length 4
1925 "Number of different positions to be recorded in the ring.
1926 Changing this requires a restart of Emacs to work correctly."
1927 :group 'org-link-follow
1928 :type 'integer)
1930 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1931 "Non-nil means internal links in Org files must exactly match a headline.
1932 When nil, the link search tries to match a phrase with all words
1933 in the search text."
1934 :group 'org-link-follow
1935 :version "24.1"
1936 :type '(choice
1937 (const :tag "Use fuzzy text search" nil)
1938 (const :tag "Match only exact headline" t)
1939 (const :tag "Match exact headline or query to create it"
1940 query-to-create)))
1942 (defcustom org-link-frame-setup
1943 '((vm . vm-visit-folder-other-frame)
1944 (vm-imap . vm-visit-imap-folder-other-frame)
1945 (gnus . org-gnus-no-new-news)
1946 (file . find-file-other-window)
1947 (wl . wl-other-frame))
1948 "Setup the frame configuration for following links.
1949 When following a link with Emacs, it may often be useful to display
1950 this link in another window or frame. This variable can be used to
1951 set this up for the different types of links.
1952 For VM, use any of
1953 `vm-visit-folder'
1954 `vm-visit-folder-other-window'
1955 `vm-visit-folder-other-frame'
1956 For Gnus, use any of
1957 `gnus'
1958 `gnus-other-frame'
1959 `org-gnus-no-new-news'
1960 For FILE, use any of
1961 `find-file'
1962 `find-file-other-window'
1963 `find-file-other-frame'
1964 For Wanderlust use any of
1965 `wl'
1966 `wl-other-frame'
1967 For the calendar, use the variable `calendar-setup'.
1968 For BBDB, it is currently only possible to display the matches in
1969 another window."
1970 :group 'org-link-follow
1971 :type '(list
1972 (cons (const vm)
1973 (choice
1974 (const vm-visit-folder)
1975 (const vm-visit-folder-other-window)
1976 (const vm-visit-folder-other-frame)))
1977 (cons (const vm-imap)
1978 (choice
1979 (const vm-visit-imap-folder)
1980 (const vm-visit-imap-folder-other-window)
1981 (const vm-visit-imap-folder-other-frame)))
1982 (cons (const gnus)
1983 (choice
1984 (const gnus)
1985 (const gnus-other-frame)
1986 (const org-gnus-no-new-news)))
1987 (cons (const file)
1988 (choice
1989 (const find-file)
1990 (const find-file-other-window)
1991 (const find-file-other-frame)))
1992 (cons (const wl)
1993 (choice
1994 (const wl)
1995 (const wl-other-frame)))))
1997 (defcustom org-display-internal-link-with-indirect-buffer nil
1998 "Non-nil means use indirect buffer to display infile links.
1999 Activating internal links (from one location in a file to another location
2000 in the same file) normally just jumps to the location. When the link is
2001 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2002 is displayed in
2003 another window. When this option is set, the other window actually displays
2004 an indirect buffer clone of the current buffer, to avoid any visibility
2005 changes to the current buffer."
2006 :group 'org-link-follow
2007 :type 'boolean)
2009 (defcustom org-open-non-existing-files nil
2010 "Non-nil means `org-open-file' will open non-existing files.
2011 When nil, an error will be generated.
2012 This variable applies only to external applications because they
2013 might choke on non-existing files. If the link is to a file that
2014 will be opened in Emacs, the variable is ignored."
2015 :group 'org-link-follow
2016 :type 'boolean)
2018 (defcustom org-open-directory-means-index-dot-org nil
2019 "Non-nil means a link to a directory really means to index.org.
2020 When nil, following a directory link will run dired or open a finder/explorer
2021 window on that directory."
2022 :group 'org-link-follow
2023 :type 'boolean)
2025 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2026 "Non-nil means ask for confirmation before executing shell links.
2027 Shell links can be dangerous: just think about a link
2029 [[shell:rm -rf ~/*][Google Search]]
2031 This link would show up in your Org-mode document as \"Google Search\",
2032 but really it would remove your entire home directory.
2033 Therefore we advise against setting this variable to nil.
2034 Just change it to `y-or-n-p' if you want to confirm with a
2035 single keystroke rather than having to type \"yes\"."
2036 :group 'org-link-follow
2037 :type '(choice
2038 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2039 (const :tag "with y-or-n (faster)" y-or-n-p)
2040 (const :tag "no confirmation (dangerous)" nil)))
2041 (put 'org-confirm-shell-link-function
2042 'safe-local-variable
2043 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2045 (defcustom org-confirm-shell-link-not-regexp ""
2046 "A regexp to skip confirmation for shell links."
2047 :group 'org-link-follow
2048 :version "24.1"
2049 :type 'regexp)
2051 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2052 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2053 Elisp links can be dangerous: just think about a link
2055 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2057 This link would show up in your Org-mode document as \"Google Search\",
2058 but really it would remove your entire home directory.
2059 Therefore we advise against setting this variable to nil.
2060 Just change it to `y-or-n-p' if you want to confirm with a
2061 single keystroke rather than having to type \"yes\"."
2062 :group 'org-link-follow
2063 :type '(choice
2064 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2065 (const :tag "with y-or-n (faster)" y-or-n-p)
2066 (const :tag "no confirmation (dangerous)" nil)))
2067 (put 'org-confirm-shell-link-function
2068 'safe-local-variable
2069 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2071 (defcustom org-confirm-elisp-link-not-regexp ""
2072 "A regexp to skip confirmation for Elisp links."
2073 :group 'org-link-follow
2074 :version "24.1"
2075 :type 'regexp)
2077 (defconst org-file-apps-defaults-gnu
2078 '((remote . emacs)
2079 (system . mailcap)
2080 (t . mailcap))
2081 "Default file applications on a UNIX or GNU/Linux system.
2082 See `org-file-apps'.")
2084 (defconst org-file-apps-defaults-macosx
2085 '((remote . emacs)
2086 (t . "open %s")
2087 (system . "open %s")
2088 ("ps.gz" . "gv %s")
2089 ("eps.gz" . "gv %s")
2090 ("dvi" . "xdvi %s")
2091 ("fig" . "xfig %s"))
2092 "Default file applications on a MacOS X system.
2093 The system \"open\" is known as a default, but we use X11 applications
2094 for some files for which the OS does not have a good default.
2095 See `org-file-apps'.")
2097 (defconst org-file-apps-defaults-windowsnt
2098 (list
2099 '(remote . emacs)
2100 (cons t
2101 (list (if (featurep 'xemacs)
2102 'mswindows-shell-execute
2103 'w32-shell-execute)
2104 "open" 'file))
2105 (cons 'system
2106 (list (if (featurep 'xemacs)
2107 'mswindows-shell-execute
2108 'w32-shell-execute)
2109 "open" 'file)))
2110 "Default file applications on a Windows NT system.
2111 The system \"open\" is used for most files.
2112 See `org-file-apps'.")
2114 (defcustom org-file-apps
2115 '((auto-mode . emacs)
2116 ("\\.mm\\'" . default)
2117 ("\\.x?html?\\'" . default)
2118 ("\\.pdf\\'" . default))
2119 "External applications for opening `file:path' items in a document.
2120 Org-mode uses system defaults for different file types, but
2121 you can use this variable to set the application for a given file
2122 extension. The entries in this list are cons cells where the car identifies
2123 files and the cdr the corresponding command. Possible values for the
2124 file identifier are
2125 \"string\" A string as a file identifier can be interpreted in different
2126 ways, depending on its contents:
2128 - Alphanumeric characters only:
2129 Match links with this file extension.
2130 Example: (\"pdf\" . \"evince %s\")
2131 to open PDFs with evince.
2133 - Regular expression: Match links where the
2134 filename matches the regexp. If you want to
2135 use groups here, use shy groups.
2137 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2138 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2139 to open *.html and *.xhtml with firefox.
2141 - Regular expression which contains (non-shy) groups:
2142 Match links where the whole link, including \"::\", and
2143 anything after that, matches the regexp.
2144 In a custom command string, %1, %2, etc. are replaced with
2145 the parts of the link that were matched by the groups.
2146 For backwards compatibility, if a command string is given
2147 that does not use any of the group matches, this case is
2148 handled identically to the second one (i.e. match against
2149 file name only).
2150 In a custom lisp form, you can access the group matches with
2151 (match-string n link).
2153 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2154 to open [[file:document.pdf::5]] with evince at page 5.
2156 `directory' Matches a directory
2157 `remote' Matches a remote file, accessible through tramp or efs.
2158 Remote files most likely should be visited through Emacs
2159 because external applications cannot handle such paths.
2160 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2161 so all files Emacs knows how to handle. Using this with
2162 command `emacs' will open most files in Emacs. Beware that this
2163 will also open html files inside Emacs, unless you add
2164 (\"html\" . default) to the list as well.
2165 t Default for files not matched by any of the other options.
2166 `system' The system command to open files, like `open' on Windows
2167 and Mac OS X, and mailcap under GNU/Linux. This is the command
2168 that will be selected if you call `C-c C-o' with a double
2169 \\[universal-argument] \\[universal-argument] prefix.
2171 Possible values for the command are:
2172 `emacs' The file will be visited by the current Emacs process.
2173 `default' Use the default application for this file type, which is the
2174 association for t in the list, most likely in the system-specific
2175 part.
2176 This can be used to overrule an unwanted setting in the
2177 system-specific variable.
2178 `system' Use the system command for opening files, like \"open\".
2179 This command is specified by the entry whose car is `system'.
2180 Most likely, the system-specific version of this variable
2181 does define this command, but you can overrule/replace it
2182 here.
2183 string A command to be executed by a shell; %s will be replaced
2184 by the path to the file.
2185 sexp A Lisp form which will be evaluated. The file path will
2186 be available in the Lisp variable `file'.
2187 For more examples, see the system specific constants
2188 `org-file-apps-defaults-macosx'
2189 `org-file-apps-defaults-windowsnt'
2190 `org-file-apps-defaults-gnu'."
2191 :group 'org-link-follow
2192 :type '(repeat
2193 (cons (choice :value ""
2194 (string :tag "Extension")
2195 (const :tag "System command to open files" system)
2196 (const :tag "Default for unrecognized files" t)
2197 (const :tag "Remote file" remote)
2198 (const :tag "Links to a directory" directory)
2199 (const :tag "Any files that have Emacs modes"
2200 auto-mode))
2201 (choice :value ""
2202 (const :tag "Visit with Emacs" emacs)
2203 (const :tag "Use default" default)
2204 (const :tag "Use the system command" system)
2205 (string :tag "Command")
2206 (sexp :tag "Lisp form")))))
2208 (defcustom org-doi-server-url "http://dx.doi.org/"
2209 "The URL of the DOI server."
2210 :type 'string
2211 :version "24.3"
2212 :group 'org-link-follow)
2214 (defgroup org-refile nil
2215 "Options concerning refiling entries in Org-mode."
2216 :tag "Org Refile"
2217 :group 'org)
2219 (defcustom org-directory "~/org"
2220 "Directory with org files.
2221 This is just a default location to look for Org files. There is no need
2222 at all to put your files into this directory. It is only used in the
2223 following situations:
2225 1. When a capture template specifies a target file that is not an
2226 absolute path. The path will then be interpreted relative to
2227 `org-directory'
2228 2. When a capture note is filed away in an interactive way (when exiting the
2229 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2230 with `org-directory' as the default path."
2231 :group 'org-refile
2232 :group 'org-capture
2233 :type 'directory)
2235 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2236 "Default target for storing notes.
2237 Used as a fall back file for org-capture.el, for templates that
2238 do not specify a target file."
2239 :group 'org-refile
2240 :group 'org-capture
2241 :type '(choice
2242 (const :tag "Default from remember-data-file" nil)
2243 file))
2245 (defcustom org-goto-interface 'outline
2246 "The default interface to be used for `org-goto'.
2247 Allowed values are:
2248 outline The interface shows an outline of the relevant file
2249 and the correct heading is found by moving through
2250 the outline or by searching with incremental search.
2251 outline-path-completion Headlines in the current buffer are offered via
2252 completion. This is the interface also used by
2253 the refile command."
2254 :group 'org-refile
2255 :type '(choice
2256 (const :tag "Outline" outline)
2257 (const :tag "Outline-path-completion" outline-path-completion)))
2259 (defcustom org-goto-max-level 5
2260 "Maximum target level when running `org-goto' with refile interface."
2261 :group 'org-refile
2262 :type 'integer)
2264 (defcustom org-reverse-note-order nil
2265 "Non-nil means store new notes at the beginning of a file or entry.
2266 When nil, new notes will be filed to the end of a file or entry.
2267 This can also be a list with cons cells of regular expressions that
2268 are matched against file names, and values."
2269 :group 'org-capture
2270 :group 'org-refile
2271 :type '(choice
2272 (const :tag "Reverse always" t)
2273 (const :tag "Reverse never" nil)
2274 (repeat :tag "By file name regexp"
2275 (cons regexp boolean))))
2277 (defcustom org-log-refile nil
2278 "Information to record when a task is refiled.
2280 Possible values are:
2282 nil Don't add anything
2283 time Add a time stamp to the task
2284 note Prompt for a note and add it with template `org-log-note-headings'
2286 This option can also be set with on a per-file-basis with
2288 #+STARTUP: nologrefile
2289 #+STARTUP: logrefile
2290 #+STARTUP: lognoterefile
2292 You can have local logging settings for a subtree by setting the LOGGING
2293 property to one or more of these keywords.
2295 When bulk-refiling from the agenda, the value `note' is forbidden and
2296 will temporarily be changed to `time'."
2297 :group 'org-refile
2298 :group 'org-progress
2299 :version "24.1"
2300 :type '(choice
2301 (const :tag "No logging" nil)
2302 (const :tag "Record timestamp" time)
2303 (const :tag "Record timestamp with note." note)))
2305 (defcustom org-refile-targets nil
2306 "Targets for refiling entries with \\[org-refile].
2307 This is a list of cons cells. Each cell contains:
2308 - a specification of the files to be considered, either a list of files,
2309 or a symbol whose function or variable value will be used to retrieve
2310 a file name or a list of file names. If you use `org-agenda-files' for
2311 that, all agenda files will be scanned for targets. Nil means consider
2312 headings in the current buffer.
2313 - A specification of how to find candidate refile targets. This may be
2314 any of:
2315 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2316 This tag has to be present in all target headlines, inheritance will
2317 not be considered.
2318 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2319 todo keyword.
2320 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2321 headlines that are refiling targets.
2322 - a cons cell (:level . N). Any headline of level N is considered a target.
2323 Note that, when `org-odd-levels-only' is set, level corresponds to
2324 order in hierarchy, not to the number of stars.
2325 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2326 Note that, when `org-odd-levels-only' is set, level corresponds to
2327 order in hierarchy, not to the number of stars.
2329 Each element of this list generates a set of possible targets.
2330 The union of these sets is presented (with completion) to
2331 the user by `org-refile'.
2333 You can set the variable `org-refile-target-verify-function' to a function
2334 to verify each headline found by the simple criteria above.
2336 When this variable is nil, all top-level headlines in the current buffer
2337 are used, equivalent to the value `((nil . (:level . 1))'."
2338 :group 'org-refile
2339 :type '(repeat
2340 (cons
2341 (choice :value org-agenda-files
2342 (const :tag "All agenda files" org-agenda-files)
2343 (const :tag "Current buffer" nil)
2344 (function) (variable) (file))
2345 (choice :tag "Identify target headline by"
2346 (cons :tag "Specific tag" (const :value :tag) (string))
2347 (cons :tag "TODO keyword" (const :value :todo) (string))
2348 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2349 (cons :tag "Level number" (const :value :level) (integer))
2350 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2352 (defcustom org-refile-target-verify-function nil
2353 "Function to verify if the headline at point should be a refile target.
2354 The function will be called without arguments, with point at the
2355 beginning of the headline. It should return t and leave point
2356 where it is if the headline is a valid target for refiling.
2358 If the target should not be selected, the function must return nil.
2359 In addition to this, it may move point to a place from where the search
2360 should be continued. For example, the function may decide that the entire
2361 subtree of the current entry should be excluded and move point to the end
2362 of the subtree."
2363 :group 'org-refile
2364 :type '(choice
2365 (const nil)
2366 (function)))
2368 (defcustom org-refile-use-cache nil
2369 "Non-nil means cache refile targets to speed up the process.
2370 The cache for a particular file will be updated automatically when
2371 the buffer has been killed, or when any of the marker used for flagging
2372 refile targets no longer points at a live buffer.
2373 If you have added new entries to a buffer that might themselves be targets,
2374 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2375 find that easier, `C-u C-u C-u C-c C-w'."
2376 :group 'org-refile
2377 :version "24.1"
2378 :type 'boolean)
2380 (defcustom org-refile-use-outline-path nil
2381 "Non-nil means provide refile targets as paths.
2382 So a level 3 headline will be available as level1/level2/level3.
2384 When the value is `file', also include the file name (without directory)
2385 into the path. In this case, you can also stop the completion after
2386 the file name, to get entries inserted as top level in the file.
2388 When `full-file-path', include the full file path."
2389 :group 'org-refile
2390 :type '(choice
2391 (const :tag "Not" nil)
2392 (const :tag "Yes" t)
2393 (const :tag "Start with file name" file)
2394 (const :tag "Start with full file path" full-file-path)))
2396 (defcustom org-outline-path-complete-in-steps t
2397 "Non-nil means complete the outline path in hierarchical steps.
2398 When Org-mode uses the refile interface to select an outline path
2399 \(see variable `org-refile-use-outline-path'), the completion of
2400 the path can be done is a single go, or if can be done in steps down
2401 the headline hierarchy. Going in steps is probably the best if you
2402 do not use a special completion package like `ido' or `icicles'.
2403 However, when using these packages, going in one step can be very
2404 fast, while still showing the whole path to the entry."
2405 :group 'org-refile
2406 :type 'boolean)
2408 (defcustom org-refile-allow-creating-parent-nodes nil
2409 "Non-nil means allow to create new nodes as refile targets.
2410 New nodes are then created by adding \"/new node name\" to the completion
2411 of an existing node. When the value of this variable is `confirm',
2412 new node creation must be confirmed by the user (recommended).
2413 When nil, the completion must match an existing entry.
2415 Note that, if the new heading is not seen by the criteria
2416 listed in `org-refile-targets', multiple instances of the same
2417 heading would be created by trying again to file under the new
2418 heading."
2419 :group 'org-refile
2420 :type '(choice
2421 (const :tag "Never" nil)
2422 (const :tag "Always" t)
2423 (const :tag "Prompt for confirmation" confirm)))
2425 (defcustom org-refile-active-region-within-subtree nil
2426 "Non-nil means also refile active region within a subtree.
2428 By default `org-refile' doesn't allow refiling regions if they
2429 don't contain a set of subtrees, but it might be convenient to
2430 do so sometimes: in that case, the first line of the region is
2431 converted to a headline before refiling."
2432 :group 'org-refile
2433 :version "24.1"
2434 :type 'boolean)
2436 (defgroup org-todo nil
2437 "Options concerning TODO items in Org-mode."
2438 :tag "Org TODO"
2439 :group 'org)
2441 (defgroup org-progress nil
2442 "Options concerning Progress logging in Org-mode."
2443 :tag "Org Progress"
2444 :group 'org-time)
2446 (defvar org-todo-interpretation-widgets
2447 '((:tag "Sequence (cycling hits every state)" sequence)
2448 (:tag "Type (cycling directly to DONE)" type))
2449 "The available interpretation symbols for customizing `org-todo-keywords'.
2450 Interested libraries should add to this list.")
2452 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2453 "List of TODO entry keyword sequences and their interpretation.
2454 \\<org-mode-map>This is a list of sequences.
2456 Each sequence starts with a symbol, either `sequence' or `type',
2457 indicating if the keywords should be interpreted as a sequence of
2458 action steps, or as different types of TODO items. The first
2459 keywords are states requiring action - these states will select a headline
2460 for inclusion into the global TODO list Org-mode produces. If one of
2461 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2462 signify that no further action is necessary. If \"|\" is not found,
2463 the last keyword is treated as the only DONE state of the sequence.
2465 The command \\[org-todo] cycles an entry through these states, and one
2466 additional state where no keyword is present. For details about this
2467 cycling, see the manual.
2469 TODO keywords and interpretation can also be set on a per-file basis with
2470 the special #+SEQ_TODO and #+TYP_TODO lines.
2472 Each keyword can optionally specify a character for fast state selection
2473 \(in combination with the variable `org-use-fast-todo-selection')
2474 and specifiers for state change logging, using the same syntax that
2475 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2476 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2477 indicates to record a time stamp each time this state is selected.
2479 Each keyword may also specify if a timestamp or a note should be
2480 recorded when entering or leaving the state, by adding additional
2481 characters in the parenthesis after the keyword. This looks like this:
2482 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2483 record only the time of the state change. With X and Y being either
2484 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2485 Y when leaving the state if and only if the *target* state does not
2486 define X. You may omit any of the fast-selection key or X or /Y,
2487 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2489 For backward compatibility, this variable may also be just a list
2490 of keywords. In this case the interpretation (sequence or type) will be
2491 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2492 :group 'org-todo
2493 :group 'org-keywords
2494 :type '(choice
2495 (repeat :tag "Old syntax, just keywords"
2496 (string :tag "Keyword"))
2497 (repeat :tag "New syntax"
2498 (cons
2499 (choice
2500 :tag "Interpretation"
2501 ;;Quick and dirty way to see
2502 ;;`org-todo-interpretations'. This takes the
2503 ;;place of item arguments
2504 :convert-widget
2505 (lambda (widget)
2506 (widget-put widget
2507 :args (mapcar
2508 (lambda (x)
2509 (widget-convert
2510 (cons 'const x)))
2511 org-todo-interpretation-widgets))
2512 widget))
2513 (repeat
2514 (string :tag "Keyword"))))))
2516 (defvar org-todo-keywords-1 nil
2517 "All TODO and DONE keywords active in a buffer.")
2518 (make-variable-buffer-local 'org-todo-keywords-1)
2519 (defvar org-todo-keywords-for-agenda nil)
2520 (defvar org-done-keywords-for-agenda nil)
2521 (defvar org-todo-keyword-alist-for-agenda nil)
2522 (defvar org-tag-alist-for-agenda nil
2523 "Alist of all tags from all agenda files.")
2524 (defvar org-tag-groups-alist-for-agenda nil
2525 "Alist of all groups tags from all current agenda files.")
2526 (defvar org-tag-groups-alist nil)
2527 (make-variable-buffer-local 'org-tag-groups-alist)
2528 (defvar org-agenda-contributing-files nil)
2529 (defvar org-not-done-keywords nil)
2530 (make-variable-buffer-local 'org-not-done-keywords)
2531 (defvar org-done-keywords nil)
2532 (make-variable-buffer-local 'org-done-keywords)
2533 (defvar org-todo-heads nil)
2534 (make-variable-buffer-local 'org-todo-heads)
2535 (defvar org-todo-sets nil)
2536 (make-variable-buffer-local 'org-todo-sets)
2537 (defvar org-todo-log-states nil)
2538 (make-variable-buffer-local 'org-todo-log-states)
2539 (defvar org-todo-kwd-alist nil)
2540 (make-variable-buffer-local 'org-todo-kwd-alist)
2541 (defvar org-todo-key-alist nil)
2542 (make-variable-buffer-local 'org-todo-key-alist)
2543 (defvar org-todo-key-trigger nil)
2544 (make-variable-buffer-local 'org-todo-key-trigger)
2546 (defcustom org-todo-interpretation 'sequence
2547 "Controls how TODO keywords are interpreted.
2548 This variable is in principle obsolete and is only used for
2549 backward compatibility, if the interpretation of todo keywords is
2550 not given already in `org-todo-keywords'. See that variable for
2551 more information."
2552 :group 'org-todo
2553 :group 'org-keywords
2554 :type '(choice (const sequence)
2555 (const type)))
2557 (defcustom org-use-fast-todo-selection t
2558 "Non-nil means use the fast todo selection scheme with C-c C-t.
2559 This variable describes if and under what circumstances the cycling
2560 mechanism for TODO keywords will be replaced by a single-key, direct
2561 selection scheme.
2563 When nil, fast selection is never used.
2565 When the symbol `prefix', it will be used when `org-todo' is called
2566 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2567 `C-u t' in an agenda buffer.
2569 When t, fast selection is used by default. In this case, the prefix
2570 argument forces cycling instead.
2572 In all cases, the special interface is only used if access keys have
2573 actually been assigned by the user, i.e. if keywords in the configuration
2574 are followed by a letter in parenthesis, like TODO(t)."
2575 :group 'org-todo
2576 :type '(choice
2577 (const :tag "Never" nil)
2578 (const :tag "By default" t)
2579 (const :tag "Only with C-u C-c C-t" prefix)))
2581 (defcustom org-provide-todo-statistics t
2582 "Non-nil means update todo statistics after insert and toggle.
2583 ALL-HEADLINES means update todo statistics by including headlines
2584 with no TODO keyword as well, counting them as not done.
2585 A list of TODO keywords means the same, but skip keywords that are
2586 not in this list.
2587 When set to a list of two lists, the first list contains keywords
2588 to consider as TODO keywords, the second list contains keywords
2589 to consider as DONE keywords.
2591 When this is set, todo statistics is updated in the parent of the
2592 current entry each time a todo state is changed."
2593 :group 'org-todo
2594 :type '(choice
2595 (const :tag "Yes, only for TODO entries" t)
2596 (const :tag "Yes, including all entries" all-headlines)
2597 (repeat :tag "Yes, for TODOs in this list"
2598 (string :tag "TODO keyword"))
2599 (list :tag "Yes, for TODOs and DONEs in these lists"
2600 (repeat (string :tag "TODO keyword"))
2601 (repeat (string :tag "DONE keyword")))
2602 (other :tag "No TODO statistics" nil)))
2604 (defcustom org-hierarchical-todo-statistics t
2605 "Non-nil means TODO statistics covers just direct children.
2606 When nil, all entries in the subtree are considered.
2607 This has only an effect if `org-provide-todo-statistics' is set.
2608 To set this to nil for only a single subtree, use a COOKIE_DATA
2609 property and include the word \"recursive\" into the value."
2610 :group 'org-todo
2611 :type 'boolean)
2613 (defcustom org-after-todo-state-change-hook nil
2614 "Hook which is run after the state of a TODO item was changed.
2615 The new state (a string with a TODO keyword, or nil) is available in the
2616 Lisp variable `org-state'."
2617 :group 'org-todo
2618 :type 'hook)
2620 (defvar org-blocker-hook nil
2621 "Hook for functions that are allowed to block a state change.
2623 Functions in this hook should not modify the buffer.
2624 Each function gets as its single argument a property list,
2625 see `org-trigger-hook' for more information about this list.
2627 If any of the functions in this hook returns nil, the state change
2628 is blocked.")
2630 (defvar org-trigger-hook nil
2631 "Hook for functions that are triggered by a state change.
2633 Each function gets as its single argument a property list with at
2634 least the following elements:
2636 (:type type-of-change :position pos-at-entry-start
2637 :from old-state :to new-state)
2639 Depending on the type, more properties may be present.
2641 This mechanism is currently implemented for:
2643 TODO state changes
2644 ------------------
2645 :type todo-state-change
2646 :from previous state (keyword as a string), or nil, or a symbol
2647 'todo' or 'done', to indicate the general type of state.
2648 :to new state, like in :from")
2650 (defcustom org-enforce-todo-dependencies nil
2651 "Non-nil means undone TODO entries will block switching the parent to DONE.
2652 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2653 be blocked if any prior sibling is not yet done.
2654 Finally, if the parent is blocked because of ordered siblings of its own,
2655 the child will also be blocked."
2656 :set (lambda (var val)
2657 (set var val)
2658 (if val
2659 (add-hook 'org-blocker-hook
2660 'org-block-todo-from-children-or-siblings-or-parent)
2661 (remove-hook 'org-blocker-hook
2662 'org-block-todo-from-children-or-siblings-or-parent)))
2663 :group 'org-todo
2664 :type 'boolean)
2666 (defcustom org-enforce-todo-checkbox-dependencies nil
2667 "Non-nil means unchecked boxes will block switching the parent to DONE.
2668 When this is nil, checkboxes have no influence on switching TODO states.
2669 When non-nil, you first need to check off all check boxes before the TODO
2670 entry can be switched to DONE.
2671 This variable needs to be set before org.el is loaded, and you need to
2672 restart Emacs after a change to make the change effective. The only way
2673 to change is while Emacs is running is through the customize interface."
2674 :set (lambda (var val)
2675 (set var val)
2676 (if val
2677 (add-hook 'org-blocker-hook
2678 'org-block-todo-from-checkboxes)
2679 (remove-hook 'org-blocker-hook
2680 'org-block-todo-from-checkboxes)))
2681 :group 'org-todo
2682 :type 'boolean)
2684 (defcustom org-treat-insert-todo-heading-as-state-change nil
2685 "Non-nil means inserting a TODO heading is treated as state change.
2686 So when the command \\[org-insert-todo-heading] is used, state change
2687 logging will apply if appropriate. When nil, the new TODO item will
2688 be inserted directly, and no logging will take place."
2689 :group 'org-todo
2690 :type 'boolean)
2692 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2693 "Non-nil means switching TODO states with S-cursor counts as state change.
2694 This is the default behavior. However, setting this to nil allows a
2695 convenient way to select a TODO state and bypass any logging associated
2696 with that."
2697 :group 'org-todo
2698 :type 'boolean)
2700 (defcustom org-todo-state-tags-triggers nil
2701 "Tag changes that should be triggered by TODO state changes.
2702 This is a list. Each entry is
2704 (state-change (tag . flag) .......)
2706 State-change can be a string with a state, and empty string to indicate the
2707 state that has no TODO keyword, or it can be one of the symbols `todo'
2708 or `done', meaning any not-done or done state, respectively."
2709 :group 'org-todo
2710 :group 'org-tags
2711 :type '(repeat
2712 (cons (choice :tag "When changing to"
2713 (const :tag "Not-done state" todo)
2714 (const :tag "Done state" done)
2715 (string :tag "State"))
2716 (repeat
2717 (cons :tag "Tag action"
2718 (string :tag "Tag")
2719 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2721 (defcustom org-log-done nil
2722 "Information to record when a task moves to the DONE state.
2724 Possible values are:
2726 nil Don't add anything, just change the keyword
2727 time Add a time stamp to the task
2728 note Prompt for a note and add it with template `org-log-note-headings'
2730 This option can also be set with on a per-file-basis with
2732 #+STARTUP: nologdone
2733 #+STARTUP: logdone
2734 #+STARTUP: lognotedone
2736 You can have local logging settings for a subtree by setting the LOGGING
2737 property to one or more of these keywords."
2738 :group 'org-todo
2739 :group 'org-progress
2740 :type '(choice
2741 (const :tag "No logging" nil)
2742 (const :tag "Record CLOSED timestamp" time)
2743 (const :tag "Record CLOSED timestamp with note." note)))
2745 ;; Normalize old uses of org-log-done.
2746 (cond
2747 ((eq org-log-done t) (setq org-log-done 'time))
2748 ((and (listp org-log-done) (memq 'done org-log-done))
2749 (setq org-log-done 'note)))
2751 (defcustom org-log-reschedule nil
2752 "Information to record when the scheduling date of a tasks is modified.
2754 Possible values are:
2756 nil Don't add anything, just change the date
2757 time Add a time stamp to the task
2758 note Prompt for a note and add it with template `org-log-note-headings'
2760 This option can also be set with on a per-file-basis with
2762 #+STARTUP: nologreschedule
2763 #+STARTUP: logreschedule
2764 #+STARTUP: lognotereschedule"
2765 :group 'org-todo
2766 :group 'org-progress
2767 :type '(choice
2768 (const :tag "No logging" nil)
2769 (const :tag "Record timestamp" time)
2770 (const :tag "Record timestamp with note." note)))
2772 (defcustom org-log-redeadline nil
2773 "Information to record when the deadline date of a tasks is modified.
2775 Possible values are:
2777 nil Don't add anything, just change the date
2778 time Add a time stamp to the task
2779 note Prompt for a note and add it with template `org-log-note-headings'
2781 This option can also be set with on a per-file-basis with
2783 #+STARTUP: nologredeadline
2784 #+STARTUP: logredeadline
2785 #+STARTUP: lognoteredeadline
2787 You can have local logging settings for a subtree by setting the LOGGING
2788 property to one or more of these keywords."
2789 :group 'org-todo
2790 :group 'org-progress
2791 :type '(choice
2792 (const :tag "No logging" nil)
2793 (const :tag "Record timestamp" time)
2794 (const :tag "Record timestamp with note." note)))
2796 (defcustom org-log-note-clock-out nil
2797 "Non-nil means record a note when clocking out of an item.
2798 This can also be configured on a per-file basis by adding one of
2799 the following lines anywhere in the buffer:
2801 #+STARTUP: lognoteclock-out
2802 #+STARTUP: nolognoteclock-out"
2803 :group 'org-todo
2804 :group 'org-progress
2805 :type 'boolean)
2807 (defcustom org-log-done-with-time t
2808 "Non-nil means the CLOSED time stamp will contain date and time.
2809 When nil, only the date will be recorded."
2810 :group 'org-progress
2811 :type 'boolean)
2813 (defcustom org-log-note-headings
2814 '((done . "CLOSING NOTE %t")
2815 (state . "State %-12s from %-12S %t")
2816 (note . "Note taken on %t")
2817 (reschedule . "Rescheduled from %S on %t")
2818 (delschedule . "Not scheduled, was %S on %t")
2819 (redeadline . "New deadline from %S on %t")
2820 (deldeadline . "Removed deadline, was %S on %t")
2821 (refile . "Refiled on %t")
2822 (clock-out . ""))
2823 "Headings for notes added to entries.
2824 The value is an alist, with the car being a symbol indicating the note
2825 context, and the cdr is the heading to be used. The heading may also be the
2826 empty string.
2827 %t in the heading will be replaced by a time stamp.
2828 %T will be an active time stamp instead the default inactive one
2829 %d will be replaced by a short-format time stamp.
2830 %D will be replaced by an active short-format time stamp.
2831 %s will be replaced by the new TODO state, in double quotes.
2832 %S will be replaced by the old TODO state, in double quotes.
2833 %u will be replaced by the user name.
2834 %U will be replaced by the full user name.
2836 In fact, it is not a good idea to change the `state' entry, because
2837 agenda log mode depends on the format of these entries."
2838 :group 'org-todo
2839 :group 'org-progress
2840 :type '(list :greedy t
2841 (cons (const :tag "Heading when closing an item" done) string)
2842 (cons (const :tag
2843 "Heading when changing todo state (todo sequence only)"
2844 state) string)
2845 (cons (const :tag "Heading when just taking a note" note) string)
2846 (cons (const :tag "Heading when rescheduling" reschedule) string)
2847 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2848 (cons (const :tag "Heading when changing deadline" redeadline) string)
2849 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2850 (cons (const :tag "Heading when refiling" refile) string)
2851 (cons (const :tag "Heading when clocking out" clock-out) string)))
2853 (unless (assq 'note org-log-note-headings)
2854 (push '(note . "%t") org-log-note-headings))
2856 (defcustom org-log-into-drawer nil
2857 "Non-nil means insert state change notes and time stamps into a drawer.
2858 When nil, state changes notes will be inserted after the headline and
2859 any scheduling and clock lines, but not inside a drawer.
2861 The value of this variable should be the name of the drawer to use.
2862 LOGBOOK is proposed as the default drawer for this purpose, you can
2863 also set this to a string to define the drawer of your choice.
2865 A value of t is also allowed, representing \"LOGBOOK\".
2867 A value of t or nil can also be set with on a per-file-basis with
2869 #+STARTUP: logdrawer
2870 #+STARTUP: nologdrawer
2872 If this variable is set, `org-log-state-notes-insert-after-drawers'
2873 will be ignored.
2875 You can set the property LOG_INTO_DRAWER to overrule this setting for
2876 a subtree."
2877 :group 'org-todo
2878 :group 'org-progress
2879 :type '(choice
2880 (const :tag "Not into a drawer" nil)
2881 (const :tag "LOGBOOK" t)
2882 (string :tag "Other")))
2884 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2886 (defun org-log-into-drawer ()
2887 "Return the value of `org-log-into-drawer', but let properties overrule.
2888 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2889 used instead of the default value."
2890 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2891 (cond
2892 ((not p) org-log-into-drawer)
2893 ((equal p "nil") nil)
2894 ((equal p "t") "LOGBOOK")
2895 (t p))))
2897 (defcustom org-log-state-notes-insert-after-drawers nil
2898 "Non-nil means insert state change notes after any drawers in entry.
2899 Only the drawers that *immediately* follow the headline and the
2900 deadline/scheduled line are skipped.
2901 When nil, insert notes right after the heading and perhaps the line
2902 with deadline/scheduling if present.
2904 This variable will have no effect if `org-log-into-drawer' is
2905 set."
2906 :group 'org-todo
2907 :group 'org-progress
2908 :type 'boolean)
2910 (defcustom org-log-states-order-reversed t
2911 "Non-nil means the latest state note will be directly after heading.
2912 When nil, the state change notes will be ordered according to time.
2914 This option can also be set with on a per-file-basis with
2916 #+STARTUP: logstatesreversed
2917 #+STARTUP: nologstatesreversed"
2918 :group 'org-todo
2919 :group 'org-progress
2920 :type 'boolean)
2922 (defcustom org-todo-repeat-to-state nil
2923 "The TODO state to which a repeater should return the repeating task.
2924 By default this is the first task in a TODO sequence, or the previous state
2925 in a TODO_TYP set. But you can specify another task here.
2926 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2927 :group 'org-todo
2928 :version "24.1"
2929 :type '(choice (const :tag "Head of sequence" nil)
2930 (string :tag "Specific state")))
2932 (defcustom org-log-repeat 'time
2933 "Non-nil means record moving through the DONE state when triggering repeat.
2934 An auto-repeating task is immediately switched back to TODO when
2935 marked DONE. If you are not logging state changes (by adding \"@\"
2936 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2937 record a closing note, there will be no record of the task moving
2938 through DONE. This variable forces taking a note anyway.
2940 nil Don't force a record
2941 time Record a time stamp
2942 note Prompt for a note and add it with template `org-log-note-headings'
2944 This option can also be set with on a per-file-basis with
2946 #+STARTUP: nologrepeat
2947 #+STARTUP: logrepeat
2948 #+STARTUP: lognoterepeat
2950 You can have local logging settings for a subtree by setting the LOGGING
2951 property to one or more of these keywords."
2952 :group 'org-todo
2953 :group 'org-progress
2954 :type '(choice
2955 (const :tag "Don't force a record" nil)
2956 (const :tag "Force recording the DONE state" time)
2957 (const :tag "Force recording a note with the DONE state" note)))
2960 (defgroup org-priorities nil
2961 "Priorities in Org-mode."
2962 :tag "Org Priorities"
2963 :group 'org-todo)
2965 (defcustom org-enable-priority-commands t
2966 "Non-nil means priority commands are active.
2967 When nil, these commands will be disabled, so that you never accidentally
2968 set a priority."
2969 :group 'org-priorities
2970 :type 'boolean)
2972 (defcustom org-highest-priority ?A
2973 "The highest priority of TODO items. A character like ?A, ?B etc.
2974 Must have a smaller ASCII number than `org-lowest-priority'."
2975 :group 'org-priorities
2976 :type 'character)
2978 (defcustom org-lowest-priority ?C
2979 "The lowest priority of TODO items. A character like ?A, ?B etc.
2980 Must have a larger ASCII number than `org-highest-priority'."
2981 :group 'org-priorities
2982 :type 'character)
2984 (defcustom org-default-priority ?B
2985 "The default priority of TODO items.
2986 This is the priority an item gets if no explicit priority is given.
2987 When starting to cycle on an empty priority the first step in the cycle
2988 depends on `org-priority-start-cycle-with-default'. The resulting first
2989 step priority must not exceed the range from `org-highest-priority' to
2990 `org-lowest-priority' which means that `org-default-priority' has to be
2991 in this range exclusive or inclusive the range boundaries. Else the
2992 first step refuses to set the default and the second will fall back
2993 to (depending on the command used) the highest or lowest priority."
2994 :group 'org-priorities
2995 :type 'character)
2997 (defcustom org-priority-start-cycle-with-default t
2998 "Non-nil means start with default priority when starting to cycle.
2999 When this is nil, the first step in the cycle will be (depending on the
3000 command used) one higher or lower than the default priority.
3001 See also `org-default-priority'."
3002 :group 'org-priorities
3003 :type 'boolean)
3005 (defcustom org-get-priority-function nil
3006 "Function to extract the priority from a string.
3007 The string is normally the headline. If this is nil Org computes the
3008 priority from the priority cookie like [#A] in the headline. It returns
3009 an integer, increasing by 1000 for each priority level.
3010 The user can set a different function here, which should take a string
3011 as an argument and return the numeric priority."
3012 :group 'org-priorities
3013 :version "24.1"
3014 :type '(choice
3015 (const nil)
3016 (function)))
3018 (defgroup org-time nil
3019 "Options concerning time stamps and deadlines in Org-mode."
3020 :tag "Org Time"
3021 :group 'org)
3023 (defcustom org-insert-labeled-timestamps-at-point nil
3024 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3025 When nil, these labeled time stamps are forces into the second line of an
3026 entry, just after the headline. When scheduling from the global TODO list,
3027 the time stamp will always be forced into the second line."
3028 :group 'org-time
3029 :type 'boolean)
3031 (defcustom org-time-stamp-rounding-minutes '(0 5)
3032 "Number of minutes to round time stamps to.
3033 These are two values, the first applies when first creating a time stamp.
3034 The second applies when changing it with the commands `S-up' and `S-down'.
3035 When changing the time stamp, this means that it will change in steps
3036 of N minutes, as given by the second value.
3038 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3039 numbers should be factors of 60, so for example 5, 10, 15.
3041 When this is larger than 1, you can still force an exact time stamp by using
3042 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3043 and by using a prefix arg to `S-up/down' to specify the exact number
3044 of minutes to shift."
3045 :group 'org-time
3046 :get (lambda (var) ; Make sure both elements are there
3047 (if (integerp (default-value var))
3048 (list (default-value var) 5)
3049 (default-value var)))
3050 :type '(list
3051 (integer :tag "when inserting times")
3052 (integer :tag "when modifying times")))
3054 ;; Normalize old customizations of this variable.
3055 (when (integerp org-time-stamp-rounding-minutes)
3056 (setq org-time-stamp-rounding-minutes
3057 (list org-time-stamp-rounding-minutes
3058 org-time-stamp-rounding-minutes)))
3060 (defcustom org-display-custom-times nil
3061 "Non-nil means overlay custom formats over all time stamps.
3062 The formats are defined through the variable `org-time-stamp-custom-formats'.
3063 To turn this on on a per-file basis, insert anywhere in the file:
3064 #+STARTUP: customtime"
3065 :group 'org-time
3066 :set 'set-default
3067 :type 'sexp)
3068 (make-variable-buffer-local 'org-display-custom-times)
3070 (defcustom org-time-stamp-custom-formats
3071 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3072 "Custom formats for time stamps. See `format-time-string' for the syntax.
3073 These are overlaid over the default ISO format if the variable
3074 `org-display-custom-times' is set. Time like %H:%M should be at the
3075 end of the second format. The custom formats are also honored by export
3076 commands, if custom time display is turned on at the time of export."
3077 :group 'org-time
3078 :type 'sexp)
3080 (defun org-time-stamp-format (&optional long inactive)
3081 "Get the right format for a time string."
3082 (let ((f (if long (cdr org-time-stamp-formats)
3083 (car org-time-stamp-formats))))
3084 (if inactive
3085 (concat "[" (substring f 1 -1) "]")
3086 f)))
3088 (defcustom org-time-clocksum-format
3089 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3090 "The format string used when creating CLOCKSUM lines.
3091 This is also used when Org mode generates a time duration.
3093 The value can be a single format string containing two
3094 %-sequences, which will be filled with the number of hours and
3095 minutes in that order.
3097 Alternatively, the value can be a plist associating any of the
3098 keys :years, :months, :weeks, :days, :hours or :minutes with
3099 format strings. The time duration is formatted using only the
3100 time components that are needed and concatenating the results.
3101 If a time unit in absent, it falls back to the next smallest
3102 unit.
3104 The keys :require-years, :require-months, :require-days,
3105 :require-weeks, :require-hours, :require-minutes are also
3106 meaningful. A non-nil value for these keys indicates that the
3107 corresponding time component should always be included, even if
3108 its value is 0.
3111 For example,
3113 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3114 :require-minutes t)
3116 means durations longer than a day will be expressed in days,
3117 hours and minutes, and durations less than a day will always be
3118 expressed in hours and minutes (even for durations less than an
3119 hour).
3121 The value
3123 \(:days \"%dd\" :minutes \"%dm\")
3125 means durations longer than a day will be expressed in days and
3126 minutes, and durations less than a day will be expressed entirely
3127 in minutes (even for durations longer than an hour)."
3128 :group 'org-time
3129 :group 'org-clock
3130 :version "24.4"
3131 :package-version '(Org . "8.0")
3132 :type '(choice (string :tag "Format string")
3133 (set :tag "Plist"
3134 (group :inline t (const :tag "Years" :years)
3135 (string :tag "Format string"))
3136 (group :inline t
3137 (const :tag "Always show years" :require-years)
3138 (const t))
3139 (group :inline t (const :tag "Months" :months)
3140 (string :tag "Format string"))
3141 (group :inline t
3142 (const :tag "Always show months" :require-months)
3143 (const t))
3144 (group :inline t (const :tag "Weeks" :weeks)
3145 (string :tag "Format string"))
3146 (group :inline t
3147 (const :tag "Always show weeks" :require-weeks)
3148 (const t))
3149 (group :inline t (const :tag "Days" :days)
3150 (string :tag "Format string"))
3151 (group :inline t
3152 (const :tag "Always show days" :require-days)
3153 (const t))
3154 (group :inline t (const :tag "Hours" :hours)
3155 (string :tag "Format string"))
3156 (group :inline t
3157 (const :tag "Always show hours" :require-hours)
3158 (const t))
3159 (group :inline t (const :tag "Minutes" :minutes)
3160 (string :tag "Format string"))
3161 (group :inline t
3162 (const :tag "Always show minutes" :require-minutes)
3163 (const t)))))
3165 (defcustom org-time-clocksum-use-fractional nil
3166 "When non-nil, \\[org-clock-display] uses fractional times.
3167 See `org-time-clocksum-format' for more on time clock formats."
3168 :group 'org-time
3169 :group 'org-clock
3170 :version "24.3"
3171 :type 'boolean)
3173 (defcustom org-time-clocksum-use-effort-durations nil
3174 "When non-nil, \\[org-clock-display] uses effort durations.
3175 E.g. by default, one day is considered to be a 8 hours effort,
3176 so a task that has been clocked for 16 hours will be displayed
3177 as during 2 days in the clock display or in the clocktable.
3179 See `org-effort-durations' on how to set effort durations
3180 and `org-time-clocksum-format' for more on time clock formats."
3181 :group 'org-time
3182 :group 'org-clock
3183 :version "24.4"
3184 :package-version '(Org . "8.0")
3185 :type 'boolean)
3187 (defcustom org-time-clocksum-fractional-format "%.2f"
3188 "The format string used when creating CLOCKSUM lines,
3189 or when Org mode generates a time duration, if
3190 `org-time-clocksum-use-fractional' is enabled.
3192 The value can be a single format string containing one
3193 %-sequence, which will be filled with the number of hours as
3194 a float.
3196 Alternatively, the value can be a plist associating any of the
3197 keys :years, :months, :weeks, :days, :hours or :minutes with
3198 a format string. The time duration is formatted using the
3199 largest time unit which gives a non-zero integer part. If all
3200 specified formats have zero integer part, the smallest time unit
3201 is used."
3202 :group 'org-time
3203 :type '(choice (string :tag "Format string")
3204 (set (group :inline t (const :tag "Years" :years)
3205 (string :tag "Format string"))
3206 (group :inline t (const :tag "Months" :months)
3207 (string :tag "Format string"))
3208 (group :inline t (const :tag "Weeks" :weeks)
3209 (string :tag "Format string"))
3210 (group :inline t (const :tag "Days" :days)
3211 (string :tag "Format string"))
3212 (group :inline t (const :tag "Hours" :hours)
3213 (string :tag "Format string"))
3214 (group :inline t (const :tag "Minutes" :minutes)
3215 (string :tag "Format string")))))
3217 (defcustom org-deadline-warning-days 14
3218 "Number of days before expiration during which a deadline becomes active.
3219 This variable governs the display in sparse trees and in the agenda.
3220 When 0 or negative, it means use this number (the absolute value of it)
3221 even if a deadline has a different individual lead time specified.
3223 Custom commands can set this variable in the options section."
3224 :group 'org-time
3225 :group 'org-agenda-daily/weekly
3226 :type 'integer)
3228 (defcustom org-scheduled-delay-days 0
3229 "Number of days before a scheduled item becomes active.
3230 This variable governs the display in sparse trees and in the agenda.
3231 The default value (i.e. 0) means: don't delay scheduled item.
3232 When negative, it means use this number (the absolute value of it)
3233 even if a scheduled item has a different individual delay time
3234 specified.
3236 Custom commands can set this variable in the options section."
3237 :group 'org-time
3238 :group 'org-agenda-daily/weekly
3239 :version "24.4"
3240 :package-version '(Org . "8.0")
3241 :type 'integer)
3243 (defcustom org-read-date-prefer-future t
3244 "Non-nil means assume future for incomplete date input from user.
3245 This affects the following situations:
3246 1. The user gives a month but not a year.
3247 For example, if it is April and you enter \"feb 2\", this will be read
3248 as Feb 2, *next* year. \"May 5\", however, will be this year.
3249 2. The user gives a day, but no month.
3250 For example, if today is the 15th, and you enter \"3\", Org-mode will
3251 read this as the third of *next* month. However, if you enter \"17\",
3252 it will be considered as *this* month.
3254 If you set this variable to the symbol `time', then also the following
3255 will work:
3257 3. If the user gives a time.
3258 If the time is before now, it will be interpreted as tomorrow.
3260 Currently none of this works for ISO week specifications.
3262 When this option is nil, the current day, month and year will always be
3263 used as defaults.
3265 See also `org-agenda-jump-prefer-future'."
3266 :group 'org-time
3267 :type '(choice
3268 (const :tag "Never" nil)
3269 (const :tag "Check month and day" t)
3270 (const :tag "Check month, day, and time" time)))
3272 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3273 "Should the agenda jump command prefer the future for incomplete dates?
3274 The default is to do the same as configured in `org-read-date-prefer-future'.
3275 But you can also set a deviating value here.
3276 This may t or nil, or the symbol `org-read-date-prefer-future'."
3277 :group 'org-agenda
3278 :group 'org-time
3279 :version "24.1"
3280 :type '(choice
3281 (const :tag "Use org-read-date-prefer-future"
3282 org-read-date-prefer-future)
3283 (const :tag "Never" nil)
3284 (const :tag "Always" t)))
3286 (defcustom org-read-date-force-compatible-dates t
3287 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3289 Depending on the system Emacs is running on, certain dates cannot
3290 be represented with the type used internally to represent time.
3291 Dates between 1970-1-1 and 2038-1-1 can always be represented
3292 correctly. Some systems allow for earlier dates, some for later,
3293 some for both. One way to find out it to insert any date into an
3294 Org buffer, putting the cursor on the year and hitting S-up and
3295 S-down to test the range.
3297 When this variable is set to t, the date/time prompt will not let
3298 you specify dates outside the 1970-2037 range, so it is certain that
3299 these dates will work in whatever version of Emacs you are
3300 running, and also that you can move a file from one Emacs implementation
3301 to another. WHenever Org is forcing the year for you, it will display
3302 a message and beep.
3304 When this variable is nil, Org will check if the date is
3305 representable in the specific Emacs implementation you are using.
3306 If not, it will force a year, usually the current year, and beep
3307 to remind you. Currently this setting is not recommended because
3308 the likelihood that you will open your Org files in an Emacs that
3309 has limited date range is not negligible.
3311 A workaround for this problem is to use diary sexp dates for time
3312 stamps outside of this range."
3313 :group 'org-time
3314 :version "24.1"
3315 :type 'boolean)
3317 (defcustom org-read-date-display-live t
3318 "Non-nil means display current interpretation of date prompt live.
3319 This display will be in an overlay, in the minibuffer."
3320 :group 'org-time
3321 :type 'boolean)
3323 (defcustom org-read-date-popup-calendar t
3324 "Non-nil means pop up a calendar when prompting for a date.
3325 In the calendar, the date can be selected with mouse-1. However, the
3326 minibuffer will also be active, and you can simply enter the date as well.
3327 When nil, only the minibuffer will be available."
3328 :group 'org-time
3329 :type 'boolean)
3330 (org-defvaralias 'org-popup-calendar-for-date-prompt
3331 'org-read-date-popup-calendar)
3333 (make-obsolete-variable
3334 'org-read-date-minibuffer-setup-hook
3335 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3336 (defcustom org-read-date-minibuffer-setup-hook nil
3337 "Hook to be used to set up keys for the date/time interface.
3338 Add key definitions to `minibuffer-local-map', which will be a
3339 temporary copy.
3341 WARNING: This option is obsolete, you should use
3342 `org-read-date-minibuffer-local-map' to set up keys."
3343 :group 'org-time
3344 :type 'hook)
3346 (defcustom org-extend-today-until 0
3347 "The hour when your day really ends. Must be an integer.
3348 This has influence for the following applications:
3349 - When switching the agenda to \"today\". It it is still earlier than
3350 the time given here, the day recognized as TODAY is actually yesterday.
3351 - When a date is read from the user and it is still before the time given
3352 here, the current date and time will be assumed to be yesterday, 23:59.
3353 Also, timestamps inserted in capture templates follow this rule.
3355 IMPORTANT: This is a feature whose implementation is and likely will
3356 remain incomplete. Really, it is only here because past midnight seems to
3357 be the favorite working time of John Wiegley :-)"
3358 :group 'org-time
3359 :type 'integer)
3361 (defcustom org-use-effective-time nil
3362 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3363 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3364 \"effective time\" of any timestamps between midnight and 8am will be
3365 23:59 of the previous day."
3366 :group 'org-time
3367 :version "24.1"
3368 :type 'boolean)
3370 (defcustom org-use-last-clock-out-time-as-effective-time nil
3371 "When non-nil, use the last clock out time for `org-todo'.
3372 Note that this option has precedence over the combined use of
3373 `org-use-effective-time' and `org-extend-today-until'."
3374 :group 'org-time
3375 :version "24.4"
3376 :package-version '(Org . "8.0")
3377 :type 'boolean)
3379 (defcustom org-edit-timestamp-down-means-later nil
3380 "Non-nil means S-down will increase the time in a time stamp.
3381 When nil, S-up will increase."
3382 :group 'org-time
3383 :type 'boolean)
3385 (defcustom org-calendar-follow-timestamp-change t
3386 "Non-nil means make the calendar window follow timestamp changes.
3387 When a timestamp is modified and the calendar window is visible, it will be
3388 moved to the new date."
3389 :group 'org-time
3390 :type 'boolean)
3392 (defgroup org-tags nil
3393 "Options concerning tags in Org-mode."
3394 :tag "Org Tags"
3395 :group 'org)
3397 (defcustom org-tag-alist nil
3398 "List of tags allowed in Org-mode files.
3399 When this list is nil, Org-mode will base TAG input on what is already in the
3400 buffer.
3401 The value of this variable is an alist, the car of each entry must be a
3402 keyword as a string, the cdr may be a character that is used to select
3403 that tag through the fast-tag-selection interface.
3404 See the manual for details."
3405 :group 'org-tags
3406 :type '(repeat
3407 (choice
3408 (cons (string :tag "Tag name")
3409 (character :tag "Access char"))
3410 (list :tag "Start radio group"
3411 (const :startgroup)
3412 (option (string :tag "Group description")))
3413 (list :tag "Group tags delimiter"
3414 (const :grouptags))
3415 (list :tag "End radio group"
3416 (const :endgroup)
3417 (option (string :tag "Group description")))
3418 (const :tag "New line" (:newline)))))
3420 (defcustom org-tag-persistent-alist nil
3421 "List of tags that will always appear in all Org-mode files.
3422 This is in addition to any in buffer settings or customizations
3423 of `org-tag-alist'.
3424 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3425 The value of this variable is an alist, the car of each entry must be a
3426 keyword as a string, the cdr may be a character that is used to select
3427 that tag through the fast-tag-selection interface.
3428 See the manual for details.
3429 To disable these tags on a per-file basis, insert anywhere in the file:
3430 #+STARTUP: noptag"
3431 :group 'org-tags
3432 :type '(repeat
3433 (choice
3434 (cons (string :tag "Tag name")
3435 (character :tag "Access char"))
3436 (const :tag "Start radio group" (:startgroup))
3437 (const :tag "Group tags delimiter" (:grouptags))
3438 (const :tag "End radio group" (:endgroup))
3439 (const :tag "New line" (:newline)))))
3441 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3442 "If non-nil, always offer completion for all tags of all agenda files.
3443 Instead of customizing this variable directly, you might want to
3444 set it locally for capture buffers, because there no list of
3445 tags in that file can be created dynamically (there are none).
3447 (add-hook 'org-capture-mode-hook
3448 (lambda ()
3449 (set (make-local-variable
3450 'org-complete-tags-always-offer-all-agenda-tags)
3451 t)))"
3452 :group 'org-tags
3453 :version "24.1"
3454 :type 'boolean)
3456 (defvar org-file-tags nil
3457 "List of tags that can be inherited by all entries in the file.
3458 The tags will be inherited if the variable `org-use-tag-inheritance'
3459 says they should be.
3460 This variable is populated from #+FILETAGS lines.")
3462 (defcustom org-use-fast-tag-selection 'auto
3463 "Non-nil means use fast tag selection scheme.
3464 This is a special interface to select and deselect tags with single keys.
3465 When nil, fast selection is never used.
3466 When the symbol `auto', fast selection is used if and only if selection
3467 characters for tags have been configured, either through the variable
3468 `org-tag-alist' or through a #+TAGS line in the buffer.
3469 When t, fast selection is always used and selection keys are assigned
3470 automatically if necessary."
3471 :group 'org-tags
3472 :type '(choice
3473 (const :tag "Always" t)
3474 (const :tag "Never" nil)
3475 (const :tag "When selection characters are configured" auto)))
3477 (defcustom org-fast-tag-selection-single-key nil
3478 "Non-nil means fast tag selection exits after first change.
3479 When nil, you have to press RET to exit it.
3480 During fast tag selection, you can toggle this flag with `C-c'.
3481 This variable can also have the value `expert'. In this case, the window
3482 displaying the tags menu is not even shown, until you press C-c again."
3483 :group 'org-tags
3484 :type '(choice
3485 (const :tag "No" nil)
3486 (const :tag "Yes" t)
3487 (const :tag "Expert" expert)))
3489 (defvar org-fast-tag-selection-include-todo nil
3490 "Non-nil means fast tags selection interface will also offer TODO states.
3491 This is an undocumented feature, you should not rely on it.")
3493 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3494 "The column to which tags should be indented in a headline.
3495 If this number is positive, it specifies the column. If it is negative,
3496 it means that the tags should be flushright to that column. For example,
3497 -80 works well for a normal 80 character screen.
3498 When 0, place tags directly after headline text, with only one space in
3499 between."
3500 :group 'org-tags
3501 :type 'integer)
3503 (defcustom org-auto-align-tags t
3504 "Non-nil keeps tags aligned when modifying headlines.
3505 Some operations (i.e. demoting) change the length of a headline and
3506 therefore shift the tags around. With this option turned on, after
3507 each such operation the tags are again aligned to `org-tags-column'."
3508 :group 'org-tags
3509 :type 'boolean)
3511 (defcustom org-use-tag-inheritance t
3512 "Non-nil means tags in levels apply also for sublevels.
3513 When nil, only the tags directly given in a specific line apply there.
3514 This may also be a list of tags that should be inherited, or a regexp that
3515 matches tags that should be inherited. Additional control is possible
3516 with the variable `org-tags-exclude-from-inheritance' which gives an
3517 explicit list of tags to be excluded from inheritance, even if the value of
3518 `org-use-tag-inheritance' would select it for inheritance.
3520 If this option is t, a match early-on in a tree can lead to a large
3521 number of matches in the subtree when constructing the agenda or creating
3522 a sparse tree. If you only want to see the first match in a tree during
3523 a search, check out the variable `org-tags-match-list-sublevels'."
3524 :group 'org-tags
3525 :type '(choice
3526 (const :tag "Not" nil)
3527 (const :tag "Always" t)
3528 (repeat :tag "Specific tags" (string :tag "Tag"))
3529 (regexp :tag "Tags matched by regexp")))
3531 (defcustom org-tags-exclude-from-inheritance nil
3532 "List of tags that should never be inherited.
3533 This is a way to exclude a few tags from inheritance. For way to do
3534 the opposite, to actively allow inheritance for selected tags,
3535 see the variable `org-use-tag-inheritance'."
3536 :group 'org-tags
3537 :type '(repeat (string :tag "Tag")))
3539 (defun org-tag-inherit-p (tag)
3540 "Check if TAG is one that should be inherited."
3541 (cond
3542 ((member tag org-tags-exclude-from-inheritance) nil)
3543 ((eq org-use-tag-inheritance t) t)
3544 ((not org-use-tag-inheritance) nil)
3545 ((stringp org-use-tag-inheritance)
3546 (string-match org-use-tag-inheritance tag))
3547 ((listp org-use-tag-inheritance)
3548 (member tag org-use-tag-inheritance))
3549 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3551 (defcustom org-tags-match-list-sublevels t
3552 "Non-nil means list also sublevels of headlines matching a search.
3553 This variable applies to tags/property searches, and also to stuck
3554 projects because this search is based on a tags match as well.
3556 When set to the symbol `indented', sublevels are indented with
3557 leading dots.
3559 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3560 the sublevels of a headline matching a tag search often also match
3561 the same search. Listing all of them can create very long lists.
3562 Setting this variable to nil causes subtrees of a match to be skipped.
3564 This variable is semi-obsolete and probably should always be true. It
3565 is better to limit inheritance to certain tags using the variables
3566 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3567 :group 'org-tags
3568 :type '(choice
3569 (const :tag "No, don't list them" nil)
3570 (const :tag "Yes, do list them" t)
3571 (const :tag "List them, indented with leading dots" indented)))
3573 (defcustom org-tags-sort-function nil
3574 "When set, tags are sorted using this function as a comparator."
3575 :group 'org-tags
3576 :type '(choice
3577 (const :tag "No sorting" nil)
3578 (const :tag "Alphabetical" string<)
3579 (const :tag "Reverse alphabetical" string>)
3580 (function :tag "Custom function" nil)))
3582 (defvar org-tags-history nil
3583 "History of minibuffer reads for tags.")
3584 (defvar org-last-tags-completion-table nil
3585 "The last used completion table for tags.")
3586 (defvar org-after-tags-change-hook nil
3587 "Hook that is run after the tags in a line have changed.")
3589 (defgroup org-properties nil
3590 "Options concerning properties in Org-mode."
3591 :tag "Org Properties"
3592 :group 'org)
3594 (defcustom org-property-format "%-10s %s"
3595 "How property key/value pairs should be formatted by `indent-line'.
3596 When `indent-line' hits a property definition, it will format the line
3597 according to this format, mainly to make sure that the values are
3598 lined-up with respect to each other."
3599 :group 'org-properties
3600 :type 'string)
3602 (defcustom org-properties-postprocess-alist nil
3603 "Alist of properties and functions to adjust inserted values.
3604 Elements of this alist must be of the form
3606 ([string] [function])
3608 where [string] must be a property name and [function] must be a
3609 lambda expression: this lambda expression must take one argument,
3610 the value to adjust, and return the new value as a string.
3612 For example, this element will allow the property \"Remaining\"
3613 to be updated wrt the relation between the \"Effort\" property
3614 and the clock summary:
3616 ((\"Remaining\" (lambda(value)
3617 (let ((clocksum (org-clock-sum-current-item))
3618 (effort (org-duration-string-to-minutes
3619 (org-entry-get (point) \"Effort\"))))
3620 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3621 :group 'org-properties
3622 :version "24.1"
3623 :type '(alist :key-type (string :tag "Property")
3624 :value-type (function :tag "Function")))
3626 (defcustom org-use-property-inheritance nil
3627 "Non-nil means properties apply also for sublevels.
3629 This setting is chiefly used during property searches. Turning it on can
3630 cause significant overhead when doing a search, which is why it is not
3631 on by default.
3633 When nil, only the properties directly given in the current entry count.
3634 When t, every property is inherited. The value may also be a list of
3635 properties that should have inheritance, or a regular expression matching
3636 properties that should be inherited.
3638 However, note that some special properties use inheritance under special
3639 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3640 and the properties ending in \"_ALL\" when they are used as descriptor
3641 for valid values of a property.
3643 Note for programmers:
3644 When querying an entry with `org-entry-get', you can control if inheritance
3645 should be used. By default, `org-entry-get' looks only at the local
3646 properties. You can request inheritance by setting the inherit argument
3647 to t (to force inheritance) or to `selective' (to respect the setting
3648 in this variable)."
3649 :group 'org-properties
3650 :type '(choice
3651 (const :tag "Not" nil)
3652 (const :tag "Always" t)
3653 (repeat :tag "Specific properties" (string :tag "Property"))
3654 (regexp :tag "Properties matched by regexp")))
3656 (defun org-property-inherit-p (property)
3657 "Check if PROPERTY is one that should be inherited."
3658 (cond
3659 ((eq org-use-property-inheritance t) t)
3660 ((not org-use-property-inheritance) nil)
3661 ((stringp org-use-property-inheritance)
3662 (string-match org-use-property-inheritance property))
3663 ((listp org-use-property-inheritance)
3664 (member property org-use-property-inheritance))
3665 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3667 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3668 "The default column format, if no other format has been defined.
3669 This variable can be set on the per-file basis by inserting a line
3671 #+COLUMNS: %25ITEM ....."
3672 :group 'org-properties
3673 :type 'string)
3675 (defcustom org-columns-ellipses ".."
3676 "The ellipses to be used when a field in column view is truncated.
3677 When this is the empty string, as many characters as possible are shown,
3678 but then there will be no visual indication that the field has been truncated.
3679 When this is a string of length N, the last N characters of a truncated
3680 field are replaced by this string. If the column is narrower than the
3681 ellipses string, only part of the ellipses string will be shown."
3682 :group 'org-properties
3683 :type 'string)
3685 (defcustom org-columns-modify-value-for-display-function nil
3686 "Function that modifies values for display in column view.
3687 For example, it can be used to cut out a certain part from a time stamp.
3688 The function must take 2 arguments:
3690 column-title The title of the column (*not* the property name)
3691 value The value that should be modified.
3693 The function should return the value that should be displayed,
3694 or nil if the normal value should be used."
3695 :group 'org-properties
3696 :type '(choice (const nil) (function)))
3698 (defconst org-global-properties-fixed
3699 '(("VISIBILITY_ALL" . "folded children content all")
3700 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3701 "List of property/value pairs that can be inherited by any entry.
3703 These are fixed values, for the preset properties. The user variable
3704 that can be used to add to this list is `org-global-properties'.
3706 The entries in this list are cons cells where the car is a property
3707 name and cdr is a string with the value. If the value represents
3708 multiple items like an \"_ALL\" property, separate the items by
3709 spaces.")
3711 (defcustom org-global-properties nil
3712 "List of property/value pairs that can be inherited by any entry.
3714 This list will be combined with the constant `org-global-properties-fixed'.
3716 The entries in this list are cons cells where the car is a property
3717 name and cdr is a string with the value.
3719 You can set buffer-local values for the same purpose in the variable
3720 `org-file-properties' this by adding lines like
3722 #+PROPERTY: NAME VALUE"
3723 :group 'org-properties
3724 :type '(repeat
3725 (cons (string :tag "Property")
3726 (string :tag "Value"))))
3728 (defvar org-file-properties nil
3729 "List of property/value pairs that can be inherited by any entry.
3730 Valid for the current buffer.
3731 This variable is populated from #+PROPERTY lines.")
3732 (make-variable-buffer-local 'org-file-properties)
3734 (defgroup org-agenda nil
3735 "Options concerning agenda views in Org-mode."
3736 :tag "Org Agenda"
3737 :group 'org)
3739 (defvar org-category nil
3740 "Variable used by org files to set a category for agenda display.
3741 Such files should use a file variable to set it, for example
3743 # -*- mode: org; org-category: \"ELisp\"
3745 or contain a special line
3747 #+CATEGORY: ELisp
3749 If the file does not specify a category, then file's base name
3750 is used instead.")
3751 (make-variable-buffer-local 'org-category)
3752 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3754 (defcustom org-agenda-files nil
3755 "The files to be used for agenda display.
3756 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3757 \\[org-remove-file]. You can also use customize to edit the list.
3759 If an entry is a directory, all files in that directory that are matched by
3760 `org-agenda-file-regexp' will be part of the file list.
3762 If the value of the variable is not a list but a single file name, then
3763 the list of agenda files is actually stored and maintained in that file, one
3764 agenda file per line. In this file paths can be given relative to
3765 `org-directory'. Tilde expansion and environment variable substitution
3766 are also made."
3767 :group 'org-agenda
3768 :type '(choice
3769 (repeat :tag "List of files and directories" file)
3770 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3772 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3773 "Regular expression to match files for `org-agenda-files'.
3774 If any element in the list in that variable contains a directory instead
3775 of a normal file, all files in that directory that are matched by this
3776 regular expression will be included."
3777 :group 'org-agenda
3778 :type 'regexp)
3780 (defcustom org-agenda-text-search-extra-files nil
3781 "List of extra files to be searched by text search commands.
3782 These files will be searched in addition to the agenda files by the
3783 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3784 Note that these files will only be searched for text search commands,
3785 not for the other agenda views like todo lists, tag searches or the weekly
3786 agenda. This variable is intended to list notes and possibly archive files
3787 that should also be searched by these two commands.
3788 In fact, if the first element in the list is the symbol `agenda-archives',
3789 then all archive files of all agenda files will be added to the search
3790 scope."
3791 :group 'org-agenda
3792 :type '(set :greedy t
3793 (const :tag "Agenda Archives" agenda-archives)
3794 (repeat :inline t (file))))
3796 (org-defvaralias 'org-agenda-multi-occur-extra-files
3797 'org-agenda-text-search-extra-files)
3799 (defcustom org-agenda-skip-unavailable-files nil
3800 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3801 A nil value means to remove them, after a query, from the list."
3802 :group 'org-agenda
3803 :type 'boolean)
3805 (defcustom org-calendar-to-agenda-key [?c]
3806 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3807 The command `org-calendar-goto-agenda' will be bound to this key. The
3808 default is the character `c' because then `c' can be used to switch back and
3809 forth between agenda and calendar."
3810 :group 'org-agenda
3811 :type 'sexp)
3813 (defcustom org-calendar-insert-diary-entry-key [?i]
3814 "The key to be installed in `calendar-mode-map' for adding diary entries.
3815 This option is irrelevant until `org-agenda-diary-file' has been configured
3816 to point to an Org-mode file. When that is the case, the command
3817 `org-agenda-diary-entry' will be bound to the key given here, by default
3818 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3819 if you want to continue doing this, you need to change this to a different
3820 key."
3821 :group 'org-agenda
3822 :type 'sexp)
3824 (defcustom org-agenda-diary-file 'diary-file
3825 "File to which to add new entries with the `i' key in agenda and calendar.
3826 When this is the symbol `diary-file', the functionality in the Emacs
3827 calendar will be used to add entries to the `diary-file'. But when this
3828 points to a file, `org-agenda-diary-entry' will be used instead."
3829 :group 'org-agenda
3830 :type '(choice
3831 (const :tag "The standard Emacs diary file" diary-file)
3832 (file :tag "Special Org file diary entries")))
3834 (eval-after-load "calendar"
3835 '(progn
3836 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3837 'org-calendar-goto-agenda)
3838 (add-hook 'calendar-mode-hook
3839 (lambda ()
3840 (unless (eq org-agenda-diary-file 'diary-file)
3841 (define-key calendar-mode-map
3842 org-calendar-insert-diary-entry-key
3843 'org-agenda-diary-entry))))))
3845 (defgroup org-latex nil
3846 "Options for embedding LaTeX code into Org-mode."
3847 :tag "Org LaTeX"
3848 :group 'org)
3850 (defcustom org-format-latex-options
3851 '(:foreground default :background default :scale 1.0
3852 :html-foreground "Black" :html-background "Transparent"
3853 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3854 "Options for creating images from LaTeX fragments.
3855 This is a property list with the following properties:
3856 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3857 `default' means use the foreground of the default face.
3858 `auto' means use the foreground from the text face.
3859 :background the background color, or \"Transparent\".
3860 `default' means use the background of the default face.
3861 `auto' means use the background from the text face.
3862 :scale a scaling factor for the size of the images, to get more pixels
3863 :html-foreground, :html-background, :html-scale
3864 the same numbers for HTML export.
3865 :matchers a list indicating which matchers should be used to
3866 find LaTeX fragments. Valid members of this list are:
3867 \"begin\" find environments
3868 \"$1\" find single characters surrounded by $.$
3869 \"$\" find math expressions surrounded by $...$
3870 \"$$\" find math expressions surrounded by $$....$$
3871 \"\\(\" find math expressions surrounded by \\(...\\)
3872 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3873 :group 'org-latex
3874 :type 'plist)
3876 (defcustom org-format-latex-signal-error t
3877 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3878 When nil, just push out a message."
3879 :group 'org-latex
3880 :version "24.1"
3881 :type 'boolean)
3883 (defcustom org-latex-to-mathml-jar-file nil
3884 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3885 Use this to specify additional executable file say a jar file.
3887 When using MathToWeb as the converter, specify the full-path to
3888 your mathtoweb.jar file."
3889 :group 'org-latex
3890 :version "24.1"
3891 :type '(choice
3892 (const :tag "None" nil)
3893 (file :tag "JAR file" :must-match t)))
3895 (defcustom org-latex-to-mathml-convert-command nil
3896 "Command to convert LaTeX fragments to MathML.
3897 Replace format-specifiers in the command as noted below and use
3898 `shell-command' to convert LaTeX to MathML.
3899 %j: Executable file in fully expanded form as specified by
3900 `org-latex-to-mathml-jar-file'.
3901 %I: Input LaTeX file in fully expanded form
3902 %o: Output MathML file
3903 This command is used by `org-create-math-formula'.
3905 When using MathToWeb as the converter, set this to
3906 \"java -jar %j -unicode -force -df %o %I\"."
3907 :group 'org-latex
3908 :version "24.1"
3909 :type '(choice
3910 (const :tag "None" nil)
3911 (string :tag "\nShell command")))
3913 (defcustom org-latex-create-formula-image-program 'dvipng
3914 "Program to convert LaTeX fragments with.
3916 dvipng Process the LaTeX fragments to dvi file, then convert
3917 dvi files to png files using dvipng.
3918 This will also include processing of non-math environments.
3919 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3920 to convert pdf files to png files"
3921 :group 'org-latex
3922 :version "24.1"
3923 :type '(choice
3924 (const :tag "dvipng" dvipng)
3925 (const :tag "imagemagick" imagemagick)))
3927 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3928 "Path to store latex preview images.
3929 A relative path here creates many directories relative to the
3930 processed org files paths. An absolute path puts all preview
3931 images at the same place."
3932 :group 'org-latex
3933 :version "24.3"
3934 :type 'string)
3936 (defun org-format-latex-mathml-available-p ()
3937 "Return t if `org-latex-to-mathml-convert-command' is usable."
3938 (save-match-data
3939 (when (and (boundp 'org-latex-to-mathml-convert-command)
3940 org-latex-to-mathml-convert-command)
3941 (let ((executable (car (split-string
3942 org-latex-to-mathml-convert-command))))
3943 (when (executable-find executable)
3944 (if (string-match
3945 "%j" org-latex-to-mathml-convert-command)
3946 (file-readable-p org-latex-to-mathml-jar-file)
3947 t))))))
3949 (defcustom org-format-latex-header "\\documentclass{article}
3950 \\usepackage[usenames]{color}
3951 \[PACKAGES]
3952 \[DEFAULT-PACKAGES]
3953 \\pagestyle{empty} % do not remove
3954 % The settings below are copied from fullpage.sty
3955 \\setlength{\\textwidth}{\\paperwidth}
3956 \\addtolength{\\textwidth}{-3cm}
3957 \\setlength{\\oddsidemargin}{1.5cm}
3958 \\addtolength{\\oddsidemargin}{-2.54cm}
3959 \\setlength{\\evensidemargin}{\\oddsidemargin}
3960 \\setlength{\\textheight}{\\paperheight}
3961 \\addtolength{\\textheight}{-\\headheight}
3962 \\addtolength{\\textheight}{-\\headsep}
3963 \\addtolength{\\textheight}{-\\footskip}
3964 \\addtolength{\\textheight}{-3cm}
3965 \\setlength{\\topmargin}{1.5cm}
3966 \\addtolength{\\topmargin}{-2.54cm}"
3967 "The document header used for processing LaTeX fragments.
3968 It is imperative that this header make sure that no page number
3969 appears on the page. The package defined in the variables
3970 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3971 will either replace the placeholder \"[PACKAGES]\" in this
3972 header, or they will be appended."
3973 :group 'org-latex
3974 :type 'string)
3976 (defun org-set-packages-alist (var val)
3977 "Set the packages alist and make sure it has 3 elements per entry."
3978 (set var (mapcar (lambda (x)
3979 (if (and (consp x) (= (length x) 2))
3980 (list (car x) (nth 1 x) t)
3982 val)))
3984 (defun org-get-packages-alist (var)
3985 "Get the packages alist and make sure it has 3 elements per entry."
3986 (mapcar (lambda (x)
3987 (if (and (consp x) (= (length x) 2))
3988 (list (car x) (nth 1 x) t)
3990 (default-value var)))
3992 (defcustom org-latex-default-packages-alist
3993 '(("AUTO" "inputenc" t)
3994 ("T1" "fontenc" t)
3995 ("" "fixltx2e" nil)
3996 ("" "graphicx" t)
3997 ("" "longtable" nil)
3998 ("" "float" nil)
3999 ("" "wrapfig" nil)
4000 ("" "rotating" nil)
4001 ("normalem" "ulem" t)
4002 ("" "amsmath" t)
4003 ("" "textcomp" t)
4004 ("" "marvosym" t)
4005 ("" "wasysym" t)
4006 ("" "amssymb" t)
4007 ("" "capt-of" nil)
4008 ("" "hyperref" nil)
4009 "\\tolerance=1000")
4010 "Alist of default packages to be inserted in the header.
4012 Change this only if one of the packages here causes an
4013 incompatibility with another package you are using.
4015 The packages in this list are needed by one part or another of
4016 Org mode to function properly:
4018 - inputenc, fontenc: for basic font and character selection
4019 - fixltx2e: Important patches of LaTeX itself
4020 - graphicx: for including images
4021 - longtable: For multipage tables
4022 - float, wrapfig: for figure placement
4023 - rotating: for sideways figures and tables
4024 - ulem: for underline and strike-through
4025 - amsmath: for subscript and superscript and math environments
4026 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4027 for interpreting the entities in `org-entities'. You can skip
4028 some of these packages if you don't use any of their symbols.
4029 - capt-of: for captions outside of floats
4030 - hyperref: for cross references
4032 Therefore you should not modify this variable unless you know
4033 what you are doing. The one reason to change it anyway is that
4034 you might be loading some other package that conflicts with one
4035 of the default packages. Each element is either a cell or
4036 a string.
4038 A cell is of the format:
4040 \( \"options\" \"package\" SNIPPET-FLAG).
4042 If SNIPPET-FLAG is non-nil, the package also needs to be included
4043 when compiling LaTeX snippets into images for inclusion into
4044 non-LaTeX output.
4046 A string will be inserted as-is in the header of the document."
4047 :group 'org-latex
4048 :group 'org-export-latex
4049 :set 'org-set-packages-alist
4050 :get 'org-get-packages-alist
4051 :version "24.1"
4052 :type '(repeat
4053 (choice
4054 (list :tag "options/package pair"
4055 (string :tag "options")
4056 (string :tag "package")
4057 (boolean :tag "Snippet"))
4058 (string :tag "A line of LaTeX"))))
4060 (defcustom org-latex-packages-alist nil
4061 "Alist of packages to be inserted in every LaTeX header.
4063 These will be inserted after `org-latex-default-packages-alist'.
4064 Each element is either a cell or a string.
4066 A cell is of the format:
4068 \(\"options\" \"package\" SNIPPET-FLAG)
4070 SNIPPET-FLAG, when non-nil, indicates that this package is also
4071 needed when turning LaTeX snippets into images for inclusion into
4072 non-LaTeX output.
4074 A string will be inserted as-is in the header of the document.
4076 Make sure that you only list packages here which:
4078 - you want in every file;
4079 - do not conflict with the setup in `org-format-latex-header';
4080 - do not conflict with the default packages in
4081 `org-latex-default-packages-alist'."
4082 :group 'org-latex
4083 :group 'org-export-latex
4084 :set 'org-set-packages-alist
4085 :get 'org-get-packages-alist
4086 :type '(repeat
4087 (choice
4088 (list :tag "options/package pair"
4089 (string :tag "options")
4090 (string :tag "package")
4091 (boolean :tag "Snippet"))
4092 (string :tag "A line of LaTeX"))))
4094 (defgroup org-appearance nil
4095 "Settings for Org-mode appearance."
4096 :tag "Org Appearance"
4097 :group 'org)
4099 (defcustom org-level-color-stars-only nil
4100 "Non-nil means fontify only the stars in each headline.
4101 When nil, the entire headline is fontified.
4102 Changing it requires restart of `font-lock-mode' to become effective
4103 also in regions already fontified."
4104 :group 'org-appearance
4105 :type 'boolean)
4107 (defcustom org-hide-leading-stars nil
4108 "Non-nil means hide the first N-1 stars in a headline.
4109 This works by using the face `org-hide' for these stars. This
4110 face is white for a light background, and black for a dark
4111 background. You may have to customize the face `org-hide' to
4112 make this work.
4113 Changing it requires restart of `font-lock-mode' to become effective
4114 also in regions already fontified.
4115 You may also set this on a per-file basis by adding one of the following
4116 lines to the buffer:
4118 #+STARTUP: hidestars
4119 #+STARTUP: showstars"
4120 :group 'org-appearance
4121 :type 'boolean)
4123 (defcustom org-hidden-keywords nil
4124 "List of symbols corresponding to keywords to be hidden the org buffer.
4125 For example, a value '(title) for this list will make the document's title
4126 appear in the buffer without the initial #+TITLE: keyword."
4127 :group 'org-appearance
4128 :version "24.1"
4129 :type '(set (const :tag "#+AUTHOR" author)
4130 (const :tag "#+DATE" date)
4131 (const :tag "#+EMAIL" email)
4132 (const :tag "#+TITLE" title)))
4134 (defcustom org-custom-properties nil
4135 "List of properties (as strings) with a special meaning.
4136 The default use of these custom properties is to let the user
4137 hide them with `org-toggle-custom-properties-visibility'."
4138 :group 'org-properties
4139 :group 'org-appearance
4140 :version "24.3"
4141 :type '(repeat (string :tag "Property Name")))
4143 (defcustom org-fontify-done-headline nil
4144 "Non-nil means change the face of a headline if it is marked DONE.
4145 Normally, only the TODO/DONE keyword indicates the state of a headline.
4146 When this is non-nil, the headline after the keyword is set to the
4147 `org-headline-done' as an additional indication."
4148 :group 'org-appearance
4149 :type 'boolean)
4151 (defcustom org-fontify-emphasized-text t
4152 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4153 Changing this variable requires a restart of Emacs to take effect."
4154 :group 'org-appearance
4155 :type 'boolean)
4157 (defcustom org-fontify-whole-heading-line nil
4158 "Non-nil means fontify the whole line for headings.
4159 This is useful when setting a background color for the
4160 org-level-* faces."
4161 :group 'org-appearance
4162 :type 'boolean)
4164 (defcustom org-highlight-latex-and-related nil
4165 "Non-nil means highlight LaTeX related syntax in the buffer.
4166 When non nil, the value should be a list containing any of the
4167 following symbols:
4168 `latex' Highlight LaTeX snippets and environments.
4169 `script' Highlight subscript and superscript.
4170 `entities' Highlight entities."
4171 :group 'org-appearance
4172 :version "24.4"
4173 :package-version '(Org . "8.0")
4174 :type '(choice
4175 (const :tag "No highlighting" nil)
4176 (set :greedy t :tag "Highlight"
4177 (const :tag "LaTeX snippets and environments" latex)
4178 (const :tag "Subscript and superscript" script)
4179 (const :tag "Entities" entities))))
4181 (defcustom org-hide-emphasis-markers nil
4182 "Non-nil mean font-lock should hide the emphasis marker characters."
4183 :group 'org-appearance
4184 :type 'boolean)
4186 (defcustom org-hide-macro-markers nil
4187 "Non-nil mean font-lock should hide the brackets marking macro calls."
4188 :group 'org-appearance
4189 :type 'boolean)
4191 (defcustom org-pretty-entities nil
4192 "Non-nil means show entities as UTF8 characters.
4193 When nil, the \\name form remains in the buffer."
4194 :group 'org-appearance
4195 :version "24.1"
4196 :type 'boolean)
4198 (defcustom org-pretty-entities-include-sub-superscripts t
4199 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4200 :group 'org-appearance
4201 :version "24.1"
4202 :type 'boolean)
4204 (defvar org-emph-re nil
4205 "Regular expression for matching emphasis.
4206 After a match, the match groups contain these elements:
4207 0 The match of the full regular expression, including the characters
4208 before and after the proper match
4209 1 The character before the proper match, or empty at beginning of line
4210 2 The proper match, including the leading and trailing markers
4211 3 The leading marker like * or /, indicating the type of highlighting
4212 4 The text between the emphasis markers, not including the markers
4213 5 The character after the match, empty at the end of a line")
4214 (defvar org-verbatim-re nil
4215 "Regular expression for matching verbatim text.")
4216 (defvar org-emphasis-regexp-components) ; defined just below
4217 (defvar org-emphasis-alist) ; defined just below
4218 (defun org-set-emph-re (var val)
4219 "Set variable and compute the emphasis regular expression."
4220 (set var val)
4221 (when (and (boundp 'org-emphasis-alist)
4222 (boundp 'org-emphasis-regexp-components)
4223 org-emphasis-alist org-emphasis-regexp-components)
4224 (let* ((e org-emphasis-regexp-components)
4225 (pre (car e))
4226 (post (nth 1 e))
4227 (border (nth 2 e))
4228 (body (nth 3 e))
4229 (nl (nth 4 e))
4230 (body1 (concat body "*?"))
4231 (markers (mapconcat 'car org-emphasis-alist ""))
4232 (vmarkers (mapconcat
4233 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4234 org-emphasis-alist "")))
4235 ;; make sure special characters appear at the right position in the class
4236 (if (string-match "\\^" markers)
4237 (setq markers (concat (replace-match "" t t markers) "^")))
4238 (if (string-match "-" markers)
4239 (setq markers (concat (replace-match "" t t markers) "-")))
4240 (if (string-match "\\^" vmarkers)
4241 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4242 (if (string-match "-" vmarkers)
4243 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4244 (if (> nl 0)
4245 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4246 (int-to-string nl) "\\}")))
4247 ;; Make the regexp
4248 (setq org-emph-re
4249 (concat "\\([" pre "]\\|^\\)"
4250 "\\("
4251 "\\([" markers "]\\)"
4252 "\\("
4253 "[^" border "]\\|"
4254 "[^" border "]"
4255 body1
4256 "[^" border "]"
4257 "\\)"
4258 "\\3\\)"
4259 "\\([" post "]\\|$\\)"))
4260 (setq org-verbatim-re
4261 (concat "\\([" pre "]\\|^\\)"
4262 "\\("
4263 "\\([" vmarkers "]\\)"
4264 "\\("
4265 "[^" border "]\\|"
4266 "[^" border "]"
4267 body1
4268 "[^" border "]"
4269 "\\)"
4270 "\\3\\)"
4271 "\\([" post "]\\|$\\)")))))
4273 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4274 ;; set this option proved cumbersome. See this message/thread:
4275 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4276 (defvar org-emphasis-regexp-components
4277 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4278 "Components used to build the regular expression for emphasis.
4279 This is a list with five entries. Terminology: In an emphasis string
4280 like \" *strong word* \", we call the initial space PREMATCH, the final
4281 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4282 and \"trong wor\" is the body. The different components in this variable
4283 specify what is allowed/forbidden in each part:
4285 pre Chars allowed as prematch. Beginning of line will be allowed too.
4286 post Chars allowed as postmatch. End of line will be allowed too.
4287 border The chars *forbidden* as border characters.
4288 body-regexp A regexp like \".\" to match a body character. Don't use
4289 non-shy groups here, and don't allow newline here.
4290 newline The maximum number of newlines allowed in an emphasis exp.
4292 You need to reload Org or to restart Emacs after customizing this.")
4294 (defcustom org-emphasis-alist
4295 `(("*" bold)
4296 ("/" italic)
4297 ("_" underline)
4298 ("=" org-verbatim verbatim)
4299 ("~" org-code verbatim)
4300 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4301 "Alist of characters and faces to emphasize text.
4302 Text starting and ending with a special character will be emphasized,
4303 for example *bold*, _underlined_ and /italic/. This variable sets the
4304 marker characters and the face to be used by font-lock for highlighting
4305 in Org-mode Emacs buffers.
4307 You need to reload Org or to restart Emacs after customizing this."
4308 :group 'org-appearance
4309 :set 'org-set-emph-re
4310 :version "24.4"
4311 :package-version '(Org . "8.0")
4312 :type '(repeat
4313 (list
4314 (string :tag "Marker character")
4315 (choice
4316 (face :tag "Font-lock-face")
4317 (plist :tag "Face property list"))
4318 (option (const verbatim)))))
4320 (defvar org-protecting-blocks
4321 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4322 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4323 This is needed for font-lock setup.")
4325 ;;; Miscellaneous options
4327 (defgroup org-completion nil
4328 "Completion in Org-mode."
4329 :tag "Org Completion"
4330 :group 'org)
4332 (defcustom org-completion-use-ido nil
4333 "Non-nil means use ido completion wherever possible.
4334 Note that `ido-mode' must be active for this variable to be relevant.
4335 If you decide to turn this variable on, you might well want to turn off
4336 `org-outline-path-complete-in-steps'.
4337 See also `org-completion-use-iswitchb'."
4338 :group 'org-completion
4339 :type 'boolean)
4341 (defcustom org-completion-use-iswitchb nil
4342 "Non-nil means use iswitchb completion wherever possible.
4343 Note that `iswitchb-mode' must be active for this variable to be relevant.
4344 If you decide to turn this variable on, you might well want to turn off
4345 `org-outline-path-complete-in-steps'.
4346 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4347 :group 'org-completion
4348 :type 'boolean)
4350 (defcustom org-completion-fallback-command 'hippie-expand
4351 "The expansion command called by \\[pcomplete] in normal context.
4352 Normal means, no org-mode-specific context."
4353 :group 'org-completion
4354 :type 'function)
4356 ;;; Functions and variables from their packages
4357 ;; Declared here to avoid compiler warnings
4359 ;; XEmacs only
4360 (defvar outline-mode-menu-heading)
4361 (defvar outline-mode-menu-show)
4362 (defvar outline-mode-menu-hide)
4363 (defvar zmacs-regions) ; XEmacs regions
4365 ;; Emacs only
4366 (defvar mark-active)
4368 ;; Various packages
4369 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4370 (declare-function calendar-forward-day "cal-move" (arg))
4371 (declare-function calendar-goto-date "cal-move" (date))
4372 (declare-function calendar-goto-today "cal-move" ())
4373 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4374 (defvar calc-embedded-close-formula)
4375 (defvar calc-embedded-open-formula)
4376 (declare-function cdlatex-tab "ext:cdlatex" ())
4377 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4378 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4379 (defvar font-lock-unfontify-region-function)
4380 (declare-function iswitchb-read-buffer "iswitchb"
4381 (prompt &optional default require-match start matches-set))
4382 (defvar iswitchb-temp-buflist)
4383 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4384 (defvar org-agenda-tags-todo-honor-ignore-options)
4385 (declare-function org-agenda-skip "org-agenda" ())
4386 (declare-function
4387 org-agenda-format-item "org-agenda"
4388 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4389 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4390 (declare-function org-agenda-change-all-lines "org-agenda"
4391 (newhead hdmarker &optional fixface just-this))
4392 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4393 (declare-function org-agenda-maybe-redo "org-agenda" ())
4394 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4395 (beg end))
4396 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4397 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4398 "org-agenda" (&optional end))
4399 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4400 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4401 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4402 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4403 (declare-function org-indent-mode "org-indent" (&optional arg))
4404 (declare-function parse-time-string "parse-time" (string))
4405 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4406 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4407 (defvar remember-data-file)
4408 (defvar texmathp-why)
4409 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4410 (declare-function table--at-cell-p "table" (position &optional object at-column))
4411 (declare-function calc-eval "calc" (str &optional separator &rest args))
4413 ;;;###autoload
4414 (defun turn-on-orgtbl ()
4415 "Unconditionally turn on `orgtbl-mode'."
4416 (require 'org-table)
4417 (orgtbl-mode 1))
4419 (defun org-at-table-p (&optional table-type)
4420 "Return t if the cursor is inside an org-type table.
4421 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4422 (if org-enable-table-editor
4423 (save-excursion
4424 (beginning-of-line 1)
4425 (looking-at (if table-type org-table-any-line-regexp
4426 org-table-line-regexp)))
4427 nil))
4428 (defsubst org-table-p () (org-at-table-p))
4430 (defun org-at-table.el-p ()
4431 "Return t if and only if we are at a table.el table."
4432 (and (org-at-table-p 'any)
4433 (save-excursion
4434 (goto-char (org-table-begin 'any))
4435 (looking-at org-table1-hline-regexp))))
4437 (defun org-table-recognize-table.el ()
4438 "If there is a table.el table nearby, recognize it and move into it."
4439 (if org-table-tab-recognizes-table.el
4440 (if (org-at-table.el-p)
4441 (progn
4442 (beginning-of-line 1)
4443 (if (looking-at org-table-dataline-regexp)
4445 (if (looking-at org-table1-hline-regexp)
4446 (progn
4447 (beginning-of-line 2)
4448 (if (looking-at org-table-any-border-regexp)
4449 (beginning-of-line -1)))))
4450 (if (re-search-forward "|" (org-table-end t) t)
4451 (progn
4452 (require 'table)
4453 (if (table--at-cell-p (point))
4455 (message "recognizing table.el table...")
4456 (table-recognize-table)
4457 (message "recognizing table.el table...done")))
4458 (error "This should not happen"))
4460 nil)
4461 nil))
4463 (defun org-at-table-hline-p ()
4464 "Return t if the cursor is inside a hline in a table."
4465 (if org-enable-table-editor
4466 (save-excursion
4467 (beginning-of-line 1)
4468 (looking-at org-table-hline-regexp))
4469 nil))
4471 (defun org-table-map-tables (function &optional quietly)
4472 "Apply FUNCTION to the start of all tables in the buffer."
4473 (save-excursion
4474 (save-restriction
4475 (widen)
4476 (goto-char (point-min))
4477 (while (re-search-forward org-table-any-line-regexp nil t)
4478 (unless quietly
4479 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4480 (beginning-of-line 1)
4481 (when (and (looking-at org-table-line-regexp)
4482 ;; Exclude tables in src/example/verbatim/clocktable blocks
4483 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4484 (save-excursion (funcall function))
4485 (or (looking-at org-table-line-regexp)
4486 (forward-char 1)))
4487 (re-search-forward org-table-any-border-regexp nil 1))))
4488 (unless quietly (message "Mapping tables: done")))
4490 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4491 (declare-function org-clock-update-mode-line "org-clock" ())
4492 (declare-function org-resolve-clocks "org-clock"
4493 (&optional also-non-dangling-p prompt last-valid))
4495 (defun org-at-TBLFM-p (&optional pos)
4496 "Return t when point (or POS) is in #+TBLFM line."
4497 (save-excursion
4498 (let ((pos pos)))
4499 (goto-char (or pos (point)))
4500 (beginning-of-line 1)
4501 (looking-at org-TBLFM-regexp)))
4503 (defvar org-clock-start-time)
4504 (defvar org-clock-marker (make-marker)
4505 "Marker recording the last clock-in.")
4506 (defvar org-clock-hd-marker (make-marker)
4507 "Marker recording the last clock-in, but the headline position.")
4508 (defvar org-clock-heading ""
4509 "The heading of the current clock entry.")
4510 (defun org-clock-is-active ()
4511 "Return the buffer where the clock is currently running.
4512 Return nil if no clock is running."
4513 (marker-buffer org-clock-marker))
4515 (defun org-check-running-clock ()
4516 "Check if the current buffer contains the running clock.
4517 If yes, offer to stop it and to save the buffer with the changes."
4518 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4519 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4520 (buffer-name))))
4521 (org-clock-out)
4522 (when (y-or-n-p "Save changed buffer?")
4523 (save-buffer))))
4525 (defun org-clocktable-try-shift (dir n)
4526 "Check if this line starts a clock table, if yes, shift the time block."
4527 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4528 (org-clocktable-shift dir n)))
4530 ;;;###autoload
4531 (defun org-clock-persistence-insinuate ()
4532 "Set up hooks for clock persistence."
4533 (require 'org-clock)
4534 (add-hook 'org-mode-hook 'org-clock-load)
4535 (add-hook 'kill-emacs-hook 'org-clock-save))
4537 (defgroup org-archive nil
4538 "Options concerning archiving in Org-mode."
4539 :tag "Org Archive"
4540 :group 'org-structure)
4542 (defcustom org-archive-location "%s_archive::"
4543 "The location where subtrees should be archived.
4545 The value of this variable is a string, consisting of two parts,
4546 separated by a double-colon. The first part is a filename and
4547 the second part is a headline.
4549 When the filename is omitted, archiving happens in the same file.
4550 %s in the filename will be replaced by the current file
4551 name (without the directory part). Archiving to a different file
4552 is useful to keep archived entries from contributing to the
4553 Org-mode Agenda.
4555 The archived entries will be filed as subtrees of the specified
4556 headline. When the headline is omitted, the subtrees are simply
4557 filed away at the end of the file, as top-level entries. Also in
4558 the heading you can use %s to represent the file name, this can be
4559 useful when using the same archive for a number of different files.
4561 Here are a few examples:
4562 \"%s_archive::\"
4563 If the current file is Projects.org, archive in file
4564 Projects.org_archive, as top-level trees. This is the default.
4566 \"::* Archived Tasks\"
4567 Archive in the current file, under the top-level headline
4568 \"* Archived Tasks\".
4570 \"~/org/archive.org::\"
4571 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4573 \"~/org/archive.org::* From %s\"
4574 Archive in file ~/org/archive.org (absolute path), under headlines
4575 \"From FILENAME\" where file name is the current file name.
4577 \"~/org/datetree.org::datetree/* Finished Tasks\"
4578 The \"datetree/\" string is special, signifying to archive
4579 items to the datetree. Items are placed in either the CLOSED
4580 date of the item, or the current date if there is no CLOSED date.
4581 The heading will be a subentry to the current date. There doesn't
4582 need to be a heading, but there always needs to be a slash after
4583 datetree. For example, to store archived items directly in the
4584 datetree, use \"~/org/datetree.org::datetree/\".
4586 \"basement::** Finished Tasks\"
4587 Archive in file ./basement (relative path), as level 3 trees
4588 below the level 2 heading \"** Finished Tasks\".
4590 You may set this option on a per-file basis by adding to the buffer a
4591 line like
4593 #+ARCHIVE: basement::** Finished Tasks
4595 You may also define it locally for a subtree by setting an ARCHIVE property
4596 in the entry. If such a property is found in an entry, or anywhere up
4597 the hierarchy, it will be used."
4598 :group 'org-archive
4599 :type 'string)
4601 (defcustom org-agenda-skip-archived-trees t
4602 "Non-nil means the agenda will skip any items located in archived trees.
4603 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4604 variable is no longer recommended, you should leave it at the value t.
4605 Instead, use the key `v' to cycle the archives-mode in the agenda."
4606 :group 'org-archive
4607 :group 'org-agenda-skip
4608 :type 'boolean)
4610 (defcustom org-columns-skip-archived-trees t
4611 "Non-nil means ignore archived trees when creating column view."
4612 :group 'org-archive
4613 :group 'org-properties
4614 :type 'boolean)
4616 (defcustom org-cycle-open-archived-trees nil
4617 "Non-nil means `org-cycle' will open archived trees.
4618 An archived tree is a tree marked with the tag ARCHIVE.
4619 When nil, archived trees will stay folded. You can still open them with
4620 normal outline commands like `show-all', but not with the cycling commands."
4621 :group 'org-archive
4622 :group 'org-cycle
4623 :type 'boolean)
4625 (defcustom org-sparse-tree-open-archived-trees nil
4626 "Non-nil means sparse tree construction shows matches in archived trees.
4627 When nil, matches in these trees are highlighted, but the trees are kept in
4628 collapsed state."
4629 :group 'org-archive
4630 :group 'org-sparse-trees
4631 :type 'boolean)
4633 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4634 "The default date type when building a sparse tree.
4635 When this is nil, a date is a scheduled or a deadline timestamp.
4636 Otherwise, these types are allowed:
4638 all: all timestamps
4639 active: only active timestamps (<...>)
4640 inactive: only inactive timestamps (<...)
4641 scheduled: only scheduled timestamps
4642 deadline: only deadline timestamps"
4643 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4644 (const :tag "All timestamps" all)
4645 (const :tag "Only active timestamps" active)
4646 (const :tag "Only inactive timestamps" inactive)
4647 (const :tag "Only scheduled timestamps" scheduled)
4648 (const :tag "Only deadline timestamps" deadline)
4649 (const :tag "Only closed timestamps" closed))
4650 :version "24.3"
4651 :group 'org-sparse-trees)
4653 (defun org-cycle-hide-archived-subtrees (state)
4654 "Re-hide all archived subtrees after a visibility state change."
4655 (when (and (not org-cycle-open-archived-trees)
4656 (not (memq state '(overview folded))))
4657 (save-excursion
4658 (let* ((globalp (memq state '(contents all)))
4659 (beg (if globalp (point-min) (point)))
4660 (end (if globalp (point-max) (org-end-of-subtree t))))
4661 (org-hide-archived-subtrees beg end)
4662 (goto-char beg)
4663 (if (looking-at (concat ".*:" org-archive-tag ":"))
4664 (message "%s" (substitute-command-keys
4665 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4667 (defun org-force-cycle-archived ()
4668 "Cycle subtree even if it is archived."
4669 (interactive)
4670 (setq this-command 'org-cycle)
4671 (let ((org-cycle-open-archived-trees t))
4672 (call-interactively 'org-cycle)))
4674 (defun org-hide-archived-subtrees (beg end)
4675 "Re-hide all archived subtrees after a visibility state change."
4676 (save-excursion
4677 (let* ((re (concat ":" org-archive-tag ":")))
4678 (goto-char beg)
4679 (while (re-search-forward re end t)
4680 (when (org-at-heading-p)
4681 (org-flag-subtree t)
4682 (org-end-of-subtree t))))))
4684 (declare-function outline-end-of-heading "outline" ())
4685 (declare-function outline-flag-region "outline" (from to flag))
4686 (defun org-flag-subtree (flag)
4687 (save-excursion
4688 (org-back-to-heading t)
4689 (outline-end-of-heading)
4690 (outline-flag-region (point)
4691 (progn (org-end-of-subtree t) (point))
4692 flag)))
4694 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4696 ;; Declare Column View Code
4698 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4699 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4700 (declare-function org-columns-compute "org-colview" (property))
4702 ;; Declare ID code
4704 (declare-function org-id-store-link "org-id")
4705 (declare-function org-id-locations-load "org-id")
4706 (declare-function org-id-locations-save "org-id")
4707 (defvar org-id-track-globally)
4709 ;;; Variables for pre-computed regular expressions, all buffer local
4711 (defvar org-todo-regexp nil
4712 "Matches any of the TODO state keywords.")
4713 (make-variable-buffer-local 'org-todo-regexp)
4714 (defvar org-not-done-regexp nil
4715 "Matches any of the TODO state keywords except the last one.")
4716 (make-variable-buffer-local 'org-not-done-regexp)
4717 (defvar org-not-done-heading-regexp nil
4718 "Matches a TODO headline that is not done.")
4719 (make-variable-buffer-local 'org-not-done-regexp)
4720 (defvar org-todo-line-regexp nil
4721 "Matches a headline and puts TODO state into group 2 if present.")
4722 (make-variable-buffer-local 'org-todo-line-regexp)
4723 (defvar org-complex-heading-regexp nil
4724 "Matches a headline and puts everything into groups:
4725 group 1: the stars
4726 group 2: The todo keyword, maybe
4727 group 3: Priority cookie
4728 group 4: True headline
4729 group 5: Tags")
4730 (make-variable-buffer-local 'org-complex-heading-regexp)
4731 (defvar org-complex-heading-regexp-format nil
4732 "Printf format to make regexp to match an exact headline.
4733 This regexp will match the headline of any node which has the
4734 exact headline text that is put into the format, but may have any
4735 TODO state, priority and tags.")
4736 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4737 (defvar org-todo-line-tags-regexp nil
4738 "Matches a headline and puts TODO state into group 2 if present.
4739 Also put tags into group 4 if tags are present.")
4740 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4741 (defvar org-ds-keyword-length 12
4742 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4743 (make-variable-buffer-local 'org-ds-keyword-length)
4744 (defvar org-deadline-regexp nil
4745 "Matches the DEADLINE keyword.")
4746 (make-variable-buffer-local 'org-deadline-regexp)
4747 (defvar org-deadline-time-regexp nil
4748 "Matches the DEADLINE keyword together with a time stamp.")
4749 (make-variable-buffer-local 'org-deadline-time-regexp)
4750 (defvar org-deadline-time-hour-regexp nil
4751 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4752 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4753 (defvar org-deadline-line-regexp nil
4754 "Matches the DEADLINE keyword and the rest of the line.")
4755 (make-variable-buffer-local 'org-deadline-line-regexp)
4756 (defvar org-scheduled-regexp nil
4757 "Matches the SCHEDULED keyword.")
4758 (make-variable-buffer-local 'org-scheduled-regexp)
4759 (defvar org-scheduled-time-regexp nil
4760 "Matches the SCHEDULED keyword together with a time stamp.")
4761 (make-variable-buffer-local 'org-scheduled-time-regexp)
4762 (defvar org-scheduled-time-hour-regexp nil
4763 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4764 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4765 (defvar org-closed-time-regexp nil
4766 "Matches the CLOSED keyword together with a time stamp.")
4767 (make-variable-buffer-local 'org-closed-time-regexp)
4769 (defvar org-keyword-time-regexp nil
4770 "Matches any of the 4 keywords, together with the time stamp.")
4771 (make-variable-buffer-local 'org-keyword-time-regexp)
4772 (defvar org-keyword-time-not-clock-regexp nil
4773 "Matches any of the 3 keywords, together with the time stamp.")
4774 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4775 (defvar org-maybe-keyword-time-regexp nil
4776 "Matches a timestamp, possibly preceded by a keyword.")
4777 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4778 (defvar org-all-time-keywords nil
4779 "List of time keywords.")
4780 (make-variable-buffer-local 'org-all-time-keywords)
4782 (defconst org-plain-time-of-day-regexp
4783 (concat
4784 "\\(\\<[012]?[0-9]"
4785 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4786 "\\(--?"
4787 "\\(\\<[012]?[0-9]"
4788 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4789 "\\)?")
4790 "Regular expression to match a plain time or time range.
4791 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4792 groups carry important information:
4793 0 the full match
4794 1 the first time, range or not
4795 8 the second time, if it is a range.")
4797 (defconst org-plain-time-extension-regexp
4798 (concat
4799 "\\(\\<[012]?[0-9]"
4800 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4801 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4802 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4803 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4804 groups carry important information:
4805 0 the full match
4806 7 hours of duration
4807 9 minutes of duration")
4809 (defconst org-stamp-time-of-day-regexp
4810 (concat
4811 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4812 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4813 "\\(--?"
4814 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4815 "Regular expression to match a timestamp time or time range.
4816 After a match, the following groups carry important information:
4817 0 the full match
4818 1 date plus weekday, for back referencing to make sure both times are on the same day
4819 2 the first time, range or not
4820 4 the second time, if it is a range.")
4822 (defconst org-startup-options
4823 '(("fold" org-startup-folded t)
4824 ("overview" org-startup-folded t)
4825 ("nofold" org-startup-folded nil)
4826 ("showall" org-startup-folded nil)
4827 ("showeverything" org-startup-folded showeverything)
4828 ("content" org-startup-folded content)
4829 ("indent" org-startup-indented t)
4830 ("noindent" org-startup-indented nil)
4831 ("hidestars" org-hide-leading-stars t)
4832 ("showstars" org-hide-leading-stars nil)
4833 ("odd" org-odd-levels-only t)
4834 ("oddeven" org-odd-levels-only nil)
4835 ("align" org-startup-align-all-tables t)
4836 ("noalign" org-startup-align-all-tables nil)
4837 ("inlineimages" org-startup-with-inline-images t)
4838 ("noinlineimages" org-startup-with-inline-images nil)
4839 ("latexpreview" org-startup-with-latex-preview t)
4840 ("nolatexpreview" org-startup-with-latex-preview nil)
4841 ("customtime" org-display-custom-times t)
4842 ("logdone" org-log-done time)
4843 ("lognotedone" org-log-done note)
4844 ("nologdone" org-log-done nil)
4845 ("lognoteclock-out" org-log-note-clock-out t)
4846 ("nolognoteclock-out" org-log-note-clock-out nil)
4847 ("logrepeat" org-log-repeat state)
4848 ("lognoterepeat" org-log-repeat note)
4849 ("logdrawer" org-log-into-drawer t)
4850 ("nologdrawer" org-log-into-drawer nil)
4851 ("logstatesreversed" org-log-states-order-reversed t)
4852 ("nologstatesreversed" org-log-states-order-reversed nil)
4853 ("nologrepeat" org-log-repeat nil)
4854 ("logreschedule" org-log-reschedule time)
4855 ("lognotereschedule" org-log-reschedule note)
4856 ("nologreschedule" org-log-reschedule nil)
4857 ("logredeadline" org-log-redeadline time)
4858 ("lognoteredeadline" org-log-redeadline note)
4859 ("nologredeadline" org-log-redeadline nil)
4860 ("logrefile" org-log-refile time)
4861 ("lognoterefile" org-log-refile note)
4862 ("nologrefile" org-log-refile nil)
4863 ("fninline" org-footnote-define-inline t)
4864 ("nofninline" org-footnote-define-inline nil)
4865 ("fnlocal" org-footnote-section nil)
4866 ("fnauto" org-footnote-auto-label t)
4867 ("fnprompt" org-footnote-auto-label nil)
4868 ("fnconfirm" org-footnote-auto-label confirm)
4869 ("fnplain" org-footnote-auto-label plain)
4870 ("fnadjust" org-footnote-auto-adjust t)
4871 ("nofnadjust" org-footnote-auto-adjust nil)
4872 ("constcgs" constants-unit-system cgs)
4873 ("constSI" constants-unit-system SI)
4874 ("noptag" org-tag-persistent-alist nil)
4875 ("hideblocks" org-hide-block-startup t)
4876 ("nohideblocks" org-hide-block-startup nil)
4877 ("beamer" org-startup-with-beamer-mode t)
4878 ("entitiespretty" org-pretty-entities t)
4879 ("entitiesplain" org-pretty-entities nil))
4880 "Variable associated with STARTUP options for org-mode.
4881 Each element is a list of three items: the startup options (as written
4882 in the #+STARTUP line), the corresponding variable, and the value to set
4883 this variable to if the option is found. An optional forth element PUSH
4884 means to push this value onto the list in the variable.")
4886 (defun org-update-property-plist (key val props)
4887 "Update PROPS with KEY and VAL."
4888 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4889 (key (if appending (substring key 0 (- (length key) 1)) key))
4890 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4891 (previous (cdr (assoc key props))))
4892 (if appending
4893 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4894 (cons (cons key val) remainder))))
4896 (defcustom org-group-tags t
4897 "When non-nil (the default), use group tags.
4898 This can be turned on/off through `org-toggle-tags-groups'."
4899 :group 'org-tags
4900 :group 'org-startup
4901 :type 'boolean)
4903 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4905 (defun org-toggle-tags-groups ()
4906 "Toggle support for group tags.
4907 Support for group tags is controlled by the option
4908 `org-group-tags', which is non-nil by default."
4909 (interactive)
4910 (setq org-group-tags (not org-group-tags))
4911 (cond ((and (derived-mode-p 'org-agenda-mode)
4912 org-group-tags)
4913 (org-agenda-redo))
4914 ((derived-mode-p 'org-mode)
4915 (let ((org-inhibit-startup t)) (org-mode))))
4916 (message "Groups tags support has been turned %s"
4917 (if org-group-tags "on" "off")))
4919 (defun org-set-regexps-and-options-for-tags ()
4920 "Precompute variables used for tags."
4921 (when (derived-mode-p 'org-mode)
4922 (org-set-local 'org-file-tags nil)
4923 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4924 (splitre "[ \t]+")
4925 (start 0)
4926 tags ftags key value)
4927 (save-excursion
4928 (save-restriction
4929 (widen)
4930 (goto-char (point-min))
4931 (while (re-search-forward re nil t)
4932 (setq key (upcase (org-match-string-no-properties 1))
4933 value (org-match-string-no-properties 2))
4934 (if (stringp value) (setq value (org-trim value)))
4935 (cond
4936 ((equal key "TAGS")
4937 (setq tags (append tags (if tags '("\\n") nil)
4938 (org-split-string value splitre))))
4939 ((equal key "FILETAGS")
4940 (when (string-match "\\S-" value)
4941 (setq ftags
4942 (append
4943 ftags
4944 (apply 'append
4945 (mapcar (lambda (x) (org-split-string x ":"))
4946 (org-split-string value)))))))))))
4947 ;; Process the file tags.
4948 (and ftags (org-set-local 'org-file-tags
4949 (mapcar 'org-add-prop-inherited ftags)))
4950 (org-set-local 'org-tag-groups-alist nil)
4951 ;; Process the tags.
4952 (when (and (not tags) org-tag-alist)
4953 (setq tags
4954 (mapcar
4955 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4956 ((eq (car tg) :endgroup) "}")
4957 ((eq (car tg) :grouptags) ":")
4958 ((eq (car tg) :newline) "\n")
4959 (t (concat (car tg)
4960 (if (characterp (cdr tg))
4961 (format "(%s)" (char-to-string (cdr tg))) "")))))
4962 org-tag-alist)))
4963 (let (e tgs g)
4964 (while (setq e (pop tags))
4965 (cond
4966 ((equal e "{")
4967 (progn (push '(:startgroup) tgs)
4968 (when (equal (nth 1 tags) ":")
4969 (push (list (replace-regexp-in-string
4970 "(.+)$" "" (nth 0 tags)))
4971 org-tag-groups-alist)
4972 (setq g 0))))
4973 ((equal e ":") (push '(:grouptags) tgs))
4974 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4975 ((equal e "\\n") (push '(:newline) tgs))
4976 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4977 (push (cons (match-string 1 e)
4978 (string-to-char (match-string 2 e))) tgs)
4979 (if (and g (> g 0))
4980 (setcar org-tag-groups-alist
4981 (append (car org-tag-groups-alist)
4982 (list (match-string 1 e)))))
4983 (if g (setq g (1+ g))))
4984 (t (push (list e) tgs)
4985 (if (and g (> g 0))
4986 (setcar org-tag-groups-alist
4987 (append (car org-tag-groups-alist) (list e))))
4988 (if g (setq g (1+ g))))))
4989 (org-set-local 'org-tag-alist nil)
4990 (while (setq e (pop tgs))
4991 (or (and (stringp (car e))
4992 (assoc (car e) org-tag-alist))
4993 (push e org-tag-alist)))
4994 ;; Return a list with tag variables
4995 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4997 (defvar org-ota nil)
4998 (defun org-set-regexps-and-options ()
4999 "Precompute regular expressions used in the current buffer."
5000 (when (derived-mode-p 'org-mode)
5001 (org-set-local 'org-todo-kwd-alist nil)
5002 (org-set-local 'org-todo-key-alist nil)
5003 (org-set-local 'org-todo-key-trigger nil)
5004 (org-set-local 'org-todo-keywords-1 nil)
5005 (org-set-local 'org-done-keywords nil)
5006 (org-set-local 'org-todo-heads nil)
5007 (org-set-local 'org-todo-sets nil)
5008 (org-set-local 'org-todo-log-states nil)
5009 (org-set-local 'org-file-properties nil)
5010 (let ((re (org-make-options-regexp
5011 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
5012 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
5013 "SETUPFILE" "OPTIONS")
5014 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
5015 (splitre "[ \t]+")
5016 (scripts org-use-sub-superscripts)
5017 kwds kws0 kwsa key log value cat arch const links hw dws
5018 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
5019 (start 0))
5020 (save-excursion
5021 (save-restriction
5022 (widen)
5023 (goto-char (point-min))
5024 (while
5025 (or (and
5026 ext-setup-or-nil
5027 (not org-ota)
5028 (let (ret)
5029 (with-temp-buffer
5030 (insert ext-setup-or-nil)
5031 (let ((major-mode 'org-mode) org-ota)
5032 (setq ret (save-match-data
5033 (org-set-regexps-and-options-for-tags)))))
5034 ;; Append setupfile tags to existing tags
5035 (setq org-ota t)
5036 (setq org-file-tags
5037 (delq nil (append org-file-tags (nth 0 ret)))
5038 org-tag-alist
5039 (delq nil (append org-tag-alist (nth 1 ret)))
5040 org-tag-groups-alist
5041 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5042 (and ext-setup-or-nil
5043 (string-match re ext-setup-or-nil start)
5044 (setq start (match-end 0)))
5045 (and (setq ext-setup-or-nil nil start 0)
5046 (re-search-forward re nil t)))
5047 (setq key (upcase (match-string 1 ext-setup-or-nil))
5048 value (org-match-string-no-properties 2 ext-setup-or-nil))
5049 (if (stringp value) (setq value (org-trim value)))
5050 (cond
5051 ((equal key "CATEGORY")
5052 (setq cat value))
5053 ((member key '("SEQ_TODO" "TODO"))
5054 (push (cons 'sequence (org-split-string value splitre)) kwds))
5055 ((equal key "TYP_TODO")
5056 (push (cons 'type (org-split-string value splitre)) kwds))
5057 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5058 ;; general TODO-like setup
5059 (push (cons (intern (downcase (match-string 1 key)))
5060 (org-split-string value splitre)) kwds))
5061 ((equal key "COLUMNS")
5062 (org-set-local 'org-columns-default-format value))
5063 ((equal key "LINK")
5064 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5065 (push (cons (match-string 1 value)
5066 (org-trim (match-string 2 value)))
5067 links)))
5068 ((equal key "PRIORITIES")
5069 (setq prio (org-split-string value " +")))
5070 ((equal key "PROPERTY")
5071 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5072 (setq props (org-update-property-plist (match-string 1 value)
5073 (match-string 2 value)
5074 props))))
5075 ((equal key "CONSTANTS")
5076 (org-table-set-constants))
5077 ((equal key "STARTUP")
5078 (let ((opts (org-split-string value splitre))
5079 l var val)
5080 (while (setq l (pop opts))
5081 (when (setq l (assoc l org-startup-options))
5082 (setq var (nth 1 l) val (nth 2 l))
5083 (if (not (nth 3 l))
5084 (set (make-local-variable var) val)
5085 (if (not (listp (symbol-value var)))
5086 (set (make-local-variable var) nil))
5087 (set (make-local-variable var) (symbol-value var))
5088 (add-to-list var val))))))
5089 ((equal key "ARCHIVE")
5090 (setq arch value)
5091 (remove-text-properties 0 (length arch)
5092 '(face t fontified t) arch))
5093 ((equal key "OPTIONS")
5094 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5095 (setq scripts (read (match-string 2 value)))))
5096 ((and (equal key "SETUPFILE")
5097 ;; Prevent checking in Gnus messages
5098 (not buffer-read-only))
5099 (setq setup-contents (org-file-contents
5100 (expand-file-name
5101 (org-remove-double-quotes value))
5102 'noerror))
5103 (if (not ext-setup-or-nil)
5104 (setq ext-setup-or-nil setup-contents start 0)
5105 (setq ext-setup-or-nil
5106 (concat (substring ext-setup-or-nil 0 start)
5107 "\n" setup-contents "\n"
5108 (substring ext-setup-or-nil start)))))))
5109 ;; search for property blocks
5110 (goto-char (point-min))
5111 (while (re-search-forward org-block-regexp nil t)
5112 (when (equal "PROPERTY" (upcase (match-string 1)))
5113 (setq value (replace-regexp-in-string
5114 "[\n\r]" " " (match-string 4)))
5115 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5116 (setq props (org-update-property-plist (match-string 1 value)
5117 (match-string 2 value)
5118 props)))))))
5119 (org-set-local 'org-use-sub-superscripts scripts)
5120 (when cat
5121 (org-set-local 'org-category (intern cat))
5122 (push (cons "CATEGORY" cat) props))
5123 (when prio
5124 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5125 (setq prio (mapcar 'string-to-char prio))
5126 (org-set-local 'org-highest-priority (nth 0 prio))
5127 (org-set-local 'org-lowest-priority (nth 1 prio))
5128 (org-set-local 'org-default-priority (nth 2 prio)))
5129 (and props (org-set-local 'org-file-properties (nreverse props)))
5130 (and arch (org-set-local 'org-archive-location arch))
5131 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5132 ;; Process the TODO keywords
5133 (unless kwds
5134 ;; Use the global values as if they had been given locally.
5135 (setq kwds (default-value 'org-todo-keywords))
5136 (if (stringp (car kwds))
5137 (setq kwds (list (cons org-todo-interpretation
5138 (default-value 'org-todo-keywords)))))
5139 (setq kwds (reverse kwds)))
5140 (setq kwds (nreverse kwds))
5141 (let (inter kws kw)
5142 (while (setq kws (pop kwds))
5143 (let ((kws (or
5144 (run-hook-with-args-until-success
5145 'org-todo-setup-filter-hook kws)
5146 kws)))
5147 (setq inter (pop kws) sep (member "|" kws)
5148 kws0 (delete "|" (copy-sequence kws))
5149 kwsa nil
5150 kws1 (mapcar
5151 (lambda (x)
5152 ;; 1 2
5153 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5154 (progn
5155 (setq kw (match-string 1 x)
5156 key (and (match-end 2) (match-string 2 x))
5157 log (org-extract-log-state-settings x))
5158 (push (cons kw (and key (string-to-char key))) kwsa)
5159 (and log (push log org-todo-log-states))
5161 (error "Invalid TODO keyword %s" x)))
5162 kws0)
5163 kwsa (if kwsa (append '((:startgroup))
5164 (nreverse kwsa)
5165 '((:endgroup))))
5166 hw (car kws1)
5167 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5168 tail (list inter hw (car dws) (org-last dws))))
5169 (add-to-list 'org-todo-heads hw 'append)
5170 (push kws1 org-todo-sets)
5171 (setq org-done-keywords (append org-done-keywords dws nil))
5172 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5173 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5174 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5175 (setq org-todo-sets (nreverse org-todo-sets)
5176 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5177 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5178 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5179 ;; Compute the regular expressions and other local variables.
5180 ;; Using `org-outline-regexp-bol' would complicate them much,
5181 ;; because of the fixed white space at the end of that string.
5182 (if (not org-done-keywords)
5183 (setq org-done-keywords (and org-todo-keywords-1
5184 (list (org-last org-todo-keywords-1)))))
5185 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5186 (length org-scheduled-string)
5187 (length org-clock-string)
5188 (length org-closed-string)))
5189 org-not-done-keywords
5190 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5191 org-todo-regexp
5192 (concat "\\("
5193 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5194 "\\)")
5195 org-not-done-regexp
5196 (concat "\\("
5197 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5198 "\\)")
5199 org-not-done-heading-regexp
5200 (format org-heading-keyword-regexp-format org-not-done-regexp)
5201 org-todo-line-regexp
5202 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5203 org-complex-heading-regexp
5204 (concat "^\\(\\*+\\)"
5205 "\\(?: +" org-todo-regexp "\\)?"
5206 "\\(?: +\\(\\[#.\\]\\)\\)?"
5207 "\\(?: +\\(.*?\\)\\)??"
5208 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5209 "[ \t]*$")
5210 org-complex-heading-regexp-format
5211 (concat "^\\(\\*+\\)"
5212 "\\(?: +" org-todo-regexp "\\)?"
5213 "\\(?: +\\(\\[#.\\]\\)\\)?"
5214 "\\(?: +"
5215 ;; Stats cookies can be stuck to body.
5216 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5217 "\\(%s\\)"
5218 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5219 "\\)"
5220 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5221 "[ \t]*$")
5222 org-todo-line-tags-regexp
5223 (concat "^\\(\\*+\\)"
5224 "\\(?: +" org-todo-regexp "\\)?"
5225 "\\(?: +\\(.*?\\)\\)??"
5226 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5227 "[ \t]*$")
5228 org-deadline-regexp (concat "\\<" org-deadline-string)
5229 org-deadline-time-regexp
5230 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5231 org-deadline-time-hour-regexp
5232 (concat "\\<" org-deadline-string
5233 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5234 org-deadline-line-regexp
5235 (concat "\\<\\(" org-deadline-string "\\).*")
5236 org-scheduled-regexp
5237 (concat "\\<" org-scheduled-string)
5238 org-scheduled-time-regexp
5239 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5240 org-scheduled-time-hour-regexp
5241 (concat "\\<" org-scheduled-string
5242 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5243 org-closed-time-regexp
5244 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5245 org-keyword-time-regexp
5246 (concat "\\<\\(" org-scheduled-string
5247 "\\|" org-deadline-string
5248 "\\|" org-closed-string
5249 "\\|" org-clock-string "\\)"
5250 " *[[<]\\([^]>]+\\)[]>]")
5251 org-keyword-time-not-clock-regexp
5252 (concat "\\<\\(" org-scheduled-string
5253 "\\|" org-deadline-string
5254 "\\|" org-closed-string
5255 "\\)"
5256 " *[[<]\\([^]>]+\\)[]>]")
5257 org-maybe-keyword-time-regexp
5258 (concat "\\(\\<\\(" org-scheduled-string
5259 "\\|" org-deadline-string
5260 "\\|" org-closed-string
5261 "\\|" org-clock-string "\\)\\)?"
5262 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5263 org-all-time-keywords
5264 (mapcar (lambda (w) (substring w 0 -1))
5265 (list org-scheduled-string org-deadline-string
5266 org-clock-string org-closed-string)))
5267 (setq org-ota nil)
5268 (org-compute-latex-and-related-regexp))))
5270 (defun org-file-contents (file &optional noerror)
5271 "Return the contents of FILE, as a string."
5272 (if (and file (file-readable-p file))
5273 (with-temp-buffer
5274 (insert-file-contents file)
5275 (buffer-string))
5276 (funcall (if noerror 'message 'error)
5277 "Cannot read file \"%s\"%s"
5278 file
5279 (let ((from (buffer-file-name (buffer-base-buffer))))
5280 (if from (concat " (referenced in file \"" from "\")") "")))))
5282 (defun org-extract-log-state-settings (x)
5283 "Extract the log state setting from a TODO keyword string.
5284 This will extract info from a string like \"WAIT(w@/!)\"."
5285 (let (kw key log1 log2)
5286 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5287 (setq kw (match-string 1 x)
5288 key (and (match-end 2) (match-string 2 x))
5289 log1 (and (match-end 3) (match-string 3 x))
5290 log2 (and (match-end 4) (match-string 4 x)))
5291 (and (or log1 log2)
5292 (list kw
5293 (and log1 (if (equal log1 "!") 'time 'note))
5294 (and log2 (if (equal log2 "!") 'time 'note)))))))
5296 (defun org-remove-keyword-keys (list)
5297 "Remove a pair of parenthesis at the end of each string in LIST."
5298 (mapcar (lambda (x)
5299 (if (string-match "(.*)$" x)
5300 (substring x 0 (match-beginning 0))
5302 list))
5304 (defun org-assign-fast-keys (alist)
5305 "Assign fast keys to a keyword-key alist.
5306 Respect keys that are already there."
5307 (let (new e (alt ?0))
5308 (while (setq e (pop alist))
5309 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5310 (cdr e)) ;; Key already assigned.
5311 (push e new)
5312 (let ((clist (string-to-list (downcase (car e))))
5313 (used (append new alist)))
5314 (when (= (car clist) ?@)
5315 (pop clist))
5316 (while (and clist (rassoc (car clist) used))
5317 (pop clist))
5318 (unless clist
5319 (while (rassoc alt used)
5320 (incf alt)))
5321 (push (cons (car e) (or (car clist) alt)) new))))
5322 (nreverse new)))
5324 ;;; Some variables used in various places
5326 (defvar org-window-configuration nil
5327 "Used in various places to store a window configuration.")
5328 (defvar org-selected-window nil
5329 "Used in various places to store a window configuration.")
5330 (defvar org-finish-function nil
5331 "Function to be called when `C-c C-c' is used.
5332 This is for getting out of special buffers like capture.")
5335 ;; FIXME: Occasionally check by commenting these, to make sure
5336 ;; no other functions uses these, forgetting to let-bind them.
5337 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5338 (defvar org-last-state)
5339 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5341 ;; Defined somewhere in this file, but used before definition.
5342 (defvar org-entities) ;; defined in org-entities.el
5343 (defvar org-struct-menu)
5344 (defvar org-org-menu)
5345 (defvar org-tbl-menu)
5347 ;;;; Define the Org-mode
5349 ;; We use a before-change function to check if a table might need
5350 ;; an update.
5351 (defvar org-table-may-need-update t
5352 "Indicates that a table might need an update.
5353 This variable is set by `org-before-change-function'.
5354 `org-table-align' sets it back to nil.")
5355 (defun org-before-change-function (beg end)
5356 "Every change indicates that a table might need an update."
5357 (setq org-table-may-need-update t))
5358 (defvar org-mode-map)
5359 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5360 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5361 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5362 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5363 (defvar org-table-buffer-is-an nil)
5365 (defvar bidi-paragraph-direction)
5366 (defvar buffer-face-mode-face)
5368 (require 'outline)
5369 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5370 (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"))
5371 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5373 ;; Other stuff we need.
5374 (require 'time-date)
5375 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5376 (require 'easymenu)
5377 (require 'overlay)
5379 ;; (require 'org-macs) moved higher up in the file before it is first used
5380 (require 'org-entities)
5381 ;; (require 'org-compat) moved higher up in the file before it is first used
5382 (require 'org-faces)
5383 (require 'org-list)
5384 (require 'org-pcomplete)
5385 (require 'org-src)
5386 (require 'org-footnote)
5387 (require 'org-macro)
5389 ;; babel
5390 (require 'ob)
5392 ;;;###autoload
5393 (define-derived-mode org-mode outline-mode "Org"
5394 "Outline-based notes management and organizer, alias
5395 \"Carsten's outline-mode for keeping track of everything.\"
5397 Org-mode develops organizational tasks around a NOTES file which
5398 contains information about projects as plain text. Org-mode is
5399 implemented on top of outline-mode, which is ideal to keep the content
5400 of large files well structured. It supports ToDo items, deadlines and
5401 time stamps, which magically appear in the diary listing of the Emacs
5402 calendar. Tables are easily created with a built-in table editor.
5403 Plain text URL-like links connect to websites, emails (VM), Usenet
5404 messages (Gnus), BBDB entries, and any files related to the project.
5405 For printing and sharing of notes, an Org-mode file (or a part of it)
5406 can be exported as a structured ASCII or HTML file.
5408 The following commands are available:
5410 \\{org-mode-map}"
5412 ;; Get rid of Outline menus, they are not needed
5413 ;; Need to do this here because define-derived-mode sets up
5414 ;; the keymap so late. Still, it is a waste to call this each time
5415 ;; we switch another buffer into org-mode.
5416 (if (featurep 'xemacs)
5417 (when (boundp 'outline-mode-menu-heading)
5418 ;; Assume this is Greg's port, it uses easymenu
5419 (easy-menu-remove outline-mode-menu-heading)
5420 (easy-menu-remove outline-mode-menu-show)
5421 (easy-menu-remove outline-mode-menu-hide))
5422 (define-key org-mode-map [menu-bar headings] 'undefined)
5423 (define-key org-mode-map [menu-bar hide] 'undefined)
5424 (define-key org-mode-map [menu-bar show] 'undefined))
5426 (org-load-modules-maybe)
5427 (easy-menu-add org-org-menu)
5428 (easy-menu-add org-tbl-menu)
5429 (org-install-agenda-files-menu)
5430 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5431 (add-to-invisibility-spec '(org-cwidth))
5432 (add-to-invisibility-spec '(org-hide-block . t))
5433 (when (featurep 'xemacs)
5434 (org-set-local 'line-move-ignore-invisible t))
5435 (org-set-local 'outline-regexp org-outline-regexp)
5436 (org-set-local 'outline-level 'org-outline-level)
5437 (setq bidi-paragraph-direction 'left-to-right)
5438 (when (and org-ellipsis
5439 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5440 (fboundp 'make-glyph-code))
5441 (unless org-display-table
5442 (setq org-display-table (make-display-table)))
5443 (set-display-table-slot
5444 org-display-table 4
5445 (vconcat (mapcar
5446 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5447 org-ellipsis)))
5448 (if (stringp org-ellipsis) org-ellipsis "..."))))
5449 (setq buffer-display-table org-display-table))
5450 (org-set-regexps-and-options-for-tags)
5451 (org-set-regexps-and-options)
5452 (org-set-font-lock-defaults)
5453 (when (and org-tag-faces (not org-tags-special-faces-re))
5454 ;; tag faces set outside customize.... force initialization.
5455 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5456 ;; Calc embedded
5457 (org-set-local 'calc-embedded-open-mode "# ")
5458 ;; Modify a few syntax entries
5459 (modify-syntax-entry ?@ "w")
5460 (modify-syntax-entry ?\" "\"")
5461 (modify-syntax-entry ?\\ "_")
5462 (modify-syntax-entry ?~ "_")
5463 (if org-startup-truncated (setq truncate-lines t))
5464 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5465 (org-set-local 'font-lock-unfontify-region-function
5466 'org-unfontify-region)
5467 ;; Activate before-change-function
5468 (org-set-local 'org-table-may-need-update t)
5469 (org-add-hook 'before-change-functions 'org-before-change-function nil
5470 'local)
5471 ;; Check for running clock before killing a buffer
5472 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5473 ;; Initialize macros templates.
5474 (org-macro-initialize-templates)
5475 ;; Initialize radio targets.
5476 (org-update-radio-target-regexp)
5477 ;; Indentation.
5478 (org-set-local 'indent-line-function 'org-indent-line)
5479 (org-set-local 'indent-region-function 'org-indent-region)
5480 ;; Filling and auto-filling.
5481 (org-setup-filling)
5482 ;; Comments.
5483 (org-setup-comments-handling)
5484 ;; Initialize cache.
5485 (org-element-cache-reset)
5486 ;; Beginning/end of defun
5487 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5488 (org-set-local 'end-of-defun-function
5489 (lambda ()
5490 (if (not (org-at-heading-p))
5491 (org-forward-element)
5492 (org-forward-element)
5493 (forward-char -1))))
5494 ;; Next error for sparse trees
5495 (org-set-local 'next-error-function 'org-occur-next-match)
5496 ;; Make sure dependence stuff works reliably, even for users who set it
5497 ;; too late :-(
5498 (if org-enforce-todo-dependencies
5499 (add-hook 'org-blocker-hook
5500 'org-block-todo-from-children-or-siblings-or-parent)
5501 (remove-hook 'org-blocker-hook
5502 'org-block-todo-from-children-or-siblings-or-parent))
5503 (if org-enforce-todo-checkbox-dependencies
5504 (add-hook 'org-blocker-hook
5505 'org-block-todo-from-checkboxes)
5506 (remove-hook 'org-blocker-hook
5507 'org-block-todo-from-checkboxes))
5509 ;; Align options lines
5510 (org-set-local
5511 'align-mode-rules-list
5512 '((org-in-buffer-settings
5513 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5514 (modes . '(org-mode)))))
5516 ;; Imenu
5517 (org-set-local 'imenu-create-index-function
5518 'org-imenu-get-tree)
5520 ;; Make isearch reveal context
5521 (if (or (featurep 'xemacs)
5522 (not (boundp 'outline-isearch-open-invisible-function)))
5523 ;; Emacs 21 and XEmacs make use of the hook
5524 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5525 ;; Emacs 22 deals with this through a special variable
5526 (org-set-local 'outline-isearch-open-invisible-function
5527 (lambda (&rest ignore) (org-show-context 'isearch))))
5529 ;; Setup the pcomplete hooks
5530 (set (make-local-variable 'pcomplete-command-completion-function)
5531 'org-pcomplete-initial)
5532 (set (make-local-variable 'pcomplete-command-name-function)
5533 'org-command-at-point)
5534 (set (make-local-variable 'pcomplete-default-completion-function)
5535 'ignore)
5536 (set (make-local-variable 'pcomplete-parse-arguments-function)
5537 'org-parse-arguments)
5538 (set (make-local-variable 'pcomplete-termination-string) "")
5539 (when (>= emacs-major-version 23)
5540 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5542 ;; If empty file that did not turn on org-mode automatically, make it to.
5543 (if (and org-insert-mode-line-in-empty-file
5544 (org-called-interactively-p 'any)
5545 (= (point-min) (point-max)))
5546 (insert "# -*- mode: org -*-\n\n"))
5547 (unless org-inhibit-startup
5548 (org-unmodified
5549 (and org-startup-with-beamer-mode (org-beamer-mode))
5550 (when org-startup-align-all-tables
5551 (org-table-map-tables 'org-table-align 'quietly))
5552 (when org-startup-with-inline-images
5553 (org-display-inline-images))
5554 (when org-startup-with-latex-preview
5555 (org-toggle-latex-fragment))
5556 (unless org-inhibit-startup-visibility-stuff
5557 (org-set-startup-visibility))
5558 (org-refresh-effort-properties)))
5559 ;; Try to set org-hide correctly
5560 (let ((foreground (org-find-invisible-foreground)))
5561 (if foreground
5562 (set-face-foreground 'org-hide foreground))))
5564 ;; Update `customize-package-emacs-version-alist'
5565 (add-to-list 'customize-package-emacs-version-alist
5566 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5567 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5568 ("8.2.6" . "24.4")))
5570 (defvar org-mode-transpose-word-syntax-table
5571 (let ((st (make-syntax-table)))
5572 (mapc (lambda(c) (modify-syntax-entry
5573 (string-to-char (car c)) "w p" st))
5574 org-emphasis-alist)
5575 st))
5577 (when (fboundp 'abbrev-table-put)
5578 (abbrev-table-put org-mode-abbrev-table
5579 :parents (list text-mode-abbrev-table)))
5581 (defun org-find-invisible-foreground ()
5582 (let ((candidates (remove
5583 "unspecified-bg"
5584 (nconc
5585 (list (face-background 'default)
5586 (face-background 'org-default))
5587 (mapcar
5588 (lambda (alist)
5589 (when (boundp alist)
5590 (cdr (assoc 'background-color (symbol-value alist)))))
5591 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5592 (list (face-foreground 'org-hide))))))
5593 (car (remove nil candidates))))
5595 (defun org-current-time (&optional rounding-minutes past)
5596 "Current time, possibly rounded to ROUNDING-MINUTES.
5597 When ROUNDING-MINUTES is not an integer, fall back on the car of
5598 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5599 the rounding returns a past time."
5600 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5601 (car org-time-stamp-rounding-minutes)))
5602 (time (decode-time)) res)
5603 (if (< r 1)
5604 (current-time)
5605 (setq res
5606 (apply 'encode-time
5607 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5608 (nthcdr 2 time))))
5609 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5610 (seconds-to-time (- (org-float-time res) (* r 60)))
5611 res))))
5613 (defun org-today ()
5614 "Return today date, considering `org-extend-today-until'."
5615 (time-to-days
5616 (time-subtract (current-time)
5617 (list 0 (* 3600 org-extend-today-until) 0))))
5619 ;;;; Font-Lock stuff, including the activators
5621 (defvar org-mouse-map (make-sparse-keymap))
5622 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5623 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5624 (when org-mouse-1-follows-link
5625 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5626 (when org-tab-follows-link
5627 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5628 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5630 (require 'font-lock)
5632 (defconst org-non-link-chars "]\t\n\r<>")
5633 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5634 "file+sys" "news" "shell" "elisp" "doi" "message"
5635 "help"))
5636 (defvar org-link-types-re nil
5637 "Matches a link that has a url-like prefix like \"http:\"")
5638 (defvar org-link-re-with-space nil
5639 "Matches a link with spaces, optional angular brackets around it.")
5640 (defvar org-link-re-with-space2 nil
5641 "Matches a link with spaces, optional angular brackets around it.")
5642 (defvar org-link-re-with-space3 nil
5643 "Matches a link with spaces, only for internal part in bracket links.")
5644 (defvar org-angle-link-re nil
5645 "Matches link with angular brackets, spaces are allowed.")
5646 (defvar org-plain-link-re nil
5647 "Matches plain link, without spaces.")
5648 (defvar org-bracket-link-regexp nil
5649 "Matches a link in double brackets.")
5650 (defvar org-bracket-link-analytic-regexp nil
5651 "Regular expression used to analyze links.
5652 Here is what the match groups contain after a match:
5653 1: http:
5654 2: http
5655 3: path
5656 4: [desc]
5657 5: desc")
5658 (defvar org-bracket-link-analytic-regexp++ nil
5659 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5660 (defvar org-any-link-re nil
5661 "Regular expression matching any link.")
5663 (defconst org-match-sexp-depth 3
5664 "Number of stacked braces for sub/superscript matching.")
5666 (defun org-create-multibrace-regexp (left right n)
5667 "Create a regular expression which will match a balanced sexp.
5668 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5669 as single character strings.
5670 The regexp returned will match the entire expression including the
5671 delimiters. It will also define a single group which contains the
5672 match except for the outermost delimiters. The maximum depth of
5673 stacked delimiters is N. Escaping delimiters is not possible."
5674 (let* ((nothing (concat "[^" left right "]*?"))
5675 (or "\\|")
5676 (re nothing)
5677 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5678 (while (> n 1)
5679 (setq n (1- n)
5680 re (concat re or next)
5681 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5682 (concat left "\\(" re "\\)" right)))
5684 (defconst org-match-substring-regexp
5685 (concat
5686 "\\(\\S-\\)\\([_^]\\)\\("
5687 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5688 "\\|"
5689 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5690 "\\|"
5691 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5692 "The regular expression matching a sub- or superscript.")
5694 (defconst org-match-substring-with-braces-regexp
5695 (concat
5696 "\\(\\S-\\)\\([_^]\\)"
5697 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5698 "The regular expression matching a sub- or superscript, forcing braces.")
5700 (defun org-make-link-regexps ()
5701 "Update the link regular expressions.
5702 This should be called after the variable `org-link-types' has changed."
5703 (let ((types-re (regexp-opt org-link-types t)))
5704 (setq org-link-types-re
5705 (concat "\\`" types-re ":")
5706 org-link-re-with-space
5707 (concat "<?" types-re ":"
5708 "\\([^" org-non-link-chars " ]"
5709 "[^" org-non-link-chars "]*"
5710 "[^" org-non-link-chars " ]\\)>?")
5711 org-link-re-with-space2
5712 (concat "<?" types-re ":"
5713 "\\([^" org-non-link-chars " ]"
5714 "[^\t\n\r]*"
5715 "[^" org-non-link-chars " ]\\)>?")
5716 org-link-re-with-space3
5717 (concat "<?" types-re ":"
5718 "\\([^" org-non-link-chars " ]"
5719 "[^\t\n\r]*\\)")
5720 org-angle-link-re
5721 (concat "<" types-re ":"
5722 "\\([^" org-non-link-chars " ]"
5723 "[^" org-non-link-chars "]*"
5724 "\\)>")
5725 org-plain-link-re
5726 (concat
5727 "\\<" types-re ":"
5728 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5729 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5730 org-bracket-link-regexp
5731 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5732 org-bracket-link-analytic-regexp
5733 (concat
5734 "\\[\\["
5735 "\\(" types-re ":\\)?"
5736 "\\([^]]+\\)"
5737 "\\]"
5738 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5739 "\\]")
5740 org-bracket-link-analytic-regexp++
5741 (concat
5742 "\\[\\["
5743 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5744 "\\([^]]+\\)"
5745 "\\]"
5746 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5747 "\\]")
5748 org-any-link-re
5749 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5750 org-angle-link-re "\\)\\|\\("
5751 org-plain-link-re "\\)"))))
5753 (org-make-link-regexps)
5755 (defvar org-emph-face nil)
5757 (defun org-do-emphasis-faces (limit)
5758 "Run through the buffer and emphasize strings."
5759 (let (rtn a)
5760 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5761 (let* ((border (char-after (match-beginning 3)))
5762 (bre (regexp-quote (char-to-string border))))
5763 (if (and (not (= border (char-after (match-beginning 4))))
5764 (not (save-match-data
5765 (string-match (concat bre ".*" bre)
5766 (replace-regexp-in-string
5767 "\n" " "
5768 (substring (match-string 2) 1 -1))))))
5769 (progn
5770 (setq rtn t)
5771 (setq a (assoc (match-string 3) org-emphasis-alist))
5772 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5773 'face
5774 (nth 1 a))
5775 (and (nth 2 a)
5776 (org-remove-flyspell-overlays-in
5777 (match-beginning 0) (match-end 0)))
5778 (add-text-properties (match-beginning 2) (match-end 2)
5779 '(font-lock-multiline t org-emphasis t))
5780 (when org-hide-emphasis-markers
5781 (add-text-properties (match-end 4) (match-beginning 5)
5782 '(invisible org-link))
5783 (add-text-properties (match-beginning 3) (match-end 3)
5784 '(invisible org-link))))))
5785 (goto-char (1+ (match-beginning 0))))
5786 rtn))
5788 (defun org-emphasize (&optional char)
5789 "Insert or change an emphasis, i.e. a font like bold or italic.
5790 If there is an active region, change that region to a new emphasis.
5791 If there is no region, just insert the marker characters and position
5792 the cursor between them.
5793 CHAR should be the marker character. If it is a space, it means to
5794 remove the emphasis of the selected region.
5795 If CHAR is not given (for example in an interactive call) it will be
5796 prompted for."
5797 (interactive)
5798 (let ((erc org-emphasis-regexp-components)
5799 (prompt "")
5800 (string "") beg end move c s)
5801 (if (org-region-active-p)
5802 (setq beg (region-beginning) end (region-end)
5803 string (buffer-substring beg end))
5804 (setq move t))
5806 (unless char
5807 (message "Emphasis marker or tag: [%s]"
5808 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5809 (setq char (read-char-exclusive)))
5810 (if (equal char ?\ )
5811 (setq s "" move nil)
5812 (unless (assoc (char-to-string char) org-emphasis-alist)
5813 (user-error "No such emphasis marker: \"%c\"" char))
5814 (setq s (char-to-string char)))
5815 (while (and (> (length string) 1)
5816 (equal (substring string 0 1) (substring string -1))
5817 (assoc (substring string 0 1) org-emphasis-alist))
5818 (setq string (substring string 1 -1)))
5819 (setq string (concat s string s))
5820 (if beg (delete-region beg end))
5821 (unless (or (bolp)
5822 (string-match (concat "[" (nth 0 erc) "\n]")
5823 (char-to-string (char-before (point)))))
5824 (insert " "))
5825 (unless (or (eobp)
5826 (string-match (concat "[" (nth 1 erc) "\n]")
5827 (char-to-string (char-after (point)))))
5828 (insert " ") (backward-char 1))
5829 (insert string)
5830 (and move (backward-char 1))))
5832 (defconst org-nonsticky-props
5833 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5835 (defsubst org-rear-nonsticky-at (pos)
5836 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5838 (defun org-activate-plain-links (limit)
5839 "Add link properties for plain links."
5840 (let (f hl)
5841 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5842 (not (member 'org-tag
5843 (get-text-property (1- (match-beginning 0)) 'face)))
5844 (not (org-in-src-block-p)))
5845 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5846 (setq f (get-text-property (match-beginning 0) 'face))
5847 (setq hl (org-match-string-no-properties 0))
5848 (if (or (eq f 'org-tag)
5849 (and (listp f) (memq 'org-tag f)))
5851 (add-text-properties (match-beginning 0) (match-end 0)
5852 (list 'mouse-face 'highlight
5853 'face 'org-link
5854 'htmlize-link `(:uri ,hl)
5855 'keymap org-mouse-map))
5856 (org-rear-nonsticky-at (match-end 0)))
5857 t)))
5859 (defun org-activate-code (limit)
5860 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5861 (progn
5862 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5863 (remove-text-properties (match-beginning 0) (match-end 0)
5864 '(display t invisible t intangible t))
5865 t)))
5867 (defcustom org-src-fontify-natively t
5868 "When non-nil, fontify code in code blocks."
5869 :type 'boolean
5870 :version "24.4"
5871 :package-version '(Org . "8.3")
5872 :group 'org-appearance
5873 :group 'org-babel)
5875 (defcustom org-allow-promoting-top-level-subtree nil
5876 "When non-nil, allow promoting a top level subtree.
5877 The leading star of the top level headline will be replaced
5878 by a #."
5879 :type 'boolean
5880 :version "24.1"
5881 :group 'org-appearance)
5883 (defun org-fontify-meta-lines-and-blocks (limit)
5884 (condition-case nil
5885 (org-fontify-meta-lines-and-blocks-1 limit)
5886 (error (message "org-mode fontification error"))))
5888 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5889 "Fontify #+ lines and blocks."
5890 (let ((case-fold-search t))
5891 (if (re-search-forward
5892 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5893 limit t)
5894 (let ((beg (match-beginning 0))
5895 (block-start (match-end 0))
5896 (block-end nil)
5897 (lang (match-string 7))
5898 (beg1 (line-beginning-position 2))
5899 (dc1 (downcase (match-string 2)))
5900 (dc3 (downcase (match-string 3)))
5901 end end1 quoting block-type ovl)
5902 (cond
5903 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5904 ;; a single line of backend-specific content
5905 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5906 (remove-text-properties (match-beginning 0) (match-end 0)
5907 '(display t invisible t intangible t))
5908 (add-text-properties (match-beginning 1) (match-end 3)
5909 '(font-lock-fontified t face org-meta-line))
5910 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5911 '(font-lock-fontified t face org-block))
5912 ; for backend-specific code
5914 ((and (match-end 4) (equal dc3 "+begin"))
5915 ;; Truly a block
5916 (setq block-type (downcase (match-string 5))
5917 quoting (member block-type org-protecting-blocks))
5918 (when (re-search-forward
5919 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5920 nil t) ;; on purpose, we look further than LIMIT
5921 (setq end (min (point-max) (match-end 0))
5922 end1 (min (point-max) (1- (match-beginning 0))))
5923 (setq block-end (match-beginning 0))
5924 (when quoting
5925 (org-remove-flyspell-overlays-in beg1 end1)
5926 (remove-text-properties beg end
5927 '(display t invisible t intangible t)))
5928 (add-text-properties
5929 beg end '(font-lock-fontified t font-lock-multiline t))
5930 (add-text-properties beg beg1 '(face org-meta-line))
5931 (org-remove-flyspell-overlays-in beg beg1)
5932 (add-text-properties ; For end_src
5933 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5934 (org-remove-flyspell-overlays-in end1 end)
5935 (cond
5936 ((and lang (not (string= lang "")) org-src-fontify-natively)
5937 (org-src-font-lock-fontify-block lang block-start block-end)
5938 (add-text-properties beg1 block-end '(src-block t)))
5939 (quoting
5940 (add-text-properties beg1 (min (point-max) (1+ end1))
5941 '(face org-block))) ; end of source block
5942 ((not org-fontify-quote-and-verse-blocks))
5943 ((string= block-type "quote")
5944 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5945 ((string= block-type "verse")
5946 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5947 (add-text-properties beg beg1 '(face org-block-begin-line))
5948 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5949 '(face org-block-end-line))
5951 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5952 (org-remove-flyspell-overlays-in
5953 (match-beginning 0)
5954 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5955 (add-text-properties
5956 beg (match-end 3)
5957 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5958 '(font-lock-fontified t invisible t)
5959 '(font-lock-fontified t face org-document-info-keyword)))
5960 (add-text-properties
5961 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5962 (if (string-equal dc1 "+title:")
5963 '(font-lock-fontified t face org-document-title)
5964 '(font-lock-fontified t face org-document-info))))
5965 ((or (equal dc1 "+results")
5966 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5967 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5968 "+call:" "+header:" "+headers:" "+name:"))
5969 (and (match-end 4) (equal dc3 "+attr")))
5970 (org-remove-flyspell-overlays-in
5971 (match-beginning 0)
5972 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5973 (add-text-properties
5974 beg (match-end 0)
5975 '(font-lock-fontified t face org-meta-line))
5977 ((member dc3 '(" " ""))
5978 (org-remove-flyspell-overlays-in beg (match-end 0))
5979 (add-text-properties
5980 beg (match-end 0)
5981 '(font-lock-fontified t face font-lock-comment-face)))
5982 (t ;; just any other in-buffer setting, but not indented
5983 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5984 (add-text-properties
5985 beg (match-end 0)
5986 '(font-lock-fontified t face org-meta-line))
5987 t))))))
5989 (defun org-fontify-drawers (limit)
5990 "Fontify drawers."
5991 (when (re-search-forward org-drawer-regexp limit t)
5992 (add-text-properties
5993 (match-beginning 0) (match-end 0)
5994 '(font-lock-fontified t face org-special-keyword))
5995 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5998 (defun org-fontify-macros (limit)
5999 "Fontify macros."
6000 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6001 (add-text-properties
6002 (match-beginning 0) (match-end 0)
6003 '(font-lock-fontified t face org-macro))
6004 (when org-hide-macro-markers
6005 (add-text-properties (match-end 2) (match-beginning 2)
6006 '(invisible t))
6007 (add-text-properties (match-beginning 1) (match-end 1)
6008 '(invisible t)))
6009 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6012 (defun org-activate-angle-links (limit)
6013 "Add text properties for angle links."
6014 (if (and (re-search-forward org-angle-link-re limit t)
6015 (not (org-in-src-block-p)))
6016 (progn
6017 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6018 (add-text-properties (match-beginning 0) (match-end 0)
6019 (list 'mouse-face 'highlight
6020 'keymap org-mouse-map))
6021 (org-rear-nonsticky-at (match-end 0))
6022 t)))
6024 (defun org-activate-footnote-links (limit)
6025 "Add text properties for footnotes."
6026 (let ((fn (org-footnote-next-reference-or-definition limit)))
6027 (when fn
6028 (let* ((beg (nth 1 fn))
6029 (end (nth 2 fn))
6030 (label (car fn))
6031 (referencep (/= (line-beginning-position) beg)))
6032 (when (and referencep (nth 3 fn))
6033 (save-excursion
6034 (goto-char beg)
6035 (search-forward (or label "fn:"))
6036 (org-remove-flyspell-overlays-in beg (match-end 0))))
6037 (add-text-properties beg end
6038 (list 'mouse-face 'highlight
6039 'keymap org-mouse-map
6040 'help-echo
6041 (if referencep "Footnote reference"
6042 "Footnote definition")
6043 'font-lock-fontified t
6044 'font-lock-multiline t
6045 'face 'org-footnote))))))
6047 (defun org-activate-bracket-links (limit)
6048 "Add text properties for bracketed links."
6049 (if (and (re-search-forward org-bracket-link-regexp limit t)
6050 (not (org-in-src-block-p)))
6051 (let* ((hl (org-match-string-no-properties 1))
6052 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6053 (ip (org-maybe-intangible
6054 (list 'invisible 'org-link
6055 'keymap org-mouse-map 'mouse-face 'highlight
6056 'font-lock-multiline t 'help-echo help
6057 'htmlize-link `(:uri ,hl))))
6058 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6059 'font-lock-multiline t 'help-echo help
6060 'htmlize-link `(:uri ,hl))))
6061 ;; We need to remove the invisible property here. Table narrowing
6062 ;; may have made some of this invisible.
6063 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6064 (remove-text-properties (match-beginning 0) (match-end 0)
6065 '(invisible nil))
6066 (if (match-end 3)
6067 (progn
6068 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6069 (org-rear-nonsticky-at (match-beginning 3))
6070 (add-text-properties (match-beginning 3) (match-end 3) vp)
6071 (org-rear-nonsticky-at (match-end 3))
6072 (add-text-properties (match-end 3) (match-end 0) ip)
6073 (org-rear-nonsticky-at (match-end 0)))
6074 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6075 (org-rear-nonsticky-at (match-beginning 1))
6076 (add-text-properties (match-beginning 1) (match-end 1) vp)
6077 (org-rear-nonsticky-at (match-end 1))
6078 (add-text-properties (match-end 1) (match-end 0) ip)
6079 (org-rear-nonsticky-at (match-end 0)))
6080 t)))
6082 (defun org-activate-dates (limit)
6083 "Add text properties for dates."
6084 (if (and (re-search-forward org-tsr-regexp-both limit t)
6085 (not (equal (char-before (match-beginning 0)) 91)))
6086 (progn
6087 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6088 (add-text-properties (match-beginning 0) (match-end 0)
6089 (list 'mouse-face 'highlight
6090 'keymap org-mouse-map))
6091 (org-rear-nonsticky-at (match-end 0))
6092 (when org-display-custom-times
6093 (if (match-end 3)
6094 (org-display-custom-time (match-beginning 3) (match-end 3)))
6095 (org-display-custom-time (match-beginning 1) (match-end 1)))
6096 t)))
6098 (defvar org-target-link-regexp nil
6099 "Regular expression matching radio targets in plain text.")
6100 (make-variable-buffer-local 'org-target-link-regexp)
6102 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6103 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6104 border border border))
6105 "Regular expression matching a link target.")
6107 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6108 "Regular expression matching a radio target.")
6110 (defconst org-any-target-regexp
6111 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6112 "Regular expression matching any target.")
6114 (defun org-activate-target-links (limit)
6115 "Add text properties for target matches."
6116 (when org-target-link-regexp
6117 (let ((case-fold-search t))
6118 (if (re-search-forward org-target-link-regexp limit t)
6119 (progn
6120 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6121 (add-text-properties (match-beginning 1) (match-end 1)
6122 (list 'mouse-face 'highlight
6123 'keymap org-mouse-map
6124 'help-echo "Radio target link"
6125 'org-linked-text t))
6126 (org-rear-nonsticky-at (match-end 1))
6127 t)))))
6129 (defun org-update-radio-target-regexp ()
6130 "Find all radio targets in this file and update the regular expression.
6131 Also refresh fontification if needed."
6132 (interactive)
6133 (let ((old-regexp org-target-link-regexp)
6134 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6135 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6136 (targets
6137 (org-with-wide-buffer
6138 (goto-char (point-min))
6139 (let (rtn)
6140 (while (re-search-forward org-radio-target-regexp nil t)
6141 ;; Make sure point is really within the object.
6142 (backward-char)
6143 (let ((obj (org-element-context)))
6144 (when (eq (org-element-type obj) 'radio-target)
6145 (add-to-list 'rtn (org-element-property :value obj)))))
6146 rtn))))
6147 (setq org-target-link-regexp
6148 (and targets
6149 (concat before-re
6150 (mapconcat
6151 (lambda (x)
6152 (replace-regexp-in-string
6153 " +" "\\s-+" (regexp-quote x) t t))
6154 targets
6155 "\\|")
6156 after-re)))
6157 (unless (equal old-regexp org-target-link-regexp)
6158 ;; Clean-up cache.
6159 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6160 ((not org-target-link-regexp) old-regexp)
6162 (concat before-re
6163 (mapconcat
6164 (lambda (re)
6165 (substring re (length before-re)
6166 (- (length after-re))))
6167 (list old-regexp org-target-link-regexp)
6168 "\\|")
6169 after-re)))))
6170 (org-with-wide-buffer
6171 (goto-char (point-min))
6172 (while (re-search-forward regexp nil t)
6173 (org-element-cache-refresh (match-beginning 1)))))
6174 ;; Re fontify buffer.
6175 (when (memq 'radio org-highlight-links)
6176 (org-restart-font-lock)))))
6178 (defun org-hide-wide-columns (limit)
6179 (let (s e)
6180 (setq s (text-property-any (point) (or limit (point-max))
6181 'org-cwidth t))
6182 (when s
6183 (setq e (next-single-property-change s 'org-cwidth))
6184 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6185 (goto-char e)
6186 t)))
6188 (defvar org-latex-and-related-regexp nil
6189 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6191 (defun org-compute-latex-and-related-regexp ()
6192 "Compute regular expression for LaTeX, entities and sub/superscript.
6193 Result depends on variable `org-highlight-latex-and-related'."
6194 (org-set-local
6195 'org-latex-and-related-regexp
6196 (let* ((re-sub
6197 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6198 ((eq org-use-sub-superscripts '{})
6199 (list org-match-substring-with-braces-regexp))
6200 (org-use-sub-superscripts (list org-match-substring-regexp))))
6201 (re-latex
6202 (when (memq 'latex org-highlight-latex-and-related)
6203 (let ((matchers (plist-get org-format-latex-options :matchers)))
6204 (delq nil
6205 (mapcar (lambda (x)
6206 (and (member (car x) matchers) (nth 1 x)))
6207 org-latex-regexps)))))
6208 (re-entities
6209 (when (memq 'entities org-highlight-latex-and-related)
6210 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6211 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6213 (defun org-do-latex-and-related (limit)
6214 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6215 LIMIT bounds the search for syntax to highlight. Stop at first
6216 highlighted object, if any. Return t if some highlighting was
6217 done, nil otherwise."
6218 (when (org-string-nw-p org-latex-and-related-regexp)
6219 (catch 'found
6220 (while (re-search-forward org-latex-and-related-regexp limit t)
6221 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6222 'face))
6223 '(org-code org-verbatim underline))
6224 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6225 '(?_ ?^))
6227 0)))
6228 (font-lock-prepend-text-property
6229 (+ offset (match-beginning 0)) (match-end 0)
6230 'face 'org-latex-and-related)
6231 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6232 '(font-lock-multiline t)))
6233 (throw 'found t)))
6234 nil)))
6236 (defun org-restart-font-lock ()
6237 "Restart `font-lock-mode', to force refontification."
6238 (when (and (boundp 'font-lock-mode) font-lock-mode)
6239 (font-lock-mode -1)
6240 (font-lock-mode 1)))
6242 (defun org-activate-tags (limit)
6243 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6244 (progn
6245 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6246 (add-text-properties (match-beginning 1) (match-end 1)
6247 (list 'mouse-face 'highlight
6248 'keymap org-mouse-map))
6249 (org-rear-nonsticky-at (match-end 1))
6250 t)))
6252 (defun org-outline-level ()
6253 "Compute the outline level of the heading at point.
6254 If this is called at a normal headline, the level is the number of stars.
6255 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6256 (save-excursion
6257 (if (not (ignore-errors (org-back-to-heading t)))
6259 (looking-at org-outline-regexp)
6260 (1- (- (match-end 0) (match-beginning 0))))))
6262 (defvar org-font-lock-keywords nil)
6264 (defsubst org-re-property (property &optional literal allow-null)
6265 "Return a regexp matching a PROPERTY line.
6267 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6268 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6269 non-nil, match properties even without a value.
6271 Match group 3 is set to the value when it exists. If there is no
6272 value and ALLOW-NULL is non-nil, it is set to the empty string."
6273 (concat
6274 "^\\(?4:[ \t]*\\)"
6275 (format "\\(?1::\\(?2:%s\\):\\)"
6276 (if literal property (regexp-quote property)))
6277 (if allow-null
6278 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$"
6279 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))
6281 (defconst org-property-re
6282 (org-re-property "\\S-+" 'literal t)
6283 "Regular expression matching a property line.
6284 There are four matching groups:
6285 1: :PROPKEY: including the leading and trailing colon,
6286 2: PROPKEY without the leading and trailing colon,
6287 3: PROPVAL without leading or trailing spaces,
6288 4: the indentation of the current line,
6289 5: trailing whitespace.")
6291 (defvar org-font-lock-hook nil
6292 "Functions to be called for special font lock stuff.")
6294 (defvar org-font-lock-set-keywords-hook nil
6295 "Functions that can manipulate `org-font-lock-extra-keywords'.
6296 This is called after `org-font-lock-extra-keywords' is defined, but before
6297 it is installed to be used by font lock. This can be useful if something
6298 needs to be inserted at a specific position in the font-lock sequence.")
6300 (defun org-font-lock-hook (limit)
6301 "Run `org-font-lock-hook' within LIMIT."
6302 (run-hook-with-args 'org-font-lock-hook limit))
6304 (defun org-set-font-lock-defaults ()
6305 "Set font lock defaults for the current buffer."
6306 (let* ((em org-fontify-emphasized-text)
6307 (lk org-highlight-links)
6308 (org-font-lock-extra-keywords
6309 (list
6310 ;; Call the hook
6311 '(org-font-lock-hook)
6312 ;; Headlines
6313 `(,(if org-fontify-whole-heading-line
6314 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6315 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6316 (1 (org-get-level-face 1))
6317 (2 (org-get-level-face 2))
6318 (3 (org-get-level-face 3)))
6319 ;; Table lines
6320 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6321 (1 'org-table t))
6322 ;; Table internals
6323 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6324 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6325 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6326 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6327 ;; Drawers
6328 '(org-fontify-drawers)
6329 ;; Properties
6330 (list org-property-re
6331 '(1 'org-special-keyword t)
6332 '(3 'org-property-value t))
6333 ;; Links
6334 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6335 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6336 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6337 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6338 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6339 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6340 (if (memq 'footnote lk) '(org-activate-footnote-links))
6341 ;; Targets.
6342 (list org-any-target-regexp '(0 'org-target t))
6343 ;; Diary sexps.
6344 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6345 ;; Macro
6346 '(org-fontify-macros)
6347 '(org-hide-wide-columns (0 nil append))
6348 ;; TODO keyword
6349 (list (format org-heading-keyword-regexp-format
6350 org-todo-regexp)
6351 '(2 (org-get-todo-face 2) t))
6352 ;; DONE
6353 (if org-fontify-done-headline
6354 (list (format org-heading-keyword-regexp-format
6355 (concat
6356 "\\(?:"
6357 (mapconcat 'regexp-quote org-done-keywords "\\|")
6358 "\\)"))
6359 '(2 'org-headline-done t))
6360 nil)
6361 ;; Priorities
6362 '(org-font-lock-add-priority-faces)
6363 ;; Tags
6364 '(org-font-lock-add-tag-faces)
6365 ;; Tags groups
6366 (if (and org-group-tags org-tag-groups-alist)
6367 (list (concat org-outline-regexp-bol ".+\\(:"
6368 (regexp-opt (mapcar 'car org-tag-groups-alist))
6369 ":\\).*$")
6370 '(1 'org-tag-group prepend)))
6371 ;; Special keywords
6372 (list (concat "\\<" org-comment-string) '(0 'org-special-keyword t))
6373 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6374 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6375 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6376 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6377 ;; Emphasis
6378 (if em
6379 (if (featurep 'xemacs)
6380 '(org-do-emphasis-faces (0 nil append))
6381 '(org-do-emphasis-faces)))
6382 ;; Checkboxes
6383 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6384 1 'org-checkbox prepend)
6385 (if (cdr (assq 'checkbox org-list-automatic-rules))
6386 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6387 (0 (org-get-checkbox-statistics-face) t)))
6388 ;; Description list items
6389 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6390 1 'org-list-dt prepend)
6391 ;; ARCHIVEd headings
6392 (list (concat
6393 org-outline-regexp-bol
6394 "\\(.*:" org-archive-tag ":.*\\)")
6395 '(1 'org-archived prepend))
6396 ;; Specials
6397 '(org-do-latex-and-related)
6398 '(org-fontify-entities)
6399 '(org-raise-scripts)
6400 ;; Code
6401 '(org-activate-code (1 'org-code t))
6402 ;; COMMENT
6403 (list (format
6404 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6405 org-todo-regexp
6406 org-comment-string)
6407 '(9 'org-special-keyword t))
6408 ;; Blocks and meta lines
6409 '(org-fontify-meta-lines-and-blocks))))
6410 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6411 (run-hooks 'org-font-lock-set-keywords-hook)
6412 ;; Now set the full font-lock-keywords
6413 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6414 (org-set-local 'font-lock-defaults
6415 '(org-font-lock-keywords t nil nil backward-paragraph))
6416 (kill-local-variable 'font-lock-keywords) nil))
6418 (defun org-toggle-pretty-entities ()
6419 "Toggle the composition display of entities as UTF8 characters."
6420 (interactive)
6421 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6422 (org-restart-font-lock)
6423 (if org-pretty-entities
6424 (message "Entities are now displayed as UTF8 characters")
6425 (save-restriction
6426 (widen)
6427 (org-decompose-region (point-min) (point-max))
6428 (message "Entities are now displayed as plain text"))))
6430 (defvar org-custom-properties-overlays nil
6431 "List of overlays used for custom properties.")
6432 (make-variable-buffer-local 'org-custom-properties-overlays)
6434 (defun org-toggle-custom-properties-visibility ()
6435 "Display or hide properties in `org-custom-properties'."
6436 (interactive)
6437 (if org-custom-properties-overlays
6438 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6439 (setq org-custom-properties-overlays nil))
6440 (unless (not org-custom-properties)
6441 (save-excursion
6442 (save-restriction
6443 (widen)
6444 (goto-char (point-min))
6445 (while (re-search-forward org-property-re nil t)
6446 (mapc (lambda(p)
6447 (when (equal p (substring (match-string 1) 1 -1))
6448 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6449 (overlay-put o 'invisible t)
6450 (overlay-put o 'org-custom-property t)
6451 (push o org-custom-properties-overlays))))
6452 org-custom-properties)))))))
6454 (defun org-fontify-entities (limit)
6455 "Find an entity to fontify."
6456 (let (ee)
6457 (when org-pretty-entities
6458 (catch 'match
6459 (while (re-search-forward
6460 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6461 limit t)
6462 (if (and (not (org-at-comment-p))
6463 (setq ee (org-entity-get (match-string 1)))
6464 (= (length (nth 6 ee)) 1))
6465 (let*
6466 ((end (if (equal (match-string 2) "{}")
6467 (match-end 2)
6468 (match-end 1))))
6469 (add-text-properties
6470 (match-beginning 0) end
6471 (list 'font-lock-fontified t))
6472 (compose-region (match-beginning 0) end
6473 (nth 6 ee) nil)
6474 (backward-char 1)
6475 (throw 'match t))))
6476 nil))))
6478 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6479 "Fontify string S like in Org-mode."
6480 (with-temp-buffer
6481 (insert s)
6482 (let ((org-odd-levels-only odd-levels))
6483 (org-mode)
6484 (font-lock-ensure)
6485 (buffer-string))))
6487 (defvar org-m nil)
6488 (defvar org-l nil)
6489 (defvar org-f nil)
6490 (defun org-get-level-face (n)
6491 "Get the right face for match N in font-lock matching of headlines."
6492 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6493 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6494 (if org-cycle-level-faces
6495 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6496 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6497 (cond
6498 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6499 ((eq n 2) org-f)
6500 (t (if org-level-color-stars-only nil org-f))))
6503 (defun org-get-todo-face (kwd)
6504 "Get the right face for a TODO keyword KWD.
6505 If KWD is a number, get the corresponding match group."
6506 (if (numberp kwd) (setq kwd (match-string kwd)))
6507 (or (org-face-from-face-or-color
6508 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6509 (and (member kwd org-done-keywords) 'org-done)
6510 'org-todo))
6512 (defun org-face-from-face-or-color (context inherit face-or-color)
6513 "Create a face list that inherits INHERIT, but sets the foreground color.
6514 When FACE-OR-COLOR is not a string, just return it."
6515 (if (stringp face-or-color)
6516 (list :inherit inherit
6517 (cdr (assoc context org-faces-easy-properties))
6518 face-or-color)
6519 face-or-color))
6521 (defun org-font-lock-add-tag-faces (limit)
6522 "Add the special tag faces."
6523 (when (and org-tag-faces org-tags-special-faces-re)
6524 (while (re-search-forward org-tags-special-faces-re limit t)
6525 (add-text-properties (match-beginning 1) (match-end 1)
6526 (list 'face (org-get-tag-face 1)
6527 'font-lock-fontified t))
6528 (backward-char 1))))
6530 (defun org-font-lock-add-priority-faces (limit)
6531 "Add the special priority faces."
6532 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6533 (when (save-match-data (org-at-heading-p))
6534 (add-text-properties
6535 (match-beginning 0) (match-end 0)
6536 (list 'face (or (org-face-from-face-or-color
6537 'priority 'org-priority
6538 (cdr (assoc (char-after (match-beginning 1))
6539 org-priority-faces)))
6540 'org-priority)
6541 'font-lock-fontified t)))))
6543 (defun org-get-tag-face (kwd)
6544 "Get the right face for a TODO keyword KWD.
6545 If KWD is a number, get the corresponding match group."
6546 (if (numberp kwd) (setq kwd (match-string kwd)))
6547 (or (org-face-from-face-or-color
6548 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6549 'org-tag))
6551 (defun org-unfontify-region (beg end &optional maybe_loudly)
6552 "Remove fontification and activation overlays from links."
6553 (font-lock-default-unfontify-region beg end)
6554 (let* ((buffer-undo-list t)
6555 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6556 (inhibit-modification-hooks t)
6557 deactivate-mark buffer-file-name buffer-file-truename)
6558 (org-decompose-region beg end)
6559 (remove-text-properties beg end
6560 '(mouse-face t keymap t org-linked-text t
6561 invisible t intangible t
6562 org-emphasis t))
6563 (org-remove-font-lock-display-properties beg end)))
6565 (defconst org-script-display '(((raise -0.3) (height 0.7))
6566 ((raise 0.3) (height 0.7))
6567 ((raise -0.5))
6568 ((raise 0.5)))
6569 "Display properties for showing superscripts and subscripts.")
6571 (defun org-remove-font-lock-display-properties (beg end)
6572 "Remove specific display properties that have been added by font lock.
6573 The will remove the raise properties that are used to show superscripts
6574 and subscripts."
6575 (let (next prop)
6576 (while (< beg end)
6577 (setq next (next-single-property-change beg 'display nil end)
6578 prop (get-text-property beg 'display))
6579 (if (member prop org-script-display)
6580 (put-text-property beg next 'display nil))
6581 (setq beg next))))
6583 (defun org-raise-scripts (limit)
6584 "Add raise properties to sub/superscripts."
6585 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6586 (if (re-search-forward
6587 (if (eq org-use-sub-superscripts t)
6588 org-match-substring-regexp
6589 org-match-substring-with-braces-regexp)
6590 limit t)
6591 (let* ((pos (point)) table-p comment-p
6592 (mpos (match-beginning 3))
6593 (emph-p (get-text-property mpos 'org-emphasis))
6594 (link-p (get-text-property mpos 'mouse-face))
6595 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6596 (goto-char (point-at-bol))
6597 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6598 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6599 (goto-char pos)
6600 ;; Handle a_b^c
6601 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6602 (if (or comment-p emph-p link-p keyw-p)
6604 (put-text-property (match-beginning 3) (match-end 0)
6605 'display
6606 (if (equal (char-after (match-beginning 2)) ?^)
6607 (nth (if table-p 3 1) org-script-display)
6608 (nth (if table-p 2 0) org-script-display)))
6609 (add-text-properties (match-beginning 2) (match-end 2)
6610 (list 'invisible t
6611 'org-dwidth t 'org-dwidth-n 1))
6612 (if (and (eq (char-after (match-beginning 3)) ?{)
6613 (eq (char-before (match-end 3)) ?}))
6614 (progn
6615 (add-text-properties
6616 (match-beginning 3) (1+ (match-beginning 3))
6617 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6618 (add-text-properties
6619 (1- (match-end 3)) (match-end 3)
6620 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6621 t)))))
6623 ;;;; Visibility cycling, including org-goto and indirect buffer
6625 ;;; Cycling
6627 (defvar org-cycle-global-status nil)
6628 (make-variable-buffer-local 'org-cycle-global-status)
6629 (put 'org-cycle-global-status 'org-state t)
6630 (defvar org-cycle-subtree-status nil)
6631 (make-variable-buffer-local 'org-cycle-subtree-status)
6632 (put 'org-cycle-subtree-status 'org-state t)
6634 (defvar org-inlinetask-min-level)
6636 (defun org-unlogged-message (&rest args)
6637 "Display a message, but avoid logging it in the *Messages* buffer."
6638 (let ((message-log-max nil))
6639 (apply 'message args)))
6641 ;;;###autoload
6642 (defun org-cycle (&optional arg)
6643 "TAB-action and visibility cycling for Org-mode.
6645 This is the command invoked in Org-mode by the TAB key. Its main purpose
6646 is outline visibility cycling, but it also invokes other actions
6647 in special contexts.
6649 - When this function is called with a prefix argument, rotate the entire
6650 buffer through 3 states (global cycling)
6651 1. OVERVIEW: Show only top-level headlines.
6652 2. CONTENTS: Show all headlines of all levels, but no body text.
6653 3. SHOW ALL: Show everything.
6654 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6655 determined by the variable `org-startup-folded', and by any VISIBILITY
6656 properties in the buffer.
6657 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6658 including any drawers.
6660 - When inside a table, re-align the table and move to the next field.
6662 - When point is at the beginning of a headline, rotate the subtree started
6663 by this line through 3 different states (local cycling)
6664 1. FOLDED: Only the main headline is shown.
6665 2. CHILDREN: The main headline and the direct children are shown.
6666 From this state, you can move to one of the children
6667 and zoom in further.
6668 3. SUBTREE: Show the entire subtree, including body text.
6669 If there is no subtree, switch directly from CHILDREN to FOLDED.
6671 - When point is at the beginning of an empty headline and the variable
6672 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6673 of the headline by demoting and promoting it to likely levels. This
6674 speeds up creation document structure by pressing TAB once or several
6675 times right after creating a new headline.
6677 - When there is a numeric prefix, go up to a heading with level ARG, do
6678 a `show-subtree' and return to the previous cursor position. If ARG
6679 is negative, go up that many levels.
6681 - When point is not at the beginning of a headline, execute the global
6682 binding for TAB, which is re-indenting the line. See the option
6683 `org-cycle-emulate-tab' for details.
6685 - Special case: if point is at the beginning of the buffer and there is
6686 no headline in line 1, this function will act as if called with prefix arg
6687 (C-u TAB, same as S-TAB) also when called without prefix arg.
6688 But only if also the variable `org-cycle-global-at-bob' is t."
6689 (interactive "P")
6690 (org-load-modules-maybe)
6691 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6692 (and org-cycle-level-after-item/entry-creation
6693 (or (org-cycle-level)
6694 (org-cycle-item-indentation))))
6695 (let* ((limit-level
6696 (or org-cycle-max-level
6697 (and (boundp 'org-inlinetask-min-level)
6698 org-inlinetask-min-level
6699 (1- org-inlinetask-min-level))))
6700 (nstars (and limit-level
6701 (if org-odd-levels-only
6702 (and limit-level (1- (* limit-level 2)))
6703 limit-level)))
6704 (org-outline-regexp
6705 (if (not (derived-mode-p 'org-mode))
6706 outline-regexp
6707 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6708 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6709 (not (looking-at org-outline-regexp))))
6710 (org-cycle-hook
6711 (if bob-special
6712 (delq 'org-optimize-window-after-visibility-change
6713 (copy-sequence org-cycle-hook))
6714 org-cycle-hook))
6715 (pos (point)))
6717 (if (or bob-special (equal arg '(4)))
6718 ;; special case: use global cycling
6719 (setq arg t))
6721 (cond
6723 ((equal arg '(16))
6724 (setq last-command 'dummy)
6725 (org-set-startup-visibility)
6726 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6728 ((equal arg '(64))
6729 (show-all)
6730 (org-unlogged-message "Entire buffer visible, including drawers"))
6732 ;; Try cdlatex TAB completion
6733 ((org-try-cdlatex-tab))
6735 ;; Table: enter it or move to the next field.
6736 ((org-at-table-p 'any)
6737 (if (org-at-table.el-p)
6738 (message "Use C-c ' to edit table.el tables")
6739 (if arg (org-table-edit-field t)
6740 (org-table-justify-field-maybe)
6741 (call-interactively 'org-table-next-field))))
6743 ((run-hook-with-args-until-success
6744 'org-tab-after-check-for-table-hook))
6746 ;; Global cycling: delegate to `org-cycle-internal-global'.
6747 ((eq arg t) (org-cycle-internal-global))
6749 ;; Drawers: delegate to `org-flag-drawer'.
6750 ((save-excursion
6751 (beginning-of-line 1)
6752 (looking-at org-drawer-regexp))
6753 (org-flag-drawer ; toggle block visibility
6754 (not (get-char-property (match-end 0) 'invisible))))
6756 ;; Show-subtree, ARG levels up from here.
6757 ((integerp arg)
6758 (save-excursion
6759 (org-back-to-heading)
6760 (outline-up-heading (if (< arg 0) (- arg)
6761 (- (funcall outline-level) arg)))
6762 (org-show-subtree)))
6764 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6765 ((and (featurep 'org-inlinetask)
6766 (org-inlinetask-at-task-p)
6767 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6768 (org-inlinetask-toggle-visibility))
6770 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6771 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6772 (save-excursion (beginning-of-line 1)
6773 (looking-at org-outline-regexp)))
6774 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6775 (org-cycle-internal-local))
6777 ;; From there: TAB emulation and template completion.
6778 (buffer-read-only (org-back-to-heading))
6780 ((run-hook-with-args-until-success
6781 'org-tab-after-check-for-cycling-hook))
6783 ((org-try-structure-completion))
6785 ((run-hook-with-args-until-success
6786 'org-tab-before-tab-emulation-hook))
6788 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6789 (or (not (bolp))
6790 (not (looking-at org-outline-regexp))))
6791 (call-interactively (global-key-binding "\t")))
6793 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6794 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6795 (or (and (eq org-cycle-emulate-tab 'white)
6796 (= (match-end 0) (point-at-eol)))
6797 (and (eq org-cycle-emulate-tab 'whitestart)
6798 (>= (match-end 0) pos))))
6800 (eq org-cycle-emulate-tab t))
6801 (call-interactively (global-key-binding "\t")))
6803 (t (save-excursion
6804 (org-back-to-heading)
6805 (org-cycle)))))))
6807 (defun org-cycle-internal-global ()
6808 "Do the global cycling action."
6809 ;; Hack to avoid display of messages for .org attachments in Gnus
6810 (let ((ga (string-match "\\*fontification" (buffer-name))))
6811 (cond
6812 ((and (eq last-command this-command)
6813 (eq org-cycle-global-status 'overview))
6814 ;; We just created the overview - now do table of contents
6815 ;; This can be slow in very large buffers, so indicate action
6816 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6817 (unless ga (org-unlogged-message "CONTENTS..."))
6818 (org-content)
6819 (unless ga (org-unlogged-message "CONTENTS...done"))
6820 (setq org-cycle-global-status 'contents)
6821 (run-hook-with-args 'org-cycle-hook 'contents))
6823 ((and (eq last-command this-command)
6824 (eq org-cycle-global-status 'contents))
6825 ;; We just showed the table of contents - now show everything
6826 (run-hook-with-args 'org-pre-cycle-hook 'all)
6827 (show-all)
6828 (unless ga (org-unlogged-message "SHOW ALL"))
6829 (setq org-cycle-global-status 'all)
6830 (run-hook-with-args 'org-cycle-hook 'all))
6833 ;; Default action: go to overview
6834 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6835 (org-overview)
6836 (unless ga (org-unlogged-message "OVERVIEW"))
6837 (setq org-cycle-global-status 'overview)
6838 (run-hook-with-args 'org-cycle-hook 'overview)))))
6840 (defvar org-called-with-limited-levels nil
6841 "Non-nil when `org-with-limited-levels' is currently active.")
6843 (defun org-cycle-internal-local ()
6844 "Do the local cycling action."
6845 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6846 ;; First, determine end of headline (EOH), end of subtree or item
6847 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6848 (save-excursion
6849 (if (org-at-item-p)
6850 (progn
6851 (beginning-of-line)
6852 (setq struct (org-list-struct))
6853 (setq eoh (point-at-eol))
6854 (setq eos (org-list-get-item-end-before-blank (point) struct))
6855 (setq has-children (org-list-has-child-p (point) struct)))
6856 (org-back-to-heading)
6857 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6858 (setq eos (save-excursion (org-end-of-subtree t t)
6859 (when (bolp) (backward-char)) (point)))
6860 (setq has-children
6861 (or (save-excursion
6862 (let ((level (funcall outline-level)))
6863 (outline-next-heading)
6864 (and (org-at-heading-p t)
6865 (> (funcall outline-level) level))))
6866 (save-excursion
6867 (org-list-search-forward (org-item-beginning-re) eos t)))))
6868 ;; Determine end invisible part of buffer (EOL)
6869 (beginning-of-line 2)
6870 ;; XEmacs doesn't have `next-single-char-property-change'
6871 (if (featurep 'xemacs)
6872 (while (and (not (eobp)) ;; this is like `next-line'
6873 (get-char-property (1- (point)) 'invisible))
6874 (beginning-of-line 2))
6875 (while (and (not (eobp)) ;; this is like `next-line'
6876 (get-char-property (1- (point)) 'invisible))
6877 (goto-char (next-single-char-property-change (point) 'invisible))
6878 (and (eolp) (beginning-of-line 2))))
6879 (setq eol (point)))
6880 ;; Find out what to do next and set `this-command'
6881 (cond
6882 ((= eos eoh)
6883 ;; Nothing is hidden behind this heading
6884 (unless (org-before-first-heading-p)
6885 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6886 (org-unlogged-message "EMPTY ENTRY")
6887 (setq org-cycle-subtree-status nil)
6888 (save-excursion
6889 (goto-char eos)
6890 (outline-next-heading)
6891 (if (outline-invisible-p) (org-flag-heading nil))))
6892 ((and (or (>= eol eos)
6893 (not (string-match "\\S-" (buffer-substring eol eos))))
6894 (or has-children
6895 (not (setq children-skipped
6896 org-cycle-skip-children-state-if-no-children))))
6897 ;; Entire subtree is hidden in one line: children view
6898 (unless (org-before-first-heading-p)
6899 (run-hook-with-args 'org-pre-cycle-hook 'children))
6900 (if (org-at-item-p)
6901 (org-list-set-item-visibility (point-at-bol) struct 'children)
6902 (org-show-entry)
6903 (org-with-limited-levels (show-children))
6904 ;; FIXME: This slows down the func way too much.
6905 ;; How keep drawers hidden in subtree anyway?
6906 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6907 ;; (org-cycle-hide-drawers 'subtree))
6909 ;; Fold every list in subtree to top-level items.
6910 (when (eq org-cycle-include-plain-lists 'integrate)
6911 (save-excursion
6912 (org-back-to-heading)
6913 (while (org-list-search-forward (org-item-beginning-re) eos t)
6914 (beginning-of-line 1)
6915 (let* ((struct (org-list-struct))
6916 (prevs (org-list-prevs-alist struct))
6917 (end (org-list-get-bottom-point struct)))
6918 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6919 (org-list-get-all-items (point) struct prevs))
6920 (goto-char (if (< end eos) end eos)))))))
6921 (org-unlogged-message "CHILDREN")
6922 (save-excursion
6923 (goto-char eos)
6924 (outline-next-heading)
6925 (if (outline-invisible-p) (org-flag-heading nil)))
6926 (setq org-cycle-subtree-status 'children)
6927 (unless (org-before-first-heading-p)
6928 (run-hook-with-args 'org-cycle-hook 'children)))
6929 ((or children-skipped
6930 (and (eq last-command this-command)
6931 (eq org-cycle-subtree-status 'children)))
6932 ;; We just showed the children, or no children are there,
6933 ;; now show everything.
6934 (unless (org-before-first-heading-p)
6935 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6936 (outline-flag-region eoh eos nil)
6937 (org-unlogged-message
6938 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6939 (setq org-cycle-subtree-status 'subtree)
6940 (unless (org-before-first-heading-p)
6941 (run-hook-with-args 'org-cycle-hook 'subtree)))
6943 ;; Default action: hide the subtree.
6944 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6945 (outline-flag-region eoh eos t)
6946 (org-unlogged-message "FOLDED")
6947 (setq org-cycle-subtree-status 'folded)
6948 (unless (org-before-first-heading-p)
6949 (run-hook-with-args 'org-cycle-hook 'folded))))))
6951 ;;;###autoload
6952 (defun org-global-cycle (&optional arg)
6953 "Cycle the global visibility. For details see `org-cycle'.
6954 With \\[universal-argument] prefix arg, switch to startup visibility.
6955 With a numeric prefix, show all headlines up to that level."
6956 (interactive "P")
6957 (let ((org-cycle-include-plain-lists
6958 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6959 (cond
6960 ((integerp arg)
6961 (show-all)
6962 (hide-sublevels arg)
6963 (setq org-cycle-global-status 'contents))
6964 ((equal arg '(4))
6965 (org-set-startup-visibility)
6966 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6968 (org-cycle '(4))))))
6970 (defun org-set-startup-visibility ()
6971 "Set the visibility required by startup options and properties."
6972 (cond
6973 ((eq org-startup-folded t)
6974 (org-overview))
6975 ((eq org-startup-folded 'content)
6976 (org-content))
6977 ((or (eq org-startup-folded 'showeverything)
6978 (eq org-startup-folded nil))
6979 (show-all)))
6980 (unless (eq org-startup-folded 'showeverything)
6981 (if org-hide-block-startup (org-hide-block-all))
6982 (org-set-visibility-according-to-property 'no-cleanup)
6983 (org-cycle-hide-archived-subtrees 'all)
6984 (org-cycle-hide-drawers 'all)
6985 (org-cycle-show-empty-lines t)))
6987 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6988 "Switch subtree visibilities according to :VISIBILITY: property."
6989 (interactive)
6990 (let (org-show-entry-below state)
6991 (save-excursion
6992 (goto-char (point-min))
6993 (while (re-search-forward
6994 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6995 nil t)
6996 (setq state (match-string 1))
6997 (save-excursion
6998 (org-back-to-heading t)
6999 (hide-subtree)
7000 (org-reveal)
7001 (cond
7002 ((equal state '("fold" "folded"))
7003 (hide-subtree))
7004 ((equal state "children")
7005 (org-show-hidden-entry)
7006 (show-children))
7007 ((equal state "content")
7008 (save-excursion
7009 (save-restriction
7010 (org-narrow-to-subtree)
7011 (org-content))))
7012 ((member state '("all" "showall"))
7013 (show-subtree)))))
7014 (unless no-cleanup
7015 (org-cycle-hide-archived-subtrees 'all)
7016 (org-cycle-hide-drawers 'all)
7017 (org-cycle-show-empty-lines 'all)))))
7019 ;; This function uses outline-regexp instead of the more fundamental
7020 ;; org-outline-regexp so that org-cycle-global works outside of Org
7021 ;; buffers, where outline-regexp is needed.
7022 (defun org-overview ()
7023 "Switch to overview mode, showing only top-level headlines.
7024 This shows all headlines with a level equal or greater than the level
7025 of the first headline in the buffer. This is important, because if the
7026 first headline is not level one, then (hide-sublevels 1) gives confusing
7027 results."
7028 (interactive)
7029 (save-excursion
7030 (let ((level
7031 (save-excursion
7032 (goto-char (point-min))
7033 (if (re-search-forward (concat "^" outline-regexp) nil t)
7034 (progn
7035 (goto-char (match-beginning 0))
7036 (funcall outline-level))))))
7037 (and level (hide-sublevels level)))))
7039 (defun org-content (&optional arg)
7040 "Show all headlines in the buffer, like a table of contents.
7041 With numerical argument N, show content up to level N."
7042 (interactive "P")
7043 (org-overview)
7044 (save-excursion
7045 ;; Visit all headings and show their offspring
7046 (and (integerp arg) (org-overview))
7047 (goto-char (point-max))
7048 (catch 'exit
7049 (while (and (progn (condition-case nil
7050 (outline-previous-visible-heading 1)
7051 (error (goto-char (point-min))))
7053 (looking-at org-outline-regexp))
7054 (if (integerp arg)
7055 (show-children (1- arg))
7056 (show-branches))
7057 (if (bobp) (throw 'exit nil))))))
7059 (defun org-optimize-window-after-visibility-change (state)
7060 "Adjust the window after a change in outline visibility.
7061 This function is the default value of the hook `org-cycle-hook'."
7062 (when (get-buffer-window (current-buffer))
7063 (cond
7064 ((eq state 'content) nil)
7065 ((eq state 'all) nil)
7066 ((eq state 'folded) nil)
7067 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7068 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7070 (defun org-remove-empty-overlays-at (pos)
7071 "Remove outline overlays that do not contain non-white stuff."
7072 (mapc
7073 (lambda (o)
7074 (and (eq 'outline (overlay-get o 'invisible))
7075 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7076 (overlay-end o))))
7077 (delete-overlay o)))
7078 (overlays-at pos)))
7080 (defun org-clean-visibility-after-subtree-move ()
7081 "Fix visibility issues after moving a subtree."
7082 ;; First, find a reasonable region to look at:
7083 ;; Start two siblings above, end three below
7084 (let* ((beg (save-excursion
7085 (and (org-get-last-sibling)
7086 (org-get-last-sibling))
7087 (point)))
7088 (end (save-excursion
7089 (and (org-get-next-sibling)
7090 (org-get-next-sibling)
7091 (org-get-next-sibling))
7092 (if (org-at-heading-p)
7093 (point-at-eol)
7094 (point))))
7095 (level (looking-at "\\*+"))
7096 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7097 (save-excursion
7098 (save-restriction
7099 (narrow-to-region beg end)
7100 (when re
7101 ;; Properly fold already folded siblings
7102 (goto-char (point-min))
7103 (while (re-search-forward re nil t)
7104 (if (and (not (outline-invisible-p))
7105 (save-excursion
7106 (goto-char (point-at-eol)) (outline-invisible-p)))
7107 (hide-entry))))
7108 (org-cycle-show-empty-lines 'overview)
7109 (org-cycle-hide-drawers 'overview)))))
7111 (defun org-cycle-show-empty-lines (state)
7112 "Show empty lines above all visible headlines.
7113 The region to be covered depends on STATE when called through
7114 `org-cycle-hook'. Lisp program can use t for STATE to get the
7115 entire buffer covered. Note that an empty line is only shown if there
7116 are at least `org-cycle-separator-lines' empty lines before the headline."
7117 (when (not (= org-cycle-separator-lines 0))
7118 (save-excursion
7119 (let* ((n (abs org-cycle-separator-lines))
7120 (re (cond
7121 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7122 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7123 (t (let ((ns (number-to-string (- n 2))))
7124 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7125 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7126 beg end b e)
7127 (cond
7128 ((memq state '(overview contents t))
7129 (setq beg (point-min) end (point-max)))
7130 ((memq state '(children folded))
7131 (setq beg (point) end (progn (org-end-of-subtree t t)
7132 (beginning-of-line 2)
7133 (point)))))
7134 (when beg
7135 (goto-char beg)
7136 (while (re-search-forward re end t)
7137 (unless (get-char-property (match-end 1) 'invisible)
7138 (setq e (match-end 1))
7139 (if (< org-cycle-separator-lines 0)
7140 (setq b (save-excursion
7141 (goto-char (match-beginning 0))
7142 (org-back-over-empty-lines)
7143 (if (save-excursion
7144 (goto-char (max (point-min) (1- (point))))
7145 (org-at-heading-p))
7146 (1- (point))
7147 (point))))
7148 (setq b (match-beginning 1)))
7149 (outline-flag-region b e nil)))))))
7150 ;; Never hide empty lines at the end of the file.
7151 (save-excursion
7152 (goto-char (point-max))
7153 (outline-previous-heading)
7154 (outline-end-of-heading)
7155 (if (and (looking-at "[ \t\n]+")
7156 (= (match-end 0) (point-max)))
7157 (outline-flag-region (point) (match-end 0) nil))))
7159 (defun org-show-empty-lines-in-parent ()
7160 "Move to the parent and re-show empty lines before visible headlines."
7161 (save-excursion
7162 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7163 (org-cycle-show-empty-lines context))))
7165 (defun org-files-list ()
7166 "Return `org-agenda-files' list, plus all open org-mode files.
7167 This is useful for operations that need to scan all of a user's
7168 open and agenda-wise Org files."
7169 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7170 (dolist (buf (buffer-list))
7171 (with-current-buffer buf
7172 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7173 (let ((file (expand-file-name (buffer-file-name))))
7174 (unless (member file files)
7175 (push file files))))))
7176 files))
7178 (defsubst org-entry-beginning-position ()
7179 "Return the beginning position of the current entry."
7180 (save-excursion (outline-back-to-heading t) (point)))
7182 (defsubst org-entry-end-position ()
7183 "Return the end position of the current entry."
7184 (save-excursion (outline-next-heading) (point)))
7186 (defun org-cycle-hide-drawers (state &optional exceptions)
7187 "Re-hide all drawers after a visibility state change.
7188 When non-nil, optional argument EXCEPTIONS is a list of strings
7189 specifying which drawers should not be hidden."
7190 (when (and (derived-mode-p 'org-mode)
7191 (not (memq state '(overview folded contents))))
7192 (save-excursion
7193 (let* ((globalp (memq state '(contents all)))
7194 (beg (if globalp (point-min) (point)))
7195 (end (if globalp (point-max)
7196 (if (eq state 'children)
7197 (save-excursion (outline-next-heading) (point))
7198 (org-end-of-subtree t)))))
7199 (goto-char beg)
7200 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7201 (unless (member-ignore-case (match-string 1) exceptions)
7202 (let ((drawer (org-element-at-point)))
7203 (when (memq (org-element-type drawer) '(drawer property-drawer))
7204 (org-flag-drawer t drawer)
7205 ;; Make sure to skip drawer entirely or we might flag
7206 ;; it another time when matching its ending line with
7207 ;; `org-drawer-regexp'.
7208 (goto-char (org-element-property :end drawer))))))))))
7210 (defun org-cycle-hide-inline-tasks (state)
7211 "Re-hide inline tasks when switching to 'contents or 'children
7212 visibility state."
7213 (case state
7214 (contents
7215 (when (org-bound-and-true-p org-inlinetask-min-level)
7216 (hide-sublevels (1- org-inlinetask-min-level))))
7217 (children
7218 (when (featurep 'org-inlinetask)
7219 (save-excursion
7220 (while (and (outline-next-heading)
7221 (org-inlinetask-at-task-p))
7222 (org-inlinetask-toggle-visibility)
7223 (org-inlinetask-goto-end)))))))
7225 (defun org-flag-drawer (flag &optional element)
7226 "When FLAG is non-nil, hide the drawer we are at.
7227 Otherwise make it visible. When optional argument ELEMENT is
7228 a parsed drawer, as returned by `org-element-at-point', hide or
7229 show that drawer instead."
7230 (when (save-excursion
7231 (beginning-of-line)
7232 (org-looking-at-p org-drawer-regexp))
7233 (let ((drawer (or element (org-element-at-point))))
7234 (when (memq (org-element-type drawer) '(drawer property-drawer))
7235 (let ((post (org-element-property :post-affiliated drawer)))
7236 (save-excursion
7237 (outline-flag-region
7238 (progn (goto-char post) (line-end-position))
7239 (progn (goto-char (org-element-property :end drawer))
7240 (skip-chars-backward " \r\t\n")
7241 (line-end-position))
7242 flag))
7243 ;; When the drawer is hidden away, make sure point lies in
7244 ;; a visible part of the buffer.
7245 (when (and flag (> (line-beginning-position) post))
7246 (goto-char post)))))))
7248 (defun org-subtree-end-visible-p ()
7249 "Is the end of the current subtree visible?"
7250 (pos-visible-in-window-p
7251 (save-excursion (org-end-of-subtree t) (point))))
7253 (defun org-first-headline-recenter ()
7254 "Move cursor to the first headline and recenter the headline."
7255 (goto-char (point-min))
7256 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7257 (set-window-start (selected-window) (point-at-bol))))
7259 ;;; Saving and restoring visibility
7261 (defun org-outline-overlay-data (&optional use-markers)
7262 "Return a list of the locations of all outline overlays.
7263 These are overlays with the `invisible' property value `outline'.
7264 The return value is a list of cons cells, with start and stop
7265 positions for each overlay.
7266 If USE-MARKERS is set, return the positions as markers."
7267 (let (beg end)
7268 (save-excursion
7269 (save-restriction
7270 (widen)
7271 (delq nil
7272 (mapcar (lambda (o)
7273 (when (eq (overlay-get o 'invisible) 'outline)
7274 (setq beg (overlay-start o)
7275 end (overlay-end o))
7276 (and beg end (> end beg)
7277 (if use-markers
7278 (cons (copy-marker beg)
7279 (copy-marker end t))
7280 (cons beg end)))))
7281 (overlays-in (point-min) (point-max))))))))
7283 (defun org-set-outline-overlay-data (data)
7284 "Create visibility overlays for all positions in DATA.
7285 DATA should have been made by `org-outline-overlay-data'."
7286 (let (o)
7287 (save-excursion
7288 (save-restriction
7289 (widen)
7290 (show-all)
7291 (mapc (lambda (c)
7292 (outline-flag-region (car c) (cdr c) t))
7293 data)))))
7295 ;;; Folding of blocks
7297 (defvar org-hide-block-overlays nil
7298 "Overlays hiding blocks.")
7299 (make-variable-buffer-local 'org-hide-block-overlays)
7301 (defun org-block-map (function &optional start end)
7302 "Call FUNCTION at the head of all source blocks in the current buffer.
7303 Optional arguments START and END can be used to limit the range."
7304 (let ((start (or start (point-min)))
7305 (end (or end (point-max))))
7306 (save-excursion
7307 (goto-char start)
7308 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7309 (save-excursion
7310 (save-match-data
7311 (goto-char (match-beginning 0))
7312 (funcall function)))))))
7314 (defun org-hide-block-toggle-all ()
7315 "Toggle the visibility of all blocks in the current buffer."
7316 (org-block-map 'org-hide-block-toggle))
7318 (defun org-hide-block-all ()
7319 "Fold all blocks in the current buffer."
7320 (interactive)
7321 (org-show-block-all)
7322 (org-block-map 'org-hide-block-toggle-maybe))
7324 (defun org-show-block-all ()
7325 "Unfold all blocks in the current buffer."
7326 (interactive)
7327 (mapc 'delete-overlay org-hide-block-overlays)
7328 (setq org-hide-block-overlays nil))
7330 (defun org-hide-block-toggle-maybe ()
7331 "Toggle visibility of block at point.
7332 Unlike to `org-hide-block-toggle', this function does not throw
7333 an error. Return a non-nil value when toggling is successful."
7334 (interactive)
7335 (ignore-errors (org-hide-block-toggle)))
7337 (defun org-hide-block-toggle (&optional force)
7338 "Toggle the visibility of the current block.
7339 When optional argument FORCE is `off', make block visible. If it
7340 is non-nil, hide it unconditionally. Throw an error when not at
7341 a block. Return a non-nil value when toggling is successful."
7342 (interactive)
7343 (let ((element (org-element-at-point)))
7344 (unless (memq (org-element-type element)
7345 '(center-block comment-block dynamic-block example-block
7346 export-block quote-block special-block
7347 src-block verse-block))
7348 (user-error "Not at a block"))
7349 (let* ((start (save-excursion
7350 (goto-char (org-element-property :post-affiliated element))
7351 (line-end-position)))
7352 (end (save-excursion
7353 (goto-char (org-element-property :end element))
7354 (skip-chars-backward " \r\t\n")
7355 (line-end-position)))
7356 (overlays (overlays-at start)))
7357 (cond
7358 ;; Do nothing when not before or at the block opening line or
7359 ;; at the block closing line.
7360 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7361 ((and (not (eq force 'off))
7362 (not (memq t (mapcar
7363 (lambda (o)
7364 (eq (overlay-get o 'invisible) 'org-hide-block))
7365 overlays))))
7366 (let ((ov (make-overlay start end)))
7367 (overlay-put ov 'invisible 'org-hide-block)
7368 ;; Make the block accessible to `isearch'.
7369 (overlay-put
7370 ov 'isearch-open-invisible
7371 (lambda (ov)
7372 (when (memq ov org-hide-block-overlays)
7373 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7374 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7375 (delete-overlay ov))))
7376 (push ov org-hide-block-overlays)
7377 ;; When the block is hidden away, make sure point is left in
7378 ;; a visible part of the buffer.
7379 (when (> (line-beginning-position) start)
7380 (goto-char start)
7381 (beginning-of-line))
7382 ;; Signal successful toggling.
7384 ((or (not force) (eq force 'off))
7385 (dolist (ov overlays t)
7386 (when (memq ov org-hide-block-overlays)
7387 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7388 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7389 (delete-overlay ov))))))))
7391 ;; org-tab-after-check-for-cycling-hook
7392 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7393 ;; Remove overlays when changing major mode
7394 (add-hook 'org-mode-hook
7395 (lambda () (org-add-hook 'change-major-mode-hook
7396 'org-show-block-all 'append 'local)))
7398 ;;; Org-goto
7400 (defvar org-goto-window-configuration nil)
7401 (defvar org-goto-marker nil)
7402 (defvar org-goto-map)
7403 (defun org-goto-map ()
7404 "Set the keymap `org-goto'."
7405 (setq org-goto-map
7406 (let ((map (make-sparse-keymap)))
7407 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7408 mouse-drag-region universal-argument org-occur))
7409 cmd)
7410 (while (setq cmd (pop cmds))
7411 (substitute-key-definition cmd cmd map global-map)))
7412 (suppress-keymap map)
7413 (org-defkey map "\C-m" 'org-goto-ret)
7414 (org-defkey map [(return)] 'org-goto-ret)
7415 (org-defkey map [(left)] 'org-goto-left)
7416 (org-defkey map [(right)] 'org-goto-right)
7417 (org-defkey map [(control ?g)] 'org-goto-quit)
7418 (org-defkey map "\C-i" 'org-cycle)
7419 (org-defkey map [(tab)] 'org-cycle)
7420 (org-defkey map [(down)] 'outline-next-visible-heading)
7421 (org-defkey map [(up)] 'outline-previous-visible-heading)
7422 (if org-goto-auto-isearch
7423 (if (fboundp 'define-key-after)
7424 (define-key-after map [t] 'org-goto-local-auto-isearch)
7425 nil)
7426 (org-defkey map "q" 'org-goto-quit)
7427 (org-defkey map "n" 'outline-next-visible-heading)
7428 (org-defkey map "p" 'outline-previous-visible-heading)
7429 (org-defkey map "f" 'outline-forward-same-level)
7430 (org-defkey map "b" 'outline-backward-same-level)
7431 (org-defkey map "u" 'outline-up-heading))
7432 (org-defkey map "/" 'org-occur)
7433 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7434 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7435 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7436 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7437 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7438 map)))
7440 (defconst org-goto-help
7441 "Browse buffer copy, to find location or copy text.%s
7442 RET=jump to location C-g=quit and return to previous location
7443 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7445 (defvar org-goto-start-pos) ; dynamically scoped parameter
7447 (defun org-goto (&optional alternative-interface)
7448 "Look up a different location in the current file, keeping current visibility.
7450 When you want look-up or go to a different location in a
7451 document, the fastest way is often to fold the entire buffer and
7452 then dive into the tree. This method has the disadvantage, that
7453 the previous location will be folded, which may not be what you
7454 want.
7456 This command works around this by showing a copy of the current
7457 buffer in an indirect buffer, in overview mode. You can dive
7458 into the tree in that copy, use org-occur and incremental search
7459 to find a location. When pressing RET or `Q', the command
7460 returns to the original buffer in which the visibility is still
7461 unchanged. After RET it will also jump to the location selected
7462 in the indirect buffer and expose the headline hierarchy above.
7464 With a prefix argument, use the alternative interface: e.g. if
7465 `org-goto-interface' is 'outline use 'outline-path-completion."
7466 (interactive "P")
7467 (org-goto-map)
7468 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7469 (org-refile-use-outline-path t)
7470 (org-refile-target-verify-function nil)
7471 (interface
7472 (if (not alternative-interface)
7473 org-goto-interface
7474 (if (eq org-goto-interface 'outline)
7475 'outline-path-completion
7476 'outline)))
7477 (org-goto-start-pos (point))
7478 (selected-point
7479 (if (eq interface 'outline)
7480 (car (org-get-location (current-buffer) org-goto-help))
7481 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7482 (org-refile-check-position pa)
7483 (nth 3 pa)))))
7484 (if selected-point
7485 (progn
7486 (org-mark-ring-push org-goto-start-pos)
7487 (goto-char selected-point)
7488 (if (or (outline-invisible-p) (org-invisible-p2))
7489 (org-show-context 'org-goto)))
7490 (message "Quit"))))
7492 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7493 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7494 (defvar org-goto-local-auto-isearch-map) ; defined below
7496 (defun org-get-location (buf help)
7497 "Let the user select a location in the Org-mode buffer BUF.
7498 This function uses a recursive edit. It returns the selected position
7499 or nil."
7500 (org-no-popups
7501 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7502 (isearch-hide-immediately nil)
7503 (isearch-search-fun-function
7504 (lambda () 'org-goto-local-search-headings))
7505 (org-goto-selected-point org-goto-exit-command))
7506 (save-excursion
7507 (save-window-excursion
7508 (delete-other-windows)
7509 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7510 (org-pop-to-buffer-same-window
7511 (condition-case nil
7512 (make-indirect-buffer (current-buffer) "*org-goto*")
7513 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7514 (with-output-to-temp-buffer "*Org Help*"
7515 (princ (format help (if org-goto-auto-isearch
7516 " Just type for auto-isearch."
7517 " n/p/f/b/u to navigate, q to quit."))))
7518 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7519 (setq buffer-read-only nil)
7520 (let ((org-startup-truncated t)
7521 (org-startup-folded nil)
7522 (org-startup-align-all-tables nil))
7523 (org-mode)
7524 (org-overview))
7525 (setq buffer-read-only t)
7526 (if (and (boundp 'org-goto-start-pos)
7527 (integer-or-marker-p org-goto-start-pos))
7528 (let ((org-show-hierarchy-above t)
7529 (org-show-siblings t)
7530 (org-show-following-heading t))
7531 (goto-char org-goto-start-pos)
7532 (and (outline-invisible-p) (org-show-context)))
7533 (goto-char (point-min)))
7534 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7535 (message "Select location and press RET")
7536 (use-local-map org-goto-map)
7537 (recursive-edit)))
7538 (kill-buffer "*org-goto*")
7539 (cons org-goto-selected-point org-goto-exit-command))))
7541 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7542 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7543 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7544 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7546 (defun org-goto-local-search-headings (string bound noerror)
7547 "Search and make sure that any matches are in headlines."
7548 (catch 'return
7549 (while (if isearch-forward
7550 (search-forward string bound noerror)
7551 (search-backward string bound noerror))
7552 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7553 (and (member :headline context)
7554 (not (member :tags context))))
7555 (throw 'return (point))))))
7557 (defun org-goto-local-auto-isearch ()
7558 "Start isearch."
7559 (interactive)
7560 (goto-char (point-min))
7561 (let ((keys (this-command-keys)))
7562 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7563 (isearch-mode t)
7564 (isearch-process-search-char (string-to-char keys)))))
7566 (defun org-goto-ret (&optional arg)
7567 "Finish `org-goto' by going to the new location."
7568 (interactive "P")
7569 (setq org-goto-selected-point (point)
7570 org-goto-exit-command 'return)
7571 (throw 'exit nil))
7573 (defun org-goto-left ()
7574 "Finish `org-goto' by going to the new location."
7575 (interactive)
7576 (if (org-at-heading-p)
7577 (progn
7578 (beginning-of-line 1)
7579 (setq org-goto-selected-point (point)
7580 org-goto-exit-command 'left)
7581 (throw 'exit nil))
7582 (user-error "Not on a heading")))
7584 (defun org-goto-right ()
7585 "Finish `org-goto' by going to the new location."
7586 (interactive)
7587 (if (org-at-heading-p)
7588 (progn
7589 (setq org-goto-selected-point (point)
7590 org-goto-exit-command 'right)
7591 (throw 'exit nil))
7592 (user-error "Not on a heading")))
7594 (defun org-goto-quit ()
7595 "Finish `org-goto' without cursor motion."
7596 (interactive)
7597 (setq org-goto-selected-point nil)
7598 (setq org-goto-exit-command 'quit)
7599 (throw 'exit nil))
7601 ;;; Indirect buffer display of subtrees
7603 (defvar org-indirect-dedicated-frame nil
7604 "This is the frame being used for indirect tree display.")
7605 (defvar org-last-indirect-buffer nil)
7607 (defun org-tree-to-indirect-buffer (&optional arg)
7608 "Create indirect buffer and narrow it to current subtree.
7609 With a numerical prefix ARG, go up to this level and then take that tree.
7610 If ARG is negative, go up that many levels.
7612 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7613 indirect buffer previously made with this command, to avoid proliferation of
7614 indirect buffers. However, when you call the command with a \
7615 \\[universal-argument] prefix, or
7616 when `org-indirect-buffer-display' is `new-frame', the last buffer
7617 is kept so that you can work with several indirect buffers at the same time.
7618 If `org-indirect-buffer-display' is `dedicated-frame', the \
7619 \\[universal-argument] prefix also
7620 requests that a new frame be made for the new buffer, so that the dedicated
7621 frame is not changed."
7622 (interactive "P")
7623 (let ((cbuf (current-buffer))
7624 (cwin (selected-window))
7625 (pos (point))
7626 beg end level heading ibuf)
7627 (save-excursion
7628 (org-back-to-heading t)
7629 (when (numberp arg)
7630 (setq level (org-outline-level))
7631 (if (< arg 0) (setq arg (+ level arg)))
7632 (while (> (setq level (org-outline-level)) arg)
7633 (org-up-heading-safe)))
7634 (setq beg (point)
7635 heading (org-get-heading))
7636 (org-end-of-subtree t t)
7637 (if (org-at-heading-p) (backward-char 1))
7638 (setq end (point)))
7639 (if (and (buffer-live-p org-last-indirect-buffer)
7640 (not (eq org-indirect-buffer-display 'new-frame))
7641 (not arg))
7642 (kill-buffer org-last-indirect-buffer))
7643 (setq ibuf (org-get-indirect-buffer cbuf heading)
7644 org-last-indirect-buffer ibuf)
7645 (cond
7646 ((or (eq org-indirect-buffer-display 'new-frame)
7647 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7648 (select-frame (make-frame))
7649 (delete-other-windows)
7650 (org-pop-to-buffer-same-window ibuf)
7651 (org-set-frame-title heading))
7652 ((eq org-indirect-buffer-display 'dedicated-frame)
7653 (raise-frame
7654 (select-frame (or (and org-indirect-dedicated-frame
7655 (frame-live-p org-indirect-dedicated-frame)
7656 org-indirect-dedicated-frame)
7657 (setq org-indirect-dedicated-frame (make-frame)))))
7658 (delete-other-windows)
7659 (org-pop-to-buffer-same-window ibuf)
7660 (org-set-frame-title (concat "Indirect: " heading)))
7661 ((eq org-indirect-buffer-display 'current-window)
7662 (org-pop-to-buffer-same-window ibuf))
7663 ((eq org-indirect-buffer-display 'other-window)
7664 (pop-to-buffer ibuf))
7665 (t (error "Invalid value")))
7666 (if (featurep 'xemacs)
7667 (save-excursion (org-mode) (turn-on-font-lock)))
7668 (narrow-to-region beg end)
7669 (show-all)
7670 (goto-char pos)
7671 (run-hook-with-args 'org-cycle-hook 'all)
7672 (and (window-live-p cwin) (select-window cwin))))
7674 (defun org-get-indirect-buffer (&optional buffer heading)
7675 (setq buffer (or buffer (current-buffer)))
7676 (let ((n 1) (base (buffer-name buffer)) bname)
7677 (while (buffer-live-p
7678 (get-buffer
7679 (setq bname
7680 (concat base "-"
7681 (if heading (concat heading "-" (number-to-string n))
7682 (number-to-string n))))))
7683 (setq n (1+ n)))
7684 (condition-case nil
7685 (make-indirect-buffer buffer bname 'clone)
7686 (error (make-indirect-buffer buffer bname)))))
7688 (defun org-set-frame-title (title)
7689 "Set the title of the current frame to the string TITLE."
7690 ;; FIXME: how to name a single frame in XEmacs???
7691 (unless (featurep 'xemacs)
7692 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7694 ;;;; Structure editing
7696 ;;; Inserting headlines
7698 (defun org-previous-line-empty-p (&optional next)
7699 "Is the previous line a blank line?
7700 When NEXT is non-nil, check the next line instead."
7701 (save-excursion
7702 (and (not (bobp))
7703 (or (beginning-of-line (if next 2 0)) t)
7704 (save-match-data
7705 (looking-at "[ \t]*$")))))
7707 (defun org-insert-heading (&optional arg invisible-ok)
7708 "Insert a new heading or an item with the same depth at point.
7710 If point is at the beginning of a heading or a list item, insert
7711 a new heading or a new item above the current one. If point is
7712 at the beginning of a normal line, turn the line into a heading.
7714 If point is in the middle of a headline or a list item, split the
7715 headline or the item and create a new headline/item with the text
7716 in the current line after point \(see `org-M-RET-may-split-line'
7717 on how to modify this behavior).
7719 With one universal prefix argument, set the user option
7720 `org-insert-heading-respect-content' to t for the duration of
7721 the command. This modifies the behavior described above in this
7722 ways: on list items and at the beginning of normal lines, force
7723 the insertion of a heading after the current subtree.
7725 With two universal prefix arguments, insert the heading at the
7726 end of the grandparent subtree. For example, if point is within
7727 a 2nd-level heading, then it will insert a 2nd-level heading at
7728 the end of the 1st-level parent heading.
7730 If point is at the beginning of a headline, insert a sibling
7731 before the current headline. If point is not at the beginning,
7732 split the line and create a new headline with the text in the
7733 current line after point \(see `org-M-RET-may-split-line' on how
7734 to modify this behavior).
7736 If point is at the beginning of a normal line, turn this line
7737 into a heading.
7739 When INVISIBLE-OK is set, stop at invisible headlines when going
7740 back. This is important for non-interactive uses of the
7741 command."
7742 (interactive "P")
7743 (if (org-called-interactively-p 'any) (org-reveal))
7744 (let ((itemp (org-in-item-p))
7745 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7746 (respect-content (or org-insert-heading-respect-content
7747 (equal arg '(4))))
7748 (initial-content "")
7749 (adjust-empty-lines t))
7751 (cond
7753 ((or (= (buffer-size) 0)
7754 (and (not (save-excursion
7755 (and (ignore-errors (org-back-to-heading invisible-ok))
7756 (org-at-heading-p))))
7757 (or arg (not itemp))))
7758 ;; At beginning of buffer or so high up that only a heading
7759 ;; makes sense.
7760 (cond ((and (bolp) (not respect-content)) (insert "* "))
7761 ((not respect-content)
7762 (unless may-split (end-of-line))
7763 (insert "\n* "))
7764 ((re-search-forward org-outline-regexp-bol nil t)
7765 (beginning-of-line)
7766 (insert "* \n")
7767 (backward-char))
7768 (t (goto-char (point-max))
7769 (insert "\n* ")))
7770 (run-hooks 'org-insert-heading-hook))
7772 ((and itemp (not (member arg '((4) (16)))))
7773 ;; Insert an item
7774 (org-insert-item))
7777 ;; Maybe move at the end of the subtree
7778 (when (equal arg '(16))
7779 (org-up-heading-safe)
7780 (org-end-of-subtree t))
7781 ;; Insert a heading
7782 (save-restriction
7783 (widen)
7784 (let* ((level nil)
7785 (on-heading (org-at-heading-p))
7786 (empty-line-p (if on-heading
7787 (org-previous-line-empty-p)
7788 ;; We will decide later
7789 nil))
7790 ;; Get a level string to fall back on
7791 (fix-level
7792 (if (org-before-first-heading-p) "*"
7793 (save-excursion
7794 (org-back-to-heading t)
7795 (if (org-previous-line-empty-p) (setq empty-line-p t))
7796 (looking-at org-outline-regexp)
7797 (make-string (1- (length (match-string 0))) ?*))))
7798 (stars
7799 (save-excursion
7800 (condition-case nil
7801 (progn
7802 (org-back-to-heading invisible-ok)
7803 (when (and (not on-heading)
7804 (featurep 'org-inlinetask)
7805 (integerp org-inlinetask-min-level)
7806 (>= (length (match-string 0))
7807 org-inlinetask-min-level))
7808 ;; Find a heading level before the inline task
7809 (while (and (setq level (org-up-heading-safe))
7810 (>= level org-inlinetask-min-level)))
7811 (if (org-at-heading-p)
7812 (org-back-to-heading invisible-ok)
7813 (error "This should not happen")))
7814 (unless (and (save-excursion
7815 (save-match-data
7816 (org-backward-heading-same-level
7817 1 invisible-ok))
7818 (= (point) (match-beginning 0)))
7819 (not (org-previous-line-empty-p t)))
7820 (setq empty-line-p (or empty-line-p
7821 (org-previous-line-empty-p))))
7822 (match-string 0))
7823 (error (or fix-level "* ")))))
7824 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7825 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7826 pos hide-previous previous-pos)
7828 ;; If we insert after content, move there and clean up whitespace
7829 (when (and respect-content
7830 (not (org-looking-at-p org-outline-regexp-bol)))
7831 (if (not (org-before-first-heading-p))
7832 (org-end-of-subtree nil t)
7833 (re-search-forward org-outline-regexp-bol)
7834 (beginning-of-line 0))
7835 (skip-chars-backward " \r\n")
7836 (and (not (looking-back "^\\*+"))
7837 (looking-at "[ \t]+") (replace-match ""))
7838 (unless (eobp) (forward-char 1))
7839 (when (looking-at "^\\*")
7840 (unless (bobp) (backward-char 1))
7841 (insert "\n")))
7843 ;; If we are splitting, grab the text that should be moved to the new headline
7844 (when may-split
7845 (if (org-on-heading-p)
7846 ;; This is a heading, we split intelligently (keeping tags)
7847 (let ((pos (point)))
7848 (goto-char (point-at-bol))
7849 (unless (looking-at org-complex-heading-regexp)
7850 (error "This should not happen"))
7851 (when (and (match-beginning 4)
7852 (> pos (match-beginning 4))
7853 (< pos (match-end 4)))
7854 (setq initial-content (buffer-substring pos (match-end 4)))
7855 (goto-char pos)
7856 (delete-region (point) (match-end 4))
7857 (if (looking-at "[ \t]*$")
7858 (replace-match "")
7859 (insert (make-string (length initial-content) ?\ )))
7860 (setq initial-content (org-trim initial-content)))
7861 (goto-char pos))
7862 ;; a normal line
7863 (setq initial-content
7864 (org-trim (buffer-substring (point) (point-at-eol))))
7865 (delete-region (point) (point-at-eol))))
7867 ;; If we are at the beginning of the line, insert before it. Else after
7868 (cond
7869 ((and (bolp) (looking-at "[ \t]*$")))
7870 ((and (bolp) (not (looking-at "[ \t]*$")))
7871 (open-line 1))
7873 (goto-char (point-at-eol))
7874 (insert "\n")))
7876 ;; Insert the new heading
7877 (insert stars)
7878 (just-one-space)
7879 (insert initial-content)
7880 (when adjust-empty-lines
7881 (if (or (not blank)
7882 (and blank (not (org-previous-line-empty-p))))
7883 (org-N-empty-lines-before-current (if blank 1 0))))
7884 (run-hooks 'org-insert-heading-hook)))))))
7886 (defun org-N-empty-lines-before-current (N)
7887 "Make the number of empty lines before current exactly N.
7888 So this will delete or add empty lines."
7889 (save-excursion
7890 (beginning-of-line)
7891 (let ((p (point)))
7892 (skip-chars-backward " \r\t\n")
7893 (unless (bolp) (forward-line))
7894 (delete-region (point) p))
7895 (when (> N 0) (insert (make-string N ?\n)))))
7897 (defun org-get-heading (&optional no-tags no-todo)
7898 "Return the heading of the current entry, without the stars.
7899 When NO-TAGS is non-nil, don't include tags.
7900 When NO-TODO is non-nil, don't include TODO keywords."
7901 (save-excursion
7902 (org-back-to-heading t)
7903 (cond
7904 ((and no-tags no-todo)
7905 (looking-at org-complex-heading-regexp)
7906 (match-string 4))
7907 (no-tags
7908 (looking-at (concat org-outline-regexp
7909 "\\(.*?\\)"
7910 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7911 (match-string 1))
7912 (no-todo
7913 (looking-at org-todo-line-regexp)
7914 (match-string 3))
7915 (t (looking-at org-heading-regexp)
7916 (match-string 2)))))
7918 (defvar orgstruct-mode) ; defined below
7920 (defun org-heading-components ()
7921 "Return the components of the current heading.
7922 This is a list with the following elements:
7923 - the level as an integer
7924 - the reduced level, different if `org-odd-levels-only' is set.
7925 - the TODO keyword, or nil
7926 - the priority character, like ?A, or nil if no priority is given
7927 - the headline text itself, or the tags string if no headline text
7928 - the tags string, or nil."
7929 (save-excursion
7930 (org-back-to-heading t)
7931 (if (let (case-fold-search)
7932 (looking-at
7933 (if orgstruct-mode
7934 org-heading-regexp
7935 org-complex-heading-regexp)))
7936 (if orgstruct-mode
7937 (list (length (match-string 1))
7938 (org-reduced-level (length (match-string 1)))
7941 (match-string 2)
7942 nil)
7943 (list (length (match-string 1))
7944 (org-reduced-level (length (match-string 1)))
7945 (org-match-string-no-properties 2)
7946 (and (match-end 3) (aref (match-string 3) 2))
7947 (org-match-string-no-properties 4)
7948 (org-match-string-no-properties 5))))))
7950 (defun org-get-entry ()
7951 "Get the entry text, after heading, entire subtree."
7952 (save-excursion
7953 (org-back-to-heading t)
7954 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7956 (defun org-insert-heading-after-current ()
7957 "Insert a new heading with same level as current, after current subtree."
7958 (interactive)
7959 (org-back-to-heading)
7960 (org-insert-heading)
7961 (org-move-subtree-down)
7962 (end-of-line 1))
7964 (defun org-insert-heading-respect-content (&optional invisible-ok)
7965 "Insert heading with `org-insert-heading-respect-content' set to t."
7966 (interactive)
7967 (org-insert-heading '(4) invisible-ok))
7969 (defun org-insert-todo-heading-respect-content (&optional force-state)
7970 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7971 (interactive)
7972 (org-insert-todo-heading force-state '(4)))
7974 (defun org-insert-todo-heading (arg &optional force-heading)
7975 "Insert a new heading with the same level and TODO state as current heading.
7976 If the heading has no TODO state, or if the state is DONE, use the first
7977 state (TODO by default). Also with one prefix arg, force first state. With
7978 two prefix args, force inserting at the end of the parent subtree."
7979 (interactive "P")
7980 (when (or force-heading (not (org-insert-item 'checkbox)))
7981 (org-insert-heading (or (and (equal arg '(16)) '(16))
7982 force-heading))
7983 (save-excursion
7984 (org-back-to-heading)
7985 (outline-previous-heading)
7986 (looking-at org-todo-line-regexp))
7987 (let*
7988 ((new-mark-x
7989 (if (or (equal arg '(4))
7990 (not (match-beginning 2))
7991 (member (match-string 2) org-done-keywords))
7992 (car org-todo-keywords-1)
7993 (match-string 2)))
7994 (new-mark
7996 (run-hook-with-args-until-success
7997 'org-todo-get-default-hook new-mark-x nil)
7998 new-mark-x)))
7999 (beginning-of-line 1)
8000 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8001 (if org-treat-insert-todo-heading-as-state-change
8002 (org-todo new-mark)
8003 (insert new-mark " "))))
8004 (when org-provide-todo-statistics
8005 (org-update-parent-todo-statistics))))
8007 (defun org-insert-subheading (arg)
8008 "Insert a new subheading and demote it.
8009 Works for outline headings and for plain lists alike."
8010 (interactive "P")
8011 (org-insert-heading arg)
8012 (cond
8013 ((org-at-heading-p) (org-do-demote))
8014 ((org-at-item-p) (org-indent-item))))
8016 (defun org-insert-todo-subheading (arg)
8017 "Insert a new subheading with TODO keyword or checkbox and demote it.
8018 Works for outline headings and for plain lists alike."
8019 (interactive "P")
8020 (org-insert-todo-heading arg)
8021 (cond
8022 ((org-at-heading-p) (org-do-demote))
8023 ((org-at-item-p) (org-indent-item))))
8025 ;;; Promotion and Demotion
8027 (defvar org-after-demote-entry-hook nil
8028 "Hook run after an entry has been demoted.
8029 The cursor will be at the beginning of the entry.
8030 When a subtree is being demoted, the hook will be called for each node.")
8032 (defvar org-after-promote-entry-hook nil
8033 "Hook run after an entry has been promoted.
8034 The cursor will be at the beginning of the entry.
8035 When a subtree is being promoted, the hook will be called for each node.")
8037 (defun org-promote-subtree ()
8038 "Promote the entire subtree.
8039 See also `org-promote'."
8040 (interactive)
8041 (save-excursion
8042 (org-with-limited-levels (org-map-tree 'org-promote)))
8043 (org-fix-position-after-promote))
8045 (defun org-demote-subtree ()
8046 "Demote the entire subtree. See `org-demote'.
8047 See also `org-promote'."
8048 (interactive)
8049 (save-excursion
8050 (org-with-limited-levels (org-map-tree 'org-demote)))
8051 (org-fix-position-after-promote))
8054 (defun org-do-promote ()
8055 "Promote the current heading higher up the tree.
8056 If the region is active in `transient-mark-mode', promote all headings
8057 in the region."
8058 (interactive)
8059 (save-excursion
8060 (if (org-region-active-p)
8061 (org-map-region 'org-promote (region-beginning) (region-end))
8062 (org-promote)))
8063 (org-fix-position-after-promote))
8065 (defun org-do-demote ()
8066 "Demote the current heading lower down the tree.
8067 If the region is active in `transient-mark-mode', demote all headings
8068 in the region."
8069 (interactive)
8070 (save-excursion
8071 (if (org-region-active-p)
8072 (org-map-region 'org-demote (region-beginning) (region-end))
8073 (org-demote)))
8074 (org-fix-position-after-promote))
8076 (defun org-fix-position-after-promote ()
8077 "Make sure that after pro/demotion cursor position is right."
8078 (let ((pos (point)))
8079 (when (save-excursion
8080 (beginning-of-line 1)
8081 (looking-at org-todo-line-regexp)
8082 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8083 (cond ((eobp) (insert " "))
8084 ((eolp) (insert " "))
8085 ((equal (char-after) ?\ ) (forward-char 1))))))
8087 (defun org-current-level ()
8088 "Return the level of the current entry, or nil if before the first headline.
8089 The level is the number of stars at the beginning of the headline."
8090 (save-excursion
8091 (org-with-limited-levels
8092 (if (ignore-errors (org-back-to-heading t))
8093 (funcall outline-level)))))
8095 (defun org-get-previous-line-level ()
8096 "Return the outline depth of the last headline before the current line.
8097 Returns 0 for the first headline in the buffer, and nil if before the
8098 first headline."
8099 (and (org-current-level)
8100 (or (and (/= (line-beginning-position) (point-min))
8101 (save-excursion (beginning-of-line 0) (org-current-level)))
8102 0)))
8104 (defun org-reduced-level (l)
8105 "Compute the effective level of a heading.
8106 This takes into account the setting of `org-odd-levels-only'."
8107 (cond
8108 ((zerop l) 0)
8109 (org-odd-levels-only (1+ (floor (/ l 2))))
8110 (t l)))
8112 (defun org-level-increment ()
8113 "Return the number of stars that will be added or removed at a
8114 time to headlines when structure editing, based on the value of
8115 `org-odd-levels-only'."
8116 (if org-odd-levels-only 2 1))
8118 (defun org-get-valid-level (level &optional change)
8119 "Rectify a level change under the influence of `org-odd-levels-only'
8120 LEVEL is a current level, CHANGE is by how much the level should be
8121 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8122 even level numbers will become the next higher odd number."
8123 (if org-odd-levels-only
8124 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8125 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8126 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8127 (max 1 (+ level (or change 0)))))
8129 (if (boundp 'define-obsolete-function-alias)
8130 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8131 (define-obsolete-function-alias 'org-get-legal-level
8132 'org-get-valid-level)
8133 (define-obsolete-function-alias 'org-get-legal-level
8134 'org-get-valid-level "23.1")))
8136 (defun org-promote ()
8137 "Promote the current heading higher up the tree.
8138 If the region is active in `transient-mark-mode', promote all headings
8139 in the region."
8140 (org-back-to-heading t)
8141 (let* ((level (save-match-data (funcall outline-level)))
8142 (after-change-functions (remove 'flyspell-after-change-function
8143 after-change-functions))
8144 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8145 (diff (abs (- level (length up-head) -1))))
8146 (cond ((and (= level 1) org-called-with-limited-levels
8147 org-allow-promoting-top-level-subtree)
8148 (replace-match "# " nil t))
8149 ((= level 1)
8150 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8151 (t (replace-match up-head nil t)))
8152 ;; Fixup tag positioning
8153 (unless (= level 1)
8154 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8155 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8156 (run-hooks 'org-after-promote-entry-hook)))
8158 (defun org-demote ()
8159 "Demote the current heading lower down the tree.
8160 If the region is active in `transient-mark-mode', demote all headings
8161 in the region."
8162 (org-back-to-heading t)
8163 (let* ((level (save-match-data (funcall outline-level)))
8164 (after-change-functions (remove 'flyspell-after-change-function
8165 after-change-functions))
8166 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8167 (diff (abs (- level (length down-head) -1))))
8168 (replace-match down-head nil t)
8169 ;; Fixup tag positioning
8170 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8171 (if org-adapt-indentation (org-fixup-indentation diff))
8172 (run-hooks 'org-after-demote-entry-hook)))
8174 (defun org-cycle-level ()
8175 "Cycle the level of an empty headline through possible states.
8176 This goes first to child, then to parent, level, then up the hierarchy.
8177 After top level, it switches back to sibling level."
8178 (interactive)
8179 (let ((org-adapt-indentation nil))
8180 (when (org-point-at-end-of-empty-headline)
8181 (setq this-command 'org-cycle-level) ; Only needed for caching
8182 (let ((cur-level (org-current-level))
8183 (prev-level (org-get-previous-line-level)))
8184 (cond
8185 ;; If first headline in file, promote to top-level.
8186 ((= prev-level 0)
8187 (loop repeat (/ (- cur-level 1) (org-level-increment))
8188 do (org-do-promote)))
8189 ;; If same level as prev, demote one.
8190 ((= prev-level cur-level)
8191 (org-do-demote))
8192 ;; If parent is top-level, promote to top level if not already.
8193 ((= prev-level 1)
8194 (loop repeat (/ (- cur-level 1) (org-level-increment))
8195 do (org-do-promote)))
8196 ;; If top-level, return to prev-level.
8197 ((= cur-level 1)
8198 (loop repeat (/ (- prev-level 1) (org-level-increment))
8199 do (org-do-demote)))
8200 ;; If less than prev-level, promote one.
8201 ((< cur-level prev-level)
8202 (org-do-promote))
8203 ;; If deeper than prev-level, promote until higher than
8204 ;; prev-level.
8205 ((> cur-level prev-level)
8206 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8207 do (org-do-promote))))
8208 t))))
8210 (defun org-map-tree (fun)
8211 "Call FUN for every heading underneath the current one."
8212 (org-back-to-heading)
8213 (let ((level (funcall outline-level)))
8214 (save-excursion
8215 (funcall fun)
8216 (while (and (progn
8217 (outline-next-heading)
8218 (> (funcall outline-level) level))
8219 (not (eobp)))
8220 (funcall fun)))))
8222 (defun org-map-region (fun beg end)
8223 "Call FUN for every heading between BEG and END."
8224 (let ((org-ignore-region t))
8225 (save-excursion
8226 (setq end (copy-marker end))
8227 (goto-char beg)
8228 (if (and (re-search-forward org-outline-regexp-bol nil t)
8229 (< (point) end))
8230 (funcall fun))
8231 (while (and (progn
8232 (outline-next-heading)
8233 (< (point) end))
8234 (not (eobp)))
8235 (funcall fun)))))
8237 (defvar org-property-end-re) ; silence byte-compiler
8238 (defun org-fixup-indentation (diff)
8239 "Change the indentation in the current entry by DIFF.
8240 However, if any line in the current entry has no indentation, or if it
8241 would end up with no indentation after the change, nothing at all is done."
8242 (save-excursion
8243 (let ((end (save-excursion (outline-next-heading)
8244 (point-marker)))
8245 (prohibit (if (> diff 0)
8246 "^\\S-"
8247 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8248 col)
8249 (unless (save-excursion (end-of-line 1)
8250 (re-search-forward prohibit end t))
8251 (while (and (< (point) end)
8252 (re-search-forward "^[ \t]+" end t))
8253 (goto-char (match-end 0))
8254 (setq col (current-column))
8255 (if (< diff 0) (replace-match ""))
8256 (org-indent-to-column (+ diff col))))
8257 (move-marker end nil))))
8259 (defun org-convert-to-odd-levels ()
8260 "Convert an org-mode file with all levels allowed to one with odd levels.
8261 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8262 level 5 etc."
8263 (interactive)
8264 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8265 (let ((outline-level 'org-outline-level)
8266 (org-odd-levels-only nil) n)
8267 (save-excursion
8268 (goto-char (point-min))
8269 (while (re-search-forward "^\\*\\*+ " nil t)
8270 (setq n (- (length (match-string 0)) 2))
8271 (while (>= (setq n (1- n)) 0)
8272 (org-demote))
8273 (end-of-line 1))))))
8275 (defun org-convert-to-oddeven-levels ()
8276 "Convert an org-mode file with only odd levels to one with odd/even levels.
8277 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8278 file contains a section with an even level, conversion would
8279 destroy the structure of the file. An error is signaled in this
8280 case."
8281 (interactive)
8282 (goto-char (point-min))
8283 ;; First check if there are no even levels
8284 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8285 (org-show-context t)
8286 (error "Not all levels are odd in this file. Conversion not possible"))
8287 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8288 (let ((outline-regexp org-outline-regexp)
8289 (outline-level 'org-outline-level)
8290 (org-odd-levels-only nil) n)
8291 (save-excursion
8292 (goto-char (point-min))
8293 (while (re-search-forward "^\\*\\*+ " nil t)
8294 (setq n (/ (1- (length (match-string 0))) 2))
8295 (while (>= (setq n (1- n)) 0)
8296 (org-promote))
8297 (end-of-line 1))))))
8299 (defun org-tr-level (n)
8300 "Make N odd if required."
8301 (if org-odd-levels-only (1+ (/ n 2)) n))
8303 ;;; Vertical tree motion, cutting and pasting of subtrees
8305 (defun org-move-subtree-up (&optional arg)
8306 "Move the current subtree up past ARG headlines of the same level."
8307 (interactive "p")
8308 (org-move-subtree-down (- (prefix-numeric-value arg))))
8310 (defun org-move-subtree-down (&optional arg)
8311 "Move the current subtree down past ARG headlines of the same level."
8312 (interactive "p")
8313 (setq arg (prefix-numeric-value arg))
8314 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8315 'org-get-last-sibling))
8316 (ins-point (make-marker))
8317 (cnt (abs arg))
8318 (col (current-column))
8319 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8320 ;; Select the tree
8321 (org-back-to-heading)
8322 (setq beg0 (point))
8323 (save-excursion
8324 (setq ne-beg (org-back-over-empty-lines))
8325 (setq beg (point)))
8326 (save-match-data
8327 (save-excursion (outline-end-of-heading)
8328 (setq folded (outline-invisible-p)))
8329 (progn (org-end-of-subtree nil t)
8330 (unless (eobp) (backward-char))))
8331 (outline-next-heading)
8332 (setq ne-end (org-back-over-empty-lines))
8333 (setq end (point))
8334 (goto-char beg0)
8335 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8336 ;; include less whitespace
8337 (save-excursion
8338 (goto-char beg)
8339 (forward-line (- ne-beg ne-end))
8340 (setq beg (point))))
8341 ;; Find insertion point, with error handling
8342 (while (> cnt 0)
8343 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8344 (progn (goto-char beg0)
8345 (user-error "Cannot move past superior level or buffer limit")))
8346 (setq cnt (1- cnt)))
8347 (if (> arg 0)
8348 ;; Moving forward - still need to move over subtree
8349 (progn (org-end-of-subtree t t)
8350 (save-excursion
8351 (org-back-over-empty-lines)
8352 (or (bolp) (newline)))))
8353 (setq ne-ins (org-back-over-empty-lines))
8354 (move-marker ins-point (point))
8355 (setq txt (buffer-substring beg end))
8356 (org-save-markers-in-region beg end)
8357 (delete-region beg end)
8358 (org-remove-empty-overlays-at beg)
8359 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8360 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8361 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8362 (let ((bbb (point)))
8363 (insert-before-markers txt)
8364 (org-reinstall-markers-in-region bbb)
8365 (move-marker ins-point bbb))
8366 (or (bolp) (insert "\n"))
8367 (setq ins-end (point))
8368 (goto-char ins-point)
8369 (org-skip-whitespace)
8370 (when (and (< arg 0)
8371 (org-first-sibling-p)
8372 (> ne-ins ne-beg))
8373 ;; Move whitespace back to beginning
8374 (save-excursion
8375 (goto-char ins-end)
8376 (let ((kill-whole-line t))
8377 (kill-line (- ne-ins ne-beg)) (point)))
8378 (insert (make-string (- ne-ins ne-beg) ?\n)))
8379 (move-marker ins-point nil)
8380 (if folded
8381 (hide-subtree)
8382 (org-show-entry)
8383 (show-children)
8384 (org-cycle-hide-drawers 'children))
8385 (org-clean-visibility-after-subtree-move)
8386 ;; move back to the initial column we were at
8387 (move-to-column col)))
8389 (defvar org-subtree-clip ""
8390 "Clipboard for cut and paste of subtrees.
8391 This is actually only a copy of the kill, because we use the normal kill
8392 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8394 (defvar org-subtree-clip-folded nil
8395 "Was the last copied subtree folded?
8396 This is used to fold the tree back after pasting.")
8398 (defun org-cut-subtree (&optional n)
8399 "Cut the current subtree into the clipboard.
8400 With prefix arg N, cut this many sequential subtrees.
8401 This is a short-hand for marking the subtree and then cutting it."
8402 (interactive "p")
8403 (org-copy-subtree n 'cut))
8405 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8406 "Copy the current subtree it in the clipboard.
8407 With prefix arg N, copy this many sequential subtrees.
8408 This is a short-hand for marking the subtree and then copying it.
8409 If CUT is non-nil, actually cut the subtree.
8410 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8411 of some markers in the region, even if CUT is non-nil. This is
8412 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8413 (interactive "p")
8414 (let (beg end folded (beg0 (point)))
8415 (if (org-called-interactively-p 'any)
8416 (org-back-to-heading nil) ; take what looks like a subtree
8417 (org-back-to-heading t)) ; take what is really there
8418 (setq beg (point))
8419 (skip-chars-forward " \t\r\n")
8420 (save-match-data
8421 (if nosubtrees
8422 (outline-next-heading)
8423 (save-excursion (outline-end-of-heading)
8424 (setq folded (outline-invisible-p)))
8425 (ignore-errors (org-forward-heading-same-level (1- n) t))
8426 (org-end-of-subtree t t)))
8427 (setq end (point))
8428 (goto-char beg0)
8429 (when (> end beg)
8430 (setq org-subtree-clip-folded folded)
8431 (when (or cut force-store-markers)
8432 (org-save-markers-in-region beg end))
8433 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8434 (setq org-subtree-clip (current-kill 0))
8435 (message "%s: Subtree(s) with %d characters"
8436 (if cut "Cut" "Copied")
8437 (length org-subtree-clip)))))
8439 (defun org-paste-subtree (&optional level tree for-yank remove)
8440 "Paste the clipboard as a subtree, with modification of headline level.
8441 The entire subtree is promoted or demoted in order to match a new headline
8442 level.
8444 If the cursor is at the beginning of a headline, the same level as
8445 that headline is used to paste the tree.
8447 If not, the new level is derived from the *visible* headings
8448 before and after the insertion point, and taken to be the inferior headline
8449 level of the two. So if the previous visible heading is level 3 and the
8450 next is level 4 (or vice versa), level 4 will be used for insertion.
8451 This makes sure that the subtree remains an independent subtree and does
8452 not swallow low level entries.
8454 You can also force a different level, either by using a numeric prefix
8455 argument, or by inserting the heading marker by hand. For example, if the
8456 cursor is after \"*****\", then the tree will be shifted to level 5.
8458 If optional TREE is given, use this text instead of the kill ring.
8460 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8461 move back over whitespace before inserting, and move point to the end of
8462 the inserted text when done.
8464 When REMOVE is non-nil, remove the subtree from the clipboard."
8465 (interactive "P")
8466 (setq tree (or tree (and kill-ring (current-kill 0))))
8467 (unless (org-kill-is-subtree-p tree)
8468 (user-error "%s"
8469 (substitute-command-keys
8470 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8471 (org-with-limited-levels
8472 (let* ((visp (not (outline-invisible-p)))
8473 (txt tree)
8474 (^re_ "\\(\\*+\\)[ \t]*")
8475 (old-level (if (string-match org-outline-regexp-bol txt)
8476 (- (match-end 0) (match-beginning 0) 1)
8477 -1))
8478 (force-level (cond (level (prefix-numeric-value level))
8479 ((and (looking-at "[ \t]*$")
8480 (string-match
8481 "^\\*+$" (buffer-substring
8482 (point-at-bol) (point))))
8483 (- (match-end 0) (match-beginning 0)))
8484 ((and (bolp)
8485 (looking-at org-outline-regexp))
8486 (- (match-end 0) (point) 1))))
8487 (previous-level (save-excursion
8488 (condition-case nil
8489 (progn
8490 (outline-previous-visible-heading 1)
8491 (if (looking-at ^re_)
8492 (- (match-end 0) (match-beginning 0) 1)
8494 (error 1))))
8495 (next-level (save-excursion
8496 (condition-case nil
8497 (progn
8498 (or (looking-at org-outline-regexp)
8499 (outline-next-visible-heading 1))
8500 (if (looking-at ^re_)
8501 (- (match-end 0) (match-beginning 0) 1)
8503 (error 1))))
8504 (new-level (or force-level (max previous-level next-level)))
8505 (shift (if (or (= old-level -1)
8506 (= new-level -1)
8507 (= old-level new-level))
8509 (- new-level old-level)))
8510 (delta (if (> shift 0) -1 1))
8511 (func (if (> shift 0) 'org-demote 'org-promote))
8512 (org-odd-levels-only nil)
8513 beg end newend)
8514 ;; Remove the forced level indicator
8515 (if force-level
8516 (delete-region (point-at-bol) (point)))
8517 ;; Paste
8518 (beginning-of-line (if (bolp) 1 2))
8519 (setq beg (point))
8520 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8521 (insert-before-markers txt)
8522 (unless (string-match "\n\\'" txt) (insert "\n"))
8523 (setq newend (point))
8524 (org-reinstall-markers-in-region beg)
8525 (setq end (point))
8526 (goto-char beg)
8527 (skip-chars-forward " \t\n\r")
8528 (setq beg (point))
8529 (if (and (outline-invisible-p) visp)
8530 (save-excursion (outline-show-heading)))
8531 ;; Shift if necessary
8532 (unless (= shift 0)
8533 (save-restriction
8534 (narrow-to-region beg end)
8535 (while (not (= shift 0))
8536 (org-map-region func (point-min) (point-max))
8537 (setq shift (+ delta shift)))
8538 (goto-char (point-min))
8539 (setq newend (point-max))))
8540 (when (or (org-called-interactively-p 'interactive) for-yank)
8541 (message "Clipboard pasted as level %d subtree" new-level))
8542 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8543 kill-ring
8544 (eq org-subtree-clip (current-kill 0))
8545 org-subtree-clip-folded)
8546 ;; The tree was folded before it was killed/copied
8547 (hide-subtree))
8548 (and for-yank (goto-char newend))
8549 (and remove (setq kill-ring (cdr kill-ring))))))
8551 (defun org-kill-is-subtree-p (&optional txt)
8552 "Check if the current kill is an outline subtree, or a set of trees.
8553 Returns nil if kill does not start with a headline, or if the first
8554 headline level is not the largest headline level in the tree.
8555 So this will actually accept several entries of equal levels as well,
8556 which is OK for `org-paste-subtree'.
8557 If optional TXT is given, check this string instead of the current kill."
8558 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8559 (re (org-get-limited-outline-regexp))
8560 (^re (concat "^" re))
8561 (start-level (and kill
8562 (string-match
8563 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8564 kill)
8565 (- (match-end 2) (match-beginning 2) 1)))
8566 (start (1+ (or (match-beginning 2) -1))))
8567 (if (not start-level)
8568 (progn
8569 nil) ;; does not even start with a heading
8570 (catch 'exit
8571 (while (setq start (string-match ^re kill (1+ start)))
8572 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8573 (throw 'exit nil)))
8574 t))))
8576 (defvar org-markers-to-move nil
8577 "Markers that should be moved with a cut-and-paste operation.
8578 Those markers are stored together with their positions relative to
8579 the start of the region.")
8581 (defun org-save-markers-in-region (beg end)
8582 "Check markers in region.
8583 If these markers are between BEG and END, record their position relative
8584 to BEG, so that after moving the block of text, we can put the markers back
8585 into place.
8586 This function gets called just before an entry or tree gets cut from the
8587 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8588 called immediately, to move the markers with the entries."
8589 (setq org-markers-to-move nil)
8590 (when (featurep 'org-clock)
8591 (org-clock-save-markers-for-cut-and-paste beg end))
8592 (when (featurep 'org-agenda)
8593 (org-agenda-save-markers-for-cut-and-paste beg end)))
8595 (defun org-check-and-save-marker (marker beg end)
8596 "Check if MARKER is between BEG and END.
8597 If yes, remember the marker and the distance to BEG."
8598 (when (and (marker-buffer marker)
8599 (equal (marker-buffer marker) (current-buffer)))
8600 (if (and (>= marker beg) (< marker end))
8601 (push (cons marker (- marker beg)) org-markers-to-move))))
8603 (defun org-reinstall-markers-in-region (beg)
8604 "Move all remembered markers to their position relative to BEG."
8605 (mapc (lambda (x)
8606 (move-marker (car x) (+ beg (cdr x))))
8607 org-markers-to-move)
8608 (setq org-markers-to-move nil))
8610 (defun org-narrow-to-subtree ()
8611 "Narrow buffer to the current subtree."
8612 (interactive)
8613 (save-excursion
8614 (save-match-data
8615 (org-with-limited-levels
8616 (narrow-to-region
8617 (progn (org-back-to-heading t) (point))
8618 (progn (org-end-of-subtree t t)
8619 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8620 (point)))))))
8622 (defun org-narrow-to-block ()
8623 "Narrow buffer to the current block."
8624 (interactive)
8625 (let* ((case-fold-search t)
8626 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8627 "^[ \t]*#\\+end_.*")))
8628 (if blockp
8629 (narrow-to-region (car blockp) (cdr blockp))
8630 (user-error "Not in a block"))))
8632 (defun org-clone-subtree-with-time-shift (n &optional shift)
8633 "Clone the task (subtree) at point N times.
8634 The clones will be inserted as siblings.
8636 In interactive use, the user will be prompted for the number of
8637 clones to be produced. If the entry has a timestamp, the user
8638 will also be prompted for a time shift, which may be a repeater
8639 as used in time stamps, for example `+3d'. To disable this,
8640 you can call the function with a universal prefix argument.
8642 When a valid repeater is given and the entry contains any time
8643 stamps, the clones will become a sequence in time, with time
8644 stamps in the subtree shifted for each clone produced. If SHIFT
8645 is nil or the empty string, time stamps will be left alone. The
8646 ID property of the original subtree is removed.
8648 If the original subtree did contain time stamps with a repeater,
8649 the following will happen:
8650 - the repeater will be removed in each clone
8651 - an additional clone will be produced, with the current, unshifted
8652 date(s) in the entry.
8653 - the original entry will be placed *after* all the clones, with
8654 repeater intact.
8655 - the start days in the repeater in the original entry will be shifted
8656 to past the last clone.
8657 In this way you can spell out a number of instances of a repeating task,
8658 and still retain the repeater to cover future instances of the task."
8659 (interactive "nNumber of clones to produce: ")
8660 (let ((shift
8661 (or shift
8662 (if (and (not (equal current-prefix-arg '(4)))
8663 (save-excursion
8664 (re-search-forward org-ts-regexp-both
8665 (save-excursion
8666 (org-end-of-subtree t)
8667 (point)) t)))
8668 (read-from-minibuffer
8669 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8670 ""))) ;; No time shift
8671 (n-no-remove -1)
8672 (drawer-re org-drawer-regexp)
8673 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8674 beg end template task idprop
8675 shift-n shift-what doshift nmin nmax)
8676 (if (not (and (integerp n) (> n 0)))
8677 (user-error "Invalid number of replications %s" n))
8678 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8679 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8680 shift)))
8681 (user-error "Invalid shift specification %s" shift))
8682 (when doshift
8683 (setq shift-n (string-to-number (match-string 1 shift))
8684 shift-what (cdr (assoc (match-string 2 shift)
8685 '(("d" . day) ("w" . week)
8686 ("m" . month) ("y" . year))))))
8687 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8688 (setq nmin 1 nmax n)
8689 (org-back-to-heading t)
8690 (setq beg (point))
8691 (setq idprop (org-entry-get nil "ID"))
8692 (org-end-of-subtree t t)
8693 (or (bolp) (insert "\n"))
8694 (setq end (point))
8695 (setq template (buffer-substring beg end))
8696 (when (and doshift
8697 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8698 (delete-region beg end)
8699 (setq end beg)
8700 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8701 (goto-char end)
8702 (loop for n from nmin to nmax do
8703 ;; prepare clone
8704 (with-temp-buffer
8705 (insert template)
8706 (org-mode)
8707 (goto-char (point-min))
8708 (org-show-subtree)
8709 (and idprop (if org-clone-delete-id
8710 (org-entry-delete nil "ID")
8711 (org-id-get-create t)))
8712 (unless (= n 0)
8713 (while (re-search-forward org-clock-re nil t)
8714 (kill-whole-line))
8715 (goto-char (point-min))
8716 (while (re-search-forward drawer-re nil t)
8717 (org-remove-empty-drawer-at (point))))
8718 (goto-char (point-min))
8719 (when doshift
8720 (while (re-search-forward org-ts-regexp-both nil t)
8721 (org-timestamp-change (* n shift-n) shift-what))
8722 (unless (= n n-no-remove)
8723 (goto-char (point-min))
8724 (while (re-search-forward org-ts-regexp nil t)
8725 (save-excursion
8726 (goto-char (match-beginning 0))
8727 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8728 (delete-region (match-beginning 1) (match-end 1)))))))
8729 (setq task (buffer-string)))
8730 (insert task))
8731 (goto-char beg)))
8733 ;;; Outline Sorting
8735 (defun org-sort (with-case)
8736 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8737 Optional argument WITH-CASE means sort case-sensitively."
8738 (interactive "P")
8739 (cond
8740 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8741 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8743 (org-call-with-arg 'org-sort-entries with-case))))
8745 (defun org-sort-remove-invisible (s)
8746 "Remove invisible links from string S."
8747 (remove-text-properties 0 (length s) org-rm-props s)
8748 (while (string-match org-bracket-link-regexp s)
8749 (setq s (replace-match (if (match-end 2)
8750 (match-string 3 s)
8751 (match-string 1 s)) t t s)))
8752 (let ((st (format " %s " s)))
8753 (while (string-match org-emph-re st)
8754 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8755 (setq s (substring st 1 -1)))
8758 (defvar org-priority-regexp) ; defined later in the file
8760 (defvar org-after-sorting-entries-or-items-hook nil
8761 "Hook that is run after a bunch of entries or items have been sorted.
8762 When children are sorted, the cursor is in the parent line when this
8763 hook gets called. When a region or a plain list is sorted, the cursor
8764 will be in the first entry of the sorted region/list.")
8766 (defun org-sort-entries
8767 (&optional with-case sorting-type getkey-func compare-func property)
8768 "Sort entries on a certain level of an outline tree.
8769 If there is an active region, the entries in the region are sorted.
8770 Else, if the cursor is before the first entry, sort the top-level items.
8771 Else, the children of the entry at point are sorted.
8773 Sorting can be alphabetically, numerically, by date/time as given by
8774 a time stamp, by a property, by priority order, or by a custom function.
8776 The command prompts for the sorting type unless it has been given to the
8777 function through the SORTING-TYPE argument, which needs to be a character,
8778 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8779 the precise meaning of each character:
8781 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8782 c By creation time, which is assumed to be the first inactive time stamp
8783 at the beginning of a line.
8784 d By deadline date/time.
8785 k By clocking time.
8786 n Numerically, by converting the beginning of the entry/item to a number.
8787 o By order of TODO keywords.
8788 p By priority according to the cookie.
8789 r By the value of a property.
8790 s By scheduled date/time.
8791 t By date/time, either the first active time stamp in the entry, or, if
8792 none exist, by the first inactive one.
8794 Capital letters will reverse the sort order.
8796 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8797 called with point at the beginning of the record. It must return either
8798 a string or a number that should serve as the sorting key for that record.
8800 Comparing entries ignores case by default. However, with an optional argument
8801 WITH-CASE, the sorting considers case as well.
8803 Sorting is done against the visible part of the headlines, it ignores hidden
8804 links.
8806 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8807 (interactive "P")
8808 (let ((case-func (if with-case 'identity 'downcase))
8809 (cmstr
8810 ;; The clock marker is lost when using `sort-subr', let's
8811 ;; store the clocking string.
8812 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8813 (save-excursion
8814 (goto-char org-clock-marker)
8815 (looking-back "^.*") (match-string-no-properties 0))))
8816 start beg end stars re re2
8817 txt what tmp)
8818 ;; Find beginning and end of region to sort
8819 (cond
8820 ((org-region-active-p)
8821 ;; we will sort the region
8822 (setq end (region-end)
8823 what "region")
8824 (goto-char (region-beginning))
8825 (if (not (org-at-heading-p)) (outline-next-heading))
8826 (setq start (point)))
8827 ((or (org-at-heading-p)
8828 (ignore-errors (progn (org-back-to-heading) t)))
8829 ;; we will sort the children of the current headline
8830 (org-back-to-heading)
8831 (setq start (point)
8832 end (progn (org-end-of-subtree t t)
8833 (or (bolp) (insert "\n"))
8834 (when (>= (org-back-over-empty-lines) 1)
8835 (forward-line 1))
8836 (point))
8837 what "children")
8838 (goto-char start)
8839 (show-subtree)
8840 (outline-next-heading))
8842 ;; we will sort the top-level entries in this file
8843 (goto-char (point-min))
8844 (or (org-at-heading-p) (outline-next-heading))
8845 (setq start (point))
8846 (goto-char (point-max))
8847 (beginning-of-line 1)
8848 (when (looking-at ".*?\\S-")
8849 ;; File ends in a non-white line
8850 (end-of-line 1)
8851 (insert "\n"))
8852 (setq end (point-max))
8853 (setq what "top-level")
8854 (goto-char start)
8855 (show-all)))
8857 (setq beg (point))
8858 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8860 (looking-at "\\(\\*+\\)")
8861 (setq stars (match-string 1)
8862 re (concat "^" (regexp-quote stars) " +")
8863 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8864 txt (buffer-substring beg end))
8865 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8866 (if (and (not (equal stars "*")) (string-match re2 txt))
8867 (user-error "Region to sort contains a level above the first entry"))
8869 (unless sorting-type
8870 (message
8871 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8872 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8873 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8874 what)
8875 (setq sorting-type (read-char-exclusive))
8877 (unless getkey-func
8878 (and (= (downcase sorting-type) ?f)
8879 (setq getkey-func
8880 (org-icompleting-read "Sort using function: "
8881 obarray 'fboundp t nil nil))
8882 (setq getkey-func (intern getkey-func))))
8884 (and (= (downcase sorting-type) ?r)
8885 (not property)
8886 (setq property
8887 (org-icompleting-read "Property: "
8888 (mapcar 'list (org-buffer-property-keys t))
8889 nil t))))
8891 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8892 (message "Sorting entries...")
8894 (save-restriction
8895 (narrow-to-region start end)
8896 (let ((dcst (downcase sorting-type))
8897 (case-fold-search nil)
8898 (now (current-time)))
8899 (sort-subr
8900 (/= dcst sorting-type)
8901 ;; This function moves to the beginning character of the "record" to
8902 ;; be sorted.
8903 (lambda nil
8904 (if (re-search-forward re nil t)
8905 (goto-char (match-beginning 0))
8906 (goto-char (point-max))))
8907 ;; This function moves to the last character of the "record" being
8908 ;; sorted.
8909 (lambda nil
8910 (save-match-data
8911 (condition-case nil
8912 (outline-forward-same-level 1)
8913 (error
8914 (goto-char (point-max))))))
8915 ;; This function returns the value that gets sorted against.
8916 (lambda nil
8917 (cond
8918 ((= dcst ?n)
8919 (if (looking-at org-complex-heading-regexp)
8920 (string-to-number (org-sort-remove-invisible (match-string 4)))
8921 nil))
8922 ((= dcst ?a)
8923 (if (looking-at org-complex-heading-regexp)
8924 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8925 nil))
8926 ((= dcst ?k)
8927 (or (get-text-property (point) :org-clock-minutes) 0))
8928 ((= dcst ?t)
8929 (let ((end (save-excursion (outline-next-heading) (point))))
8930 (if (or (re-search-forward org-ts-regexp end t)
8931 (re-search-forward org-ts-regexp-both end t))
8932 (org-time-string-to-seconds (match-string 0))
8933 (org-float-time now))))
8934 ((= dcst ?c)
8935 (let ((end (save-excursion (outline-next-heading) (point))))
8936 (if (re-search-forward
8937 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8938 end t)
8939 (org-time-string-to-seconds (match-string 0))
8940 (org-float-time now))))
8941 ((= dcst ?s)
8942 (let ((end (save-excursion (outline-next-heading) (point))))
8943 (if (re-search-forward org-scheduled-time-regexp end t)
8944 (org-time-string-to-seconds (match-string 1))
8945 (org-float-time now))))
8946 ((= dcst ?d)
8947 (let ((end (save-excursion (outline-next-heading) (point))))
8948 (if (re-search-forward org-deadline-time-regexp end t)
8949 (org-time-string-to-seconds (match-string 1))
8950 (org-float-time now))))
8951 ((= dcst ?p)
8952 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8953 (string-to-char (match-string 2))
8954 org-default-priority))
8955 ((= dcst ?r)
8956 (or (org-entry-get nil property) ""))
8957 ((= dcst ?o)
8958 (if (looking-at org-complex-heading-regexp)
8959 (let* ((m (match-string 2))
8960 (s (if (member m org-done-keywords) '- '+)))
8961 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8962 ((= dcst ?f)
8963 (if getkey-func
8964 (progn
8965 (setq tmp (funcall getkey-func))
8966 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8967 tmp)
8968 (error "Invalid key function `%s'" getkey-func)))
8969 (t (error "Invalid sorting type `%c'" sorting-type))))
8971 (cond
8972 ((= dcst ?a) 'string<)
8973 ((= dcst ?f) compare-func)
8974 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8975 (run-hooks 'org-after-sorting-entries-or-items-hook)
8976 ;; Reset the clock marker if needed
8977 (when cmstr
8978 (save-excursion
8979 (goto-char start)
8980 (search-forward cmstr nil t)
8981 (move-marker org-clock-marker (point))))
8982 (message "Sorting entries...done")))
8984 (defun org-do-sort (table what &optional with-case sorting-type)
8985 "Sort TABLE of WHAT according to SORTING-TYPE.
8986 The user will be prompted for the SORTING-TYPE if the call to this
8987 function does not specify it.
8988 WHAT is only for the prompt, to indicate what is being sorted.
8989 The sorting key will be extracted from the car of the elements of
8990 the table.
8991 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8992 (unless sorting-type
8993 (message
8994 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8995 what)
8996 (setq sorting-type (read-char-exclusive)))
8997 (let ((dcst (downcase sorting-type))
8998 extractfun comparefun)
8999 ;; Define the appropriate functions
9000 (cond
9001 ((= dcst ?n)
9002 (setq extractfun 'string-to-number
9003 comparefun (if (= dcst sorting-type) '< '>)))
9004 ((= dcst ?a)
9005 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
9006 (lambda(x) (downcase (org-sort-remove-invisible x))))
9007 comparefun (if (= dcst sorting-type)
9008 'string<
9009 (lambda (a b) (and (not (string< a b))
9010 (not (string= a b)))))))
9011 ((= dcst ?t)
9012 (setq extractfun
9013 (lambda (x)
9014 (cond ((or (string-match org-ts-regexp x)
9015 (string-match org-ts-regexp-both x))
9016 (org-float-time
9017 (org-time-string-to-time (match-string 0 x))))
9018 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
9019 (org-hh:mm-string-to-minutes x))
9020 (t 0)))
9021 comparefun (if (= dcst sorting-type) '< '>)))
9022 (t (error "Invalid sorting type `%c'" sorting-type)))
9024 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
9025 table)
9026 (lambda (a b) (funcall comparefun (car a) (car b))))))
9029 ;;; The orgstruct minor mode
9031 ;; Define a minor mode which can be used in other modes in order to
9032 ;; integrate the org-mode structure editing commands.
9034 ;; This is really a hack, because the org-mode structure commands use
9035 ;; keys which normally belong to the major mode. Here is how it
9036 ;; works: The minor mode defines all the keys necessary to operate the
9037 ;; structure commands, but wraps the commands into a function which
9038 ;; tests if the cursor is currently at a headline or a plain list
9039 ;; item. If that is the case, the structure command is used,
9040 ;; temporarily setting many Org-mode variables like regular
9041 ;; expressions for filling etc. However, when any of those keys is
9042 ;; used at a different location, function uses `key-binding' to look
9043 ;; up if the key has an associated command in another currently active
9044 ;; keymap (minor modes, major mode, global), and executes that
9045 ;; command. There might be problems if any of the keys is otherwise
9046 ;; used as a prefix key.
9048 (defcustom orgstruct-heading-prefix-regexp ""
9049 "Regexp that matches the custom prefix of Org headlines in
9050 orgstruct(++)-mode."
9051 :group 'org
9052 :version "24.4"
9053 :package-version '(Org . "8.3")
9054 :type 'regexp)
9055 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9057 (defcustom orgstruct-setup-hook nil
9058 "Hook run after orgstruct-mode-map is filled."
9059 :group 'org
9060 :version "24.4"
9061 :package-version '(Org . "8.0")
9062 :type 'hook)
9064 (defvar orgstruct-initialized nil)
9066 (defvar org-local-vars nil
9067 "List of local variables, for use by `orgstruct-mode'.")
9069 ;;;###autoload
9070 (define-minor-mode orgstruct-mode
9071 "Toggle the minor mode `orgstruct-mode'.
9072 This mode is for using Org-mode structure commands in other
9073 modes. The following keys behave as if Org-mode were active, if
9074 the cursor is on a headline, or on a plain list item (both as
9075 defined by Org-mode)."
9076 nil " OrgStruct" (make-sparse-keymap)
9077 (funcall (if orgstruct-mode
9078 'add-to-invisibility-spec
9079 'remove-from-invisibility-spec)
9080 '(outline . t))
9081 (when orgstruct-mode
9082 (org-load-modules-maybe)
9083 (unless orgstruct-initialized
9084 (orgstruct-setup)
9085 (setq orgstruct-initialized t))))
9087 ;;;###autoload
9088 (defun turn-on-orgstruct ()
9089 "Unconditionally turn on `orgstruct-mode'."
9090 (orgstruct-mode 1))
9092 (defvar org-fb-vars nil)
9093 (make-variable-buffer-local 'org-fb-vars)
9094 (defun orgstruct++-mode (&optional arg)
9095 "Toggle `orgstruct-mode', the enhanced version of it.
9096 In addition to setting orgstruct-mode, this also exports all
9097 indentation and autofilling variables from org-mode into the
9098 buffer. It will also recognize item context in multiline items."
9099 (interactive "P")
9100 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9101 (if (< arg 1)
9102 (progn (orgstruct-mode -1)
9103 (mapc (lambda(v)
9104 (org-set-local (car v)
9105 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9106 org-fb-vars))
9107 (orgstruct-mode 1)
9108 (setq org-fb-vars nil)
9109 (unless org-local-vars
9110 (setq org-local-vars (org-get-local-variables)))
9111 (let (var val)
9112 (mapc
9113 (lambda (x)
9114 (when (string-match
9115 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9116 (symbol-name (car x)))
9117 (setq var (car x) val (nth 1 x))
9118 (push (list var `(quote ,(eval var))) org-fb-vars)
9119 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9120 org-local-vars)
9121 (org-set-local 'orgstruct-is-++ t))))
9123 (defvar orgstruct-is-++ nil
9124 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9125 (make-variable-buffer-local 'orgstruct-is-++)
9127 ;;;###autoload
9128 (defun turn-on-orgstruct++ ()
9129 "Unconditionally turn on `orgstruct++-mode'."
9130 (orgstruct++-mode 1))
9132 (defun orgstruct-error ()
9133 "Error when there is no default binding for a structure key."
9134 (interactive)
9135 (funcall (if (fboundp 'user-error)
9136 'user-error
9137 'error)
9138 "This key has no function outside structure elements"))
9140 (defun orgstruct-setup ()
9141 "Setup orgstruct keymap."
9142 (dolist (cell '((org-demote . t)
9143 (org-metaleft . t)
9144 (org-metaright . t)
9145 (org-promote . t)
9146 (org-shiftmetaleft . t)
9147 (org-shiftmetaright . t)
9148 org-backward-element
9149 org-backward-heading-same-level
9150 org-ctrl-c-ret
9151 org-ctrl-c-minus
9152 org-ctrl-c-star
9153 org-cycle
9154 org-forward-heading-same-level
9155 org-insert-heading
9156 org-insert-heading-respect-content
9157 org-kill-note-or-show-branches
9158 org-mark-subtree
9159 org-meta-return
9160 org-metadown
9161 org-metaup
9162 org-narrow-to-subtree
9163 org-promote-subtree
9164 org-reveal
9165 org-shiftdown
9166 org-shiftleft
9167 org-shiftmetadown
9168 org-shiftmetaup
9169 org-shiftright
9170 org-shifttab
9171 org-shifttab
9172 org-shiftup
9173 org-show-subtree
9174 org-sort
9175 org-up-element
9176 outline-demote
9177 outline-next-visible-heading
9178 outline-previous-visible-heading
9179 outline-promote
9180 outline-up-heading
9181 show-children))
9182 (let ((f (or (car-safe cell) cell))
9183 (disable-when-heading-prefix (cdr-safe cell)))
9184 (when (fboundp f)
9185 (let ((new-bindings))
9186 (dolist (binding (nconc (where-is-internal f org-mode-map)
9187 (where-is-internal f outline-mode-map)))
9188 (push binding new-bindings)
9189 ;; TODO use local-function-key-map
9190 (dolist (rep '(("<tab>" . "TAB")
9191 ("<return>" . "RET")
9192 ("<escape>" . "ESC")
9193 ("<delete>" . "DEL")))
9194 (setq binding (read-kbd-macro
9195 (let ((case-fold-search))
9196 (replace-regexp-in-string
9197 (regexp-quote (cdr rep))
9198 (car rep)
9199 (key-description binding)))))
9200 (pushnew binding new-bindings :test 'equal)))
9201 (dolist (binding new-bindings)
9202 (let ((key (lookup-key orgstruct-mode-map binding)))
9203 (when (or (not key) (numberp key))
9204 (ignore-errors
9205 (org-defkey orgstruct-mode-map
9206 binding
9207 (orgstruct-make-binding
9208 f binding disable-when-heading-prefix))))))))))
9209 (run-hooks 'orgstruct-setup-hook))
9211 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9212 "Create a function for binding in the structure minor mode.
9213 FUN is the command to call inside a table. KEY is the key that
9214 should be checked in for a command to execute outside of tables.
9215 Non-nil `disable-when-heading-prefix' means to disable the command
9216 if `orgstruct-heading-prefix-regexp' is not empty."
9217 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9218 (let ((nname name)
9219 (i 0))
9220 (while (fboundp (intern nname))
9221 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9222 (setq name (intern nname)))
9223 (eval
9224 (let ((bindings '((org-heading-regexp
9225 (concat "^"
9226 orgstruct-heading-prefix-regexp
9227 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9228 (org-outline-regexp
9229 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9230 (org-outline-regexp-bol
9231 (concat "^" org-outline-regexp))
9232 (outline-regexp org-outline-regexp)
9233 (outline-heading-end-regexp "\n")
9234 (outline-level 'org-outline-level)
9235 (outline-heading-alist))))
9236 `(defun ,name (arg)
9237 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9238 "Outside of structure, run the binding of `"
9239 (key-description key) "'."
9240 (when disable-when-heading-prefix
9241 (concat
9242 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9243 "back to the default binding due to limitations of Org's implementation of\n"
9244 "`" (symbol-name fun) "'.")))
9245 (interactive "p")
9246 (let* ((disable
9247 ,(and disable-when-heading-prefix
9248 '(not (string= orgstruct-heading-prefix-regexp ""))))
9249 (fallback
9250 (or disable
9251 (not
9252 (let* ,bindings
9253 (org-context-p 'headline 'item
9254 ,(when (memq fun
9255 '(org-insert-heading
9256 org-insert-heading-respect-content
9257 org-meta-return))
9258 '(when orgstruct-is-++
9259 'item-body))))))))
9260 (if fallback
9261 (let* ((orgstruct-mode)
9262 (binding
9263 (let ((key ,key))
9264 (catch 'exit
9265 (dolist
9266 (rep
9267 '(nil
9268 ("<\\([^>]*\\)tab>" . "\\1TAB")
9269 ("<\\([^>]*\\)return>" . "\\1RET")
9270 ("<\\([^>]*\\)escape>" . "\\1ESC")
9271 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9272 nil)
9273 (when rep
9274 (setq key (read-kbd-macro
9275 (let ((case-fold-search))
9276 (replace-regexp-in-string
9277 (car rep)
9278 (cdr rep)
9279 (key-description key))))))
9280 (when (key-binding key)
9281 (throw 'exit (key-binding key))))))))
9282 (if (keymapp binding)
9283 (org-set-transient-map binding)
9284 (let ((func (or binding
9285 (unless disable
9286 'orgstruct-error))))
9287 (when func
9288 (call-interactively func)))))
9289 (org-run-like-in-org-mode
9290 (lambda ()
9291 (interactive)
9292 (let* ,bindings
9293 (call-interactively ',fun)))))))))
9294 name))
9296 (defun org-contextualize-keys (alist contexts)
9297 "Return valid elements in ALIST depending on CONTEXTS.
9299 `org-agenda-custom-commands' or `org-capture-templates' are the
9300 values used for ALIST, and `org-agenda-custom-commands-contexts'
9301 or `org-capture-templates-contexts' are the associated contexts
9302 definitions."
9303 (let ((contexts
9304 ;; normalize contexts
9305 (mapcar
9306 (lambda(c) (cond ((listp (cadr c))
9307 (list (car c) (car c) (cadr c)))
9308 ((string= "" (cadr c))
9309 (list (car c) (car c) (caddr c)))
9310 (t c))) contexts))
9311 (a alist) c r s)
9312 ;; loop over all commands or templates
9313 (while (setq c (pop a))
9314 (let (vrules repl)
9315 (cond
9316 ((not (assoc (car c) contexts))
9317 (push c r))
9318 ((and (assoc (car c) contexts)
9319 (setq vrules (org-contextualize-validate-key
9320 (car c) contexts)))
9321 (mapc (lambda (vr)
9322 (when (not (equal (car vr) (cadr vr)))
9323 (setq repl vr))) vrules)
9324 (if (not repl) (push c r)
9325 (push (cadr repl) s)
9326 (push
9327 (cons (car c)
9328 (cdr (or (assoc (cadr repl) alist)
9329 (error "Undefined key `%s' as contextual replacement for `%s'"
9330 (cadr repl) (car c)))))
9331 r))))))
9332 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9333 (delq
9335 (delete-dups
9336 (mapcar (lambda (x)
9337 (let ((tpl (car x)))
9338 (when (not (delq
9340 (mapcar (lambda(y)
9341 (equal y tpl)) s))) x)))
9342 (reverse r))))))
9344 (defun org-contextualize-validate-key (key contexts)
9345 "Check CONTEXTS for agenda or capture KEY."
9346 (let (r rr res)
9347 (while (setq r (pop contexts))
9348 (mapc
9349 (lambda (rr)
9350 (when
9351 (and (equal key (car r))
9352 (if (functionp rr) (funcall rr)
9353 (or (and (eq (car rr) 'in-file)
9354 (buffer-file-name)
9355 (string-match (cdr rr) (buffer-file-name)))
9356 (and (eq (car rr) 'in-mode)
9357 (string-match (cdr rr) (symbol-name major-mode)))
9358 (and (eq (car rr) 'in-buffer)
9359 (string-match (cdr rr) (buffer-name)))
9360 (when (and (eq (car rr) 'not-in-file)
9361 (buffer-file-name))
9362 (not (string-match (cdr rr) (buffer-file-name))))
9363 (when (eq (car rr) 'not-in-mode)
9364 (not (string-match (cdr rr) (symbol-name major-mode))))
9365 (when (eq (car rr) 'not-in-buffer)
9366 (not (string-match (cdr rr) (buffer-name)))))))
9367 (push r res)))
9368 (car (last r))))
9369 (delete-dups (delq nil res))))
9371 (defun org-context-p (&rest contexts)
9372 "Check if local context is any of CONTEXTS.
9373 Possible values in the list of contexts are `table', `headline', and `item'."
9374 (let ((pos (point)))
9375 (goto-char (point-at-bol))
9376 (prog1 (or (and (memq 'table contexts)
9377 (looking-at "[ \t]*|"))
9378 (and (memq 'headline contexts)
9379 (looking-at org-outline-regexp))
9380 (and (memq 'item contexts)
9381 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9382 (and (memq 'item-body contexts)
9383 (org-in-item-p)))
9384 (goto-char pos))))
9386 (defun org-get-local-variables ()
9387 "Return a list of all local variables in an Org mode buffer."
9388 (let (varlist)
9389 (with-current-buffer (get-buffer-create "*Org tmp*")
9390 (erase-buffer)
9391 (org-mode)
9392 (setq varlist (buffer-local-variables)))
9393 (kill-buffer "*Org tmp*")
9394 (delq nil
9395 (mapcar
9396 (lambda (x)
9397 (setq x
9398 (if (symbolp x)
9399 (list x)
9400 (list (car x) (cdr x))))
9401 (if (and (not (get (car x) 'org-state))
9402 (string-match
9403 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9404 (symbol-name (car x))))
9405 x nil))
9406 varlist))))
9408 (defun org-clone-local-variables (from-buffer &optional regexp)
9409 "Clone local variables from FROM-BUFFER.
9410 Optional argument REGEXP selects variables to clone."
9411 (mapc
9412 (lambda (pair)
9413 (and (symbolp (car pair))
9414 (or (null regexp)
9415 (string-match regexp (symbol-name (car pair))))
9416 (set (make-local-variable (car pair))
9417 (cdr pair))))
9418 (buffer-local-variables from-buffer)))
9420 ;;;###autoload
9421 (defun org-run-like-in-org-mode (cmd)
9422 "Run a command, pretending that the current buffer is in Org-mode.
9423 This will temporarily bind local variables that are typically bound in
9424 Org-mode to the values they have in Org-mode, and then interactively
9425 call CMD."
9426 (org-load-modules-maybe)
9427 (unless org-local-vars
9428 (setq org-local-vars (org-get-local-variables)))
9429 (let (binds)
9430 (dolist (var org-local-vars)
9431 (when (or (not (boundp (car var)))
9432 (eq (symbol-value (car var))
9433 (default-value (car var))))
9434 (push (list (car var) `(quote ,(cadr var))) binds)))
9435 (eval `(let ,binds
9436 (call-interactively (quote ,cmd))))))
9438 (defun org-get-category (&optional pos force-refresh)
9439 "Get the category applying to position POS."
9440 (save-match-data
9441 (if force-refresh (org-refresh-category-properties))
9442 (let ((pos (or pos (point))))
9443 (or (get-text-property pos 'org-category)
9444 (progn (org-refresh-category-properties)
9445 (get-text-property pos 'org-category))))))
9447 ;;; Refresh properties
9449 (defun org-refresh-properties (dprop tprop)
9450 "Refresh buffer text properties.
9451 DPROP is the drawer property and TPROP is either the
9452 corresponding text property to set, or an alist with each element
9453 being a text property (as a symbol) and a function to apply to
9454 the value of the drawer property."
9455 (let ((case-fold-search t)
9456 (inhibit-read-only t))
9457 (org-with-silent-modifications
9458 (save-excursion
9459 (save-restriction
9460 (widen)
9461 (goto-char (point-min))
9462 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9463 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9465 (defun org-refresh-property (tprop p)
9466 "Refresh the buffer text property TPROP from the drawer property P.
9467 The refresh happens only for the current tree (not subtree)."
9468 (save-excursion
9469 (org-back-to-heading t)
9470 ;; tprop is a text property symbol
9471 (if (symbolp tprop)
9472 (put-text-property
9473 (point) (or (outline-next-heading) (point-max)) tprop p)
9474 ;; tprop is an alist with (properties . function) elements
9475 (mapc (lambda(al)
9476 (save-excursion
9477 (put-text-property
9478 (point-at-bol) (or (outline-next-heading) (point-max))
9479 (car al)
9480 (funcall (cdr al) p))))
9481 tprop))))
9483 (defun org-refresh-category-properties ()
9484 "Refresh category text properties in the buffer."
9485 (let ((case-fold-search t)
9486 (inhibit-read-only t)
9487 (def-cat (cond
9488 ((null org-category)
9489 (if buffer-file-name
9490 (file-name-sans-extension
9491 (file-name-nondirectory buffer-file-name))
9492 "???"))
9493 ((symbolp org-category) (symbol-name org-category))
9494 (t org-category)))
9495 beg end cat pos optionp)
9496 (org-with-silent-modifications
9497 (save-excursion
9498 (save-restriction
9499 (widen)
9500 (goto-char (point-min))
9501 (put-text-property (point) (point-max) 'org-category def-cat)
9502 (while (re-search-forward
9503 "^[ \t]*\\(\\(?:#\\+\\|:\\)CATEGORY:\\)\\(.*\\)" nil t)
9504 (setq pos (match-end 0)
9505 optionp (equal (char-after (match-beginning 0)) ?#)
9506 cat (org-trim (match-string 2)))
9507 (if optionp
9508 (setq beg (point-at-bol) end (point-max))
9509 (org-back-to-heading t)
9510 (setq beg (point) end (org-end-of-subtree t t)))
9511 (put-text-property beg end 'org-category cat)
9512 (goto-char pos)))))))
9514 (defun org-refresh-stats-properties ()
9515 "Refresh stats text properties in the buffer."
9516 (let (stats)
9517 (org-with-silent-modifications
9518 (save-excursion
9519 (save-restriction
9520 (widen)
9521 (goto-char (point-min))
9522 (while (re-search-forward
9523 (concat org-outline-regexp-bol ".*"
9524 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9525 nil t)
9526 (setq stats (cond ((equal (match-string 3) "0") 0)
9527 ((match-string 2)
9528 (/ (* (string-to-number (match-string 2)) 100)
9529 (string-to-number (match-string 3))))
9530 (t (string-to-number (match-string 1)))))
9531 (org-back-to-heading t)
9532 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9533 'org-stats stats)))))))
9535 (defun org-refresh-effort-properties ()
9536 "Refresh effort properties"
9537 (org-refresh-properties
9538 org-effort-property
9539 '((effort . identity)
9540 (effort-minutes . org-duration-string-to-minutes))))
9542 ;;;; Link Stuff
9544 ;;; Link abbreviations
9546 (defun org-link-expand-abbrev (link)
9547 "Apply replacements as defined in `org-link-abbrev-alist'."
9548 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9549 (let* ((key (match-string 1 link))
9550 (as (or (assoc key org-link-abbrev-alist-local)
9551 (assoc key org-link-abbrev-alist)))
9552 (tag (and (match-end 2) (match-string 3 link)))
9553 rpl)
9554 (if (not as)
9555 link
9556 (setq rpl (cdr as))
9557 (cond
9558 ((symbolp rpl) (funcall rpl tag))
9559 ((string-match "%(\\([^)]+\\))" rpl)
9560 (replace-match
9561 (save-match-data
9562 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9563 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9564 ((string-match "%h" rpl)
9565 (replace-match (url-hexify-string (or tag "")) t t rpl))
9566 (t (concat rpl tag)))))
9567 link))
9569 ;;; Storing and inserting links
9571 (defvar org-insert-link-history nil
9572 "Minibuffer history for links inserted with `org-insert-link'.")
9574 (defvar org-stored-links nil
9575 "Contains the links stored with `org-store-link'.")
9577 (defvar org-store-link-plist nil
9578 "Plist with info about the most recently link created with `org-store-link'.")
9580 (defvar org-link-protocols nil
9581 "Link protocols added to Org-mode using `org-add-link-type'.")
9583 (defvar org-store-link-functions nil
9584 "List of functions that are called to create and store a link.
9585 Each function will be called in turn until one returns a non-nil
9586 value. Each function should check if it is responsible for creating
9587 this link (for example by looking at the major mode).
9588 If not, it must exit and return nil.
9589 If yes, it should return a non-nil value after a calling
9590 `org-store-link-props' with a list of properties and values.
9591 Special properties are:
9593 :type The link prefix, like \"http\". This must be given.
9594 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9595 This is obligatory as well.
9596 :description Optional default description for the second pair
9597 of brackets in an Org-mode link. The user can still change
9598 this when inserting this link into an Org-mode buffer.
9600 In addition to these, any additional properties can be specified
9601 and then used in capture templates.")
9603 (defun org-add-link-type (type &optional follow export)
9604 "Add TYPE to the list of `org-link-types'.
9605 Re-compute all regular expressions depending on `org-link-types'
9607 FOLLOW and EXPORT are two functions.
9609 FOLLOW should take the link path as the single argument and do whatever
9610 is necessary to follow the link, for example find a file or display
9611 a mail message.
9613 EXPORT should format the link path for export to one of the export formats.
9614 It should be a function accepting three arguments:
9616 path the path of the link, the text after the prefix (like \"http:\")
9617 desc the description of the link, if any, or a description added by
9618 org-export-normalize-links if there is none
9619 format the export format, a symbol like `html' or `latex' or `ascii'..
9621 The function may use the FORMAT information to return different values
9622 depending on the format. The return value will be put literally into
9623 the exported file. If the return value is nil, this means Org should
9624 do what it normally does with links which do not have EXPORT defined.
9626 Org-mode has a built-in default for exporting links. If you are happy with
9627 this default, there is no need to define an export function for the link
9628 type. For a simple example of an export function, see `org-bbdb.el'."
9629 (add-to-list 'org-link-types type t)
9630 (org-make-link-regexps)
9631 (if (assoc type org-link-protocols)
9632 (setcdr (assoc type org-link-protocols) (list follow export))
9633 (push (list type follow export) org-link-protocols)))
9635 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9636 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9638 ;;;###autoload
9639 (defun org-store-link (arg)
9640 "\\<org-mode-map>Store an org-link to the current location.
9641 This link is added to `org-stored-links' and can later be inserted
9642 into an org-buffer with \\[org-insert-link].
9644 For some link types, a prefix arg is interpreted.
9645 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9646 For file links, arg negates `org-context-in-file-links'.
9648 A double prefix arg force skipping storing functions that are not
9649 part of Org's core.
9651 A triple prefix arg force storing a link for each line in the
9652 active region."
9653 (interactive "P")
9654 (org-load-modules-maybe)
9655 (if (and (equal arg '(64)) (org-region-active-p))
9656 (save-excursion
9657 (let ((end (region-end)))
9658 (goto-char (region-beginning))
9659 (set-mark (point))
9660 (while (< (point-at-eol) end)
9661 (move-end-of-line 1) (activate-mark)
9662 (let (current-prefix-arg)
9663 (call-interactively 'org-store-link))
9664 (move-beginning-of-line 2)
9665 (set-mark (point)))))
9666 (org-with-limited-levels
9667 (setq org-store-link-plist nil)
9668 (let (link cpltxt desc description search
9669 txt custom-id agenda-link sfuns sfunsn)
9670 (cond
9672 ;; Store a link using an external link type
9673 ((and (not (equal arg '(16)))
9674 (setq sfuns
9675 (delq
9676 nil (mapcar (lambda (f)
9677 (let (fs) (if (funcall f) (push f fs))))
9678 org-store-link-functions))
9679 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9680 (or (and (cdr sfuns)
9681 (funcall (intern
9682 (completing-read
9683 "Which function for creating the link? "
9684 sfunsn nil t (car sfunsn)))))
9685 (funcall (caar sfuns)))
9686 (setq link (plist-get org-store-link-plist :link)
9687 desc (or (plist-get org-store-link-plist
9688 :description) link))))
9690 ;; Store a link from a source code buffer
9691 ((org-src-edit-buffer-p)
9692 (let (label gc)
9693 (while (or (not label)
9694 (save-excursion
9695 (save-restriction
9696 (widen)
9697 (goto-char (point-min))
9698 (re-search-forward
9699 (regexp-quote (format org-coderef-label-format label))
9700 nil t))))
9701 (when label (message "Label exists already") (sit-for 2))
9702 (setq label (read-string "Code line label: " label)))
9703 (end-of-line 1)
9704 (setq link (format org-coderef-label-format label))
9705 (setq gc (- 79 (length link)))
9706 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9707 (insert link)
9708 (setq link (concat "(" label ")") desc nil)))
9710 ;; We are in the agenda, link to referenced location
9711 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9712 (let ((m (or (get-text-property (point) 'org-hd-marker)
9713 (get-text-property (point) 'org-marker))))
9714 (when m
9715 (org-with-point-at m
9716 (setq agenda-link
9717 (if (org-called-interactively-p 'any)
9718 (call-interactively 'org-store-link)
9719 (org-store-link nil)))))))
9721 ((eq major-mode 'calendar-mode)
9722 (let ((cd (calendar-cursor-to-date)))
9723 (setq link
9724 (format-time-string
9725 (car org-time-stamp-formats)
9726 (apply 'encode-time
9727 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9728 nil nil nil))))
9729 (org-store-link-props :type "calendar" :date cd)))
9731 ((eq major-mode 'help-mode)
9732 (setq link (concat "help:" (save-excursion
9733 (goto-char (point-min))
9734 (looking-at "^[^ ]+")
9735 (match-string 0))))
9736 (org-store-link-props :type "help"))
9738 ((eq major-mode 'w3-mode)
9739 (setq cpltxt (if (and (buffer-name)
9740 (not (string-match "Untitled" (buffer-name))))
9741 (buffer-name)
9742 (url-view-url t))
9743 link (url-view-url t))
9744 (org-store-link-props :type "w3" :url (url-view-url t)))
9746 ((eq major-mode 'image-mode)
9747 (setq cpltxt (concat "file:"
9748 (abbreviate-file-name buffer-file-name))
9749 link cpltxt)
9750 (org-store-link-props :type "image" :file buffer-file-name))
9752 ;; In dired, store a link to the file of the current line
9753 ((derived-mode-p 'dired-mode)
9754 (let ((file (dired-get-filename nil t)))
9755 (setq file (if file
9756 (abbreviate-file-name
9757 (expand-file-name (dired-get-filename nil t)))
9758 ;; otherwise, no file so use current directory.
9759 default-directory))
9760 (setq cpltxt (concat "file:" file)
9761 link cpltxt)))
9763 ((setq search (run-hook-with-args-until-success
9764 'org-create-file-search-functions))
9765 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9766 "::" search))
9767 (setq cpltxt (or description link)))
9769 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9770 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9771 (cond
9772 ;; Store a link using the target at point
9773 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9774 (setq cpltxt
9775 (concat "file:"
9776 (abbreviate-file-name
9777 (buffer-file-name (buffer-base-buffer)))
9778 "::" (match-string 1))
9779 link cpltxt))
9780 ((and (featurep 'org-id)
9781 (or (eq org-id-link-to-org-use-id t)
9782 (and (org-called-interactively-p 'any)
9783 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9784 (and (eq org-id-link-to-org-use-id
9785 'create-if-interactive-and-no-custom-id)
9786 (not custom-id))))
9787 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9788 ;; Store a link using the ID at point
9789 (setq link (condition-case nil
9790 (prog1 (org-id-store-link)
9791 (setq desc (or (plist-get org-store-link-plist
9792 :description)
9793 "")))
9794 (error
9795 ;; Probably before first headline, link only to file
9796 (concat "file:"
9797 (abbreviate-file-name
9798 (buffer-file-name (buffer-base-buffer))))))))
9800 ;; Just link to current headline
9801 (setq cpltxt (concat "file:"
9802 (abbreviate-file-name
9803 (buffer-file-name (buffer-base-buffer)))))
9804 ;; Add a context search string
9805 (when (org-xor org-context-in-file-links arg)
9806 (let* ((ee (org-element-at-point))
9807 (et (org-element-type ee))
9808 (ev (plist-get (cadr ee) :value))
9809 (ek (plist-get (cadr ee) :key))
9810 (eok (and (stringp ek) (string-match "name" ek))))
9811 (setq txt (cond
9812 ((org-at-heading-p) nil)
9813 ((and (eq et 'keyword) eok) ev)
9814 ((org-region-active-p)
9815 (buffer-substring (region-beginning) (region-end)))))
9816 (when (or (null txt) (string-match "\\S-" txt))
9817 (setq cpltxt
9818 (concat cpltxt "::"
9819 (condition-case nil
9820 (org-make-org-heading-search-string txt)
9821 (error "")))
9822 desc (or (and (eq et 'keyword) eok ev)
9823 (nth 4 (ignore-errors (org-heading-components)))
9824 "NONE")))))
9825 (if (string-match "::\\'" cpltxt)
9826 (setq cpltxt (substring cpltxt 0 -2)))
9827 (setq link cpltxt))))
9829 ((buffer-file-name (buffer-base-buffer))
9830 ;; Just link to this file here.
9831 (setq cpltxt (concat "file:"
9832 (abbreviate-file-name
9833 (buffer-file-name (buffer-base-buffer)))))
9834 ;; Add a context string.
9835 (when (org-xor org-context-in-file-links arg)
9836 (setq txt (if (org-region-active-p)
9837 (buffer-substring (region-beginning) (region-end))
9838 (buffer-substring (point-at-bol) (point-at-eol))))
9839 ;; Only use search option if there is some text.
9840 (when (string-match "\\S-" txt)
9841 (setq cpltxt
9842 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9843 desc "NONE")))
9844 (setq link cpltxt))
9846 ((org-called-interactively-p 'interactive)
9847 (user-error "No method for storing a link from this buffer"))
9849 (t (setq link nil)))
9851 ;; We're done setting link and desc, clean up
9852 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9853 (setq link (or link cpltxt)
9854 desc (or desc cpltxt))
9855 (cond ((equal desc "NONE") (setq desc nil))
9856 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9857 (let ((d0 (match-string 3 desc))
9858 (p0 (match-string 5 desc)))
9859 (setq desc
9860 (replace-regexp-in-string
9861 org-bracket-link-regexp
9862 (concat (or p0 d0)
9863 (if (equal (length (match-string 0 desc))
9864 (length desc)) "*" "")) desc)))))
9866 ;; Return the link
9867 (if (not (and (or (org-called-interactively-p 'any)
9868 executing-kbd-macro) link))
9869 (or agenda-link (and link (org-make-link-string link desc)))
9870 (push (list link desc) org-stored-links)
9871 (message "Stored: %s" (or desc link))
9872 (when custom-id
9873 (setq link (concat "file:" (abbreviate-file-name
9874 (buffer-file-name)) "::#" custom-id))
9875 (push (list link desc) org-stored-links))
9876 (car org-stored-links))))))
9878 (defun org-store-link-props (&rest plist)
9879 "Store link properties, extract names and addresses."
9880 (let (x adr)
9881 (when (setq x (plist-get plist :from))
9882 (setq adr (mail-extract-address-components x))
9883 (setq plist (plist-put plist :fromname (car adr)))
9884 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9885 (when (setq x (plist-get plist :to))
9886 (setq adr (mail-extract-address-components x))
9887 (setq plist (plist-put plist :toname (car adr)))
9888 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9889 (let ((from (plist-get plist :from))
9890 (to (plist-get plist :to)))
9891 (when (and from to org-from-is-user-regexp)
9892 (setq plist
9893 (plist-put plist :fromto
9894 (if (string-match org-from-is-user-regexp from)
9895 (concat "to %t")
9896 (concat "from %f"))))))
9897 (setq org-store-link-plist plist))
9899 (defun org-add-link-props (&rest plist)
9900 "Add these properties to the link property list."
9901 (let (key value)
9902 (while plist
9903 (setq key (pop plist) value (pop plist))
9904 (setq org-store-link-plist
9905 (plist-put org-store-link-plist key value)))))
9907 (defun org-email-link-description (&optional fmt)
9908 "Return the description part of an email link.
9909 This takes information from `org-store-link-plist' and formats it
9910 according to FMT (default from `org-email-link-description-format')."
9911 (setq fmt (or fmt org-email-link-description-format))
9912 (let* ((p org-store-link-plist)
9913 (to (plist-get p :toaddress))
9914 (from (plist-get p :fromaddress))
9915 (table
9916 (list
9917 (cons "%c" (plist-get p :fromto))
9918 (cons "%F" (plist-get p :from))
9919 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9920 (cons "%T" (plist-get p :to))
9921 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9922 (cons "%s" (plist-get p :subject))
9923 (cons "%d" (plist-get p :date))
9924 (cons "%m" (plist-get p :message-id)))))
9925 (when (string-match "%c" fmt)
9926 ;; Check if the user wrote this message
9927 (if (and org-from-is-user-regexp from to
9928 (save-match-data (string-match org-from-is-user-regexp from)))
9929 (setq fmt (replace-match "to %t" t t fmt))
9930 (setq fmt (replace-match "from %f" t t fmt))))
9931 (org-replace-escapes fmt table)))
9933 (defun org-make-org-heading-search-string (&optional string)
9934 "Make search string for the current headline or STRING."
9935 (let ((s (or string
9936 (and (derived-mode-p 'org-mode)
9937 (save-excursion
9938 (org-back-to-heading t)
9939 (org-element-property :raw-value (org-element-at-point))))))
9940 (lines org-context-in-file-links))
9941 (or string (setq s (concat "*" s))) ; Add * for headlines
9942 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9943 (when (and string (integerp lines) (> lines 0))
9944 (let ((slines (org-split-string s "\n")))
9945 (when (< lines (length slines))
9946 (setq s (mapconcat
9947 'identity
9948 (reverse (nthcdr (- (length slines) lines)
9949 (reverse slines))) "\n")))))
9950 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9952 (defun org-make-link-string (link &optional description)
9953 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9954 (unless (string-match "\\S-" link)
9955 (error "Empty link"))
9956 (when (and description
9957 (stringp description)
9958 (not (string-match "\\S-" description)))
9959 (setq description nil))
9960 (when (stringp description)
9961 ;; Remove brackets from the description, they are fatal.
9962 (while (string-match "\\[" description)
9963 (setq description (replace-match "{" t t description)))
9964 (while (string-match "\\]" description)
9965 (setq description (replace-match "}" t t description))))
9966 (when (equal link description)
9967 ;; No description needed, it is identical
9968 (setq description nil))
9969 (when (and (not description)
9970 (not (string-match (org-image-file-name-regexp) link))
9971 (not (equal link (org-link-escape link))))
9972 (setq description (org-extract-attributes link)))
9973 (setq link
9974 (cond ((string-match (org-image-file-name-regexp) link) link)
9975 ((string-match org-link-types-re link)
9976 (concat (match-string 1 link)
9977 (org-link-escape (substring link (match-end 1)))))
9978 (t (org-link-escape link))))
9979 (concat "[[" link "]"
9980 (if description (concat "[" description "]") "")
9981 "]"))
9983 (defconst org-link-escape-chars
9984 ;;%20 %5B %5D
9985 '(?\ ?\[ ?\])
9986 "List of characters that should be escaped in a link when stored to Org.
9987 This is the list that is used for internal purposes.")
9989 (defconst org-link-escape-chars-browser
9990 ;;%20 %22
9991 '(?\ ?\")
9992 "List of characters to be escaped before handing over to the browser.
9993 If you consider using this constant then you probably want to use
9994 the function `org-link-escape-browser' instead. See there why
9995 this constant is a candidate to be removed once Org drops support
9996 for Emacs 24.1 and 24.2.")
9998 (defun org-link-escape (text &optional table merge)
9999 "Return percent escaped representation of TEXT.
10000 TEXT is a string with the text to escape.
10001 Optional argument TABLE is a list with characters that should be
10002 escaped. When nil, `org-link-escape-chars' is used.
10003 If optional argument MERGE is set, merge TABLE into
10004 `org-link-escape-chars'."
10005 ;; Don't escape chars in internal links
10006 (if (string-match "^\\*[[:alnum:]]+" text)
10007 text
10008 (cond
10009 ((and table merge)
10010 (mapc (lambda (defchr)
10011 (unless (member defchr table)
10012 (setq table (cons defchr table))))
10013 org-link-escape-chars))
10014 ((null table)
10015 (setq table org-link-escape-chars)))
10016 (mapconcat
10017 (lambda (char)
10018 (if (or (member char table)
10019 (and (or (< char 32) (= char ?\%) (> char 126))
10020 org-url-hexify-p))
10021 (mapconcat (lambda (sequence-element)
10022 (format "%%%.2X" sequence-element))
10023 (or (encode-coding-char char 'utf-8)
10024 (error "Unable to percent escape character: %s"
10025 (char-to-string char))) "")
10026 (char-to-string char))) text "")))
10028 (defun org-link-escape-browser (text)
10029 "Escape some characters before handing over to the browser.
10030 This function is a candidate to be removed together with the
10031 constant `org-link-escape-chars-browser' once Org drops support
10032 for Emacs 24.1 and 24.2. All calls to this function will have to
10033 be replaced with `url-encode-url' which is available since Emacs
10034 24.3.1."
10035 ;; Example with the Org link
10036 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10037 ;; to open the browser with +subject:"Release 8.2" filled into the
10038 ;; query field: In this case the variable TEXT contains the
10039 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10040 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10041 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10042 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10043 (if (fboundp 'url-encode-url)
10044 (url-encode-url text)
10045 (if (org-string-match-p
10046 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10047 text)
10048 (org-link-escape text org-link-escape-chars-browser)
10049 text)))
10051 (defun org-link-unescape (str)
10052 "Unhex hexified Unicode strings as returned from the JavaScript function
10053 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10054 (unless (and (null str) (string= "" str))
10055 (let ((pos 0) (case-fold-search t) unhexed)
10056 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10057 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10058 (setq str (replace-match unhexed t t str))
10059 (setq pos (+ pos (length unhexed))))))
10060 str)
10062 (defun org-link-unescape-compound (hex)
10063 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10064 Note: this function also decodes single byte encodings like
10065 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10066 (save-match-data
10067 (let* ((bytes (cdr (split-string hex "%")))
10068 (ret "")
10069 (eat 0)
10070 (sum 0))
10071 (while bytes
10072 (let* ((val (string-to-number (pop bytes) 16))
10073 (shift-xor
10074 (if (= 0 eat)
10075 (cond
10076 ((>= val 252) (cons 6 252))
10077 ((>= val 248) (cons 5 248))
10078 ((>= val 240) (cons 4 240))
10079 ((>= val 224) (cons 3 224))
10080 ((>= val 192) (cons 2 192))
10081 (t (cons 0 0)))
10082 (cons 6 128))))
10083 (if (>= val 192) (setq eat (car shift-xor)))
10084 (setq val (logxor val (cdr shift-xor)))
10085 (setq sum (+ (lsh sum (car shift-xor)) val))
10086 (if (> eat 0) (setq eat (- eat 1)))
10087 (cond
10088 ((= 0 eat) ;multi byte
10089 (setq ret (concat ret (org-char-to-string sum)))
10090 (setq sum 0))
10091 ((not bytes) ; single byte(s)
10092 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10093 ret)))
10095 (defun org-link-unescape-single-byte-sequence (hex)
10096 "Unhexify hex-encoded single byte character sequences."
10097 (mapconcat (lambda (byte)
10098 (char-to-string (string-to-number byte 16)))
10099 (cdr (split-string hex "%")) ""))
10101 (defun org-xor (a b)
10102 "Exclusive or."
10103 (if a (not b) b))
10105 (defun org-fixup-message-id-for-http (s)
10106 "Replace special characters in a message id, so it can be used in an http query."
10107 (when (string-match "%" s)
10108 (setq s (mapconcat (lambda (c)
10109 (if (eq c ?%)
10110 "%25"
10111 (char-to-string c)))
10112 s "")))
10113 (while (string-match "<" s)
10114 (setq s (replace-match "%3C" t t s)))
10115 (while (string-match ">" s)
10116 (setq s (replace-match "%3E" t t s)))
10117 (while (string-match "@" s)
10118 (setq s (replace-match "%40" t t s)))
10121 (defun org-link-prettify (link)
10122 "Return a human-readable representation of LINK.
10123 The car of LINK must be a raw link.
10124 The cdr of LINK must be either a link description or nil."
10125 (let ((desc (or (cadr link) "<no description>")))
10126 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10127 "<" (car link) ">")))
10129 ;;;###autoload
10130 (defun org-insert-link-global ()
10131 "Insert a link like Org-mode does.
10132 This command can be called in any mode to insert a link in Org-mode syntax."
10133 (interactive)
10134 (org-load-modules-maybe)
10135 (org-run-like-in-org-mode 'org-insert-link))
10137 (defun org-insert-all-links (arg &optional pre post)
10138 "Insert all links in `org-stored-links'.
10139 When a universal prefix, do not delete the links from `org-stored-links'.
10140 When `ARG' is a number, insert the last N link(s).
10141 `PRE' and `POST' are optional arguments to define a string to
10142 prepend or to append."
10143 (interactive "P")
10144 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10145 (links (copy-seq org-stored-links))
10146 (pr (or pre "- "))
10147 (po (or post "\n"))
10148 (cnt 1) l)
10149 (if (null org-stored-links)
10150 (message "No link to insert")
10151 (while (and (or (listp arg) (>= arg cnt))
10152 (setq l (if (listp arg)
10153 (pop links)
10154 (pop org-stored-links))))
10155 (setq cnt (1+ cnt))
10156 (insert pr)
10157 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10158 (insert po)))))
10160 (defun org-insert-last-stored-link (arg)
10161 "Insert the last link stored in `org-stored-links'."
10162 (interactive "p")
10163 (org-insert-all-links arg "" "\n"))
10165 (defun org-link-fontify-links-to-this-file ()
10166 "Fontify links to the current file in `org-stored-links'."
10167 (let ((f (buffer-file-name)) a b)
10168 (setq a (mapcar (lambda(l)
10169 (let ((ll (car l)))
10170 (when (and (string-match "^file:\\(.+\\)::" ll)
10171 (equal f (expand-file-name (match-string 1 ll))))
10172 ll)))
10173 org-stored-links))
10174 (when (featurep 'org-id)
10175 (setq b (mapcar (lambda(l)
10176 (let ((ll (car l)))
10177 (when (and (string-match "^id:\\(.+\\)$" ll)
10178 (equal f (expand-file-name
10179 (or (org-id-find-id-file
10180 (match-string 1 ll)) ""))))
10181 ll)))
10182 org-stored-links)))
10183 (mapcar (lambda(l)
10184 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10185 (delq nil (append a b)))))
10187 (defvar org-link-links-in-this-file nil)
10188 (defun org-insert-link (&optional complete-file link-location default-description)
10189 "Insert a link. At the prompt, enter the link.
10191 Completion can be used to insert any of the link protocol prefixes like
10192 http or ftp in use.
10194 The history can be used to select a link previously stored with
10195 `org-store-link'. When the empty string is entered (i.e. if you just
10196 press RET at the prompt), the link defaults to the most recently
10197 stored link. As SPC triggers completion in the minibuffer, you need to
10198 use M-SPC or C-q SPC to force the insertion of a space character.
10200 You will also be prompted for a description, and if one is given, it will
10201 be displayed in the buffer instead of the link.
10203 If there is already a link at point, this command will allow you to edit link
10204 and description parts.
10206 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10207 be selected using completion. The path to the file will be relative to the
10208 current directory if the file is in the current directory or a subdirectory.
10209 Otherwise, the link will be the absolute path as completed in the minibuffer
10210 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10211 option `org-link-file-path-type'.
10213 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10214 the current directory or below.
10216 With three \\[universal-argument] prefixes, negate the meaning of
10217 `org-keep-stored-link-after-insertion'.
10219 If `org-make-link-description-function' is non-nil, this function will be
10220 called with the link target, and the result will be the default
10221 link description.
10223 If the LINK-LOCATION parameter is non-nil, this value will be
10224 used as the link location instead of reading one interactively.
10226 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10227 be used as the default description."
10228 (interactive "P")
10229 (let* ((wcf (current-window-configuration))
10230 (origbuf (current-buffer))
10231 (region (if (org-region-active-p)
10232 (buffer-substring (region-beginning) (region-end))))
10233 (remove (and region (list (region-beginning) (region-end))))
10234 (desc region)
10235 tmphist ; byte-compile incorrectly complains about this
10236 (link link-location)
10237 (abbrevs org-link-abbrev-alist-local)
10238 entry file all-prefixes auto-desc)
10239 (cond
10240 (link-location) ; specified by arg, just use it.
10241 ((org-in-regexp org-bracket-link-regexp 1)
10242 ;; We do have a link at point, and we are going to edit it.
10243 (setq remove (list (match-beginning 0) (match-end 0)))
10244 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10245 (setq link (read-string "Link: "
10246 (org-link-unescape
10247 (org-match-string-no-properties 1)))))
10248 ((or (org-in-regexp org-angle-link-re)
10249 (org-in-regexp org-plain-link-re))
10250 ;; Convert to bracket link
10251 (setq remove (list (match-beginning 0) (match-end 0))
10252 link (read-string "Link: "
10253 (org-remove-angle-brackets (match-string 0)))))
10254 ((member complete-file '((4) (16)))
10255 ;; Completing read for file names.
10256 (setq link (org-file-complete-link complete-file)))
10258 ;; Read link, with completion for stored links.
10259 (org-link-fontify-links-to-this-file)
10260 (org-switch-to-buffer-other-window "*Org Links*")
10261 (with-current-buffer "*Org Links*"
10262 (erase-buffer)
10263 (insert "Insert a link.
10264 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10265 (when org-stored-links
10266 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10267 (insert (mapconcat 'org-link-prettify
10268 (reverse org-stored-links) "\n")))
10269 (goto-char (point-min)))
10270 (let ((cw (selected-window)))
10271 (select-window (get-buffer-window "*Org Links*" 'visible))
10272 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10273 (unless (pos-visible-in-window-p (point-max))
10274 (org-fit-window-to-buffer))
10275 (and (window-live-p cw) (select-window cw)))
10276 ;; Fake a link history, containing the stored links.
10277 (setq tmphist (append (mapcar 'car org-stored-links)
10278 org-insert-link-history))
10279 (setq all-prefixes (append (mapcar 'car abbrevs)
10280 (mapcar 'car org-link-abbrev-alist)
10281 org-link-types))
10282 (unwind-protect
10283 (progn
10284 (setq link
10285 (org-completing-read
10286 "Link: "
10287 (append
10288 (mapcar (lambda (x) (concat x ":"))
10289 all-prefixes)
10290 (mapcar 'car org-stored-links))
10291 nil nil nil
10292 'tmphist
10293 (caar org-stored-links)))
10294 (if (not (string-match "\\S-" link))
10295 (user-error "No link selected"))
10296 (mapc (lambda(l)
10297 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10298 org-stored-links)
10299 (if (or (member link all-prefixes)
10300 (and (equal ":" (substring link -1))
10301 (member (substring link 0 -1) all-prefixes)
10302 (setq link (substring link 0 -1))))
10303 (setq link (with-current-buffer origbuf
10304 (org-link-try-special-completion link)))))
10305 (set-window-configuration wcf)
10306 (kill-buffer "*Org Links*"))
10307 (setq entry (assoc link org-stored-links))
10308 (or entry (push link org-insert-link-history))
10309 (setq desc (or desc (nth 1 entry)))))
10311 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10312 (not org-keep-stored-link-after-insertion))
10313 (setq org-stored-links (delq (assoc link org-stored-links)
10314 org-stored-links)))
10316 (if (and (string-match org-plain-link-re link)
10317 (not (string-match org-ts-regexp link)))
10318 ;; URL-like link, normalize the use of angular brackets.
10319 (setq link (org-remove-angle-brackets link)))
10321 ;; Check if we are linking to the current file with a search
10322 ;; option If yes, simplify the link by using only the search
10323 ;; option.
10324 (when (and buffer-file-name
10325 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10326 (let* ((path (match-string 1 link))
10327 (case-fold-search nil)
10328 (search (match-string 2 link)))
10329 (save-match-data
10330 (if (equal (file-truename buffer-file-name) (file-truename path))
10331 ;; We are linking to this same file, with a search option
10332 (setq link search)))))
10334 ;; Check if we can/should use a relative path. If yes, simplify the link
10335 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10336 (let* ((type (match-string 1 link))
10337 (path (match-string 2 link))
10338 (origpath path)
10339 (case-fold-search nil))
10340 (cond
10341 ((or (eq org-link-file-path-type 'absolute)
10342 (equal complete-file '(16)))
10343 (setq path (abbreviate-file-name (expand-file-name path))))
10344 ((eq org-link-file-path-type 'noabbrev)
10345 (setq path (expand-file-name path)))
10346 ((eq org-link-file-path-type 'relative)
10347 (setq path (file-relative-name path)))
10349 (save-match-data
10350 (if (string-match (concat "^" (regexp-quote
10351 (expand-file-name
10352 (file-name-as-directory
10353 default-directory))))
10354 (expand-file-name path))
10355 ;; We are linking a file with relative path name.
10356 (setq path (substring (expand-file-name path)
10357 (match-end 0)))
10358 (setq path (abbreviate-file-name (expand-file-name path)))))))
10359 (setq link (concat type path))
10360 (if (equal desc origpath)
10361 (setq desc path))))
10363 (if org-make-link-description-function
10364 (setq desc
10365 (or (condition-case nil
10366 (funcall org-make-link-description-function link desc)
10367 (error (progn (message "Can't get link description from `%s'"
10368 (symbol-name org-make-link-description-function))
10369 (sit-for 2) nil)))
10370 (read-string "Description: " default-description)))
10371 (if default-description (setq desc default-description)
10372 (setq desc (or (and auto-desc desc)
10373 (read-string "Description: " desc)))))
10375 (unless (string-match "\\S-" desc) (setq desc nil))
10376 (if remove (apply 'delete-region remove))
10377 (insert (org-make-link-string link desc))))
10379 (defun org-link-try-special-completion (type)
10380 "If there is completion support for link type TYPE, offer it."
10381 (let ((fun (intern (concat "org-" type "-complete-link"))))
10382 (if (functionp fun)
10383 (funcall fun)
10384 (read-string "Link (no completion support): " (concat type ":")))))
10386 (defun org-file-complete-link (&optional arg)
10387 "Create a file link using completion."
10388 (let (file link)
10389 (setq file (org-iread-file-name "File: "))
10390 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10391 (pwd1 (file-name-as-directory (abbreviate-file-name
10392 (expand-file-name ".")))))
10393 (cond
10394 ((equal arg '(16))
10395 (setq link (concat
10396 "file:"
10397 (abbreviate-file-name (expand-file-name file)))))
10398 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10399 (setq link (concat "file:" (match-string 1 file))))
10400 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10401 (expand-file-name file))
10402 (setq link (concat
10403 "file:" (match-string 1 (expand-file-name file)))))
10404 (t (setq link (concat "file:" file)))))
10405 link))
10407 (defun org-iread-file-name (&rest args)
10408 "Read-file-name using `ido-mode' speedup if available.
10409 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10410 See `read-file-name' for a description of parameters."
10411 (org-without-partial-completion
10412 (if (and org-completion-use-ido
10413 (fboundp 'ido-read-file-name)
10414 (boundp 'ido-mode) ido-mode
10415 (listp (second args)))
10416 (let ((ido-enter-matching-directory nil))
10417 (apply 'ido-read-file-name args))
10418 (apply 'read-file-name args))))
10420 (defun org-completing-read (&rest args)
10421 "Completing-read with SPACE being a normal character."
10422 (let ((enable-recursive-minibuffers t)
10423 (minibuffer-local-completion-map
10424 (copy-keymap minibuffer-local-completion-map)))
10425 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10426 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10427 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10428 (apply 'org-icompleting-read args)))
10430 (defun org-completing-read-no-i (&rest args)
10431 (let (org-completion-use-ido org-completion-use-iswitchb)
10432 (apply 'org-completing-read args)))
10434 (defun org-iswitchb-completing-read (prompt choices &rest args)
10435 "Use iswitch as a completing-read replacement to choose from choices.
10436 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10437 from."
10438 (let* ((iswitchb-use-virtual-buffers nil)
10439 (iswitchb-make-buflist-hook
10440 (lambda ()
10441 (setq iswitchb-temp-buflist choices))))
10442 (iswitchb-read-buffer prompt)))
10444 (defun org-icompleting-read (&rest args)
10445 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10446 (org-without-partial-completion
10447 (if (and org-completion-use-ido
10448 (fboundp 'ido-completing-read)
10449 (boundp 'ido-mode) ido-mode
10450 (listp (second args)))
10451 (let ((ido-enter-matching-directory nil))
10452 (apply 'ido-completing-read (concat (car args))
10453 (if (consp (car (nth 1 args)))
10454 (mapcar 'car (nth 1 args))
10455 (nth 1 args))
10456 (cddr args)))
10457 (if (and org-completion-use-iswitchb
10458 (boundp 'iswitchb-mode) iswitchb-mode
10459 (listp (second args)))
10460 (apply 'org-iswitchb-completing-read (concat (car args))
10461 (if (consp (car (nth 1 args)))
10462 (mapcar 'car (nth 1 args))
10463 (nth 1 args))
10464 (cddr args))
10465 (apply 'completing-read args)))))
10467 (defun org-extract-attributes (s)
10468 "Extract the attributes cookie from a string and set as text property."
10469 (let (a attr (start 0) key value)
10470 (save-match-data
10471 (when (string-match "{{\\([^}]+\\)}}$" s)
10472 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10473 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10474 (setq key (match-string 1 a) value (match-string 2 a)
10475 start (match-end 0)
10476 attr (plist-put attr (intern key) value))))
10477 (org-add-props s nil 'org-attr attr))
10480 ;;; Opening/following a link
10482 (defvar org-link-search-failed nil)
10484 (defvar org-open-link-functions nil
10485 "Hook for functions finding a plain text link.
10486 These functions must take a single argument, the link content.
10487 They will be called for links that look like [[link text][description]]
10488 when LINK TEXT does not have a protocol like \"http:\" and does not look
10489 like a filename (e.g. \"./blue.png\").
10491 These functions will be called *before* Org attempts to resolve the
10492 link by doing text searches in the current buffer - so if you want a
10493 link \"[[target]]\" to still find \"<<target>>\", your function should
10494 handle this as a special case.
10496 When the function does handle the link, it must return a non-nil value.
10497 If it decides that it is not responsible for this link, it must return
10498 nil to indicate that that Org-mode can continue with other options
10499 like exact and fuzzy text search.")
10501 (defun org-next-link (&optional search-backward)
10502 "Move forward to the next link.
10503 If the link is in hidden text, expose it."
10504 (interactive "P")
10505 (when (and org-link-search-failed (eq this-command last-command))
10506 (goto-char (point-min))
10507 (message "Link search wrapped back to beginning of buffer"))
10508 (setq org-link-search-failed nil)
10509 (let* ((pos (point))
10510 (ct (org-context))
10511 (a (assoc :link ct))
10512 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10513 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10514 ((looking-at org-any-link-re)
10515 ;; Don't stay stuck at link without an org-link face
10516 (forward-char (if search-backward -1 1))))
10517 (if (funcall srch-fun org-any-link-re nil t)
10518 (progn
10519 (goto-char (match-beginning 0))
10520 (if (outline-invisible-p) (org-show-context)))
10521 (goto-char pos)
10522 (setq org-link-search-failed t)
10523 (message "No further link found"))))
10525 (defun org-previous-link ()
10526 "Move backward to the previous link.
10527 If the link is in hidden text, expose it."
10528 (interactive)
10529 (funcall 'org-next-link t))
10531 (defun org-translate-link (s)
10532 "Translate a link string if a translation function has been defined."
10533 (if (and org-link-translation-function
10534 (fboundp org-link-translation-function)
10535 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10536 (progn
10537 (setq s (funcall org-link-translation-function
10538 (match-string 1 s) (match-string 2 s)))
10539 (concat (car s) ":" (cdr s)))
10542 (defun org-translate-link-from-planner (type path)
10543 "Translate a link from Emacs Planner syntax so that Org can follow it.
10544 This is still an experimental function, your mileage may vary."
10545 (cond
10546 ((member type '("http" "https" "news" "ftp"))
10547 ;; standard Internet links are the same.
10548 nil)
10549 ((and (equal type "irc") (string-match "^//" path))
10550 ;; Planner has two / at the beginning of an irc link, we have 1.
10551 ;; We should have zero, actually....
10552 (setq path (substring path 1)))
10553 ((and (equal type "lisp") (string-match "^/" path))
10554 ;; Planner has a slash, we do not.
10555 (setq type "elisp" path (substring path 1)))
10556 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10557 ;; A typical message link. Planner has the id after the final slash,
10558 ;; we separate it with a hash mark
10559 (setq path (concat (match-string 1 path) "#"
10560 (org-remove-angle-brackets (match-string 2 path))))))
10561 (cons type path))
10563 (defun org-find-file-at-mouse (ev)
10564 "Open file link or URL at mouse."
10565 (interactive "e")
10566 (mouse-set-point ev)
10567 (org-open-at-point 'in-emacs))
10569 (defun org-open-at-mouse (ev)
10570 "Open file link or URL at mouse.
10571 See the docstring of `org-open-file' for details."
10572 (interactive "e")
10573 (mouse-set-point ev)
10574 (if (eq major-mode 'org-agenda-mode)
10575 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10576 (org-open-at-point))
10578 (defvar org-window-config-before-follow-link nil
10579 "The window configuration before following a link.
10580 This is saved in case the need arises to restore it.")
10582 (defvar org-open-link-marker (make-marker)
10583 "Marker pointing to the location where `org-open-at-point' was called.")
10585 ;;;###autoload
10586 (defun org-open-at-point-global ()
10587 "Follow a link like Org-mode does.
10588 This command can be called in any mode to follow a link that has
10589 Org-mode syntax."
10590 (interactive)
10591 (org-run-like-in-org-mode 'org-open-at-point))
10593 ;;;###autoload
10594 (defun org-open-link-from-string (s &optional arg reference-buffer)
10595 "Open a link in the string S, as if it was in Org-mode."
10596 (interactive "sLink: \nP")
10597 (let ((reference-buffer (or reference-buffer (current-buffer))))
10598 (with-temp-buffer
10599 (let ((org-inhibit-startup (not reference-buffer)))
10600 (org-mode)
10601 (insert s)
10602 (goto-char (point-min))
10603 (when reference-buffer
10604 (setq org-link-abbrev-alist-local
10605 (with-current-buffer reference-buffer
10606 org-link-abbrev-alist-local)))
10607 (org-open-at-point arg reference-buffer)))))
10609 (defvar org-open-at-point-functions nil
10610 "Hook that is run when following a link at point.
10612 Functions in this hook must return t if they identify and follow
10613 a link at point. If they don't find anything interesting at point,
10614 they must return nil.")
10616 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10617 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10618 (defun org-open-at-point (&optional arg reference-buffer)
10619 "Open link, timestamp, footnote or tags at point.
10621 When point is on a link, follow it. Normally, files will be
10622 opened by an appropriate application. If the optional prefix
10623 argument ARG is non-nil, Emacs will visit the file. With
10624 a double prefix argument, try to open outside of Emacs, in the
10625 application the system uses for this file type.
10627 When point is on a timestamp, open the agenda at the day
10628 specified.
10630 When point is a footnote definition, move to the first reference
10631 found. If it is on a reference, move to the associated
10632 definition.
10634 When point is on a headline, display a list of every link in the
10635 entry, so it is possible to pick one, or all, of them. If point
10636 is on a tag, call `org-tags-view' instead.
10638 When optional argument REFERENCE-BUFFER is non-nil, it should
10639 specify a buffer from where the link search should happen. This
10640 is used internally by `org-open-link-from-string'.
10642 On top of syntactically correct links, this function will open
10643 the link at point in comments or comment blocks and the first
10644 link in a property drawer line."
10645 (interactive "P")
10646 ;; On a code block, open block's results.
10647 (unless (call-interactively 'org-babel-open-src-block-result)
10648 (org-load-modules-maybe)
10649 (move-marker org-open-link-marker (point))
10650 (setq org-window-config-before-follow-link (current-window-configuration))
10651 (org-remove-occur-highlights nil nil t)
10652 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10653 (let* ((context (org-element-context)) type value)
10654 ;; On an unsupported type, check if point is contained within
10655 ;; a support one.
10656 (while (and (not (memq (setq type (org-element-type context))
10657 '(comment comment-block
10658 headline inlinetask link
10659 footnote-definition footnote-reference
10660 node-property timestamp)))
10661 (setq context (org-element-property :parent context))))
10662 (setq value (org-element-property :value context))
10663 (cond
10664 ;; Blank lines at the beginning of buffer: bail out.
10665 ((not context) (user-error "No link found"))
10666 ;; Exception n°1: links in property drawers
10667 ((eq type 'node-property)
10668 (org-open-link-from-string
10669 (and (string-match org-any-link-re value)
10670 (match-string-no-properties 0 value))))
10671 ;; Exception n°2: links in comments.
10672 ((memq type '(comment comment-block))
10673 (save-excursion
10674 (skip-chars-forward "\\S-" (point-at-eol))
10675 (let ((string-rear (replace-regexp-in-string
10676 "^[ \t]*# [ \t]*" ""
10677 (buffer-substring (point) (line-beginning-position))))
10678 (string-front (buffer-substring (point) (line-end-position))))
10679 (with-temp-buffer
10680 (let ((org-inhibit-startup t)) (org-mode))
10681 (insert value)
10682 (goto-char (point-min))
10683 (when (and (search-forward string-rear nil t)
10684 (search-forward string-front (line-end-position) t))
10685 (goto-char (match-beginning 0))
10686 (org-open-at-point)
10687 (when (string= string-rear "") (forward-char)))))))
10688 ;; On a headline or an inlinetask, but not on a timestamp,
10689 ;; a link, a footnote reference or on tags.
10690 ((and (memq type '(headline inlinetask))
10691 ;; Not on tags.
10692 (progn (save-excursion (beginning-of-line)
10693 (looking-at org-complex-heading-regexp))
10694 (or (not (match-beginning 5))
10695 (< (point) (match-beginning 5)))))
10696 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10697 (links (car data))
10698 (links-end (cdr data)))
10699 (if links
10700 (dolist (link (if (stringp links) (list links) links))
10701 (search-forward link nil links-end)
10702 (goto-char (match-beginning 0))
10703 (org-open-at-point))
10704 (require 'org-attach)
10705 (org-attach-reveal 'if-exists))))
10706 ;; Do nothing on white spaces after an object, unless point
10707 ;; is right after it.
10708 ((> (point)
10709 (save-excursion
10710 (goto-char (org-element-property :end context))
10711 (skip-chars-backward " \t")
10712 (point)))
10713 (user-error "No link found"))
10714 ((eq type 'timestamp) (org-follow-timestamp-link))
10715 ;; On tags within a headline or an inlinetask.
10716 ((and (memq type '(headline inlinetask))
10717 (progn (save-excursion (beginning-of-line)
10718 (looking-at org-complex-heading-regexp))
10719 (and (match-beginning 5)
10720 (>= (point) (match-beginning 5)))))
10721 (org-tags-view arg (substring (match-string 5) 0 -1)))
10722 ((eq type 'link)
10723 (let ((type (org-element-property :type context))
10724 (path (org-link-unescape (org-element-property :path context))))
10725 ;; Switch back to REFERENCE-BUFFER needed when called in
10726 ;; a temporary buffer through `org-open-link-from-string'.
10727 (with-current-buffer (or reference-buffer (current-buffer))
10728 (cond
10729 ((equal type "file")
10730 (if (string-match "[*?{]" (file-name-nondirectory path))
10731 (dired path)
10732 ;; Look into `org-link-protocols' in order to find
10733 ;; a DEDICATED-FUNCTION to open file. The function
10734 ;; will be applied on raw link instead of parsed
10735 ;; link due to the limitation in `org-add-link-type'
10736 ;; ("open" function called with a single argument).
10737 ;; If no such function is found, fallback to
10738 ;; `org-open-file'.
10740 ;; Note : "file+emacs" and "file+sys" types are
10741 ;; hard-coded in order to escape the previous
10742 ;; limitation.
10743 (let* ((option (org-element-property :search-option context))
10744 (app (org-element-property :application context))
10745 (dedicated-function
10746 (nth 1 (assoc app org-link-protocols))))
10747 (if dedicated-function
10748 (funcall dedicated-function
10749 (concat path
10750 (and option (concat "::" option))))
10751 (apply 'org-open-file
10752 path
10753 (cond (arg)
10754 ((equal app "emacs") 'emacs)
10755 ((equal app "sys") 'system))
10756 (cond ((not option) nil)
10757 ((org-string-match-p "\\`[0-9]+\\'" option)
10758 (list (string-to-number option)))
10759 (t (list nil
10760 (org-link-unescape option)))))))))
10761 ((assoc type org-link-protocols)
10762 (funcall (nth 1 (assoc type org-link-protocols)) path))
10763 ((equal type "help")
10764 (let ((f-or-v (intern path)))
10765 (cond ((fboundp f-or-v) (describe-function f-or-v))
10766 ((boundp f-or-v) (describe-variable f-or-v))
10767 (t (error "Not a known function or variable")))))
10768 ((member type '("http" "https" "ftp" "mailto" "news"))
10769 (browse-url (org-link-escape-browser (concat type ":" path))))
10770 ((equal type "doi")
10771 (browse-url
10772 (org-link-escape-browser (concat org-doi-server-url path))))
10773 ((equal type "message") (browse-url (concat type ":" path)))
10774 ((equal type "shell")
10775 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10776 (cmd path))
10777 (if (or (and (org-string-nw-p
10778 org-confirm-shell-link-not-regexp)
10779 (string-match
10780 org-confirm-shell-link-not-regexp cmd))
10781 (not org-confirm-shell-link-function)
10782 (funcall org-confirm-shell-link-function
10783 (format "Execute \"%s\" in shell? "
10784 (org-add-props cmd nil
10785 'face 'org-warning))))
10786 (progn
10787 (message "Executing %s" cmd)
10788 (shell-command cmd buf)
10789 (when (featurep 'midnight)
10790 (setq clean-buffer-list-kill-buffer-names
10791 (cons buf
10792 clean-buffer-list-kill-buffer-names))))
10793 (user-error "Abort"))))
10794 ((equal type "elisp")
10795 (let ((cmd path))
10796 (if (or (and (org-string-nw-p
10797 org-confirm-elisp-link-not-regexp)
10798 (org-string-match-p
10799 org-confirm-elisp-link-not-regexp cmd))
10800 (not org-confirm-elisp-link-function)
10801 (funcall org-confirm-elisp-link-function
10802 (format "Execute \"%s\" as elisp? "
10803 (org-add-props cmd nil
10804 'face 'org-warning))))
10805 (message "%s => %s" cmd
10806 (if (eq (string-to-char cmd) ?\()
10807 (eval (read cmd))
10808 (call-interactively (read cmd))))
10809 (user-error "Abort"))))
10810 ((equal type "id")
10811 (require 'ord-id)
10812 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10813 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10814 (unless (run-hook-with-args-until-success
10815 'org-open-link-functions path)
10816 (if (not arg) (org-mark-ring-push)
10817 (switch-to-buffer-other-window
10818 (org-get-buffer-for-internal-link (current-buffer))))
10819 (let ((cmd `(org-link-search
10820 ,(if (member type '("custom-id" "coderef"))
10821 (org-element-property :raw-link context)
10822 path)
10823 ,(cond ((equal arg '(4)) 'occur)
10824 ((equal arg '(16)) 'org-occur))
10825 ,(org-element-property :begin context))))
10826 (condition-case nil
10827 (let ((org-link-search-inhibit-query t))
10828 (eval cmd))
10829 (error (progn (widen) (eval cmd)))))))
10830 (t (browse-url-at-point))))))
10831 ;; On a footnote reference or at a footnote definition's label.
10832 ((or (eq type 'footnote-reference)
10833 (and (eq type 'footnote-definition)
10834 (save-excursion
10835 ;; Do not validate action when point is on the
10836 ;; spaces right after the footnote label, in
10837 ;; order to be on par with behaviour on links.
10838 (skip-chars-forward " \t")
10839 (let ((begin
10840 (org-element-property :contents-begin context)))
10841 (if begin (< (point) begin)
10842 (= (org-element-property :post-affiliated context)
10843 (line-beginning-position)))))))
10844 (org-footnote-action))
10845 (t (user-error "No link found")))))
10846 (move-marker org-open-link-marker nil)
10847 (run-hook-with-args 'org-follow-link-hook)))
10849 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10850 "Offer links in the current entry and return the selected link.
10851 If there is only one link, return it.
10852 If NTH is an integer, return the NTH link found.
10853 If ZERO is a string, check also this string for a link, and if
10854 there is one, return it."
10855 (with-current-buffer buffer
10856 (save-excursion
10857 (save-restriction
10858 (widen)
10859 (goto-char marker)
10860 (let ((cnt ?0)
10861 (in-emacs (if (integerp nth) nil nth))
10862 have-zero end links link c)
10863 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10864 (push (match-string 0 zero) links)
10865 (setq cnt (1- cnt) have-zero t))
10866 (save-excursion
10867 (org-back-to-heading t)
10868 (setq end (save-excursion (outline-next-heading) (point)))
10869 (while (re-search-forward org-any-link-re end t)
10870 (push (match-string 0) links))
10871 (setq links (org-uniquify (reverse links))))
10872 (cond
10873 ((null links)
10874 (message "No links"))
10875 ((equal (length links) 1)
10876 (setq link (car links)))
10877 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10878 (setq link (nth (if have-zero nth (1- nth)) links)))
10879 (t ; we have to select a link
10880 (save-excursion
10881 (save-window-excursion
10882 (delete-other-windows)
10883 (with-output-to-temp-buffer "*Select Link*"
10884 (mapc (lambda (l)
10885 (if (not (string-match org-bracket-link-regexp l))
10886 (princ (format "[%c] %s\n" (incf cnt)
10887 (org-remove-angle-brackets l)))
10888 (if (match-end 3)
10889 (princ (format "[%c] %s (%s)\n" (incf cnt)
10890 (match-string 3 l) (match-string 1 l)))
10891 (princ (format "[%c] %s\n" (incf cnt)
10892 (match-string 1 l))))))
10893 links))
10894 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10895 (message "Select link to open, RET to open all:")
10896 (setq c (read-char-exclusive))
10897 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10898 (when (equal c ?q) (user-error "Abort"))
10899 (if (equal c ?\C-m)
10900 (setq link links)
10901 (setq nth (- c ?0))
10902 (if have-zero (setq nth (1+ nth)))
10903 (unless (and (integerp nth) (>= (length links) nth))
10904 (user-error "Invalid link selection"))
10905 (setq link (nth (1- nth) links)))))
10906 (cons link end))))))
10908 ;; TODO: These functions are deprecated since `org-open-at-point'
10909 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10910 (defun org-open-file-with-system (path)
10911 "Open file at PATH using the system way of opening it."
10912 (org-open-file path 'system))
10913 (defun org-open-file-with-emacs (path)
10914 "Open file at PATH in Emacs."
10915 (org-open-file path 'emacs))
10918 ;;; File search
10920 (defvar org-create-file-search-functions nil
10921 "List of functions to construct the right search string for a file link.
10922 These functions are called in turn with point at the location to
10923 which the link should point.
10925 A function in the hook should first test if it would like to
10926 handle this file type, for example by checking the `major-mode'
10927 or the file extension. If it decides not to handle this file, it
10928 should just return nil to give other functions a chance. If it
10929 does handle the file, it must return the search string to be used
10930 when following the link. The search string will be part of the
10931 file link, given after a double colon, and `org-open-at-point'
10932 will automatically search for it. If special measures must be
10933 taken to make the search successful, another function should be
10934 added to the companion hook `org-execute-file-search-functions',
10935 which see.
10937 A function in this hook may also use `setq' to set the variable
10938 `description' to provide a suggestion for the descriptive text to
10939 be used for this link when it gets inserted into an Org-mode
10940 buffer with \\[org-insert-link].")
10942 (defvar org-execute-file-search-functions nil
10943 "List of functions to execute a file search triggered by a link.
10945 Functions added to this hook must accept a single argument, the
10946 search string that was part of the file link, the part after the
10947 double colon. The function must first check if it would like to
10948 handle this search, for example by checking the `major-mode' or
10949 the file extension. If it decides not to handle this search, it
10950 should just return nil to give other functions a chance. If it
10951 does handle the search, it must return a non-nil value to keep
10952 other functions from trying.
10954 Each function can access the current prefix argument through the
10955 variable `current-prefix-arg'. Note that a single prefix is used
10956 to force opening a link in Emacs, so it may be good to only use a
10957 numeric or double prefix to guide the search function.
10959 In case this is needed, a function in this hook can also restore
10960 the window configuration before `org-open-at-point' was called using:
10962 (set-window-configuration org-window-config-before-follow-link)")
10964 (defun org-link-search (s &optional type avoid-pos stealth)
10965 "Search for a link search option.
10966 If S is surrounded by forward slashes, it is interpreted as a
10967 regular expression. In org-mode files, this will create an `org-occur'
10968 sparse tree. In ordinary files, `occur' will be used to list matches.
10969 If the current buffer is in `dired-mode', grep will be used to search
10970 in all files. If AVOID-POS is given, ignore matches near that position.
10972 When optional argument STEALTH is non-nil, do not modify
10973 visibility around point, thus ignoring
10974 `org-show-hierarchy-above', `org-show-following-heading' and
10975 `org-show-siblings' variables."
10976 (let ((case-fold-search t)
10977 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10978 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10979 (append '(("") (" ") ("\t") ("\n"))
10980 org-emphasis-alist)
10981 "\\|") "\\)"))
10982 (pos (point))
10983 (pre nil) (post nil)
10984 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10985 (cond
10986 ;; First check if there are any special search functions
10987 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10988 ;; Now try the builtin stuff
10989 ((and (equal (string-to-char s0) ?#)
10990 (> (length s0) 1)
10991 (save-excursion
10992 (goto-char (point-min))
10993 (and
10994 (re-search-forward
10995 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10996 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10997 (setq type 'dedicated
10998 pos (match-beginning 0))))
10999 ;; There is an exact target for this
11000 (goto-char pos)
11001 (org-back-to-heading t)))
11002 ((save-excursion
11003 (goto-char (point-min))
11004 (and
11005 (re-search-forward
11006 (concat "<<" (regexp-quote s0) ">>") nil t)
11007 (setq type 'dedicated
11008 pos (match-beginning 0))))
11009 ;; There is an exact target for this
11010 (goto-char pos))
11011 ((save-excursion
11012 (goto-char (point-min))
11013 (and
11014 (re-search-forward
11015 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
11016 (setq type 'dedicated pos (match-beginning 0))))
11017 ;; Found an element with a matching #+name affiliated keyword.
11018 (goto-char pos))
11019 ((and (string-match "^(\\(.*\\))$" s0)
11020 (save-excursion
11021 (goto-char (point-min))
11022 (and
11023 (re-search-forward
11024 (concat "[^[]" (regexp-quote
11025 (format org-coderef-label-format
11026 (match-string 1 s0))))
11027 nil t)
11028 (setq type 'dedicated
11029 pos (1+ (match-beginning 0))))))
11030 ;; There is a coderef target for this
11031 (goto-char pos))
11032 ((string-match "^/\\(.*\\)/$" s)
11033 ;; A regular expression
11034 (cond
11035 ((derived-mode-p 'org-mode)
11036 (org-occur (match-string 1 s)))
11037 (t (org-do-occur (match-string 1 s)))))
11038 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11039 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11040 (goto-char (point-min))
11041 (cond
11042 ((let (case-fold-search)
11043 (re-search-forward (format org-complex-heading-regexp-format
11044 (regexp-quote s))
11045 nil t))
11046 ;; OK, found a match
11047 (setq type 'dedicated)
11048 (goto-char (match-beginning 0)))
11049 ((and (not org-link-search-inhibit-query)
11050 (eq org-link-search-must-match-exact-headline 'query-to-create)
11051 (y-or-n-p "No match - create this as a new heading? "))
11052 (goto-char (point-max))
11053 (or (bolp) (newline))
11054 (insert "* " s "\n")
11055 (beginning-of-line 0))
11057 (goto-char pos)
11058 (error "No match"))))
11060 ;; A normal search string
11061 (when (equal (string-to-char s) ?*)
11062 ;; Anchor on headlines, post may include tags.
11063 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11064 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11065 s (substring s 1)))
11066 (remove-text-properties
11067 0 (length s)
11068 '(face nil mouse-face nil keymap nil fontified nil) s)
11069 ;; Make a series of regular expressions to find a match
11070 (setq words (org-split-string s "[ \n\r\t]+")
11072 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11073 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11074 "\\)" markers)
11075 re2a_ (concat "\\(" (mapconcat 'downcase words
11076 "[ \t\r\n]+") "\\)[ \t\r\n]")
11077 re2a (concat "[ \t\r\n]" re2a_)
11078 re4_ (concat "\\(" (mapconcat 'downcase words
11079 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11080 re4 (concat "[^a-zA-Z_]" re4_)
11082 re1 (concat pre re2 post)
11083 re3 (concat pre (if pre re4_ re4) post)
11084 re5 (concat pre ".*" re4)
11085 re2 (concat pre re2)
11086 re2a (concat pre (if pre re2a_ re2a))
11087 re4 (concat pre (if pre re4_ re4))
11088 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11089 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11090 re5 "\\)"))
11091 (cond
11092 ((eq type 'org-occur) (org-occur reall))
11093 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11094 (t (goto-char (point-min))
11095 (setq type 'fuzzy)
11096 (if (or (and (org-search-not-self 1 re0 nil t)
11097 (setq type 'dedicated))
11098 (org-search-not-self 1 re1 nil t)
11099 (org-search-not-self 1 re2 nil t)
11100 (org-search-not-self 1 re2a nil t)
11101 (org-search-not-self 1 re3 nil t)
11102 (org-search-not-self 1 re4 nil t)
11103 (org-search-not-self 1 re5 nil t))
11104 (goto-char (match-beginning 1))
11105 (goto-char pos)
11106 (error "No match"))))))
11107 (and (derived-mode-p 'org-mode)
11108 (not stealth)
11109 (org-show-context 'link-search))
11110 type))
11112 (defun org-search-not-self (group &rest args)
11113 "Execute `re-search-forward', but only accept matches that do not
11114 enclose the position of `org-open-link-marker'."
11115 (let ((m org-open-link-marker))
11116 (catch 'exit
11117 (while (apply 're-search-forward args)
11118 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11119 (goto-char (match-end group))
11120 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11121 (> (match-beginning 0) (marker-position m))
11122 (< (match-end 0) (marker-position m)))
11123 (save-match-data
11124 (or (not (org-in-regexp
11125 org-bracket-link-analytic-regexp 1))
11126 (not (match-end 4)) ; no description
11127 (and (<= (match-beginning 4) (point))
11128 (>= (match-end 4) (point))))))
11129 (throw 'exit (point))))))))
11131 (defun org-get-buffer-for-internal-link (buffer)
11132 "Return a buffer to be used for displaying the link target of internal links."
11133 (cond
11134 ((not org-display-internal-link-with-indirect-buffer)
11135 buffer)
11136 ((string-match "(Clone)$" (buffer-name buffer))
11137 (message "Buffer is already a clone, not making another one")
11138 ;; we also do not modify visibility in this case
11139 buffer)
11140 (t ; make a new indirect buffer for displaying the link
11141 (let* ((bn (buffer-name buffer))
11142 (ibn (concat bn "(Clone)"))
11143 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11144 (with-current-buffer ib (org-overview))
11145 ib))))
11147 (defun org-do-occur (regexp &optional cleanup)
11148 "Call the Emacs command `occur'.
11149 If CLEANUP is non-nil, remove the printout of the regular expression
11150 in the *Occur* buffer. This is useful if the regex is long and not useful
11151 to read."
11152 (occur regexp)
11153 (when cleanup
11154 (let ((cwin (selected-window)) win beg end)
11155 (when (setq win (get-buffer-window "*Occur*"))
11156 (select-window win))
11157 (goto-char (point-min))
11158 (when (re-search-forward "match[a-z]+" nil t)
11159 (setq beg (match-end 0))
11160 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11161 (setq end (1- (match-beginning 0)))))
11162 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11163 (goto-char (point-min))
11164 (select-window cwin))))
11166 ;;; The mark ring for links jumps
11168 (defvar org-mark-ring nil
11169 "Mark ring for positions before jumps in Org-mode.")
11170 (defvar org-mark-ring-last-goto nil
11171 "Last position in the mark ring used to go back.")
11172 ;; Fill and close the ring
11173 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11174 (loop for i from 1 to org-mark-ring-length do
11175 (push (make-marker) org-mark-ring))
11176 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11177 org-mark-ring)
11179 (defun org-mark-ring-push (&optional pos buffer)
11180 "Put the current position or POS into the mark ring and rotate it."
11181 (interactive)
11182 (setq pos (or pos (point)))
11183 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11184 (move-marker (car org-mark-ring)
11185 (or pos (point))
11186 (or buffer (current-buffer)))
11187 (message "%s"
11188 (substitute-command-keys
11189 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11191 (defun org-mark-ring-goto (&optional n)
11192 "Jump to the previous position in the mark ring.
11193 With prefix arg N, jump back that many stored positions. When
11194 called several times in succession, walk through the entire ring.
11195 Org-mode commands jumping to a different position in the current file,
11196 or to another Org-mode file, automatically push the old position
11197 onto the ring."
11198 (interactive "p")
11199 (let (p m)
11200 (if (eq last-command this-command)
11201 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11202 (setq p org-mark-ring))
11203 (setq org-mark-ring-last-goto p)
11204 (setq m (car p))
11205 (org-pop-to-buffer-same-window (marker-buffer m))
11206 (goto-char m)
11207 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11209 (defun org-remove-angle-brackets (s)
11210 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11211 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11213 (defun org-add-angle-brackets (s)
11214 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11215 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11217 (defun org-remove-double-quotes (s)
11218 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11219 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11222 ;;; Following specific links
11224 (defun org-follow-timestamp-link ()
11225 "Open an agenda view for the time-stamp date/range at point."
11226 (cond
11227 ((org-at-date-range-p t)
11228 (let ((org-agenda-start-on-weekday)
11229 (t1 (match-string 1))
11230 (t2 (match-string 2)) tt1 tt2)
11231 (setq tt1 (time-to-days (org-time-string-to-time t1))
11232 tt2 (time-to-days (org-time-string-to-time t2)))
11233 (let ((org-agenda-buffer-tmp-name
11234 (format "*Org Agenda(a:%s)"
11235 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11236 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11237 ((org-at-timestamp-p t)
11238 (let ((org-agenda-buffer-tmp-name
11239 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11240 (org-agenda-list nil (time-to-days (org-time-string-to-time
11241 (substring (match-string 1) 0 10)))
11242 1)))
11243 (t (error "This should not happen"))))
11246 ;;; Following file links
11247 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11248 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11249 (declare-function mailcap-mime-info
11250 "mailcap" (string &optional request no-decode))
11251 (defvar org-wait nil)
11252 (defun org-open-file (path &optional in-emacs line search)
11253 "Open the file at PATH.
11254 First, this expands any special file name abbreviations. Then the
11255 configuration variable `org-file-apps' is checked if it contains an
11256 entry for this file type, and if yes, the corresponding command is launched.
11258 If no application is found, Emacs simply visits the file.
11260 With optional prefix argument IN-EMACS, Emacs will visit the file.
11261 With a double \\[universal-argument] \\[universal-argument] \
11262 prefix arg, Org tries to avoid opening in Emacs
11263 and to use an external application to visit the file.
11265 Optional LINE specifies a line to go to, optional SEARCH a string
11266 to search for. If LINE or SEARCH is given, the file will be
11267 opened in Emacs, unless an entry from org-file-apps that makes
11268 use of groups in a regexp matches.
11270 If you want to change the way frames are used when following a
11271 link, please customize `org-link-frame-setup'.
11273 If the file does not exist, an error is thrown."
11274 (let* ((file (if (equal path "")
11275 buffer-file-name
11276 (substitute-in-file-name (expand-file-name path))))
11277 (file-apps (append org-file-apps (org-default-apps)))
11278 (apps (org-remove-if
11279 'org-file-apps-entry-match-against-dlink-p file-apps))
11280 (apps-dlink (org-remove-if-not
11281 'org-file-apps-entry-match-against-dlink-p file-apps))
11282 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11283 (dirp (if remp nil (file-directory-p file)))
11284 (file (if (and dirp org-open-directory-means-index-dot-org)
11285 (concat (file-name-as-directory file) "index.org")
11286 file))
11287 (a-m-a-p (assq 'auto-mode apps))
11288 (dfile (downcase file))
11289 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11290 (link (cond ((and (eq line nil)
11291 (eq search nil))
11292 file)
11293 (line
11294 (concat file "::" (number-to-string line)))
11295 (search
11296 (concat file "::" search))))
11297 (dlink (downcase link))
11298 (old-buffer (current-buffer))
11299 (old-pos (point))
11300 (old-mode major-mode)
11301 ext cmd link-match-data)
11302 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11303 (setq ext (match-string 1 dfile))
11304 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11305 (setq ext (match-string 1 dfile))))
11306 (cond
11307 ((member in-emacs '((16) system))
11308 (setq cmd (cdr (assoc 'system apps))))
11309 (in-emacs (setq cmd 'emacs))
11311 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11312 (and dirp (cdr (assoc 'directory apps)))
11313 ; first, try matching against apps-dlink
11314 ; if we get a match here, store the match data for later
11315 (let ((match (assoc-default dlink apps-dlink
11316 'string-match)))
11317 (if match
11318 (progn (setq link-match-data (match-data))
11319 match)
11320 (progn (setq in-emacs (or in-emacs line search))
11321 nil))) ; if we have no match in apps-dlink,
11322 ; always open the file in emacs if line or search
11323 ; is given (for backwards compatibility)
11324 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11325 'string-match)
11326 (cdr (assoc ext apps))
11327 (cdr (assoc t apps))))))
11328 (when (eq cmd 'system)
11329 (setq cmd (cdr (assoc 'system apps))))
11330 (when (eq cmd 'default)
11331 (setq cmd (cdr (assoc t apps))))
11332 (when (eq cmd 'mailcap)
11333 (require 'mailcap)
11334 (mailcap-parse-mailcaps)
11335 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11336 (command (mailcap-mime-info mime-type)))
11337 (if (stringp command)
11338 (setq cmd command)
11339 (setq cmd 'emacs))))
11340 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11341 (not (file-exists-p file))
11342 (not org-open-non-existing-files))
11343 (user-error "No such file: %s" file))
11344 (cond
11345 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11346 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11347 (while (string-match "['\"]%s['\"]" cmd)
11348 (setq cmd (replace-match "%s" t t cmd)))
11349 (while (string-match "%s" cmd)
11350 (setq cmd (replace-match
11351 (save-match-data
11352 (shell-quote-argument
11353 (convert-standard-filename file)))
11354 t t cmd)))
11356 ;; Replace "%1", "%2" etc. in command with group matches from regex
11357 (save-match-data
11358 (let ((match-index 1)
11359 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11360 (set-match-data link-match-data)
11361 (while (<= match-index number-of-groups)
11362 (let ((regex (concat "%" (number-to-string match-index)))
11363 (replace-with (match-string match-index dlink)))
11364 (while (string-match regex cmd)
11365 (setq cmd (replace-match replace-with t t cmd))))
11366 (setq match-index (+ match-index 1)))))
11368 (save-window-excursion
11369 (message "Running %s...done" cmd)
11370 (start-process-shell-command cmd nil cmd)
11371 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11372 ((or (stringp cmd)
11373 (eq cmd 'emacs))
11374 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11375 (widen)
11376 (if line (progn (org-goto-line line)
11377 (if (derived-mode-p 'org-mode)
11378 (org-reveal)))
11379 (if search (org-link-search search))))
11380 ((consp cmd)
11381 (let ((file (convert-standard-filename file)))
11382 (save-match-data
11383 (set-match-data link-match-data)
11384 (eval cmd))))
11385 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11386 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11387 (or (not (equal old-buffer (current-buffer)))
11388 (not (equal old-pos (point))))
11389 (org-mark-ring-push old-pos old-buffer))))
11391 (defun org-file-apps-entry-match-against-dlink-p (entry)
11392 "This function returns non-nil if `entry' uses a regular
11393 expression which should be matched against the whole link by
11394 org-open-file.
11396 It assumes that is the case when the entry uses a regular
11397 expression which has at least one grouping construct and the
11398 action is either a lisp form or a command string containing
11399 '%1', i.e. using at least one subexpression match as a
11400 parameter."
11401 (let ((selector (car entry))
11402 (action (cdr entry)))
11403 (if (stringp selector)
11404 (and (> (regexp-opt-depth selector) 0)
11405 (or (and (stringp action)
11406 (string-match "%[0-9]" action))
11407 (consp action)))
11408 nil)))
11410 (defun org-default-apps ()
11411 "Return the default applications for this operating system."
11412 (cond
11413 ((eq system-type 'darwin)
11414 org-file-apps-defaults-macosx)
11415 ((eq system-type 'windows-nt)
11416 org-file-apps-defaults-windowsnt)
11417 (t org-file-apps-defaults-gnu)))
11419 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11420 "Convert extensions to regular expressions in the cars of LIST.
11421 Also, weed out any non-string entries, because the return value is used
11422 only for regexp matching.
11423 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11424 point to the symbol `emacs', indicating that the file should
11425 be opened in Emacs."
11426 (append
11427 (delq nil
11428 (mapcar (lambda (x)
11429 (if (not (stringp (car x)))
11431 (if (string-match "\\W" (car x))
11433 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11434 list))
11435 (if add-auto-mode
11436 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11438 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11439 (defun org-file-remote-p (file)
11440 "Test whether FILE specifies a location on a remote system.
11441 Return non-nil if the location is indeed remote.
11443 For example, the filename \"/user@host:/foo\" specifies a location
11444 on the system \"/user@host:\"."
11445 (cond ((fboundp 'file-remote-p)
11446 (file-remote-p file))
11447 ((fboundp 'tramp-handle-file-remote-p)
11448 (tramp-handle-file-remote-p file))
11449 ((and (boundp 'ange-ftp-name-format)
11450 (string-match (car ange-ftp-name-format) file))
11451 t)))
11454 ;;;; Refiling
11456 (defun org-get-org-file ()
11457 "Read a filename, with default directory `org-directory'."
11458 (let ((default (or org-default-notes-file remember-data-file)))
11459 (read-file-name (format "File name [%s]: " default)
11460 (file-name-as-directory org-directory)
11461 default)))
11463 (defun org-notes-order-reversed-p ()
11464 "Check if the current file should receive notes in reversed order."
11465 (cond
11466 ((not org-reverse-note-order) nil)
11467 ((eq t org-reverse-note-order) t)
11468 ((not (listp org-reverse-note-order)) nil)
11469 (t (catch 'exit
11470 (let ((all org-reverse-note-order)
11471 entry)
11472 (while (setq entry (pop all))
11473 (if (string-match (car entry) buffer-file-name)
11474 (throw 'exit (cdr entry))))
11475 nil)))))
11477 (defvar org-refile-target-table nil
11478 "The list of refile targets, created by `org-refile'.")
11480 (defvar org-agenda-new-buffers nil
11481 "Buffers created to visit agenda files.")
11483 (defvar org-refile-cache nil
11484 "Cache for refile targets.")
11486 (defvar org-refile-markers nil
11487 "All the markers used for caching refile locations.")
11489 (defun org-refile-marker (pos)
11490 "Get a new refile marker, but only if caching is in use."
11491 (if (not org-refile-use-cache)
11493 (let ((m (make-marker)))
11494 (move-marker m pos)
11495 (push m org-refile-markers)
11496 m)))
11498 (defun org-refile-cache-clear ()
11499 "Clear the refile cache and disable all the markers."
11500 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11501 (setq org-refile-markers nil)
11502 (setq org-refile-cache nil)
11503 (message "Refile cache has been cleared"))
11505 (defun org-refile-cache-check-set (set)
11506 "Check if all the markers in the cache still have live buffers."
11507 (let (marker)
11508 (catch 'exit
11509 (while (and set (setq marker (nth 3 (pop set))))
11510 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11511 (when (and marker (null (marker-buffer marker)))
11512 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11513 (sit-for 3)
11514 (throw 'exit nil)))
11515 t)))
11517 (defun org-refile-cache-put (set &rest identifiers)
11518 "Push the refile targets SET into the cache, under IDENTIFIERS."
11519 (let* ((key (sha1 (prin1-to-string identifiers)))
11520 (entry (assoc key org-refile-cache)))
11521 (if entry
11522 (setcdr entry set)
11523 (push (cons key set) org-refile-cache))))
11525 (defun org-refile-cache-get (&rest identifiers)
11526 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11527 (cond
11528 ((not org-refile-cache) nil)
11529 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11531 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11532 org-refile-cache))))
11533 (and set (org-refile-cache-check-set set) set)))))
11535 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11536 "Produce a table with refile targets."
11537 (let ((case-fold-search nil)
11538 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11539 (entries (or org-refile-targets '((nil . (:level . 1)))))
11540 targets tgs txt re files f desc descre fast-path-p level pos0)
11541 (message "Getting targets...")
11542 (with-current-buffer (or default-buffer (current-buffer))
11543 (while (setq entry (pop entries))
11544 (setq files (car entry) desc (cdr entry))
11545 (setq fast-path-p nil)
11546 (cond
11547 ((null files) (setq files (list (current-buffer))))
11548 ((eq files 'org-agenda-files)
11549 (setq files (org-agenda-files 'unrestricted)))
11550 ((and (symbolp files) (fboundp files))
11551 (setq files (funcall files)))
11552 ((and (symbolp files) (boundp files))
11553 (setq files (symbol-value files))))
11554 (if (stringp files) (setq files (list files)))
11555 (cond
11556 ((eq (car desc) :tag)
11557 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11558 ((eq (car desc) :todo)
11559 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11560 ((eq (car desc) :regexp)
11561 (setq descre (cdr desc)))
11562 ((eq (car desc) :level)
11563 (setq descre (concat "^\\*\\{" (number-to-string
11564 (if org-odd-levels-only
11565 (1- (* 2 (cdr desc)))
11566 (cdr desc)))
11567 "\\}[ \t]")))
11568 ((eq (car desc) :maxlevel)
11569 (setq fast-path-p t)
11570 (setq descre (concat "^\\*\\{1," (number-to-string
11571 (if org-odd-levels-only
11572 (1- (* 2 (cdr desc)))
11573 (cdr desc)))
11574 "\\}[ \t]")))
11575 (t (error "Bad refiling target description %s" desc)))
11576 (while (setq f (pop files))
11577 (with-current-buffer
11578 (if (bufferp f) f (org-get-agenda-file-buffer f))
11580 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11581 (progn
11582 (if (bufferp f) (setq f (buffer-file-name
11583 (buffer-base-buffer f))))
11584 (setq f (and f (expand-file-name f)))
11585 (if (eq org-refile-use-outline-path 'file)
11586 (push (list (file-name-nondirectory f) f nil nil) tgs))
11587 (save-excursion
11588 (save-restriction
11589 (widen)
11590 (goto-char (point-min))
11591 (while (re-search-forward descre nil t)
11592 (goto-char (setq pos0 (point-at-bol)))
11593 (catch 'next
11594 (when org-refile-target-verify-function
11595 (save-match-data
11596 (or (funcall org-refile-target-verify-function)
11597 (throw 'next t))))
11598 (when (and (looking-at org-complex-heading-regexp)
11599 (not (member (match-string 4) excluded-entries))
11600 (match-string 4))
11601 (setq level (org-reduced-level
11602 (- (match-end 1) (match-beginning 1)))
11603 txt (org-link-display-format (match-string 4))
11604 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11605 re (format org-complex-heading-regexp-format
11606 (regexp-quote (match-string 4))))
11607 (when org-refile-use-outline-path
11608 (setq txt (mapconcat
11609 'org-protect-slash
11610 (append
11611 (if (eq org-refile-use-outline-path
11612 'file)
11613 (list (file-name-nondirectory
11614 (buffer-file-name
11615 (buffer-base-buffer))))
11616 (if (eq org-refile-use-outline-path
11617 'full-file-path)
11618 (list (buffer-file-name
11619 (buffer-base-buffer)))))
11620 (org-get-outline-path fast-path-p
11621 level txt)
11622 (list txt))
11623 "/")))
11624 (push (list txt f re (org-refile-marker (point)))
11625 tgs)))
11626 (when (= (point) pos0)
11627 ;; verification function has not moved point
11628 (goto-char (point-at-eol))))))))
11629 (when org-refile-use-cache
11630 (org-refile-cache-put tgs (buffer-file-name) descre))
11631 (setq targets (append tgs targets))))))
11632 (message "Getting targets...done")
11633 (nreverse targets)))
11635 (defun org-protect-slash (s)
11636 (while (string-match "/" s)
11637 (setq s (replace-match "\\" t t s)))
11640 (defvar org-olpa (make-vector 20 nil))
11642 (defun org-get-outline-path (&optional fastp level heading)
11643 "Return the outline path to the current entry, as a list.
11645 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11646 routine which makes outline path derivations for an entire file,
11647 avoiding backtracing. Refile target collection makes use of that."
11648 (if fastp
11649 (progn
11650 (if (> level 19)
11651 (error "Outline path failure, more than 19 levels"))
11652 (loop for i from level upto 19 do
11653 (aset org-olpa i nil))
11654 (prog1
11655 (delq nil (append org-olpa nil))
11656 (aset org-olpa level heading)))
11657 (let (rtn case-fold-search)
11658 (save-excursion
11659 (save-restriction
11660 (widen)
11661 (while (org-up-heading-safe)
11662 (when (looking-at org-complex-heading-regexp)
11663 (push (org-trim
11664 (replace-regexp-in-string
11665 ;; Remove statistical/checkboxes cookies
11666 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11667 (org-match-string-no-properties 4)))
11668 rtn)))
11669 rtn)))))
11671 (defun org-format-outline-path (path &optional width prefix separator)
11672 "Format the outline path PATH for display.
11673 WIDTH is the maximum number of characters that is available.
11674 PREFIX is a prefix to be included in the returned string,
11675 such as the file name.
11676 SEPARATOR is inserted between the different parts of the path,
11677 the default is \"/\"."
11678 (setq width (or width 79))
11679 (if prefix (setq width (- width (length prefix))))
11680 (if (not path)
11681 (or prefix "")
11682 (let* ((nsteps (length path))
11683 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11684 (maxwidth (if (<= total-width width)
11685 10000 ;; everything fits
11686 ;; we need to shorten the level headings
11687 (/ (- width nsteps) nsteps)))
11688 (org-odd-levels-only nil)
11689 (n 0)
11690 (total (1+ (length prefix))))
11691 (setq maxwidth (max maxwidth 10))
11692 (concat prefix
11693 (if prefix (or separator "/"))
11694 (mapconcat
11695 (lambda (h)
11696 (setq n (1+ n))
11697 (if (and (= n nsteps) (< maxwidth 10000))
11698 (setq maxwidth (- total-width total)))
11699 (if (< (length h) maxwidth)
11700 (progn (setq total (+ total (length h) 1)) h)
11701 (setq h (substring h 0 (- maxwidth 2))
11702 total (+ total maxwidth 1))
11703 (if (string-match "[ \t]+\\'" h)
11704 (setq h (substring h 0 (match-beginning 0))))
11705 (setq h (concat h "..")))
11706 (org-add-props h nil 'face
11707 (nth (% (1- n) org-n-level-faces)
11708 org-level-faces))
11710 path (or separator "/"))))))
11712 (defun org-display-outline-path (&optional file current separator just-return-string)
11713 "Display the current outline path in the echo area.
11715 If FILE is non-nil, prepend the output with the file name.
11716 If CURRENT is non-nil, append the current heading to the output.
11717 SEPARATOR is passed through to `org-format-outline-path'. It separates
11718 the different parts of the path and defaults to \"/\".
11719 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11720 (interactive "P")
11721 (let* (case-fold-search
11722 (bfn (buffer-file-name (buffer-base-buffer)))
11723 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11724 res)
11725 (if current (setq path (append path
11726 (save-excursion
11727 (org-back-to-heading t)
11728 (if (looking-at org-complex-heading-regexp)
11729 (list (match-string 4)))))))
11730 (setq res
11731 (org-format-outline-path
11732 path
11733 (1- (frame-width))
11734 (and file bfn (concat (file-name-nondirectory bfn) separator))
11735 separator))
11736 (if just-return-string
11737 (org-no-properties res)
11738 (org-unlogged-message "%s" res))))
11740 (defvar org-refile-history nil
11741 "History for refiling operations.")
11743 (defvar org-after-refile-insert-hook nil
11744 "Hook run after `org-refile' has inserted its stuff at the new location.
11745 Note that this is still *before* the stuff will be removed from
11746 the *old* location.")
11748 (defvar org-capture-last-stored-marker)
11749 (defvar org-refile-keep nil
11750 "Non-nil means `org-refile' will copy instead of refile.")
11752 (defun org-copy ()
11753 "Like `org-refile', but copy."
11754 (interactive)
11755 (let ((org-refile-keep t))
11756 (funcall 'org-refile nil nil nil "Copy")))
11758 (defun org-refile (&optional arg default-buffer rfloc msg)
11759 "Move the entry or entries at point to another heading.
11760 The list of target headings is compiled using the information in
11761 `org-refile-targets', which see.
11763 At the target location, the entry is filed as a subitem of the
11764 target heading. Depending on `org-reverse-note-order', the new
11765 subitem will either be the first or the last subitem.
11767 If there is an active region, all entries in that region will be
11768 refiled. However, the region must fulfill the requirement that
11769 the first heading sets the top-level of the moved text.
11771 With prefix arg ARG, the command will only visit the target
11772 location and not actually move anything.
11774 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11775 refiling operation has put the subtree.
11777 With a numeric prefix argument of `2', refile to the running clock.
11779 With a numeric prefix argument of `3', emulate `org-refile-keep'
11780 being set to `t' and copy to the target location, don't move it.
11781 Beware that keeping refiled entries may result in duplicated ID
11782 properties.
11784 RFLOC can be a refile location obtained in a different way.
11786 MSG is a string to replace \"Refile\" in the default prompt with
11787 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11789 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11791 If you are using target caching (see `org-refile-use-cache'), you
11792 have to clear the target cache in order to find new targets.
11793 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11794 prefix argument (`C-u C-u C-u C-c C-w')."
11795 (interactive "P")
11796 (if (member arg '(0 (64)))
11797 (org-refile-cache-clear)
11798 (let* ((actionmsg (cond (msg msg)
11799 ((equal arg 3) "Refile (and keep)")
11800 (t "Refile")))
11801 (cbuf (current-buffer))
11802 (regionp (org-region-active-p))
11803 (region-start (and regionp (region-beginning)))
11804 (region-end (and regionp (region-end)))
11805 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11806 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11807 pos it nbuf file re level reversed)
11808 (setq last-command nil)
11809 (when regionp
11810 (goto-char region-start)
11811 (or (bolp) (goto-char (point-at-bol)))
11812 (setq region-start (point))
11813 (unless (or (org-kill-is-subtree-p
11814 (buffer-substring region-start region-end))
11815 (prog1 org-refile-active-region-within-subtree
11816 (let ((s (point-at-eol)))
11817 (org-toggle-heading)
11818 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11819 (user-error "The region is not a (sequence of) subtree(s)")))
11820 (if (equal arg '(16))
11821 (org-refile-goto-last-stored)
11822 (when (or
11823 (and (equal arg 2)
11824 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11825 (prog1
11826 (setq it (list (or org-clock-heading "running clock")
11827 (buffer-file-name
11828 (marker-buffer org-clock-hd-marker))
11830 (marker-position org-clock-hd-marker)))
11831 (setq arg nil)))
11832 (setq it (or rfloc
11833 (let (heading-text)
11834 (save-excursion
11835 (unless (and arg (listp arg))
11836 (org-back-to-heading t)
11837 (setq heading-text
11838 (replace-regexp-in-string
11839 org-bracket-link-regexp
11840 "\\3"
11841 (nth 4 (org-heading-components)))))
11842 (org-refile-get-location
11843 (cond ((and arg (listp arg)) "Goto")
11844 (regionp (concat actionmsg " region to"))
11845 (t (concat actionmsg " subtree \""
11846 heading-text "\" to")))
11847 default-buffer
11848 (and (not (equal '(4) arg))
11849 org-refile-allow-creating-parent-nodes)
11850 arg))))))
11851 (setq file (nth 1 it)
11852 re (nth 2 it)
11853 pos (nth 3 it))
11854 (if (and (not arg)
11856 (equal (buffer-file-name) file)
11857 (if regionp
11858 (and (>= pos region-start)
11859 (<= pos region-end))
11860 (and (>= pos (point))
11861 (< pos (save-excursion
11862 (org-end-of-subtree t t))))))
11863 (error "Cannot refile to position inside the tree or region"))
11864 (setq nbuf (or (find-buffer-visiting file)
11865 (find-file-noselect file)))
11866 (if (and arg (not (equal arg 3)))
11867 (progn
11868 (org-pop-to-buffer-same-window nbuf)
11869 (goto-char pos)
11870 (org-show-context 'org-goto))
11871 (if regionp
11872 (progn
11873 (org-kill-new (buffer-substring region-start region-end))
11874 (org-save-markers-in-region region-start region-end))
11875 (org-copy-subtree 1 nil t))
11876 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11877 (find-file-noselect file)))
11878 (setq reversed (org-notes-order-reversed-p))
11879 (save-excursion
11880 (save-restriction
11881 (widen)
11882 (if pos
11883 (progn
11884 (goto-char pos)
11885 (looking-at org-outline-regexp)
11886 (setq level (org-get-valid-level (funcall outline-level) 1))
11887 (goto-char
11888 (if reversed
11889 (or (outline-next-heading) (point-max))
11890 (or (save-excursion (org-get-next-sibling))
11891 (org-end-of-subtree t t)
11892 (point-max)))))
11893 (setq level 1)
11894 (if (not reversed)
11895 (goto-char (point-max))
11896 (goto-char (point-min))
11897 (or (outline-next-heading) (goto-char (point-max)))))
11898 (if (not (bolp)) (newline))
11899 (org-paste-subtree level nil nil t)
11900 (when org-log-refile
11901 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11902 (unless (eq org-log-refile 'note)
11903 (save-excursion (org-add-log-note))))
11904 (and org-auto-align-tags
11905 (let ((org-loop-over-headlines-in-active-region nil))
11906 (org-set-tags nil t)))
11907 (let ((bookmark-name (plist-get org-bookmark-names-plist
11908 :last-refile)))
11909 (when bookmark-name
11910 (with-demoted-errors
11911 (bookmark-set bookmark-name))))
11912 ;; If we are refiling for capture, make sure that the
11913 ;; last-capture pointers point here
11914 (when (org-bound-and-true-p org-refile-for-capture)
11915 (let ((bookmark-name (plist-get org-bookmark-names-plist
11916 :last-capture-marker)))
11917 (when bookmark-name
11918 (with-demoted-errors
11919 (bookmark-set bookmark-name))))
11920 (move-marker org-capture-last-stored-marker (point)))
11921 (if (fboundp 'deactivate-mark) (deactivate-mark))
11922 (run-hooks 'org-after-refile-insert-hook))))
11923 (unless org-refile-keep
11924 (if regionp
11925 (delete-region (point) (+ (point) (- region-end region-start)))
11926 (delete-region
11927 (and (org-back-to-heading t) (point))
11928 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11929 (when (featurep 'org-inlinetask)
11930 (org-inlinetask-remove-END-maybe))
11931 (setq org-markers-to-move nil)
11932 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11934 (defun org-refile-goto-last-stored ()
11935 "Go to the location where the last refile was stored."
11936 (interactive)
11937 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11938 (message "This is the location of the last refile"))
11940 (defun org-refile--get-location (refloc tbl)
11941 "When user refile to REFLOC, find the associated target in TBL.
11942 Also check `org-refile-target-table'."
11943 (car (delq
11945 (mapcar
11946 (lambda (r) (or (assoc r tbl)
11947 (assoc r org-refile-target-table)))
11948 (list (replace-regexp-in-string "/$" "" refloc)
11949 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11951 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11952 no-exclude)
11953 "Prompt the user for a refile location, using PROMPT.
11954 PROMPT should not be suffixed with a colon and a space, because
11955 this function appends the default value from
11956 `org-refile-history' automatically, if that is not empty.
11957 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11958 this is used for the GOTO interface."
11959 (let ((org-refile-targets org-refile-targets)
11960 (org-refile-use-outline-path org-refile-use-outline-path)
11961 excluded-entries)
11962 (when (and (derived-mode-p 'org-mode)
11963 (not org-refile-use-cache)
11964 (not no-exclude))
11965 (org-map-tree
11966 (lambda()
11967 (setq excluded-entries
11968 (append excluded-entries (list (org-get-heading t t)))))))
11969 (setq org-refile-target-table
11970 (org-refile-get-targets default-buffer excluded-entries)))
11971 (unless org-refile-target-table
11972 (user-error "No refile targets"))
11973 (let* ((cbuf (current-buffer))
11974 (partial-completion-mode nil)
11975 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11976 (cfunc (if (and org-refile-use-outline-path
11977 org-outline-path-complete-in-steps)
11978 'org-olpath-completing-read
11979 'org-icompleting-read))
11980 (extra (if org-refile-use-outline-path "/" ""))
11981 (cbnex (concat (buffer-name) extra))
11982 (filename (and cfn (expand-file-name cfn)))
11983 (tbl (mapcar
11984 (lambda (x)
11985 (if (and (not (member org-refile-use-outline-path
11986 '(file full-file-path)))
11987 (not (equal filename (nth 1 x))))
11988 (cons (concat (car x) extra " ("
11989 (file-name-nondirectory (nth 1 x)) ")")
11990 (cdr x))
11991 (cons (concat (car x) extra) (cdr x))))
11992 org-refile-target-table))
11993 (completion-ignore-case t)
11994 cdef
11995 (prompt (concat prompt
11996 (or (and (car org-refile-history)
11997 (concat " (default " (car org-refile-history) ")"))
11998 (and (assoc cbnex tbl) (setq cdef cbnex)
11999 (concat " (default " cbnex ")"))) ": "))
12000 pa answ parent-target child parent old-hist)
12001 (setq old-hist org-refile-history)
12002 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12003 nil 'org-refile-history (or cdef (car org-refile-history))))
12004 (if (setq pa (org-refile--get-location answ tbl))
12005 (progn
12006 (org-refile-check-position pa)
12007 (when (or (not org-refile-history)
12008 (not (eq old-hist org-refile-history))
12009 (not (equal (car pa) (car org-refile-history))))
12010 (setq org-refile-history
12011 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12012 org-refile-history
12013 (cdr org-refile-history))))
12014 (if (equal (car org-refile-history) (nth 1 org-refile-history))
12015 (pop org-refile-history)))
12017 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12018 (progn
12019 (setq parent (match-string 1 answ)
12020 child (match-string 2 answ))
12021 (setq parent-target (org-refile--get-location parent tbl))
12022 (when (and parent-target
12023 (or (eq new-nodes t)
12024 (and (eq new-nodes 'confirm)
12025 (y-or-n-p (format "Create new node \"%s\"? "
12026 child)))))
12027 (org-refile-new-child parent-target child)))
12028 (user-error "Invalid target location")))))
12030 (declare-function org-string-nw-p "org-macs" (s))
12031 (defun org-refile-check-position (refile-pointer)
12032 "Check if the refile pointer matches the headline to which it points."
12033 (let* ((file (nth 1 refile-pointer))
12034 (re (nth 2 refile-pointer))
12035 (pos (nth 3 refile-pointer))
12036 buffer)
12037 (if (and (not (markerp pos)) (not file))
12038 (user-error "Please indicate a target file in the refile path")
12039 (when (org-string-nw-p re)
12040 (setq buffer (if (markerp pos)
12041 (marker-buffer pos)
12042 (or (find-buffer-visiting file)
12043 (find-file-noselect file))))
12044 (with-current-buffer buffer
12045 (save-excursion
12046 (save-restriction
12047 (widen)
12048 (goto-char pos)
12049 (beginning-of-line 1)
12050 (unless (org-looking-at-p re)
12051 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12053 (defun org-refile-new-child (parent-target child)
12054 "Use refile target PARENT-TARGET to add new CHILD below it."
12055 (unless parent-target
12056 (error "Cannot find parent for new node"))
12057 (let ((file (nth 1 parent-target))
12058 (pos (nth 3 parent-target))
12059 level)
12060 (with-current-buffer (or (find-buffer-visiting file)
12061 (find-file-noselect file))
12062 (save-excursion
12063 (save-restriction
12064 (widen)
12065 (if pos
12066 (goto-char pos)
12067 (goto-char (point-max))
12068 (if (not (bolp)) (newline)))
12069 (when (looking-at org-outline-regexp)
12070 (setq level (funcall outline-level))
12071 (org-end-of-subtree t t))
12072 (org-back-over-empty-lines)
12073 (insert "\n" (make-string
12074 (if pos (org-get-valid-level level 1) 1) ?*)
12075 " " child "\n")
12076 (beginning-of-line 0)
12077 (list (concat (car parent-target) "/" child) file "" (point)))))))
12079 (defun org-olpath-completing-read (prompt collection &rest args)
12080 "Read an outline path like a file name."
12081 (let ((thetable collection)
12082 (org-completion-use-ido nil) ; does not work with ido.
12083 (org-completion-use-iswitchb nil)) ; or iswitchb
12084 (apply
12085 'org-icompleting-read prompt
12086 (lambda (string predicate &optional flag)
12087 (let (rtn r f (l (length string)))
12088 (cond
12089 ((eq flag nil)
12090 ;; try completion
12091 (try-completion string thetable))
12092 ((eq flag t)
12093 ;; all-completions
12094 (setq rtn (all-completions string thetable predicate))
12095 (mapcar
12096 (lambda (x)
12097 (setq r (substring x l))
12098 (if (string-match " ([^)]*)$" x)
12099 (setq f (match-string 0 x))
12100 (setq f ""))
12101 (if (string-match "/" r)
12102 (concat string (substring r 0 (match-end 0)) f)
12104 rtn))
12105 ((eq flag 'lambda)
12106 ;; exact match?
12107 (assoc string thetable)))))
12108 args)))
12110 ;;;; Dynamic blocks
12112 (defun org-find-dblock (name)
12113 "Find the first dynamic block with name NAME in the buffer.
12114 If not found, stay at current position and return nil."
12115 (let ((case-fold-search t) pos)
12116 (save-excursion
12117 (goto-char (point-min))
12118 (setq pos (and (re-search-forward
12119 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12120 (match-beginning 0))))
12121 (if pos (goto-char pos))
12122 pos))
12124 (defun org-create-dblock (plist)
12125 "Create a dynamic block section, with parameters taken from PLIST.
12126 PLIST must contain a :name entry which is used as the name of the block."
12127 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12128 (end-of-line 1)
12129 (newline))
12130 (let ((col (current-column))
12131 (name (plist-get plist :name)))
12132 (insert "#+BEGIN: " name)
12133 (while plist
12134 (if (eq (car plist) :name)
12135 (setq plist (cddr plist))
12136 (insert " " (prin1-to-string (pop plist)))))
12137 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12138 (beginning-of-line -2)))
12140 (defun org-prepare-dblock ()
12141 "Prepare dynamic block for refresh.
12142 This empties the block, puts the cursor at the insert position and returns
12143 the property list including an extra property :name with the block name."
12144 (unless (looking-at org-dblock-start-re)
12145 (user-error "Not at a dynamic block"))
12146 (let* ((begdel (1+ (match-end 0)))
12147 (name (org-no-properties (match-string 1)))
12148 (params (append (list :name name)
12149 (read (concat "(" (match-string 3) ")")))))
12150 (save-excursion
12151 (beginning-of-line 1)
12152 (skip-chars-forward " \t")
12153 (setq params (plist-put params :indentation-column (current-column))))
12154 (unless (re-search-forward org-dblock-end-re nil t)
12155 (error "Dynamic block not terminated"))
12156 (setq params
12157 (append params
12158 (list :content (buffer-substring
12159 begdel (match-beginning 0)))))
12160 (delete-region begdel (match-beginning 0))
12161 (goto-char begdel)
12162 (open-line 1)
12163 params))
12165 (defun org-map-dblocks (&optional command)
12166 "Apply COMMAND to all dynamic blocks in the current buffer.
12167 If COMMAND is not given, use `org-update-dblock'."
12168 (let ((cmd (or command 'org-update-dblock)))
12169 (save-excursion
12170 (goto-char (point-min))
12171 (while (re-search-forward org-dblock-start-re nil t)
12172 (goto-char (match-beginning 0))
12173 (save-excursion
12174 (condition-case nil
12175 (funcall cmd)
12176 (error (message "Error during update of dynamic block"))))
12177 (unless (re-search-forward org-dblock-end-re nil t)
12178 (error "Dynamic block not terminated"))))))
12180 (defun org-dblock-update (&optional arg)
12181 "User command for updating dynamic blocks.
12182 Update the dynamic block at point. With prefix ARG, update all dynamic
12183 blocks in the buffer."
12184 (interactive "P")
12185 (if arg
12186 (org-update-all-dblocks)
12187 (or (looking-at org-dblock-start-re)
12188 (org-beginning-of-dblock))
12189 (org-update-dblock)))
12191 (defun org-update-dblock ()
12192 "Update the dynamic block at point.
12193 This means to empty the block, parse for parameters and then call
12194 the correct writing function."
12195 (interactive)
12196 (save-excursion
12197 (let* ((win (selected-window))
12198 (pos (point))
12199 (line (org-current-line))
12200 (params (org-prepare-dblock))
12201 (name (plist-get params :name))
12202 (indent (plist-get params :indentation-column))
12203 (cmd (intern (concat "org-dblock-write:" name))))
12204 (message "Updating dynamic block `%s' at line %d..." name line)
12205 (funcall cmd params)
12206 (message "Updating dynamic block `%s' at line %d...done" name line)
12207 (goto-char pos)
12208 (when (and indent (> indent 0))
12209 (setq indent (make-string indent ?\ ))
12210 (save-excursion
12211 (select-window win)
12212 (org-beginning-of-dblock)
12213 (forward-line 1)
12214 (while (not (looking-at org-dblock-end-re))
12215 (insert indent)
12216 (beginning-of-line 2))
12217 (when (looking-at org-dblock-end-re)
12218 (and (looking-at "[ \t]+")
12219 (replace-match ""))
12220 (insert indent)))))))
12222 (defun org-beginning-of-dblock ()
12223 "Find the beginning of the dynamic block at point.
12224 Error if there is no such block at point."
12225 (let ((pos (point))
12226 beg)
12227 (end-of-line 1)
12228 (if (and (re-search-backward org-dblock-start-re nil t)
12229 (setq beg (match-beginning 0))
12230 (re-search-forward org-dblock-end-re nil t)
12231 (> (match-end 0) pos))
12232 (goto-char beg)
12233 (goto-char pos)
12234 (error "Not in a dynamic block"))))
12236 (defun org-update-all-dblocks ()
12237 "Update all dynamic blocks in the buffer.
12238 This function can be used in a hook."
12239 (interactive)
12240 (when (derived-mode-p 'org-mode)
12241 (org-map-dblocks 'org-update-dblock)))
12244 ;;;; Completion
12246 (declare-function org-export-backend-name "org-export" (cl-x))
12247 (declare-function org-export-backend-options "org-export" (cl-x))
12248 (defun org-get-export-keywords ()
12249 "Return a list of all currently understood export keywords.
12250 Export keywords include options, block names, attributes and
12251 keywords relative to each registered export back-end."
12252 (let (keywords)
12253 (dolist (backend
12254 (org-bound-and-true-p org-export--registered-backends)
12255 (delq nil keywords))
12256 ;; Back-end name (for keywords, like #+LATEX:)
12257 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12258 (dolist (option-entry (org-export-backend-options backend))
12259 ;; Back-end options.
12260 (push (nth 1 option-entry) keywords)))))
12262 (defconst org-options-keywords
12263 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12264 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12265 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12266 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12267 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12269 (defcustom org-structure-template-alist
12270 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12271 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12272 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12273 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12274 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12275 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12276 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12277 ("L" "#+LaTeX: ")
12278 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12279 ("H" "#+HTML: ")
12280 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12281 ("A" "#+ASCII: ")
12282 ("i" "#+INDEX: ?")
12283 ("I" "#+INCLUDE: %file ?"))
12284 "Structure completion elements.
12285 This is a list of abbreviation keys and values. The value gets inserted
12286 if you type `<' followed by the key and then press the completion key,
12287 usually `TAB'. %file will be replaced by a file name after prompting
12288 for the file using completion. The cursor will be placed at the position
12289 of the `?` in the template.
12290 There are two templates for each key, the first uses the original Org syntax,
12291 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12292 the default when the /org-mtags.el/ module has been loaded. See also the
12293 variable `org-mtags-prefer-muse-templates'."
12294 :group 'org-completion
12295 :type '(repeat
12296 (list
12297 (string :tag "Key")
12298 (string :tag "Template")))
12299 :version 24.4
12300 :package-version '(Org . "8.3"))
12302 (defun org-try-structure-completion ()
12303 "Try to complete a structure template before point.
12304 This looks for strings like \"<e\" on an otherwise empty line and
12305 expands them."
12306 (let ((l (buffer-substring (point-at-bol) (point)))
12308 (when (and (looking-at "[ \t]*$")
12309 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12310 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12311 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12312 (match-beginning 1)) a)
12313 t)))
12315 (defun org-complete-expand-structure-template (start cell)
12316 "Expand a structure template."
12317 (let ((rpl (nth 1 cell))
12318 (ind ""))
12319 (delete-region start (point))
12320 (when (string-match "\\`[ \t]*#\\+" rpl)
12321 (cond
12322 ((bolp))
12323 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12324 (setq ind (buffer-substring (point-at-bol) (point))))
12325 (t (newline))))
12326 (setq start (point))
12327 (if (string-match "%file" rpl)
12328 (setq rpl (replace-match
12329 (concat
12330 "\""
12331 (save-match-data
12332 (abbreviate-file-name (read-file-name "Include file: ")))
12333 "\"")
12334 t t rpl)))
12335 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12336 (concat "\n" ind)))
12337 (insert rpl)
12338 (if (re-search-backward "\\?" start t) (delete-char 1))))
12340 ;;;; TODO, DEADLINE, Comments
12342 (defun org-toggle-comment ()
12343 "Change the COMMENT state of an entry."
12344 (interactive)
12345 (save-excursion
12346 (org-back-to-heading)
12347 (looking-at org-complex-heading-regexp)
12348 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12349 (skip-chars-forward " \t")
12350 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12351 (if (org-in-commented-heading-p t)
12352 (delete-region (point)
12353 (progn (search-forward " " (line-end-position) 'move)
12354 (skip-chars-forward " \t")
12355 (point)))
12356 (insert org-comment-string)
12357 (unless (eolp) (insert " ")))))
12359 (defvar org-last-todo-state-is-todo nil
12360 "This is non-nil when the last TODO state change led to a TODO state.
12361 If the last change removed the TODO tag or switched to DONE, then
12362 this is nil.")
12364 (defvar org-setting-tags nil) ; dynamically skipped
12366 (defvar org-todo-setup-filter-hook nil
12367 "Hook for functions that pre-filter todo specs.
12368 Each function takes a todo spec and returns either nil or the spec
12369 transformed into canonical form." )
12371 (defvar org-todo-get-default-hook nil
12372 "Hook for functions that get a default item for todo.
12373 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12374 nil or a string to be used for the todo mark." )
12376 (defvar org-agenda-headline-snapshot-before-repeat)
12378 (defun org-current-effective-time ()
12379 "Return current time adjusted for `org-extend-today-until' variable."
12380 (let* ((ct (org-current-time))
12381 (dct (decode-time ct))
12382 (ct1
12383 (cond
12384 (org-use-last-clock-out-time-as-effective-time
12385 (or (org-clock-get-last-clock-out-time) ct))
12386 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12387 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12388 (t ct))))
12389 ct1))
12391 (defun org-todo-yesterday (&optional arg)
12392 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12393 (interactive "P")
12394 (if (eq major-mode 'org-agenda-mode)
12395 (apply 'org-agenda-todo-yesterday arg)
12396 (let* ((hour (third (decode-time
12397 (org-current-time))))
12398 (org-extend-today-until (1+ hour)))
12399 (org-todo arg))))
12401 (defvar org-block-entry-blocking ""
12402 "First entry preventing the TODO state change.")
12404 (defun org-cancel-repeater ()
12405 "Cancel a repeater by setting its numeric value to zero."
12406 (interactive)
12407 (save-excursion
12408 (org-back-to-heading t)
12409 (let ((bound1 (point))
12410 (bound0 (save-excursion (outline-next-heading) (point))))
12411 (when (re-search-forward
12412 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12413 org-deadline-time-regexp "\\)\\|\\("
12414 org-ts-regexp "\\)")
12415 bound0 t)
12416 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12417 (replace-match "0" t nil nil 1))))))
12419 (defun org-todo (&optional arg)
12420 "Change the TODO state of an item.
12421 The state of an item is given by a keyword at the start of the heading,
12422 like
12423 *** TODO Write paper
12424 *** DONE Call mom
12426 The different keywords are specified in the variable `org-todo-keywords'.
12427 By default the available states are \"TODO\" and \"DONE\".
12428 So for this example: when the item starts with TODO, it is changed to DONE.
12429 When it starts with DONE, the DONE is removed. And when neither TODO nor
12430 DONE are present, add TODO at the beginning of the heading.
12432 With \\[universal-argument] prefix arg, use completion to determine the new \
12433 state.
12434 With numeric prefix arg, switch to that state.
12435 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12436 keywords (nextset).
12437 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12438 With a numeric prefix arg of 0, inhibit note taking for the change.
12439 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12441 When called through ELisp, arg is also interpreted in the following way:
12442 'none -> empty state
12443 \"\"(empty string) -> switch to empty state
12444 'done -> switch to DONE
12445 'nextset -> switch to the next set of keywords
12446 'previousset -> switch to the previous set of keywords
12447 \"WAITING\" -> switch to the specified keyword, but only if it
12448 really is a member of `org-todo-keywords'."
12449 (interactive "P")
12450 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12451 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12452 'region-start-level 'region))
12453 org-loop-over-headlines-in-active-region)
12454 (org-map-entries
12455 `(org-todo ,arg)
12456 org-loop-over-headlines-in-active-region
12457 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12458 (if (equal arg '(16)) (setq arg 'nextset))
12459 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12460 (let ((org-blocker-hook org-blocker-hook)
12461 commentp
12462 case-fold-search)
12463 (when (equal arg '(64))
12464 (setq arg nil org-blocker-hook nil))
12465 (when (and org-blocker-hook
12466 (or org-inhibit-blocking
12467 (org-entry-get nil "NOBLOCKING")))
12468 (setq org-blocker-hook nil))
12469 (save-excursion
12470 (catch 'exit
12471 (org-back-to-heading t)
12472 (when (org-in-commented-heading-p t)
12473 (org-toggle-comment)
12474 (setq commentp t))
12475 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12476 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12477 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12478 (let* ((match-data (match-data))
12479 (startpos (point-at-bol))
12480 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12481 (org-log-done org-log-done)
12482 (org-log-repeat org-log-repeat)
12483 (org-todo-log-states org-todo-log-states)
12484 (org-inhibit-logging
12485 (if (equal arg 0)
12486 (progn (setq arg nil) 'note) org-inhibit-logging))
12487 (this (match-string 1))
12488 (hl-pos (match-beginning 0))
12489 (head (org-get-todo-sequence-head this))
12490 (ass (assoc head org-todo-kwd-alist))
12491 (interpret (nth 1 ass))
12492 (done-word (nth 3 ass))
12493 (final-done-word (nth 4 ass))
12494 (org-last-state (or this ""))
12495 (completion-ignore-case t)
12496 (member (member this org-todo-keywords-1))
12497 (tail (cdr member))
12498 (org-state (cond
12499 ((and org-todo-key-trigger
12500 (or (and (equal arg '(4))
12501 (eq org-use-fast-todo-selection 'prefix))
12502 (and (not arg) org-use-fast-todo-selection
12503 (not (eq org-use-fast-todo-selection
12504 'prefix)))))
12505 ;; Use fast selection
12506 (org-fast-todo-selection))
12507 ((and (equal arg '(4))
12508 (or (not org-use-fast-todo-selection)
12509 (not org-todo-key-trigger)))
12510 ;; Read a state with completion
12511 (org-icompleting-read
12512 "State: " (mapcar 'list org-todo-keywords-1)
12513 nil t))
12514 ((eq arg 'right)
12515 (if this
12516 (if tail (car tail) nil)
12517 (car org-todo-keywords-1)))
12518 ((eq arg 'left)
12519 (if (equal member org-todo-keywords-1)
12521 (if this
12522 (nth (- (length org-todo-keywords-1)
12523 (length tail) 2)
12524 org-todo-keywords-1)
12525 (org-last org-todo-keywords-1))))
12526 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12527 (setq arg nil))) ; hack to fall back to cycling
12528 (arg
12529 ;; user or caller requests a specific state
12530 (cond
12531 ((equal arg "") nil)
12532 ((eq arg 'none) nil)
12533 ((eq arg 'done) (or done-word (car org-done-keywords)))
12534 ((eq arg 'nextset)
12535 (or (car (cdr (member head org-todo-heads)))
12536 (car org-todo-heads)))
12537 ((eq arg 'previousset)
12538 (let ((org-todo-heads (reverse org-todo-heads)))
12539 (or (car (cdr (member head org-todo-heads)))
12540 (car org-todo-heads))))
12541 ((car (member arg org-todo-keywords-1)))
12542 ((stringp arg)
12543 (user-error "State `%s' not valid in this file" arg))
12544 ((nth (1- (prefix-numeric-value arg))
12545 org-todo-keywords-1))))
12546 ((null member) (or head (car org-todo-keywords-1)))
12547 ((equal this final-done-word) nil) ;; -> make empty
12548 ((null tail) nil) ;; -> first entry
12549 ((memq interpret '(type priority))
12550 (if (eq this-command last-command)
12551 (car tail)
12552 (if (> (length tail) 0)
12553 (or done-word (car org-done-keywords))
12554 nil)))
12556 (car tail))))
12557 (org-state (or
12558 (run-hook-with-args-until-success
12559 'org-todo-get-default-hook org-state org-last-state)
12560 org-state))
12561 (next (if org-state (concat " " org-state " ") " "))
12562 (change-plist (list :type 'todo-state-change :from this :to org-state
12563 :position startpos))
12564 dolog now-done-p)
12565 (when org-blocker-hook
12566 (setq org-last-todo-state-is-todo
12567 (not (member this org-done-keywords)))
12568 (unless (save-excursion
12569 (save-match-data
12570 (org-with-wide-buffer
12571 (run-hook-with-args-until-failure
12572 'org-blocker-hook change-plist))))
12573 (if (org-called-interactively-p 'interactive)
12574 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12575 this org-state org-block-entry-blocking)
12576 ;; fail silently
12577 (message "TODO state change from %s to %s blocked (by \"%s\")"
12578 this org-state org-block-entry-blocking)
12579 (throw 'exit nil))))
12580 (store-match-data match-data)
12581 (replace-match next t t)
12582 (cond ((equal this org-state)
12583 (message "TODO state was already %s" (org-trim next)))
12584 ((pos-visible-in-window-p hl-pos)
12585 (message "TODO state changed to %s" (org-trim next))))
12586 (unless head
12587 (setq head (org-get-todo-sequence-head org-state)
12588 ass (assoc head org-todo-kwd-alist)
12589 interpret (nth 1 ass)
12590 done-word (nth 3 ass)
12591 final-done-word (nth 4 ass)))
12592 (when (memq arg '(nextset previousset))
12593 (message "Keyword-Set %d/%d: %s"
12594 (- (length org-todo-sets) -1
12595 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12596 (length org-todo-sets)
12597 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12598 (setq org-last-todo-state-is-todo
12599 (not (member org-state org-done-keywords)))
12600 (setq now-done-p (and (member org-state org-done-keywords)
12601 (not (member this org-done-keywords))))
12602 (and logging (org-local-logging logging))
12603 (when (and (or org-todo-log-states org-log-done)
12604 (not (eq org-inhibit-logging t))
12605 (not (memq arg '(nextset previousset))))
12606 ;; we need to look at recording a time and note
12607 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12608 (nth 2 (assoc this org-todo-log-states))))
12609 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12610 (setq dolog 'time))
12611 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12612 (and org-state
12613 (member org-state org-not-done-keywords)
12614 (not (member this org-not-done-keywords))))
12615 ;; This is now a todo state and was not one before
12616 ;; If there was a CLOSED time stamp, get rid of it.
12617 (org-add-planning-info nil nil 'closed))
12618 (when (and now-done-p org-log-done)
12619 ;; It is now done, and it was not done before
12620 (org-add-planning-info 'closed (org-current-effective-time))
12621 (if (and (not dolog) (eq 'note org-log-done))
12622 (org-add-log-setup 'done org-state this 'findpos 'note)))
12623 (when (and org-state dolog)
12624 ;; This is a non-nil state, and we need to log it
12625 (org-add-log-setup 'state org-state this 'findpos dolog)))
12626 ;; Fixup tag positioning
12627 (org-todo-trigger-tag-changes org-state)
12628 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12629 (when org-provide-todo-statistics
12630 (org-update-parent-todo-statistics))
12631 (run-hooks 'org-after-todo-state-change-hook)
12632 (if (and arg (not (member org-state org-done-keywords)))
12633 (setq head (org-get-todo-sequence-head org-state)))
12634 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12635 ;; Do we need to trigger a repeat?
12636 (when now-done-p
12637 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12638 ;; This is for the agenda, take a snapshot of the headline.
12639 (save-match-data
12640 (setq org-agenda-headline-snapshot-before-repeat
12641 (org-get-heading))))
12642 (org-auto-repeat-maybe org-state))
12643 ;; Fixup cursor location if close to the keyword
12644 (if (and (outline-on-heading-p)
12645 (not (bolp))
12646 (save-excursion (beginning-of-line 1)
12647 (looking-at org-todo-line-regexp))
12648 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12649 (progn
12650 (goto-char (or (match-end 2) (match-end 1)))
12651 (and (looking-at " ") (just-one-space))))
12652 (when org-trigger-hook
12653 (save-excursion
12654 (run-hook-with-args 'org-trigger-hook change-plist)))
12655 (when commentp (org-toggle-comment))))))))
12657 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12658 "Block turning an entry into a TODO, using the hierarchy.
12659 This checks whether the current task should be blocked from state
12660 changes. Such blocking occurs when:
12662 1. The task has children which are not all in a completed state.
12664 2. A task has a parent with the property :ORDERED:, and there
12665 are siblings prior to the current task with incomplete
12666 status.
12668 3. The parent of the task is blocked because it has siblings that should
12669 be done first, or is child of a block grandparent TODO entry."
12671 (if (not org-enforce-todo-dependencies)
12672 t ; if locally turned off don't block
12673 (catch 'dont-block
12674 ;; If this is not a todo state change, or if this entry is already DONE,
12675 ;; do not block
12676 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12677 (member (plist-get change-plist :from)
12678 (cons 'done org-done-keywords))
12679 (member (plist-get change-plist :to)
12680 (cons 'todo org-not-done-keywords))
12681 (not (plist-get change-plist :to)))
12682 (throw 'dont-block t))
12683 ;; If this task has children, and any are undone, it's blocked
12684 (save-excursion
12685 (org-back-to-heading t)
12686 (let ((this-level (funcall outline-level)))
12687 (outline-next-heading)
12688 (let ((child-level (funcall outline-level)))
12689 (while (and (not (eobp))
12690 (> child-level this-level))
12691 ;; this todo has children, check whether they are all
12692 ;; completed
12693 (if (and (not (org-entry-is-done-p))
12694 (org-entry-is-todo-p))
12695 (progn (setq org-block-entry-blocking (org-get-heading))
12696 (throw 'dont-block nil)))
12697 (outline-next-heading)
12698 (setq child-level (funcall outline-level))))))
12699 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12700 ;; any previous siblings are undone, it's blocked
12701 (save-excursion
12702 (org-back-to-heading t)
12703 (let* ((pos (point))
12704 (parent-pos (and (org-up-heading-safe) (point))))
12705 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12706 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12707 (forward-line 1)
12708 (re-search-forward org-not-done-heading-regexp pos t))
12709 (setq org-block-entry-blocking (match-string 0))
12710 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12711 ;; Search further up the hierarchy, to see if an ancestor is blocked
12712 (while t
12713 (goto-char parent-pos)
12714 (if (not (looking-at org-not-done-heading-regexp))
12715 (throw 'dont-block t)) ; do not block, parent is not a TODO
12716 (setq pos (point))
12717 (setq parent-pos (and (org-up-heading-safe) (point)))
12718 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12719 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12720 (forward-line 1)
12721 (re-search-forward org-not-done-heading-regexp pos t)
12722 (setq org-block-entry-blocking (org-get-heading)))
12723 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12725 (defcustom org-track-ordered-property-with-tag nil
12726 "Should the ORDERED property also be shown as a tag?
12727 The ORDERED property decides if an entry should require subtasks to be
12728 completed in sequence. Since a property is not very visible, setting
12729 this option means that toggling the ORDERED property with the command
12730 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12731 not relevant for the behavior, but it makes things more visible.
12733 Note that toggling the tag with tags commands will not change the property
12734 and therefore not influence behavior!
12736 This can be t, meaning the tag ORDERED should be used, It can also be a
12737 string to select a different tag for this task."
12738 :group 'org-todo
12739 :type '(choice
12740 (const :tag "No tracking" nil)
12741 (const :tag "Track with ORDERED tag" t)
12742 (string :tag "Use other tag")))
12744 (defun org-toggle-ordered-property ()
12745 "Toggle the ORDERED property of the current entry.
12746 For better visibility, you can track the value of this property with a tag.
12747 See variable `org-track-ordered-property-with-tag'."
12748 (interactive)
12749 (let* ((t1 org-track-ordered-property-with-tag)
12750 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12751 (save-excursion
12752 (org-back-to-heading)
12753 (if (org-entry-get nil "ORDERED")
12754 (progn
12755 (org-delete-property "ORDERED")
12756 (and tag (org-toggle-tag tag 'off))
12757 (message "Subtasks can be completed in arbitrary order"))
12758 (org-entry-put nil "ORDERED" "t")
12759 (and tag (org-toggle-tag tag 'on))
12760 (message "Subtasks must be completed in sequence")))))
12762 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12763 (defun org-block-todo-from-checkboxes (change-plist)
12764 "Block turning an entry into a TODO, using checkboxes.
12765 This checks whether the current task should be blocked from state
12766 changes because there are unchecked boxes in this entry."
12767 (if (not org-enforce-todo-checkbox-dependencies)
12768 t ; if locally turned off don't block
12769 (catch 'dont-block
12770 ;; If this is not a todo state change, or if this entry is already DONE,
12771 ;; do not block
12772 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12773 (member (plist-get change-plist :from)
12774 (cons 'done org-done-keywords))
12775 (member (plist-get change-plist :to)
12776 (cons 'todo org-not-done-keywords))
12777 (not (plist-get change-plist :to)))
12778 (throw 'dont-block t))
12779 ;; If this task has checkboxes that are not checked, it's blocked
12780 (save-excursion
12781 (org-back-to-heading t)
12782 (let ((beg (point)) end)
12783 (outline-next-heading)
12784 (setq end (point))
12785 (goto-char beg)
12786 (if (org-list-search-forward
12787 (concat (org-item-beginning-re)
12788 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12789 "\\[[- ]\\]")
12790 end t)
12791 (progn
12792 (if (boundp 'org-blocked-by-checkboxes)
12793 (setq org-blocked-by-checkboxes t))
12794 (throw 'dont-block nil)))))
12795 t))) ; do not block
12797 (defun org-entry-blocked-p ()
12798 "Is the current entry blocked?"
12799 (org-with-silent-modifications
12800 (if (org-entry-get nil "NOBLOCKING")
12801 nil ;; Never block this entry
12802 (not (run-hook-with-args-until-failure
12803 'org-blocker-hook
12804 (list :type 'todo-state-change
12805 :position (point)
12806 :from 'todo
12807 :to 'done))))))
12809 (defun org-update-statistics-cookies (all)
12810 "Update the statistics cookie, either from TODO or from checkboxes.
12811 This should be called with the cursor in a line with a statistics cookie."
12812 (interactive "P")
12813 (if all
12814 (progn
12815 (org-update-checkbox-count 'all)
12816 (org-map-entries 'org-update-parent-todo-statistics))
12817 (if (not (org-at-heading-p))
12818 (org-update-checkbox-count)
12819 (let ((pos (point-marker))
12820 end l1 l2)
12821 (ignore-errors (org-back-to-heading t))
12822 (if (not (org-at-heading-p))
12823 (org-update-checkbox-count)
12824 (setq l1 (org-outline-level))
12825 (setq end (save-excursion
12826 (outline-next-heading)
12827 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12828 (point)))
12829 (if (and (save-excursion
12830 (re-search-forward
12831 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12832 (not (save-excursion (re-search-forward
12833 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12834 (org-update-checkbox-count)
12835 (if (and l2 (> l2 l1))
12836 (progn
12837 (goto-char end)
12838 (org-update-parent-todo-statistics))
12839 (goto-char pos)
12840 (beginning-of-line 1)
12841 (while (re-search-forward
12842 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12843 (point-at-eol) t)
12844 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12845 (goto-char pos)
12846 (move-marker pos nil)))))
12848 (defvar org-entry-property-inherited-from) ;; defined below
12849 (defun org-update-parent-todo-statistics ()
12850 "Update any statistics cookie in the parent of the current headline.
12851 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12852 the entire subtree and this will travel up the hierarchy and update
12853 statistics everywhere."
12854 (let* ((prop (save-excursion (org-up-heading-safe)
12855 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12856 (recursive (or (not org-hierarchical-todo-statistics)
12857 (and prop (string-match "\\<recursive\\>" prop))))
12858 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12860 (first t)
12861 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12862 level ltoggle l1 new ndel
12863 (cnt-all 0) (cnt-done 0) is-percent kwd
12864 checkbox-beg ov ovs ove cookie-present)
12865 (catch 'exit
12866 (save-excursion
12867 (beginning-of-line 1)
12868 (setq ltoggle (funcall outline-level))
12869 ;; Three situations are to consider:
12871 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12872 ;; to the top-level ancestor on the headline;
12874 ;; 2. If parent has "recursive" property, repeat up to the
12875 ;; headline setting that property, taking inheritance into
12876 ;; account;
12878 ;; 3. Else, move up to direct parent and proceed only once.
12879 (while (and (setq level (org-up-heading-safe))
12880 (or recursive first)
12881 (>= (point) lim))
12882 (setq first nil cookie-present nil)
12883 (unless (and level
12884 (not (string-match
12885 "\\<checkbox\\>"
12886 (downcase (or (org-entry-get nil "COOKIE_DATA")
12887 "")))))
12888 (throw 'exit nil))
12889 (while (re-search-forward box-re (point-at-eol) t)
12890 (setq cnt-all 0 cnt-done 0 cookie-present t)
12891 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12892 (save-match-data
12893 (unless (outline-next-heading) (throw 'exit nil))
12894 (while (and (looking-at org-complex-heading-regexp)
12895 (> (setq l1 (length (match-string 1))) level))
12896 (setq kwd (and (or recursive (= l1 ltoggle))
12897 (match-string 2)))
12898 (if (or (eq org-provide-todo-statistics 'all-headlines)
12899 (and (eq org-provide-todo-statistics t)
12900 (or (member kwd org-done-keywords)))
12901 (and (listp org-provide-todo-statistics)
12902 (stringp (car org-provide-todo-statistics))
12903 (or (member kwd org-provide-todo-statistics)
12904 (member kwd org-done-keywords)))
12905 (and (listp org-provide-todo-statistics)
12906 (listp (car org-provide-todo-statistics))
12907 (or (member kwd (car org-provide-todo-statistics))
12908 (and (member kwd org-done-keywords)
12909 (member kwd (cadr org-provide-todo-statistics))))))
12910 (setq cnt-all (1+ cnt-all))
12911 (if (eq org-provide-todo-statistics t)
12912 (and kwd (setq cnt-all (1+ cnt-all)))))
12913 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12914 (member kwd org-done-keywords))
12915 (and (listp org-provide-todo-statistics)
12916 (listp (car org-provide-todo-statistics))
12917 (member kwd org-done-keywords)
12918 (member kwd (cadr org-provide-todo-statistics)))
12919 (and (listp org-provide-todo-statistics)
12920 (stringp (car org-provide-todo-statistics))
12921 (member kwd org-done-keywords)))
12922 (setq cnt-done (1+ cnt-done)))
12923 (outline-next-heading)))
12924 (setq new
12925 (if is-percent
12926 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12927 (format "[%d/%d]" cnt-done cnt-all))
12928 ndel (- (match-end 0) checkbox-beg))
12929 ;; handle overlays when updating cookie from column view
12930 (when (setq ov (car (overlays-at checkbox-beg)))
12931 (setq ovs (overlay-start ov) ove (overlay-end ov))
12932 (delete-overlay ov))
12933 (goto-char checkbox-beg)
12934 (insert new)
12935 (delete-region (point) (+ (point) ndel))
12936 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12937 (when ov (move-overlay ov ovs ove)))
12938 (when cookie-present
12939 (run-hook-with-args 'org-after-todo-statistics-hook
12940 cnt-done (- cnt-all cnt-done))))))
12941 (run-hooks 'org-todo-statistics-hook)))
12943 (defvar org-after-todo-statistics-hook nil
12944 "Hook that is called after a TODO statistics cookie has been updated.
12945 Each function is called with two arguments: the number of not-done entries
12946 and the number of done entries.
12948 For example, the following function, when added to this hook, will switch
12949 an entry to DONE when all children are done, and back to TODO when new
12950 entries are set to a TODO status. Note that this hook is only called
12951 when there is a statistics cookie in the headline!
12953 (defun org-summary-todo (n-done n-not-done)
12954 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12955 (let (org-log-done org-log-states) ; turn off logging
12956 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12959 (defvar org-todo-statistics-hook nil
12960 "Hook that is run whenever Org thinks TODO statistics should be updated.
12961 This hook runs even if there is no statistics cookie present, in which case
12962 `org-after-todo-statistics-hook' would not run.")
12964 (defun org-todo-trigger-tag-changes (state)
12965 "Apply the changes defined in `org-todo-state-tags-triggers'."
12966 (let ((l org-todo-state-tags-triggers)
12967 changes)
12968 (when (or (not state) (equal state ""))
12969 (setq changes (append changes (cdr (assoc "" l)))))
12970 (when (and (stringp state) (> (length state) 0))
12971 (setq changes (append changes (cdr (assoc state l)))))
12972 (when (member state org-not-done-keywords)
12973 (setq changes (append changes (cdr (assoc 'todo l)))))
12974 (when (member state org-done-keywords)
12975 (setq changes (append changes (cdr (assoc 'done l)))))
12976 (dolist (c changes)
12977 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12979 (defun org-local-logging (value)
12980 "Get logging settings from a property VALUE."
12981 (let* (words w a)
12982 ;; directly set the variables, they are already local.
12983 (setq org-log-done nil
12984 org-log-repeat nil
12985 org-todo-log-states nil)
12986 (setq words (org-split-string value))
12987 (while (setq w (pop words))
12988 (cond
12989 ((setq a (assoc w org-startup-options))
12990 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12991 (set (nth 1 a) (nth 2 a))))
12992 ((setq a (org-extract-log-state-settings w))
12993 (and (member (car a) org-todo-keywords-1)
12994 (push a org-todo-log-states)))))))
12996 (defun org-get-todo-sequence-head (kwd)
12997 "Return the head of the TODO sequence to which KWD belongs.
12998 If KWD is not set, check if there is a text property remembering the
12999 right sequence."
13000 (let (p)
13001 (cond
13002 ((not kwd)
13003 (or (get-text-property (point-at-bol) 'org-todo-head)
13004 (progn
13005 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13006 nil (point-at-eol)))
13007 (get-text-property p 'org-todo-head))))
13008 ((not (member kwd org-todo-keywords-1))
13009 (car org-todo-keywords-1))
13010 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13012 (defun org-fast-todo-selection ()
13013 "Fast TODO keyword selection with single keys.
13014 Returns the new TODO keyword, or nil if no state change should occur."
13015 (let* ((fulltable org-todo-key-alist)
13016 (done-keywords org-done-keywords) ;; needed for the faces.
13017 (maxlen (apply 'max (mapcar
13018 (lambda (x)
13019 (if (stringp (car x)) (string-width (car x)) 0))
13020 fulltable)))
13021 (expert nil)
13022 (fwidth (+ maxlen 3 1 3))
13023 (ncol (/ (- (window-width) 4) fwidth))
13024 tg cnt e c tbl
13025 groups ingroup)
13026 (save-excursion
13027 (save-window-excursion
13028 (if expert
13029 (set-buffer (get-buffer-create " *Org todo*"))
13030 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13031 (erase-buffer)
13032 (org-set-local 'org-done-keywords done-keywords)
13033 (setq tbl fulltable cnt 0)
13034 (while (setq e (pop tbl))
13035 (cond
13036 ((equal e '(:startgroup))
13037 (push '() groups) (setq ingroup t)
13038 (when (not (= cnt 0))
13039 (setq cnt 0)
13040 (insert "\n"))
13041 (insert "{ "))
13042 ((equal e '(:endgroup))
13043 (setq ingroup nil cnt 0)
13044 (insert "}\n"))
13045 ((equal e '(:newline))
13046 (when (not (= cnt 0))
13047 (setq cnt 0)
13048 (insert "\n")
13049 (setq e (car tbl))
13050 (while (equal (car tbl) '(:newline))
13051 (insert "\n")
13052 (setq tbl (cdr tbl)))))
13054 (setq tg (car e) c (cdr e))
13055 (if ingroup (push tg (car groups)))
13056 (setq tg (org-add-props tg nil 'face
13057 (org-get-todo-face tg)))
13058 (if (and (= cnt 0) (not ingroup)) (insert " "))
13059 (insert "[" c "] " tg (make-string
13060 (- fwidth 4 (length tg)) ?\ ))
13061 (when (= (setq cnt (1+ cnt)) ncol)
13062 (insert "\n")
13063 (if ingroup (insert " "))
13064 (setq cnt 0)))))
13065 (insert "\n")
13066 (goto-char (point-min))
13067 (if (not expert) (org-fit-window-to-buffer))
13068 (message "[a-z..]:Set [SPC]:clear")
13069 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13070 (cond
13071 ((or (= c ?\C-g)
13072 (and (= c ?q) (not (rassoc c fulltable))))
13073 (setq quit-flag t))
13074 ((= c ?\ ) nil)
13075 ((setq e (rassoc c fulltable) tg (car e))
13077 (t (setq quit-flag t)))))))
13079 (defun org-entry-is-todo-p ()
13080 (member (org-get-todo-state) org-not-done-keywords))
13082 (defun org-entry-is-done-p ()
13083 (member (org-get-todo-state) org-done-keywords))
13085 (defun org-get-todo-state ()
13086 "Return the TODO keyword of the current subtree."
13087 (save-excursion
13088 (org-back-to-heading t)
13089 (and (looking-at org-todo-line-regexp)
13090 (match-end 2)
13091 (match-string 2))))
13093 (defun org-at-date-range-p (&optional inactive-ok)
13094 "Is the cursor inside a date range?"
13095 (interactive)
13096 (save-excursion
13097 (catch 'exit
13098 (let ((pos (point)))
13099 (skip-chars-backward "^[<\r\n")
13100 (skip-chars-backward "<[")
13101 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13102 (>= (match-end 0) pos)
13103 (throw 'exit t))
13104 (skip-chars-backward "^<[\r\n")
13105 (skip-chars-backward "<[")
13106 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13107 (>= (match-end 0) pos)
13108 (throw 'exit t)))
13109 nil)))
13111 (defun org-get-repeat (&optional tagline)
13112 "Check if there is a deadline/schedule with repeater in this entry."
13113 (save-match-data
13114 (save-excursion
13115 (org-back-to-heading t)
13116 (and (re-search-forward (if tagline
13117 (concat tagline "\\s-*" org-repeat-re)
13118 org-repeat-re)
13119 (org-entry-end-position) t)
13120 (match-string-no-properties 1)))))
13122 (defvar org-last-changed-timestamp)
13123 (defvar org-last-inserted-timestamp)
13124 (defvar org-log-post-message)
13125 (defvar org-log-note-purpose)
13126 (defvar org-log-note-how nil)
13127 (defvar org-log-note-extra)
13128 (defun org-auto-repeat-maybe (done-word)
13129 "Check if the current headline contains a repeated deadline/schedule.
13130 If yes, set TODO state back to what it was and change the base date
13131 of repeating deadline/scheduled time stamps to new date.
13132 This function is run automatically after each state change to a DONE state."
13133 ;; last-state is dynamically scoped into this function
13134 (let* ((repeat (org-get-repeat))
13135 (aa (assoc org-last-state org-todo-kwd-alist))
13136 (interpret (nth 1 aa))
13137 (head (nth 2 aa))
13138 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13139 (msg "Entry repeats: ")
13140 (org-log-done nil)
13141 (org-todo-log-states nil)
13142 re type n what ts time to-state)
13143 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13144 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13145 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13146 org-todo-repeat-to-state))
13147 (unless (and to-state (member to-state org-todo-keywords-1))
13148 (setq to-state (if (eq interpret 'type) org-last-state head)))
13149 (org-todo to-state)
13150 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13151 (org-entry-put nil "LAST_REPEAT" (format-time-string
13152 (org-time-stamp-format t t))))
13153 (when org-log-repeat
13154 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13155 (memq 'org-add-log-note post-command-hook))
13156 ;; OK, we are already setup for some record
13157 (if (eq org-log-repeat 'note)
13158 ;; make sure we take a note, not only a time stamp
13159 (setq org-log-note-how 'note))
13160 ;; Set up for taking a record
13161 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13162 org-last-state
13163 'findpos org-log-repeat)))
13164 (org-back-to-heading t)
13165 (org-add-planning-info nil nil 'closed)
13166 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13167 org-deadline-time-regexp "\\)\\|\\("
13168 org-ts-regexp "\\)"))
13169 (while (re-search-forward
13170 re (save-excursion (outline-next-heading) (point)) t)
13171 (setq type (if (match-end 1) org-scheduled-string
13172 (if (match-end 3) org-deadline-string "Plain:"))
13173 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13174 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13175 (setq n (string-to-number (match-string 2 ts))
13176 what (match-string 3 ts))
13177 (if (equal what "w") (setq n (* n 7) what "d"))
13178 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13179 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13180 ;; Preparation, see if we need to modify the start date for the change
13181 (when (match-end 1)
13182 (setq time (save-match-data (org-time-string-to-time ts)))
13183 (cond
13184 ((equal (match-string 1 ts) ".")
13185 ;; Shift starting date to today
13186 (org-timestamp-change
13187 (- (org-today) (time-to-days time))
13188 'day))
13189 ((equal (match-string 1 ts) "+")
13190 (let ((nshiftmax 10) (nshift 0))
13191 (while (or (= nshift 0)
13192 (<= (time-to-days time)
13193 (time-to-days (current-time))))
13194 (when (= (incf nshift) nshiftmax)
13195 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13196 (user-error "Abort")))
13197 (org-timestamp-change n (cdr (assoc what whata)))
13198 (org-at-timestamp-p t)
13199 (setq ts (match-string 1))
13200 (setq time (save-match-data (org-time-string-to-time ts)))))
13201 (org-timestamp-change (- n) (cdr (assoc what whata)))
13202 ;; rematch, so that we have everything in place for the real shift
13203 (org-at-timestamp-p t)
13204 (setq ts (match-string 1))
13205 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13206 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13207 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13208 (setq org-log-post-message msg)
13209 (message "%s" msg))))
13211 (defun org-show-todo-tree (arg)
13212 "Make a compact tree which shows all headlines marked with TODO.
13213 The tree will show the lines where the regexp matches, and all higher
13214 headlines above the match.
13215 With a \\[universal-argument] prefix, prompt for a regexp to match.
13216 With a numeric prefix N, construct a sparse tree for the Nth element
13217 of `org-todo-keywords-1'."
13218 (interactive "P")
13219 (let ((case-fold-search nil)
13220 (kwd-re
13221 (cond ((null arg) org-not-done-regexp)
13222 ((equal arg '(4))
13223 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13224 (mapcar 'list org-todo-keywords-1))))
13225 (concat "\\("
13226 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13227 "\\)\\>")))
13228 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13229 (regexp-quote (nth (1- (prefix-numeric-value arg))
13230 org-todo-keywords-1)))
13231 (t (user-error "Invalid prefix argument: %s" arg)))))
13232 (message "%d TODO entries found"
13233 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13235 (defun org-deadline (arg &optional time)
13236 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13237 With one universal prefix argument, remove any deadline from the item.
13238 With two universal prefix arguments, prompt for a warning delay.
13239 With argument TIME, set the deadline at the corresponding date. TIME
13240 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13241 (interactive "P")
13242 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13243 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13244 'region-start-level 'region))
13245 org-loop-over-headlines-in-active-region)
13246 (org-map-entries
13247 `(org-deadline ',arg ,time)
13248 org-loop-over-headlines-in-active-region
13249 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13250 (let* ((old-date (org-entry-get nil "DEADLINE"))
13251 (old-date-time (if old-date (org-time-string-to-time old-date)))
13252 (repeater (and old-date
13253 (string-match
13254 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13255 old-date)
13256 (match-string 1 old-date))))
13257 (cond
13258 ((equal arg '(4))
13259 (when (and old-date org-log-redeadline)
13260 (org-add-log-setup 'deldeadline nil old-date 'findpos
13261 org-log-redeadline))
13262 (org-remove-timestamp-with-keyword org-deadline-string)
13263 (message "Item no longer has a deadline."))
13264 ((equal arg '(16))
13265 (save-excursion
13266 (org-back-to-heading t)
13267 (if (re-search-forward
13268 org-deadline-time-regexp
13269 (save-excursion (outline-next-heading) (point)) t)
13270 (let* ((rpl0 (match-string 1))
13271 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13272 (replace-match
13273 (concat org-deadline-string
13274 " <" rpl
13275 (format " -%dd"
13276 (abs
13277 (- (time-to-days
13278 (save-match-data
13279 (org-read-date nil t nil "Warn starting from" old-date-time)))
13280 (time-to-days old-date-time))))
13281 ">") t t))
13282 (user-error "No deadline information to update"))))
13284 (org-add-planning-info 'deadline time 'closed)
13285 (when (and old-date org-log-redeadline
13286 (not (equal old-date
13287 (substring org-last-inserted-timestamp 1 -1))))
13288 (org-add-log-setup 'redeadline nil old-date 'findpos
13289 org-log-redeadline))
13290 (when repeater
13291 (save-excursion
13292 (org-back-to-heading t)
13293 (when (re-search-forward (concat org-deadline-string " "
13294 org-last-inserted-timestamp)
13295 (save-excursion
13296 (outline-next-heading) (point)) t)
13297 (goto-char (1- (match-end 0)))
13298 (insert " " repeater)
13299 (setq org-last-inserted-timestamp
13300 (concat (substring org-last-inserted-timestamp 0 -1)
13301 " " repeater
13302 (substring org-last-inserted-timestamp -1))))))
13303 (message "Deadline on %s" org-last-inserted-timestamp))))))
13305 (defun org-schedule (arg &optional time)
13306 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13307 With one universal prefix argument, remove any scheduling date from the item.
13308 With two universal prefix arguments, prompt for a delay cookie.
13309 With argument TIME, scheduled at the corresponding date. TIME can
13310 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13311 (interactive "P")
13312 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13313 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13314 'region-start-level 'region))
13315 org-loop-over-headlines-in-active-region)
13316 (org-map-entries
13317 `(org-schedule ',arg ,time)
13318 org-loop-over-headlines-in-active-region
13319 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13320 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13321 (old-date-time (if old-date (org-time-string-to-time old-date)))
13322 (repeater (and old-date
13323 (string-match
13324 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13325 old-date)
13326 (match-string 1 old-date))))
13327 (cond
13328 ((equal arg '(4))
13329 (progn
13330 (when (and old-date org-log-reschedule)
13331 (org-add-log-setup 'delschedule nil old-date 'findpos
13332 org-log-reschedule))
13333 (org-remove-timestamp-with-keyword org-scheduled-string)
13334 (message "Item is no longer scheduled.")))
13335 ((equal arg '(16))
13336 (save-excursion
13337 (org-back-to-heading t)
13338 (if (re-search-forward
13339 org-scheduled-time-regexp
13340 (save-excursion (outline-next-heading) (point)) t)
13341 (let* ((rpl0 (match-string 1))
13342 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13343 (replace-match
13344 (concat org-scheduled-string
13345 " <" rpl
13346 (format " -%dd"
13347 (abs
13348 (- (time-to-days
13349 (save-match-data
13350 (org-read-date nil t nil "Delay until" old-date-time)))
13351 (time-to-days old-date-time))))
13352 ">") t t))
13353 (user-error "No scheduled information to update"))))
13355 (org-add-planning-info 'scheduled time 'closed)
13356 (when (and old-date org-log-reschedule
13357 (not (equal old-date
13358 (substring org-last-inserted-timestamp 1 -1))))
13359 (org-add-log-setup 'reschedule nil old-date 'findpos
13360 org-log-reschedule))
13361 (when repeater
13362 (save-excursion
13363 (org-back-to-heading t)
13364 (when (re-search-forward (concat org-scheduled-string " "
13365 org-last-inserted-timestamp)
13366 (save-excursion
13367 (outline-next-heading) (point)) t)
13368 (goto-char (1- (match-end 0)))
13369 (insert " " repeater)
13370 (setq org-last-inserted-timestamp
13371 (concat (substring org-last-inserted-timestamp 0 -1)
13372 " " repeater
13373 (substring org-last-inserted-timestamp -1))))))
13374 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13376 (defun org-get-scheduled-time (pom &optional inherit)
13377 "Get the scheduled time as a time tuple, of a format suitable
13378 for calling org-schedule with, or if there is no scheduling,
13379 returns nil."
13380 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13381 (when time
13382 (apply 'encode-time (org-parse-time-string time)))))
13384 (defun org-get-deadline-time (pom &optional inherit)
13385 "Get the deadline as a time tuple, of a format suitable for
13386 calling org-deadline with, or if there is no scheduling, returns
13387 nil."
13388 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13389 (when time
13390 (apply 'encode-time (org-parse-time-string time)))))
13392 (defun org-remove-timestamp-with-keyword (keyword)
13393 "Remove all time stamps with KEYWORD in the current entry."
13394 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13395 beg)
13396 (save-excursion
13397 (org-back-to-heading t)
13398 (setq beg (point))
13399 (outline-next-heading)
13400 (while (re-search-backward re beg t)
13401 (replace-match "")
13402 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13403 (equal (char-before) ?\ ))
13404 (backward-delete-char 1)
13405 (if (string-match "^[ \t]*$" (buffer-substring
13406 (point-at-bol) (point-at-eol)))
13407 (delete-region (point-at-bol)
13408 (min (point-max) (1+ (point-at-eol))))))))))
13410 (defvar org-time-was-given) ; dynamically scoped parameter
13411 (defvar org-end-time-was-given) ; dynamically scoped parameter
13413 (defun org-add-planning-info (what &optional time &rest remove)
13414 "Insert new timestamp with keyword in the line directly after the headline.
13415 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13416 If non is given, the user is prompted for a date.
13417 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13418 be removed."
13419 (interactive)
13420 (let (org-time-was-given org-end-time-was-given ts
13421 end default-time default-input)
13423 (catch 'exit
13424 (when (and (memq what '(scheduled deadline))
13425 (or (not time)
13426 (and (stringp time)
13427 (string-match "^[-+]+[0-9]" time))))
13428 ;; Try to get a default date/time from existing timestamp
13429 (save-excursion
13430 (org-back-to-heading t)
13431 (setq end (save-excursion (outline-next-heading) (point)))
13432 (when (re-search-forward (if (eq what 'scheduled)
13433 org-scheduled-time-regexp
13434 org-deadline-time-regexp)
13435 end t)
13436 (setq ts (match-string 1)
13437 default-time
13438 (apply 'encode-time (org-parse-time-string ts))
13439 default-input (and ts (org-get-compact-tod ts))))))
13440 (when what
13441 (setq time
13442 (if (stringp time)
13443 ;; This is a string (relative or absolute), set proper date
13444 (apply 'encode-time
13445 (org-read-date-analyze
13446 time default-time (decode-time default-time)))
13447 ;; If necessary, get the time from the user
13448 (or time (org-read-date nil 'to-time nil nil
13449 default-time default-input)))))
13451 (when (and org-insert-labeled-timestamps-at-point
13452 (member what '(scheduled deadline)))
13453 (insert
13454 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13455 (org-insert-time-stamp time org-time-was-given
13456 nil nil nil (list org-end-time-was-given))
13457 (setq what nil))
13458 (save-excursion
13459 (save-restriction
13460 (let (col list elt ts buffer-invisibility-spec)
13461 (org-back-to-heading t)
13462 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13463 (goto-char (match-end 1))
13464 (setq col (current-column))
13465 (goto-char (match-end 0))
13466 (if (eobp) (insert "\n") (forward-char 1))
13467 (when (and (not what)
13468 (not (looking-at
13469 (concat "[ \t]*"
13470 org-keyword-time-not-clock-regexp))))
13471 ;; Nothing to add, nothing to remove...... :-)
13472 (throw 'exit nil))
13473 (if (and (not (looking-at org-outline-regexp))
13474 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13475 "[^\r\n]*"))
13476 (not (equal (match-string 1) org-clock-string)))
13477 (narrow-to-region (match-beginning 0) (match-end 0))
13478 (insert-before-markers "\n")
13479 (backward-char 1)
13480 (narrow-to-region (point) (point))
13481 (and org-adapt-indentation (org-indent-to-column col)))
13482 ;; Check if we have to remove something.
13483 (setq list (cons what remove))
13484 (while list
13485 (setq elt (pop list))
13486 (when (or (and (eq elt 'scheduled)
13487 (re-search-forward org-scheduled-time-regexp nil t))
13488 (and (eq elt 'deadline)
13489 (re-search-forward org-deadline-time-regexp nil t))
13490 (and (eq elt 'closed)
13491 (re-search-forward org-closed-time-regexp nil t)))
13492 (replace-match "")
13493 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13494 (and (looking-at "[ \t]+") (replace-match ""))
13495 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13496 (when what
13497 (insert
13498 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13499 (cond ((eq what 'scheduled) org-scheduled-string)
13500 ((eq what 'deadline) org-deadline-string)
13501 ((eq what 'closed) org-closed-string))
13502 " ")
13503 (setq ts (org-insert-time-stamp
13504 time
13505 (or org-time-was-given
13506 (and (eq what 'closed) org-log-done-with-time))
13507 (eq what 'closed)
13508 nil nil (list org-end-time-was-given)))
13509 (insert
13510 (if (not (or (bolp) (eq (char-before) ?\ )
13511 (memq (char-after) '(32 10))
13512 (eobp))) " " ""))
13513 (end-of-line 1))
13514 (goto-char (point-min))
13515 (widen)
13516 (if (and (looking-at "[ \t]*\n")
13517 (equal (char-before) ?\n))
13518 (delete-region (1- (point)) (point-at-eol)))
13519 ts))))))
13521 (defvar org-log-note-marker (make-marker))
13522 (defvar org-log-note-purpose nil)
13523 (defvar org-log-note-state nil)
13524 (defvar org-log-note-previous-state nil)
13525 (defvar org-log-note-extra nil)
13526 (defvar org-log-note-window-configuration nil)
13527 (defvar org-log-note-return-to (make-marker))
13528 (defvar org-log-note-effective-time nil
13529 "Remembered current time so that dynamically scoped
13530 `org-extend-today-until' affects tha timestamps in state change
13531 log")
13533 (defvar org-log-post-message nil
13534 "Message to be displayed after a log note has been stored.
13535 The auto-repeater uses this.")
13537 (defun org-add-note ()
13538 "Add a note to the current entry.
13539 This is done in the same way as adding a state change note."
13540 (interactive)
13541 (org-add-log-setup 'note nil nil 'findpos nil))
13543 (defvar org-property-end-re)
13544 (defun org-add-log-setup (&optional purpose state prev-state
13545 findpos how extra)
13546 "Set up the post command hook to take a note.
13547 If this is about to TODO state change, the new state is expected in STATE.
13548 When FINDPOS is non-nil, find the correct position for the note in
13549 the current entry. If not, assume that it can be inserted at point.
13550 HOW is an indicator what kind of note should be created.
13551 EXTRA is additional text that will be inserted into the notes buffer."
13552 (let* ((org-log-into-drawer (org-log-into-drawer))
13553 (drawer (cond ((stringp org-log-into-drawer)
13554 org-log-into-drawer)
13555 (org-log-into-drawer "LOGBOOK"))))
13556 (save-restriction
13557 (save-excursion
13558 (when findpos
13559 (org-back-to-heading t)
13560 (narrow-to-region (point) (save-excursion
13561 (outline-next-heading) (point)))
13562 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13563 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13564 "[^\r\n]*\\)?"))
13565 (goto-char (match-end 0))
13566 (cond
13567 (drawer
13568 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13569 nil t)
13570 (progn
13571 (goto-char (match-end 0))
13572 (or org-log-states-order-reversed
13573 (and (re-search-forward org-property-end-re nil t)
13574 (goto-char (1- (match-beginning 0))))))
13575 (insert "\n:" drawer ":\n:END:")
13576 (beginning-of-line 0)
13577 (org-indent-line)
13578 (beginning-of-line 2)
13579 (org-indent-line)
13580 (end-of-line 0)))
13581 ((and org-log-state-notes-insert-after-drawers
13582 (save-excursion
13583 (forward-line) (looking-at org-drawer-regexp)))
13584 (forward-line)
13585 (while (looking-at org-drawer-regexp)
13586 (goto-char (match-end 0))
13587 (re-search-forward org-property-end-re (point-max) t)
13588 (forward-line))
13589 (forward-line -1)))
13590 (unless org-log-states-order-reversed
13591 (and (= (char-after) ?\n) (forward-char 1))
13592 (org-skip-over-state-notes)
13593 (skip-chars-backward " \t\n\r")))
13594 (move-marker org-log-note-marker (point))
13595 (setq org-log-note-purpose purpose
13596 org-log-note-state state
13597 org-log-note-previous-state prev-state
13598 org-log-note-how how
13599 org-log-note-extra extra
13600 org-log-note-effective-time (org-current-effective-time))
13601 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13603 (defun org-skip-over-state-notes ()
13604 "Skip past the list of State notes in an entry."
13605 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13606 (when (ignore-errors (goto-char (org-in-item-p)))
13607 (let* ((struct (org-list-struct))
13608 (prevs (org-list-prevs-alist struct)))
13609 (while (looking-at "[ \t]*- State")
13610 (goto-char (or (org-list-get-next-item (point) struct prevs)
13611 (org-list-get-item-end (point) struct)))))))
13613 (defun org-add-log-note (&optional purpose)
13614 "Pop up a window for taking a note, and add this note later at point."
13615 (remove-hook 'post-command-hook 'org-add-log-note)
13616 (setq org-log-note-window-configuration (current-window-configuration))
13617 (delete-other-windows)
13618 (move-marker org-log-note-return-to (point))
13619 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13620 (goto-char org-log-note-marker)
13621 (org-switch-to-buffer-other-window "*Org Note*")
13622 (erase-buffer)
13623 (if (memq org-log-note-how '(time state))
13624 (let (current-prefix-arg) (org-store-log-note))
13625 (let ((org-inhibit-startup t)) (org-mode))
13626 (insert (format "# Insert note for %s.
13627 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13628 (cond
13629 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13630 ((eq org-log-note-purpose 'done) "closed todo item")
13631 ((eq org-log-note-purpose 'state)
13632 (format "state change from \"%s\" to \"%s\""
13633 (or org-log-note-previous-state "")
13634 (or org-log-note-state "")))
13635 ((eq org-log-note-purpose 'reschedule)
13636 "rescheduling")
13637 ((eq org-log-note-purpose 'delschedule)
13638 "no longer scheduled")
13639 ((eq org-log-note-purpose 'redeadline)
13640 "changing deadline")
13641 ((eq org-log-note-purpose 'deldeadline)
13642 "removing deadline")
13643 ((eq org-log-note-purpose 'refile)
13644 "refiling")
13645 ((eq org-log-note-purpose 'note)
13646 "this entry")
13647 (t (error "This should not happen")))))
13648 (if org-log-note-extra (insert org-log-note-extra))
13649 (org-set-local 'org-finish-function 'org-store-log-note)
13650 (run-hooks 'org-log-buffer-setup-hook)))
13652 (defvar org-note-abort nil) ; dynamically scoped
13653 (defun org-store-log-note ()
13654 "Finish taking a log note, and insert it to where it belongs."
13655 (let ((txt (buffer-string)))
13656 (kill-buffer (current-buffer))
13657 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13658 lines ind bul)
13659 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13660 (setq txt (replace-match "" t t txt)))
13661 (if (string-match "\\s-+\\'" txt)
13662 (setq txt (replace-match "" t t txt)))
13663 (setq lines (org-split-string txt "\n"))
13664 (when (and note (string-match "\\S-" note))
13665 (setq note
13666 (org-replace-escapes
13667 note
13668 (list (cons "%u" (user-login-name))
13669 (cons "%U" user-full-name)
13670 (cons "%t" (format-time-string
13671 (org-time-stamp-format 'long 'inactive)
13672 org-log-note-effective-time))
13673 (cons "%T" (format-time-string
13674 (org-time-stamp-format 'long nil)
13675 org-log-note-effective-time))
13676 (cons "%d" (format-time-string
13677 (org-time-stamp-format nil 'inactive)
13678 org-log-note-effective-time))
13679 (cons "%D" (format-time-string
13680 (org-time-stamp-format nil nil)
13681 org-log-note-effective-time))
13682 (cons "%s" (if org-log-note-state
13683 (concat "\"" org-log-note-state "\"")
13684 ""))
13685 (cons "%S" (if org-log-note-previous-state
13686 (concat "\"" org-log-note-previous-state "\"")
13687 "\"\"")))))
13688 (if lines (setq note (concat note " \\\\")))
13689 (push note lines))
13690 (when (or current-prefix-arg org-note-abort)
13691 (when org-log-into-drawer
13692 (org-remove-empty-drawer-at org-log-note-marker))
13693 (setq lines nil))
13694 (when lines
13695 (with-current-buffer (marker-buffer org-log-note-marker)
13696 (save-excursion
13697 (goto-char org-log-note-marker)
13698 (move-marker org-log-note-marker nil)
13699 (end-of-line 1)
13700 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13701 (setq ind (save-excursion
13702 (if (ignore-errors (goto-char (org-in-item-p)))
13703 (let ((struct (org-list-struct)))
13704 (org-list-get-ind
13705 (org-list-get-top-point struct) struct))
13706 (skip-chars-backward " \r\t\n")
13707 (cond
13708 ((and (org-at-heading-p)
13709 org-adapt-indentation)
13710 (1+ (org-current-level)))
13711 ((org-at-heading-p) 0)
13712 (t (org-get-indentation))))))
13713 (setq bul (org-list-bullet-string "-"))
13714 (org-indent-line-to ind)
13715 (insert bul (pop lines))
13716 (let ((ind-body (+ (length bul) ind)))
13717 (while lines
13718 (insert "\n")
13719 (org-indent-line-to ind-body)
13720 (insert (pop lines))))
13721 (message "Note stored")
13722 (org-back-to-heading t)
13723 (org-cycle-hide-drawers 'children))
13724 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13725 ;; from within `org-add-log-note' because `buffer-undo-list'
13726 ;; is then modified outside of `org-with-remote-undo'.
13727 (when (eq this-command 'org-agenda-todo)
13728 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13729 ;; Don't add undo information when called from `org-agenda-todo'
13730 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13731 (set-window-configuration org-log-note-window-configuration)
13732 (with-current-buffer (marker-buffer org-log-note-return-to)
13733 (goto-char org-log-note-return-to))
13734 (move-marker org-log-note-return-to nil)
13735 (and org-log-post-message (message "%s" org-log-post-message))))
13737 (defun org-remove-empty-drawer-at (pos)
13738 "Remove an empty drawer at position POS.
13739 POS may also be a marker."
13740 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13741 (org-with-wide-buffer
13742 (goto-char pos)
13743 (let ((drawer (org-element-at-point)))
13744 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13745 (not (org-element-property :contents-begin drawer)))
13746 (delete-region (org-element-property :begin drawer)
13747 (progn (goto-char (org-element-property :end drawer))
13748 (skip-chars-backward " \r\t\n")
13749 (forward-line)
13750 (point))))))))
13752 (defvar org-ts-type nil)
13753 (defun org-sparse-tree (&optional arg type)
13754 "Create a sparse tree, prompt for the details.
13755 This command can create sparse trees. You first need to select the type
13756 of match used to create the tree:
13758 t Show all TODO entries.
13759 T Show entries with a specific TODO keyword.
13760 m Show entries selected by a tags/property match.
13761 p Enter a property name and its value (both with completion on existing
13762 names/values) and show entries with that property.
13763 r Show entries matching a regular expression (`/' can be used as well).
13764 b Show deadlines and scheduled items before a date.
13765 a Show deadlines and scheduled items after a date.
13766 d Show deadlines due within `org-deadline-warning-days'.
13767 D Show deadlines and scheduled items between a date range."
13768 (interactive "P")
13769 (setq type (or type org-sparse-tree-default-date-type))
13770 (setq org-ts-type type)
13771 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13772 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13773 [c]ycle through date types: %s"
13774 (case type
13775 (all "all timestamps")
13776 (scheduled "only scheduled")
13777 (deadline "only deadline")
13778 (active "only active timestamps")
13779 (inactive "only inactive timestamps")
13780 (scheduled-or-deadline "scheduled/deadline")
13781 (closed "with a closed time-stamp")
13782 (otherwise "scheduled/deadline")))
13783 (let ((answer (read-char-exclusive)))
13784 (case answer
13786 (org-sparse-tree
13788 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13789 inactive closed)))))
13790 (?d (call-interactively 'org-check-deadlines))
13791 (?b (call-interactively 'org-check-before-date))
13792 (?a (call-interactively 'org-check-after-date))
13793 (?D (call-interactively 'org-check-dates-range))
13794 (?t (call-interactively 'org-show-todo-tree))
13795 (?T (org-show-todo-tree '(4)))
13796 (?m (call-interactively 'org-match-sparse-tree))
13797 ((?p ?P)
13798 (let* ((kwd (org-icompleting-read
13799 "Property: " (mapcar 'list (org-buffer-property-keys))))
13800 (value (org-icompleting-read
13801 "Value: " (mapcar 'list (org-property-values kwd)))))
13802 (unless (string-match "\\`{.*}\\'" value)
13803 (setq value (concat "\"" value "\"")))
13804 (org-match-sparse-tree arg (concat kwd "=" value))))
13805 ((?r ?R ?/) (call-interactively 'org-occur))
13806 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13808 (defvar org-occur-highlights nil
13809 "List of overlays used for occur matches.")
13810 (make-variable-buffer-local 'org-occur-highlights)
13811 (defvar org-occur-parameters nil
13812 "Parameters of the active org-occur calls.
13813 This is a list, each call to org-occur pushes as cons cell,
13814 containing the regular expression and the callback, onto the list.
13815 The list can contain several entries if `org-occur' has been called
13816 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13817 will only contain one set of parameters. When the highlights are
13818 removed (for example with `C-c C-c', or with the next edit (depending
13819 on `org-remove-highlights-with-change'), this variable is emptied
13820 as well.")
13821 (make-variable-buffer-local 'org-occur-parameters)
13823 (defun org-occur (regexp &optional keep-previous callback)
13824 "Make a compact tree which shows all matches of REGEXP.
13825 The tree will show the lines where the regexp matches, and all higher
13826 headlines above the match. It will also show the heading after the match,
13827 to make sure editing the matching entry is easy.
13828 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13829 call to `org-occur' will be kept, to allow stacking of calls to this
13830 command.
13831 If CALLBACK is non-nil, it is a function which is called to confirm
13832 that the match should indeed be shown."
13833 (interactive "sRegexp: \nP")
13834 (when (equal regexp "")
13835 (user-error "Regexp cannot be empty"))
13836 (unless keep-previous
13837 (org-remove-occur-highlights nil nil t))
13838 (push (cons regexp callback) org-occur-parameters)
13839 (let ((cnt 0))
13840 (save-excursion
13841 (goto-char (point-min))
13842 (if (or (not keep-previous) ; do not want to keep
13843 (not org-occur-highlights)) ; no previous matches
13844 ;; hide everything
13845 (org-overview))
13846 (while (re-search-forward regexp nil t)
13847 (when (or (not callback)
13848 (save-match-data (funcall callback)))
13849 (setq cnt (1+ cnt))
13850 (when org-highlight-sparse-tree-matches
13851 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13852 (org-show-context 'occur-tree))))
13853 (when org-remove-highlights-with-change
13854 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13855 nil 'local))
13856 (unless org-sparse-tree-open-archived-trees
13857 (org-hide-archived-subtrees (point-min) (point-max)))
13858 (run-hooks 'org-occur-hook)
13859 (if (org-called-interactively-p 'interactive)
13860 (message "%d match(es) for regexp %s" cnt regexp))
13861 cnt))
13863 (defun org-occur-next-match (&optional n reset)
13864 "Function for `next-error-function' to find sparse tree matches.
13865 N is the number of matches to move, when negative move backwards.
13866 RESET is entirely ignored - this function always goes back to the
13867 starting point when no match is found."
13868 (let* ((limit (if (< n 0) (point-min) (point-max)))
13869 (search-func (if (< n 0)
13870 'previous-single-char-property-change
13871 'next-single-char-property-change))
13872 (n (abs n))
13873 (pos (point))
13875 (catch 'exit
13876 (while (setq p1 (funcall search-func (point) 'org-type))
13877 (when (equal p1 limit)
13878 (goto-char pos)
13879 (user-error "No more matches"))
13880 (when (equal (get-char-property p1 'org-type) 'org-occur)
13881 (setq n (1- n))
13882 (when (= n 0)
13883 (goto-char p1)
13884 (throw 'exit (point))))
13885 (goto-char p1))
13886 (goto-char p1)
13887 (user-error "No more matches"))))
13889 (defun org-show-context (&optional key)
13890 "Make sure point and context are visible.
13891 How much context is shown depends upon the variables
13892 `org-show-hierarchy-above', `org-show-following-heading',
13893 `org-show-entry-below' and `org-show-siblings'."
13894 (let ((heading-p (org-at-heading-p t))
13895 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13896 (following-p (org-get-alist-option org-show-following-heading key))
13897 (entry-p (org-get-alist-option org-show-entry-below key))
13898 (siblings-p (org-get-alist-option org-show-siblings key)))
13899 ;; Show heading or entry text
13900 (if (and heading-p (not entry-p))
13901 (org-flag-heading nil) ; only show the heading
13902 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13903 (org-show-hidden-entry))) ; show entire entry
13904 (when following-p
13905 ;; Show next sibling, or heading below text
13906 (save-excursion
13907 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13908 (org-flag-heading nil))))
13909 (when siblings-p (org-show-siblings))
13910 (when hierarchy-p
13911 ;; show all higher headings, possibly with siblings
13912 (save-excursion
13913 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13914 (not (bobp)))
13915 (org-flag-heading nil)
13916 (when siblings-p (org-show-siblings)))))))
13918 (defvar org-reveal-start-hook nil
13919 "Hook run before revealing a location.")
13921 (defun org-reveal (&optional siblings)
13922 "Show current entry, hierarchy above it, and the following headline.
13923 This can be used to show a consistent set of context around locations
13924 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13925 not t for the search context.
13927 With optional argument SIBLINGS, on each level of the hierarchy all
13928 siblings are shown. This repairs the tree structure to what it would
13929 look like when opened with hierarchical calls to `org-cycle'.
13930 With double optional argument \\[universal-argument] \\[universal-argument], \
13931 go to the parent and show the
13932 entire tree."
13933 (interactive "P")
13934 (run-hooks 'org-reveal-start-hook)
13935 (let ((org-show-hierarchy-above t)
13936 (org-show-following-heading t)
13937 (org-show-siblings (if siblings t org-show-siblings)))
13938 (org-show-context nil))
13939 (when (equal siblings '(16))
13940 (save-excursion
13941 (when (org-up-heading-safe)
13942 (org-show-subtree)
13943 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13945 (defun org-highlight-new-match (beg end)
13946 "Highlight from BEG to END and mark the highlight is an occur headline."
13947 (let ((ov (make-overlay beg end)))
13948 (overlay-put ov 'face 'secondary-selection)
13949 (overlay-put ov 'org-type 'org-occur)
13950 (push ov org-occur-highlights)))
13952 (defun org-remove-occur-highlights (&optional beg end noremove)
13953 "Remove the occur highlights from the buffer.
13954 BEG and END are ignored. If NOREMOVE is nil, remove this function
13955 from the `before-change-functions' in the current buffer."
13956 (interactive)
13957 (unless org-inhibit-highlight-removal
13958 (mapc 'delete-overlay org-occur-highlights)
13959 (setq org-occur-highlights nil)
13960 (setq org-occur-parameters nil)
13961 (unless noremove
13962 (remove-hook 'before-change-functions
13963 'org-remove-occur-highlights 'local))))
13965 ;;;; Priorities
13967 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13968 "Regular expression matching the priority indicator.")
13970 (defvar org-remove-priority-next-time nil)
13972 (defun org-priority-up ()
13973 "Increase the priority of the current item."
13974 (interactive)
13975 (org-priority 'up))
13977 (defun org-priority-down ()
13978 "Decrease the priority of the current item."
13979 (interactive)
13980 (org-priority 'down))
13982 (defun org-priority (&optional action show)
13983 "Change the priority of an item.
13984 ACTION can be `set', `up', `down', or a character."
13985 (interactive "P")
13986 (if (equal action '(4))
13987 (org-show-priority)
13988 (unless org-enable-priority-commands
13989 (user-error "Priority commands are disabled"))
13990 (setq action (or action 'set))
13991 (let (current new news have remove)
13992 (save-excursion
13993 (org-back-to-heading t)
13994 (if (looking-at org-priority-regexp)
13995 (setq current (string-to-char (match-string 2))
13996 have t))
13997 (cond
13998 ((eq action 'remove)
13999 (setq remove t new ?\ ))
14000 ((or (eq action 'set)
14001 (if (featurep 'xemacs) (characterp action) (integerp action)))
14002 (if (not (eq action 'set))
14003 (setq new action)
14004 (message "Priority %c-%c, SPC to remove: "
14005 org-highest-priority org-lowest-priority)
14006 (save-match-data
14007 (setq new (read-char-exclusive))))
14008 (if (and (= (upcase org-highest-priority) org-highest-priority)
14009 (= (upcase org-lowest-priority) org-lowest-priority))
14010 (setq new (upcase new)))
14011 (cond ((equal new ?\ ) (setq remove t))
14012 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14013 (user-error "Priority must be between `%c' and `%c'"
14014 org-highest-priority org-lowest-priority))))
14015 ((eq action 'up)
14016 (setq new (if have
14017 (1- current) ; normal cycling
14018 ;; last priority was empty
14019 (if (eq last-command this-command)
14020 org-lowest-priority ; wrap around empty to lowest
14021 ;; default
14022 (if org-priority-start-cycle-with-default
14023 org-default-priority
14024 (1- org-default-priority))))))
14025 ((eq action 'down)
14026 (setq new (if have
14027 (1+ current) ; normal cycling
14028 ;; last priority was empty
14029 (if (eq last-command this-command)
14030 org-highest-priority ; wrap around empty to highest
14031 ;; default
14032 (if org-priority-start-cycle-with-default
14033 org-default-priority
14034 (1+ org-default-priority))))))
14035 (t (user-error "Invalid action")))
14036 (if (or (< (upcase new) org-highest-priority)
14037 (> (upcase new) org-lowest-priority))
14038 (if (and (memq action '(up down))
14039 (not have) (not (eq last-command this-command)))
14040 ;; `new' is from default priority
14041 (error
14042 "The default can not be set, see `org-default-priority' why")
14043 ;; normal cycling: `new' is beyond highest/lowest priority
14044 ;; and is wrapped around to the empty priority
14045 (setq remove t)))
14046 (setq news (format "%c" new))
14047 (if have
14048 (if remove
14049 (replace-match "" t t nil 1)
14050 (replace-match news t t nil 2))
14051 (if remove
14052 (user-error "No priority cookie found in line")
14053 (let ((case-fold-search nil))
14054 (looking-at org-todo-line-regexp))
14055 (if (match-end 2)
14056 (progn
14057 (goto-char (match-end 2))
14058 (insert " [#" news "]"))
14059 (goto-char (match-beginning 3))
14060 (insert "[#" news "] "))))
14061 (org-set-tags nil 'align))
14062 (if remove
14063 (message "Priority removed")
14064 (message "Priority of current item set to %s" news)))))
14066 (defun org-show-priority ()
14067 "Show the priority of the current item.
14068 This priority is composed of the main priority given with the [#A] cookies,
14069 and by additional input from the age of a schedules or deadline entry."
14070 (interactive)
14071 (let ((pri (if (eq major-mode 'org-agenda-mode)
14072 (org-get-at-bol 'priority)
14073 (save-excursion
14074 (save-match-data
14075 (beginning-of-line)
14076 (and (looking-at org-heading-regexp)
14077 (org-get-priority (match-string 0))))))))
14078 (message "Priority is %d" (if pri pri -1000))))
14080 (defun org-get-priority (s)
14081 "Find priority cookie and return priority."
14082 (save-match-data
14083 (if (functionp org-get-priority-function)
14084 (funcall org-get-priority-function)
14085 (if (not (string-match org-priority-regexp s))
14086 (* 1000 (- org-lowest-priority org-default-priority))
14087 (* 1000 (- org-lowest-priority
14088 (string-to-char (match-string 2 s))))))))
14090 ;;;; Tags
14092 (defvar org-agenda-archives-mode)
14093 (defvar org-map-continue-from nil
14094 "Position from where mapping should continue.
14095 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14097 (defvar org-scanner-tags nil
14098 "The current tag list while the tags scanner is running.")
14099 (defvar org-trust-scanner-tags nil
14100 "Should `org-get-tags-at' use the tags for the scanner.
14101 This is for internal dynamical scoping only.
14102 When this is non-nil, the function `org-get-tags-at' will return the value
14103 of `org-scanner-tags' instead of building the list by itself. This
14104 can lead to large speed-ups when the tags scanner is used in a file with
14105 many entries, and when the list of tags is retrieved, for example to
14106 obtain a list of properties. Building the tags list for each entry in such
14107 a file becomes an N^2 operation - but with this variable set, it scales
14108 as N.")
14110 (defun org-scan-tags (action matcher todo-only &optional start-level)
14111 "Scan headline tags with inheritance and produce output ACTION.
14113 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14114 or `agenda' to produce an entry list for an agenda view. It can also be
14115 a Lisp form or a function that should be called at each matched headline, in
14116 this case the return value is a list of all return values from these calls.
14118 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14119 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14120 only lines with a not-done TODO keyword are included in the output.
14121 This should be the same variable that was scoped into
14122 and set by `org-make-tags-matcher' when it constructed MATCHER.
14124 START-LEVEL can be a string with asterisks, reducing the scope to
14125 headlines matching this string."
14126 (require 'org-agenda)
14127 (let* ((re (concat "^"
14128 (if start-level
14129 ;; Get the correct level to match
14130 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14131 org-outline-regexp)
14132 " *\\(\\<\\("
14133 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14134 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14135 (props (list 'face 'default
14136 'done-face 'org-agenda-done
14137 'undone-face 'default
14138 'mouse-face 'highlight
14139 'org-not-done-regexp org-not-done-regexp
14140 'org-todo-regexp org-todo-regexp
14141 'org-complex-heading-regexp org-complex-heading-regexp
14142 'help-echo
14143 (format "mouse-2 or RET jump to org file %s"
14144 (abbreviate-file-name
14145 (or (buffer-file-name (buffer-base-buffer))
14146 (buffer-name (buffer-base-buffer)))))))
14147 (org-map-continue-from nil)
14148 lspos tags tags-list
14149 (tags-alist (list (cons 0 org-file-tags)))
14150 (llast 0) rtn rtn1 level category i txt
14151 todo marker entry priority)
14152 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14153 (setq action (list 'lambda nil action)))
14154 (save-excursion
14155 (goto-char (point-min))
14156 (when (eq action 'sparse-tree)
14157 (org-overview)
14158 (org-remove-occur-highlights))
14159 (while (let (case-fold-search)
14160 (re-search-forward re nil t))
14161 (setq org-map-continue-from nil)
14162 (catch :skip
14163 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14164 tags (if (match-end 4) (org-match-string-no-properties 4)))
14165 (goto-char (setq lspos (match-beginning 0)))
14166 (setq level (org-reduced-level (org-outline-level))
14167 category (org-get-category))
14168 (setq i llast llast level)
14169 ;; remove tag lists from same and sublevels
14170 (while (>= i level)
14171 (when (setq entry (assoc i tags-alist))
14172 (setq tags-alist (delete entry tags-alist)))
14173 (setq i (1- i)))
14174 ;; add the next tags
14175 (when tags
14176 (setq tags (org-split-string tags ":")
14177 tags-alist
14178 (cons (cons level tags) tags-alist)))
14179 ;; compile tags for current headline
14180 (setq tags-list
14181 (if org-use-tag-inheritance
14182 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14183 tags)
14184 org-scanner-tags tags-list)
14185 (when org-use-tag-inheritance
14186 (setcdr (car tags-alist)
14187 (mapcar (lambda (x)
14188 (setq x (copy-sequence x))
14189 (org-add-prop-inherited x))
14190 (cdar tags-alist))))
14191 (when (and tags org-use-tag-inheritance
14192 (or (not (eq t org-use-tag-inheritance))
14193 org-tags-exclude-from-inheritance))
14194 ;; selective inheritance, remove uninherited ones
14195 (setcdr (car tags-alist)
14196 (org-remove-uninherited-tags (cdar tags-alist))))
14197 (when (and
14199 ;; eval matcher only when the todo condition is OK
14200 (and (or (not todo-only) (member todo org-not-done-keywords))
14201 (let ((case-fold-search t) (org-trust-scanner-tags t))
14202 (eval matcher)))
14204 ;; Call the skipper, but return t if it does not skip,
14205 ;; so that the `and' form continues evaluating
14206 (progn
14207 (unless (eq action 'sparse-tree) (org-agenda-skip))
14210 ;; Check if timestamps are deselecting this entry
14211 (or (not todo-only)
14212 (and (member todo org-not-done-keywords)
14213 (or (not org-agenda-tags-todo-honor-ignore-options)
14214 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14216 ;; select this headline
14217 (cond
14218 ((eq action 'sparse-tree)
14219 (and org-highlight-sparse-tree-matches
14220 (org-get-heading) (match-end 0)
14221 (org-highlight-new-match
14222 (match-beginning 1) (match-end 1)))
14223 (org-show-context 'tags-tree))
14224 ((eq action 'agenda)
14225 (setq txt (org-agenda-format-item
14227 (concat
14228 (if (eq org-tags-match-list-sublevels 'indented)
14229 (make-string (1- level) ?.) "")
14230 (org-get-heading))
14231 level category
14232 tags-list)
14233 priority (org-get-priority txt))
14234 (goto-char lspos)
14235 (setq marker (org-agenda-new-marker))
14236 (org-add-props txt props
14237 'org-marker marker 'org-hd-marker marker 'org-category category
14238 'todo-state todo
14239 'priority priority 'type "tagsmatch")
14240 (push txt rtn))
14241 ((functionp action)
14242 (setq org-map-continue-from nil)
14243 (save-excursion
14244 (setq rtn1 (funcall action))
14245 (push rtn1 rtn)))
14246 (t (user-error "Invalid action")))
14248 ;; if we are to skip sublevels, jump to end of subtree
14249 (unless org-tags-match-list-sublevels
14250 (org-end-of-subtree t)
14251 (backward-char 1))))
14252 ;; Get the correct position from where to continue
14253 (if org-map-continue-from
14254 (goto-char org-map-continue-from)
14255 (and (= (point) lspos) (end-of-line 1)))))
14256 (when (and (eq action 'sparse-tree)
14257 (not org-sparse-tree-open-archived-trees))
14258 (org-hide-archived-subtrees (point-min) (point-max)))
14259 (nreverse rtn)))
14261 (defun org-remove-uninherited-tags (tags)
14262 "Remove all tags that are not inherited from the list TAGS."
14263 (cond
14264 ((eq org-use-tag-inheritance t)
14265 (if org-tags-exclude-from-inheritance
14266 (org-delete-all org-tags-exclude-from-inheritance tags)
14267 tags))
14268 ((not org-use-tag-inheritance) nil)
14269 ((stringp org-use-tag-inheritance)
14270 (delq nil (mapcar
14271 (lambda (x)
14272 (if (and (string-match org-use-tag-inheritance x)
14273 (not (member x org-tags-exclude-from-inheritance)))
14274 x nil))
14275 tags)))
14276 ((listp org-use-tag-inheritance)
14277 (delq nil (mapcar
14278 (lambda (x)
14279 (if (member x org-use-tag-inheritance) x nil))
14280 tags)))))
14282 (defun org-match-sparse-tree (&optional todo-only match)
14283 "Create a sparse tree according to tags string MATCH.
14284 MATCH can contain positive and negative selection of tags, like
14285 \"+WORK+URGENT-WITHBOSS\".
14286 If optional argument TODO-ONLY is non-nil, only select lines that are
14287 also TODO lines."
14288 (interactive "P")
14289 (org-agenda-prepare-buffers (list (current-buffer)))
14290 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14292 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14294 (defvar org-cached-props nil)
14295 (defun org-cached-entry-get (pom property)
14296 (if (or (eq t org-use-property-inheritance)
14297 (and (stringp org-use-property-inheritance)
14298 (string-match org-use-property-inheritance property))
14299 (and (listp org-use-property-inheritance)
14300 (member property org-use-property-inheritance)))
14301 ;; Caching is not possible, check it directly
14302 (org-entry-get pom property 'inherit)
14303 ;; Get all properties, so that we can do complicated checks easily
14304 (cdr (assoc property (or org-cached-props
14305 (setq org-cached-props
14306 (org-entry-properties pom)))))))
14308 (defun org-global-tags-completion-table (&optional files)
14309 "Return the list of all tags in all agenda buffer/files.
14310 Optional FILES argument is a list of files which can be used
14311 instead of the agenda files."
14312 (save-excursion
14313 (org-uniquify
14314 (delq nil
14315 (apply 'append
14316 (mapcar
14317 (lambda (file)
14318 (set-buffer (find-file-noselect file))
14319 (append (org-get-buffer-tags)
14320 (mapcar (lambda (x) (if (stringp (car-safe x))
14321 (list (car-safe x)) nil))
14322 org-tag-alist)))
14323 (if (and files (car files))
14324 files
14325 (org-agenda-files))))))))
14327 (defun org-make-tags-matcher (match)
14328 "Create the TAGS/TODO matcher form for the selection string MATCH.
14330 The variable `todo-only' is scoped dynamically into this function.
14331 It will be set to t if the matcher restricts matching to TODO entries,
14332 otherwise will not be touched.
14334 Returns a cons of the selection string MATCH and the constructed
14335 lisp form implementing the matcher. The matcher is to be evaluated
14336 at an Org entry, with point on the headline, and returns t if the
14337 entry matches the selection string MATCH. The returned lisp form
14338 references two variables with information about the entry, which
14339 must be bound around the form's evaluation: todo, the TODO keyword
14340 at the entry (or nil of none); and tags-list, the list of all tags
14341 at the entry including inherited ones. Additionally, the category
14342 of the entry (if any) must be specified as the text property
14343 'org-category on the headline.
14345 See also `org-scan-tags'.
14347 (declare (special todo-only))
14348 (unless (boundp 'todo-only)
14349 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14350 (unless match
14351 ;; Get a new match request, with completion against the global
14352 ;; tags table and the local tags in current buffer
14353 (let ((org-last-tags-completion-table
14354 (org-uniquify
14355 (delq nil (append (org-get-buffer-tags)
14356 (org-global-tags-completion-table))))))
14357 (setq match (org-completing-read-no-i
14358 "Match: " 'org-tags-completion-function nil nil nil
14359 'org-tags-history))))
14361 ;; Parse the string and create a lisp form
14362 (let ((match0 match)
14363 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14364 minus tag mm
14365 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14366 orterms term orlist re-p str-p level-p level-op time-p
14367 prop-p pn pv po gv rest (start 0) (ss 0))
14368 ;; Expand group tags
14369 (setq match (org-tags-expand match))
14371 ;; Check if there is a TODO part of this match, which would be the
14372 ;; part after a "/". TO make sure that this slash is not part of
14373 ;; a property value to be matched against, we also check that there
14374 ;; is no " after that slash.
14375 ;; First, find the last slash
14376 (while (string-match "/+" match ss)
14377 (setq start (match-beginning 0) ss (match-end 0)))
14378 (if (and (string-match "/+" match start)
14379 (not (save-match-data (string-match "\"" match start))))
14380 ;; match contains also a todo-matching request
14381 (progn
14382 (setq tagsmatch (substring match 0 (match-beginning 0))
14383 todomatch (substring match (match-end 0)))
14384 (if (string-match "^!" todomatch)
14385 (setq todo-only t todomatch (substring todomatch 1)))
14386 (if (string-match "^\\s-*$" todomatch)
14387 (setq todomatch nil)))
14388 ;; only matching tags
14389 (setq tagsmatch match todomatch nil))
14391 ;; Make the tags matcher
14392 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14393 (setq tagsmatcher t)
14394 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14395 (while (setq term (pop orterms))
14396 (while (and (equal (substring term -1) "\\") orterms)
14397 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14398 (while (string-match re term)
14399 (setq rest (substring term (match-end 0))
14400 minus (and (match-end 1)
14401 (equal (match-string 1 term) "-"))
14402 tag (save-match-data (replace-regexp-in-string
14403 "\\\\-" "-"
14404 (match-string 2 term)))
14405 re-p (equal (string-to-char tag) ?{)
14406 level-p (match-end 4)
14407 prop-p (match-end 5)
14408 mm (cond
14409 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14410 (level-p
14411 (setq level-op (org-op-to-function (match-string 3 term)))
14412 `(,level-op level ,(string-to-number
14413 (match-string 4 term))))
14414 (prop-p
14415 (setq pn (match-string 5 term)
14416 po (match-string 6 term)
14417 pv (match-string 7 term)
14418 re-p (equal (string-to-char pv) ?{)
14419 str-p (equal (string-to-char pv) ?\")
14420 time-p (save-match-data
14421 (string-match "^\"[[<].*[]>]\"$" pv))
14422 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14423 (if time-p (setq pv (org-matcher-time pv)))
14424 (setq po (org-op-to-function po (if time-p 'time str-p)))
14425 (cond
14426 ((equal pn "CATEGORY")
14427 (setq gv '(get-text-property (point) 'org-category)))
14428 ((equal pn "TODO")
14429 (setq gv 'todo))
14431 (setq gv `(org-cached-entry-get nil ,pn))))
14432 (if re-p
14433 (if (eq po 'org<>)
14434 `(not (string-match ,pv (or ,gv "")))
14435 `(string-match ,pv (or ,gv "")))
14436 (if str-p
14437 `(,po (or ,gv "") ,pv)
14438 `(,po (string-to-number (or ,gv ""))
14439 ,(string-to-number pv) ))))
14440 (t `(member ,tag tags-list)))
14441 mm (if minus (list 'not mm) mm)
14442 term rest)
14443 (push mm tagsmatcher))
14444 (push (if (> (length tagsmatcher) 1)
14445 (cons 'and tagsmatcher)
14446 (car tagsmatcher))
14447 orlist)
14448 (setq tagsmatcher nil))
14449 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14450 (setq tagsmatcher
14451 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14452 ;; Make the todo matcher
14453 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14454 (setq todomatcher t)
14455 (setq orterms (org-split-string todomatch "|") orlist nil)
14456 (while (setq term (pop orterms))
14457 (while (string-match re term)
14458 (setq minus (and (match-end 1)
14459 (equal (match-string 1 term) "-"))
14460 kwd (match-string 2 term)
14461 re-p (equal (string-to-char kwd) ?{)
14462 term (substring term (match-end 0))
14463 mm (if re-p
14464 `(string-match ,(substring kwd 1 -1) todo)
14465 (list 'equal 'todo kwd))
14466 mm (if minus (list 'not mm) mm))
14467 (push mm todomatcher))
14468 (push (if (> (length todomatcher) 1)
14469 (cons 'and todomatcher)
14470 (car todomatcher))
14471 orlist)
14472 (setq todomatcher nil))
14473 (setq todomatcher (if (> (length orlist) 1)
14474 (cons 'or orlist) (car orlist))))
14476 ;; Return the string and lisp forms of the matcher
14477 (setq matcher (if todomatcher
14478 (list 'and tagsmatcher todomatcher)
14479 tagsmatcher))
14480 (when todo-only
14481 (setq matcher (list 'and '(member todo org-not-done-keywords)
14482 matcher)))
14483 (cons match0 matcher)))
14485 (defun org-tags-expand (match &optional single-as-list downcased)
14486 "Expand group tags in MATCH.
14488 This replaces every group tag in MATCH with a regexp tag search.
14489 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14490 will be replaced like this:
14492 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14493 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14494 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14496 Replacing by a regexp preserves the structure of the match.
14497 E.g., this expansion
14499 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14501 will match anything tagged with \"Lab\" and \"Home\", or tagged
14502 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14504 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14505 assumed to be a single group tag, and the function will return
14506 the list of tags in this group.
14508 When DOWNCASE is non-nil, expand downcased TAGS."
14509 (if org-group-tags
14510 (let* ((case-fold-search t)
14511 (stable org-mode-syntax-table)
14512 (tal (or org-tag-groups-alist-for-agenda
14513 org-tag-groups-alist))
14514 (tal (if downcased
14515 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14516 (tml (mapcar 'car tal))
14517 (rtnmatch match) rpl)
14518 ;; @ and _ are allowed as word-components in tags
14519 (modify-syntax-entry ?@ "w" stable)
14520 (modify-syntax-entry ?_ "w" stable)
14521 (while (and tml
14522 (with-syntax-table stable
14523 (string-match
14524 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14525 (regexp-opt tml) "\\>\\)") rtnmatch)))
14526 (let* ((dir (match-string 1 rtnmatch))
14527 (tag (match-string 2 rtnmatch))
14528 (tag (if downcased (downcase tag) tag)))
14529 (setq tml (delete tag tml))
14530 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14531 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14532 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14533 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14534 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14535 (if single-as-list
14536 (or (reverse rpl) (list rtnmatch))
14537 rtnmatch))
14538 (if single-as-list (list (if downcased (downcase match) match))
14539 match)))
14541 (defun org-op-to-function (op &optional stringp)
14542 "Turn an operator into the appropriate function."
14543 (setq op
14544 (cond
14545 ((equal op "<" ) '(< string< org-time<))
14546 ((equal op ">" ) '(> org-string> org-time>))
14547 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14548 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14549 ((member op '("=" "==")) '(= string= org-time=))
14550 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14551 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14553 (defun org<> (a b) (not (= a b)))
14554 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14555 (defun org-string>= (a b) (not (string< a b)))
14556 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14557 (defun org-string<> (a b) (not (string= a b)))
14558 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14559 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14560 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14561 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14562 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14563 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14564 (defun org-2ft (s)
14565 "Convert S to a floating point time.
14566 If S is already a number, just return it. If it is a string, parse
14567 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14568 (cond
14569 ((numberp s) s)
14570 ((stringp s)
14571 (condition-case nil
14572 (float-time (apply 'encode-time (org-parse-time-string s)))
14573 (error 0.)))
14574 (t 0.)))
14576 (defun org-time-today ()
14577 "Time in seconds today at 0:00.
14578 Returns the float number of seconds since the beginning of the
14579 epoch to the beginning of today (00:00)."
14580 (float-time (apply 'encode-time
14581 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14583 (defun org-matcher-time (s)
14584 "Interpret a time comparison value."
14585 (save-match-data
14586 (cond
14587 ((string= s "<now>") (float-time))
14588 ((string= s "<today>") (org-time-today))
14589 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14590 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14591 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14592 (+ (org-time-today)
14593 (* (string-to-number (match-string 1 s))
14594 (cdr (assoc (match-string 2 s)
14595 '(("d" . 86400.0) ("w" . 604800.0)
14596 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14597 (t (org-2ft s)))))
14599 (defun org-match-any-p (re list)
14600 "Does re match any element of list?"
14601 (setq list (mapcar (lambda (x) (string-match re x)) list))
14602 (delq nil list))
14604 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14605 (defvar org-tags-overlay (make-overlay 1 1))
14606 (org-detach-overlay org-tags-overlay)
14608 (defun org-get-local-tags-at (&optional pos)
14609 "Get a list of tags defined in the current headline."
14610 (org-get-tags-at pos 'local))
14612 (defun org-get-local-tags ()
14613 "Get a list of tags defined in the current headline."
14614 (org-get-tags-at nil 'local))
14616 (defun org-get-tags-at (&optional pos local)
14617 "Get a list of all headline tags applicable at POS.
14618 POS defaults to point. If tags are inherited, the list contains
14619 the targets in the same sequence as the headlines appear, i.e.
14620 the tags of the current headline come last.
14621 When LOCAL is non-nil, only return tags from the current headline,
14622 ignore inherited ones."
14623 (interactive)
14624 (if (and org-trust-scanner-tags
14625 (or (not pos) (equal pos (point)))
14626 (not local))
14627 org-scanner-tags
14628 (let (tags ltags lastpos parent)
14629 (save-excursion
14630 (save-restriction
14631 (widen)
14632 (goto-char (or pos (point)))
14633 (save-match-data
14634 (catch 'done
14635 (condition-case nil
14636 (progn
14637 (org-back-to-heading t)
14638 (while (not (equal lastpos (point)))
14639 (setq lastpos (point))
14640 (when (looking-at
14641 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14642 (setq ltags (org-split-string
14643 (org-match-string-no-properties 1) ":"))
14644 (when parent
14645 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14646 (setq tags (append
14647 (if parent
14648 (org-remove-uninherited-tags ltags)
14649 ltags)
14650 tags)))
14651 (or org-use-tag-inheritance (throw 'done t))
14652 (if local (throw 'done t))
14653 (or (org-up-heading-safe) (error nil))
14654 (setq parent t)))
14655 (error nil)))))
14656 (if local
14657 tags
14658 (reverse (delete-dups
14659 (reverse (append
14660 (org-remove-uninherited-tags
14661 org-file-tags) tags)))))))))
14663 (defun org-add-prop-inherited (s)
14664 (add-text-properties 0 (length s) '(inherited t) s)
14667 (defun org-toggle-tag (tag &optional onoff)
14668 "Toggle the tag TAG for the current line.
14669 If ONOFF is `on' or `off', don't toggle but set to this state."
14670 (let (res current)
14671 (save-excursion
14672 (org-back-to-heading t)
14673 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14674 (point-at-eol) t)
14675 (progn
14676 (setq current (match-string 1))
14677 (replace-match ""))
14678 (setq current ""))
14679 (setq current (nreverse (org-split-string current ":")))
14680 (cond
14681 ((eq onoff 'on)
14682 (setq res t)
14683 (or (member tag current) (push tag current)))
14684 ((eq onoff 'off)
14685 (or (not (member tag current)) (setq current (delete tag current))))
14686 (t (if (member tag current)
14687 (setq current (delete tag current))
14688 (setq res t)
14689 (push tag current))))
14690 (end-of-line 1)
14691 (if current
14692 (progn
14693 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14694 (org-set-tags nil t))
14695 (delete-horizontal-space))
14696 (run-hooks 'org-after-tags-change-hook))
14697 res))
14699 (defun org-align-tags-here (to-col)
14700 ;; Assumes that this is a headline
14701 "Align tags on the current headline to TO-COL."
14702 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14703 (beginning-of-line 1)
14704 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14705 (< pos (match-beginning 2)))
14706 (progn
14707 (setq tags-l (- (match-end 2) (match-beginning 2)))
14708 (goto-char (match-beginning 1))
14709 (insert " ")
14710 (delete-region (point) (1+ (match-beginning 2)))
14711 (setq ncol (max (current-column)
14712 (1+ col)
14713 (if (> to-col 0)
14714 to-col
14715 (- (abs to-col) tags-l))))
14716 (setq p (point))
14717 (insert (make-string (- ncol (current-column)) ?\ ))
14718 (setq ncol (current-column))
14719 (when indent-tabs-mode (tabify p (point-at-eol)))
14720 (org-move-to-column (min ncol col)))
14721 (goto-char pos))))
14723 (defun org-set-tags-command (&optional arg just-align)
14724 "Call the set-tags command for the current entry."
14725 (interactive "P")
14726 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14727 (org-set-tags arg just-align)
14728 (save-excursion
14729 (unless (and (org-region-active-p)
14730 org-loop-over-headlines-in-active-region)
14731 (org-back-to-heading t))
14732 (org-set-tags arg just-align))))
14734 (defun org-set-tags-to (data)
14735 "Set the tags of the current entry to DATA, replacing the current tags.
14736 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14737 If DATA is nil or the empty string, any tags will be removed."
14738 (interactive "sTags: ")
14739 (setq data
14740 (cond
14741 ((eq data nil) "")
14742 ((equal data "") "")
14743 ((stringp data)
14744 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14745 ":"))
14746 ((listp data)
14747 (concat ":" (mapconcat 'identity data ":") ":"))))
14748 (when data
14749 (save-excursion
14750 (org-back-to-heading t)
14751 (when (looking-at org-complex-heading-regexp)
14752 (if (match-end 5)
14753 (progn
14754 (goto-char (match-beginning 5))
14755 (insert data)
14756 (delete-region (point) (point-at-eol))
14757 (org-set-tags nil 'align))
14758 (goto-char (point-at-eol))
14759 (insert " " data)
14760 (org-set-tags nil 'align)))
14761 (beginning-of-line 1)
14762 (if (looking-at ".*?\\([ \t]+\\)$")
14763 (delete-region (match-beginning 1) (match-end 1))))))
14765 (defun org-align-all-tags ()
14766 "Align the tags i all headings."
14767 (interactive)
14768 (save-excursion
14769 (or (ignore-errors (org-back-to-heading t))
14770 (outline-next-heading))
14771 (if (org-at-heading-p)
14772 (org-set-tags t)
14773 (message "No headings"))))
14775 (defvar org-indent-indentation-per-level)
14776 (defun org-set-tags (&optional arg just-align)
14777 "Set the tags for the current headline.
14778 With prefix ARG, realign all tags in headings in the current buffer.
14779 When JUST-ALIGN is non-nil, only align tags."
14780 (interactive "P")
14781 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14782 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14783 'region-start-level 'region))
14784 org-loop-over-headlines-in-active-region)
14785 (org-map-entries
14786 ;; We don't use ARG and JUST-ALIGN here because these args
14787 ;; are not useful when looping over headlines.
14788 `(org-set-tags)
14789 org-loop-over-headlines-in-active-region
14790 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14791 (let* ((re org-outline-regexp-bol)
14792 (current (unless arg (org-get-tags-string)))
14793 (col (current-column))
14794 (org-setting-tags t)
14795 table current-tags inherited-tags ; computed below when needed
14796 tags p0 c0 c1 rpl di tc level)
14797 (if arg
14798 (save-excursion
14799 (goto-char (point-min))
14800 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14801 (while (re-search-forward re nil t)
14802 (org-set-tags nil t)
14803 (end-of-line 1)))
14804 (message "All tags realigned to column %d" org-tags-column))
14805 (if just-align
14806 (setq tags current)
14807 ;; Get a new set of tags from the user
14808 (save-excursion
14809 (setq table (append org-tag-persistent-alist
14810 (or org-tag-alist (org-get-buffer-tags))
14811 (and
14812 org-complete-tags-always-offer-all-agenda-tags
14813 (org-global-tags-completion-table
14814 (org-agenda-files))))
14815 org-last-tags-completion-table table
14816 current-tags (org-split-string current ":")
14817 inherited-tags (nreverse
14818 (nthcdr (length current-tags)
14819 (nreverse (org-get-tags-at))))
14820 tags
14821 (if (or (eq t org-use-fast-tag-selection)
14822 (and org-use-fast-tag-selection
14823 (delq nil (mapcar 'cdr table))))
14824 (org-fast-tag-selection
14825 current-tags inherited-tags table
14826 (if org-fast-tag-selection-include-todo
14827 org-todo-key-alist))
14828 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14829 (org-trim
14830 (org-icompleting-read "Tags: "
14831 'org-tags-completion-function
14832 nil nil current 'org-tags-history))))))
14833 (while (string-match "[-+&]+" tags)
14834 ;; No boolean logic, just a list
14835 (setq tags (replace-match ":" t t tags))))
14837 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14839 (if org-tags-sort-function
14840 (setq tags (mapconcat 'identity
14841 (sort (org-split-string
14842 tags (org-re "[^[:alnum:]_@#%]+"))
14843 org-tags-sort-function) ":")))
14845 (if (string-match "\\`[\t ]*\\'" tags)
14846 (setq tags "")
14847 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14848 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14850 ;; Insert new tags at the correct column
14851 (beginning-of-line 1)
14852 (setq level (or (and (looking-at org-outline-regexp)
14853 (- (match-end 0) (point) 1))
14855 (cond
14856 ((and (equal current "") (equal tags "")))
14857 ((re-search-forward
14858 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14859 (point-at-eol) t)
14860 (if (equal tags "")
14861 (setq rpl "")
14862 (goto-char (match-beginning 0))
14863 (setq c0 (current-column)
14864 ;; compute offset for the case of org-indent-mode active
14865 di (if (org-bound-and-true-p org-indent-mode)
14866 (* (1- org-indent-indentation-per-level) (1- level))
14868 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14869 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14870 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14871 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14872 (replace-match rpl t t)
14873 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14874 tags)
14875 (t (error "Tags alignment failed")))
14876 (org-move-to-column col)
14877 (unless just-align
14878 (run-hooks 'org-after-tags-change-hook))))))
14880 (defun org-change-tag-in-region (beg end tag off)
14881 "Add or remove TAG for each entry in the region.
14882 This works in the agenda, and also in an org-mode buffer."
14883 (interactive
14884 (list (region-beginning) (region-end)
14885 (let ((org-last-tags-completion-table
14886 (if (derived-mode-p 'org-mode)
14887 (org-uniquify
14888 (delq nil (append (org-get-buffer-tags)
14889 (org-global-tags-completion-table))))
14890 (org-global-tags-completion-table))))
14891 (org-icompleting-read
14892 "Tag: " 'org-tags-completion-function nil nil nil
14893 'org-tags-history))
14894 (progn
14895 (message "[s]et or [r]emove? ")
14896 (equal (read-char-exclusive) ?r))))
14897 (if (fboundp 'deactivate-mark) (deactivate-mark))
14898 (let ((agendap (equal major-mode 'org-agenda-mode))
14899 l1 l2 m buf pos newhead (cnt 0))
14900 (goto-char end)
14901 (setq l2 (1- (org-current-line)))
14902 (goto-char beg)
14903 (setq l1 (org-current-line))
14904 (loop for l from l1 to l2 do
14905 (org-goto-line l)
14906 (setq m (get-text-property (point) 'org-hd-marker))
14907 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14908 (and agendap m))
14909 (setq buf (if agendap (marker-buffer m) (current-buffer))
14910 pos (if agendap m (point)))
14911 (with-current-buffer buf
14912 (save-excursion
14913 (save-restriction
14914 (goto-char pos)
14915 (setq cnt (1+ cnt))
14916 (org-toggle-tag tag (if off 'off 'on))
14917 (setq newhead (org-get-heading)))))
14918 (and agendap (org-agenda-change-all-lines newhead m))))
14919 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14921 (defun org-tags-completion-function (string predicate &optional flag)
14922 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14923 (confirm (lambda (x) (stringp (car x)))))
14924 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14925 (setq s1 (match-string 1 string)
14926 s2 (match-string 2 string))
14927 (setq s1 "" s2 string))
14928 (cond
14929 ((eq flag nil)
14930 ;; try completion
14931 (setq rtn (try-completion s2 ctable confirm))
14932 (if (stringp rtn)
14933 (setq rtn
14934 (concat s1 s2 (substring rtn (length s2))
14935 (if (and org-add-colon-after-tag-completion
14936 (assoc rtn ctable))
14937 ":" ""))))
14938 rtn)
14939 ((eq flag t)
14940 ;; all-completions
14941 (all-completions s2 ctable confirm))
14942 ((eq flag 'lambda)
14943 ;; exact match?
14944 (assoc s2 ctable)))))
14946 (defun org-fast-tag-insert (kwd tags face &optional end)
14947 "Insert KDW, and the TAGS, the latter with face FACE.
14948 Also insert END."
14949 (insert (format "%-12s" (concat kwd ":"))
14950 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14951 (or end "")))
14953 (defun org-fast-tag-show-exit (flag)
14954 (save-excursion
14955 (org-goto-line 3)
14956 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14957 (replace-match ""))
14958 (when flag
14959 (end-of-line 1)
14960 (org-move-to-column (- (window-width) 19) t)
14961 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14963 (defun org-set-current-tags-overlay (current prefix)
14964 "Add an overlay to CURRENT tag with PREFIX."
14965 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14966 (if (featurep 'xemacs)
14967 (org-overlay-display org-tags-overlay (concat prefix s)
14968 'secondary-selection)
14969 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14970 (org-overlay-display org-tags-overlay (concat prefix s)))))
14972 (defvar org-last-tag-selection-key nil)
14973 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14974 "Fast tag selection with single keys.
14975 CURRENT is the current list of tags in the headline, INHERITED is the
14976 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14977 possibly with grouping information. TODO-TABLE is a similar table with
14978 TODO keywords, should these have keys assigned to them.
14979 If the keys are nil, a-z are automatically assigned.
14980 Returns the new tags string, or nil to not change the current settings."
14981 (let* ((fulltable (append table todo-table))
14982 (maxlen (apply 'max (mapcar
14983 (lambda (x)
14984 (if (stringp (car x)) (string-width (car x)) 0))
14985 fulltable)))
14986 (buf (current-buffer))
14987 (expert (eq org-fast-tag-selection-single-key 'expert))
14988 (buffer-tags nil)
14989 (fwidth (+ maxlen 3 1 3))
14990 (ncol (/ (- (window-width) 4) fwidth))
14991 (i-face 'org-done)
14992 (c-face 'org-todo)
14993 tg cnt e c char c1 c2 ntable tbl rtn
14994 ov-start ov-end ov-prefix
14995 (exit-after-next org-fast-tag-selection-single-key)
14996 (done-keywords org-done-keywords)
14997 groups ingroup)
14998 (save-excursion
14999 (beginning-of-line 1)
15000 (if (looking-at
15001 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15002 (setq ov-start (match-beginning 1)
15003 ov-end (match-end 1)
15004 ov-prefix "")
15005 (setq ov-start (1- (point-at-eol))
15006 ov-end (1+ ov-start))
15007 (skip-chars-forward "^\n\r")
15008 (setq ov-prefix
15009 (concat
15010 (buffer-substring (1- (point)) (point))
15011 (if (> (current-column) org-tags-column)
15013 (make-string (- org-tags-column (current-column)) ?\ ))))))
15014 (move-overlay org-tags-overlay ov-start ov-end)
15015 (save-window-excursion
15016 (if expert
15017 (set-buffer (get-buffer-create " *Org tags*"))
15018 (delete-other-windows)
15019 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15020 (org-switch-to-buffer-other-window " *Org tags*"))
15021 (erase-buffer)
15022 (org-set-local 'org-done-keywords done-keywords)
15023 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15024 (org-fast-tag-insert "Current" current c-face "\n\n")
15025 (org-fast-tag-show-exit exit-after-next)
15026 (org-set-current-tags-overlay current ov-prefix)
15027 (setq tbl fulltable char ?a cnt 0)
15028 (while (setq e (pop tbl))
15029 (cond
15030 ((equal (car e) :startgroup)
15031 (push '() groups) (setq ingroup t)
15032 (when (not (= cnt 0))
15033 (setq cnt 0)
15034 (insert "\n"))
15035 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15036 ((equal (car e) :endgroup)
15037 (setq ingroup nil cnt 0)
15038 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15039 ((equal e '(:newline))
15040 (when (not (= cnt 0))
15041 (setq cnt 0)
15042 (insert "\n")
15043 (setq e (car tbl))
15044 (while (equal (car tbl) '(:newline))
15045 (insert "\n")
15046 (setq tbl (cdr tbl)))))
15047 ((equal e '(:grouptags)) nil)
15049 (setq tg (copy-sequence (car e)) c2 nil)
15050 (if (cdr e)
15051 (setq c (cdr e))
15052 ;; automatically assign a character.
15053 (setq c1 (string-to-char
15054 (downcase (substring
15055 tg (if (= (string-to-char tg) ?@) 1 0)))))
15056 (if (or (rassoc c1 ntable) (rassoc c1 table))
15057 (while (or (rassoc char ntable) (rassoc char table))
15058 (setq char (1+ char)))
15059 (setq c2 c1))
15060 (setq c (or c2 char)))
15061 (if ingroup (push tg (car groups)))
15062 (setq tg (org-add-props tg nil 'face
15063 (cond
15064 ((not (assoc tg table))
15065 (org-get-todo-face tg))
15066 ((member tg current) c-face)
15067 ((member tg inherited) i-face))))
15068 (if (equal (caar tbl) :grouptags)
15069 (org-add-props tg nil 'face 'org-tag-group))
15070 (if (and (= cnt 0) (not ingroup)) (insert " "))
15071 (insert "[" c "] " tg (make-string
15072 (- fwidth 4 (length tg)) ?\ ))
15073 (push (cons tg c) ntable)
15074 (when (= (setq cnt (1+ cnt)) ncol)
15075 (insert "\n")
15076 (if ingroup (insert " "))
15077 (setq cnt 0)))))
15078 (setq ntable (nreverse ntable))
15079 (insert "\n")
15080 (goto-char (point-min))
15081 (if (not expert) (org-fit-window-to-buffer))
15082 (setq rtn
15083 (catch 'exit
15084 (while t
15085 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15086 (if (not groups) "no " "")
15087 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15088 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15089 (setq org-last-tag-selection-key c)
15090 (cond
15091 ((= c ?\r) (throw 'exit t))
15092 ((= c ?!)
15093 (setq groups (not groups))
15094 (goto-char (point-min))
15095 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15096 ((= c ?\C-c)
15097 (if (not expert)
15098 (org-fast-tag-show-exit
15099 (setq exit-after-next (not exit-after-next)))
15100 (setq expert nil)
15101 (delete-other-windows)
15102 (set-window-buffer (split-window-vertically) " *Org tags*")
15103 (org-switch-to-buffer-other-window " *Org tags*")
15104 (org-fit-window-to-buffer)))
15105 ((or (= c ?\C-g)
15106 (and (= c ?q) (not (rassoc c ntable))))
15107 (org-detach-overlay org-tags-overlay)
15108 (setq quit-flag t))
15109 ((= c ?\ )
15110 (setq current nil)
15111 (if exit-after-next (setq exit-after-next 'now)))
15112 ((= c ?\t)
15113 (condition-case nil
15114 (setq tg (org-icompleting-read
15115 "Tag: "
15116 (or buffer-tags
15117 (with-current-buffer buf
15118 (org-get-buffer-tags)))))
15119 (quit (setq tg "")))
15120 (when (string-match "\\S-" tg)
15121 (add-to-list 'buffer-tags (list tg))
15122 (if (member tg current)
15123 (setq current (delete tg current))
15124 (push tg current)))
15125 (if exit-after-next (setq exit-after-next 'now)))
15126 ((setq e (rassoc c todo-table) tg (car e))
15127 (with-current-buffer buf
15128 (save-excursion (org-todo tg)))
15129 (if exit-after-next (setq exit-after-next 'now)))
15130 ((setq e (rassoc c ntable) tg (car e))
15131 (if (member tg current)
15132 (setq current (delete tg current))
15133 (loop for g in groups do
15134 (if (member tg g)
15135 (mapc (lambda (x)
15136 (setq current (delete x current)))
15137 g)))
15138 (push tg current))
15139 (if exit-after-next (setq exit-after-next 'now))))
15141 ;; Create a sorted list
15142 (setq current
15143 (sort current
15144 (lambda (a b)
15145 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15146 (if (eq exit-after-next 'now) (throw 'exit t))
15147 (goto-char (point-min))
15148 (beginning-of-line 2)
15149 (delete-region (point) (point-at-eol))
15150 (org-fast-tag-insert "Current" current c-face)
15151 (org-set-current-tags-overlay current ov-prefix)
15152 (while (re-search-forward
15153 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15154 (setq tg (match-string 1))
15155 (add-text-properties
15156 (match-beginning 1) (match-end 1)
15157 (list 'face
15158 (cond
15159 ((member tg current) c-face)
15160 ((member tg inherited) i-face)
15161 (t (get-text-property (match-beginning 1) 'face))))))
15162 (goto-char (point-min)))))
15163 (org-detach-overlay org-tags-overlay)
15164 (if rtn
15165 (mapconcat 'identity current ":")
15166 nil))))
15168 (defun org-get-tags-string ()
15169 "Get the TAGS string in the current headline."
15170 (unless (org-at-heading-p t)
15171 (user-error "Not on a heading"))
15172 (save-excursion
15173 (beginning-of-line 1)
15174 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15175 (org-match-string-no-properties 1)
15176 "")))
15178 (defun org-get-tags ()
15179 "Get the list of tags specified in the current headline."
15180 (org-split-string (org-get-tags-string) ":"))
15182 (defun org-get-buffer-tags ()
15183 "Get a table of all tags used in the buffer, for completion."
15184 (let (tags)
15185 (save-excursion
15186 (goto-char (point-min))
15187 (while (re-search-forward
15188 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15189 (when (equal (char-after (point-at-bol 0)) ?*)
15190 (mapc (lambda (x) (add-to-list 'tags x))
15191 (org-split-string (org-match-string-no-properties 1) ":")))))
15192 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15193 (mapcar 'list tags)))
15195 ;;;; The mapping API
15197 (defun org-map-entries (func &optional match scope &rest skip)
15198 "Call FUNC at each headline selected by MATCH in SCOPE.
15200 FUNC is a function or a lisp form. The function will be called without
15201 arguments, with the cursor positioned at the beginning of the headline.
15202 The return values of all calls to the function will be collected and
15203 returned as a list.
15205 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15206 does not need to preserve point. After evaluation, the cursor will be
15207 moved to the end of the line (presumably of the headline of the
15208 processed entry) and search continues from there. Under some
15209 circumstances, this may not produce the wanted results. For example,
15210 if you have removed (e.g. archived) the current (sub)tree it could
15211 mean that the next entry will be skipped entirely. In such cases, you
15212 can specify the position from where search should continue by making
15213 FUNC set the variable `org-map-continue-from' to the desired buffer
15214 position.
15216 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15217 Only headlines that are matched by this query will be considered during
15218 the iteration. When MATCH is nil or t, all headlines will be
15219 visited by the iteration.
15221 SCOPE determines the scope of this command. It can be any of:
15223 nil The current buffer, respecting the restriction if any
15224 tree The subtree started with the entry at point
15225 region The entries within the active region, if any
15226 region-start-level
15227 The entries within the active region, but only those at
15228 the same level than the first one.
15229 file The current buffer, without restriction
15230 file-with-archives
15231 The current buffer, and any archives associated with it
15232 agenda All agenda files
15233 agenda-with-archives
15234 All agenda files with any archive files associated with them
15235 \(file1 file2 ...)
15236 If this is a list, all files in the list will be scanned
15238 The remaining args are treated as settings for the skipping facilities of
15239 the scanner. The following items can be given here:
15241 archive skip trees with the archive tag
15242 comment skip trees with the COMMENT keyword
15243 function or Emacs Lisp form:
15244 will be used as value for `org-agenda-skip-function', so
15245 whenever the function returns a position, FUNC will not be
15246 called for that entry and search will continue from the
15247 position returned
15249 If your function needs to retrieve the tags including inherited tags
15250 at the *current* entry, you can use the value of the variable
15251 `org-scanner-tags' which will be much faster than getting the value
15252 with `org-get-tags-at'. If your function gets properties with
15253 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15254 to t around the call to `org-entry-properties' to get the same speedup.
15255 Note that if your function moves around to retrieve tags and properties at
15256 a *different* entry, you cannot use these techniques."
15257 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15258 (not (org-region-active-p)))
15259 (let* ((org-agenda-archives-mode nil) ; just to make sure
15260 (org-agenda-skip-archived-trees (memq 'archive skip))
15261 (org-agenda-skip-comment-trees (memq 'comment skip))
15262 (org-agenda-skip-function
15263 (car (org-delete-all '(comment archive) skip)))
15264 (org-tags-match-list-sublevels t)
15265 (start-level (eq scope 'region-start-level))
15266 matcher file res
15267 org-todo-keywords-for-agenda
15268 org-done-keywords-for-agenda
15269 org-todo-keyword-alist-for-agenda
15270 org-tag-alist-for-agenda
15271 todo-only)
15273 (cond
15274 ((eq match t) (setq matcher t))
15275 ((eq match nil) (setq matcher t))
15276 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15278 (save-excursion
15279 (save-restriction
15280 (cond ((eq scope 'tree)
15281 (org-back-to-heading t)
15282 (org-narrow-to-subtree)
15283 (setq scope nil))
15284 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15285 (org-region-active-p))
15286 ;; If needed, set start-level to a string like "2"
15287 (when start-level
15288 (save-excursion
15289 (goto-char (region-beginning))
15290 (unless (org-at-heading-p) (outline-next-heading))
15291 (setq start-level (org-current-level))))
15292 (narrow-to-region (region-beginning)
15293 (save-excursion
15294 (goto-char (region-end))
15295 (unless (and (bolp) (org-at-heading-p))
15296 (outline-next-heading))
15297 (point)))
15298 (setq scope nil)))
15300 (if (not scope)
15301 (progn
15302 (org-agenda-prepare-buffers
15303 (list (buffer-file-name (current-buffer))))
15304 (setq res (org-scan-tags func matcher todo-only start-level)))
15305 ;; Get the right scope
15306 (cond
15307 ((and scope (listp scope) (symbolp (car scope)))
15308 (setq scope (eval scope)))
15309 ((eq scope 'agenda)
15310 (setq scope (org-agenda-files t)))
15311 ((eq scope 'agenda-with-archives)
15312 (setq scope (org-agenda-files t))
15313 (setq scope (org-add-archive-files scope)))
15314 ((eq scope 'file)
15315 (setq scope (list (buffer-file-name))))
15316 ((eq scope 'file-with-archives)
15317 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15318 (org-agenda-prepare-buffers scope)
15319 (while (setq file (pop scope))
15320 (with-current-buffer (org-find-base-buffer-visiting file)
15321 (save-excursion
15322 (save-restriction
15323 (widen)
15324 (goto-char (point-min))
15325 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15326 res)))
15328 ;;;; Properties
15330 ;;; Setting and retrieving properties
15332 (defconst org-special-properties
15333 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15334 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15335 "The special properties valid in Org-mode.
15337 These are properties that are not defined in the property drawer,
15338 but in some other way.")
15340 (defconst org-default-properties
15341 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15342 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15343 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15344 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15345 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15346 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15347 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15348 "Some properties that are used by Org-mode for various purposes.
15349 Being in this list makes sure that they are offered for completion.")
15351 (defun org-property-action ()
15352 "Do an action on properties."
15353 (interactive)
15354 (let (c)
15355 (org-at-property-p)
15356 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15357 (setq c (read-char-exclusive))
15358 (cond
15359 ((equal c ?s)
15360 (call-interactively 'org-set-property))
15361 ((equal c ?d)
15362 (call-interactively 'org-delete-property))
15363 ((equal c ?D)
15364 (call-interactively 'org-delete-property-globally))
15365 ((equal c ?c)
15366 (call-interactively 'org-compute-property-at-point))
15367 (t (user-error "No such property action %c" c)))))
15369 (defun org-inc-effort ()
15370 "Increment the value of the effort property in the current entry."
15371 (interactive)
15372 (org-set-effort nil t))
15374 (defvar org-clock-effort) ;; Defined in org-clock.el
15375 (defvar org-clock-current-task) ;; Defined in org-clock.el
15376 (defun org-set-effort (&optional value increment)
15377 "Set the effort property of the current entry.
15378 With numerical prefix arg, use the nth allowed value, 0 stands for the
15379 10th allowed value.
15381 When INCREMENT is non-nil, set the property to the next allowed value."
15382 (interactive "P")
15383 (if (equal value 0) (setq value 10))
15384 (let* ((completion-ignore-case t)
15385 (prop org-effort-property)
15386 (cur (org-entry-get nil prop))
15387 (allowed (org-property-get-allowed-values nil prop 'table))
15388 (existing (mapcar 'list (org-property-values prop)))
15389 (heading (nth 4 (org-heading-components)))
15391 (val (cond
15392 ((stringp value) value)
15393 ((and allowed (integerp value))
15394 (or (car (nth (1- value) allowed))
15395 (car (org-last allowed))))
15396 ((and allowed increment)
15397 (or (caadr (member (list cur) allowed))
15398 (user-error "Allowed effort values are not set")))
15399 (allowed
15400 (message "Select 1-9,0, [RET%s]: %s"
15401 (if cur (concat "=" cur) "")
15402 (mapconcat 'car allowed " "))
15403 (setq rpl (read-char-exclusive))
15404 (if (equal rpl ?\r)
15406 (setq rpl (- rpl ?0))
15407 (if (equal rpl 0) (setq rpl 10))
15408 (if (and (> rpl 0) (<= rpl (length allowed)))
15409 (car (nth (1- rpl) allowed))
15410 (org-completing-read "Effort: " allowed nil))))
15412 (let (org-completion-use-ido org-completion-use-iswitchb)
15413 (org-completing-read
15414 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15415 (concat "[" cur "]") "")
15416 ": ")
15417 existing nil nil "" nil cur))))))
15418 (unless (equal (org-entry-get nil prop) val)
15419 (org-entry-put nil prop val))
15420 (org-refresh-property
15421 '((effort . identity)
15422 (effort-minutes . org-duration-string-to-minutes))
15423 val)
15424 (when (string= heading org-clock-current-task)
15425 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15426 (org-clock-update-mode-line))
15427 (message "%s is now %s" prop val)))
15429 (defun org-get-property-block (&optional beg force)
15430 "Return the (beg . end) range of the body of the property drawer.
15431 BEG is the beginning and end of the current subtree, or of the
15432 part before the first headline. If it is not given, it will be
15433 found. If the drawer does not exist, create it if FORCE is
15434 non-nil, or return nil."
15435 (org-with-wide-buffer
15436 (when beg (goto-char beg))
15437 (unless (org-before-first-heading-p)
15438 (let ((beg (cond (beg)
15439 ((or (not (featurep 'org-inlinetask))
15440 (org-inlinetask-in-task-p))
15441 (org-back-to-heading t))
15442 (t (org-with-limited-levels (org-back-to-heading t))))))
15443 (forward-line)
15444 (when (org-looking-at-p org-planning-line-re) (forward-line))
15445 (cond ((looking-at org-property-drawer-re)
15446 (forward-line)
15447 (cons (point) (progn (goto-char (match-end 0))
15448 (line-beginning-position))))
15449 (force
15450 (org-insert-property-drawer)
15451 (let ((pos (save-excursion (search-forward ":END:")
15452 (line-beginning-position))))
15453 (cons pos pos))))))))
15455 (defun org-at-property-p ()
15456 "Non-nil when point is inside a property drawer.
15457 See `org-property-re' for match data, if applicable."
15458 (save-excursion
15459 (beginning-of-line)
15460 (and (looking-at org-property-re)
15461 (let ((property-drawer (save-match-data (org-get-property-block))))
15462 (and property-drawer (< (point) (cdr property-drawer)))))))
15464 (defun org-entry-properties (&optional pom which specific)
15465 "Get all properties of the entry at point-or-marker POM.
15466 This includes the TODO keyword, the tags, time strings for deadline,
15467 scheduled, and clocking, and any additional properties defined in the
15468 entry. The return value is an alist, keys may occur multiple times
15469 if the property key was used several times.
15470 POM may also be nil, in which case the current entry is used.
15471 If WHICH is nil or `all', get all properties. If WHICH is
15472 `special' or `standard', only get that subclass. If WHICH
15473 is a string only get exactly this property. SPECIFIC can be a string, the
15474 specific property we are interested in. Specifying it can speed
15475 things up because then unnecessary parsing is avoided."
15476 (setq which (or which 'all))
15477 (org-with-wide-buffer
15478 (org-with-point-at pom
15479 (let ((clockstr (substring org-clock-string 0 -1))
15480 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15481 (case-fold-search nil)
15482 beg end range props sum-props key key1 value string clocksum clocksumt)
15483 (when (and (derived-mode-p 'org-mode)
15484 (ignore-errors (org-back-to-heading t)))
15485 (setq beg (point))
15486 (setq sum-props (get-text-property (point) 'org-summaries))
15487 (setq clocksum (get-text-property (point) :org-clock-minutes)
15488 clocksumt (get-text-property (point) :org-clock-minutes-today))
15489 (outline-next-heading)
15490 (setq end (point))
15491 (when (memq which '(all special))
15492 ;; Get the special properties, like TODO and tags
15493 (goto-char beg)
15494 (when (and (or (not specific) (string= specific "TODO"))
15495 (looking-at org-todo-line-regexp) (match-end 2))
15496 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15497 (when (and (or (not specific) (string= specific "PRIORITY"))
15498 (looking-at org-priority-regexp))
15499 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15500 (when (or (not specific) (string= specific "FILE"))
15501 (push (cons "FILE" buffer-file-name) props))
15502 (when (and (or (not specific) (string= specific "TAGS"))
15503 (setq value (org-get-tags-string))
15504 (string-match "\\S-" value))
15505 (push (cons "TAGS" value) props))
15506 (when (and (or (not specific) (string= specific "ALLTAGS"))
15507 (setq value (org-get-tags-at)))
15508 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15509 ":"))
15510 props))
15511 (when (or (not specific) (string= specific "BLOCKED"))
15512 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15513 (when (or (not specific)
15514 (member specific
15515 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15516 "TIMESTAMP" "TIMESTAMP_IA")))
15517 (catch 'match
15518 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15519 (not (text-property-any 0 (length (match-string 0))
15520 'face 'font-lock-comment-face
15521 (match-string 0))))
15522 (setq key (if (match-end 1)
15523 (substring (org-match-string-no-properties 1)
15524 0 -1))
15525 string (if (equal key clockstr)
15526 (org-trim
15527 (buffer-substring-no-properties
15528 (match-beginning 3) (goto-char
15529 (point-at-eol))))
15530 (substring (org-match-string-no-properties 3)
15531 1 -1)))
15532 ;; Get the correct property name from the key. This is
15533 ;; necessary if the user has configured time keywords.
15534 (setq key1 (concat key ":"))
15535 (cond
15536 ((not key)
15537 (setq key
15538 (if (= (char-after (match-beginning 3)) ?\[)
15539 "TIMESTAMP_IA" "TIMESTAMP")))
15540 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15541 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15542 ((equal key1 org-closed-string) (setq key "CLOSED"))
15543 ((equal key1 org-clock-string) (setq key "CLOCK")))
15544 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15545 (progn
15546 (push (cons key string) props)
15547 ;; no need to search further if match is found
15548 (throw 'match t))
15549 (when (or (equal key "CLOCK") (not (assoc key props)))
15550 (push (cons key string) props)))))))
15552 (when (memq which '(all standard))
15553 ;; Get the standard properties, like :PROP: ...
15554 (setq range (org-get-property-block beg))
15555 (when range
15556 (goto-char (car range))
15557 (while (re-search-forward org-property-re
15558 (cdr range) t)
15559 (setq key (org-match-string-no-properties 2)
15560 value (org-trim (or (org-match-string-no-properties 3) "")))
15561 (unless (member key excluded)
15562 (push (cons key (or value "")) props)))))
15563 (if clocksum
15564 (push (cons "CLOCKSUM"
15565 (org-columns-number-to-string (/ (float clocksum) 60.)
15566 'add_times))
15567 props))
15568 (if clocksumt
15569 (push (cons "CLOCKSUM_T"
15570 (org-columns-number-to-string (/ (float clocksumt) 60.)
15571 'add_times))
15572 props))
15573 (unless (assoc "CATEGORY" props)
15574 (push (cons "CATEGORY" (org-get-category)) props))
15575 (append sum-props (nreverse props)))))))
15577 (defun org-entry-get (pom property &optional inherit literal-nil)
15578 "Get value of PROPERTY for entry or content at point-or-marker POM.
15579 If INHERIT is non-nil and the entry does not have the property,
15580 then also check higher levels of the hierarchy.
15581 If INHERIT is the symbol `selective', use inheritance only if the setting
15582 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15583 If the property is present but empty, the return value is the empty string.
15584 If the property is not present at all, nil is returned.
15586 Return the value as a string.
15588 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15589 do not interpret it as the list atom nil. This is used for inheritance
15590 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15591 (org-with-point-at pom
15592 (if (and inherit (if (eq inherit 'selective)
15593 (org-property-inherit-p property)
15595 (org-entry-get-with-inheritance property literal-nil)
15596 (if (member property org-special-properties)
15597 ;; We need a special property. Use `org-entry-properties'
15598 ;; to retrieve it, but specify the wanted property
15599 (cdr (assoc property (org-entry-properties nil 'special property)))
15600 (org-with-wide-buffer
15601 (let ((range (org-get-property-block)))
15602 (when (and range (not (eq (car range) (cdr range)))
15603 (save-excursion
15604 (goto-char (car range))
15605 (re-search-forward
15606 (concat (org-re-property property) "\\|"
15607 (org-re-property (concat property "+")))
15608 (cdr range) t)))
15609 (let* ((props
15610 (list (or (assoc property org-file-properties)
15611 (assoc property org-global-properties)
15612 (assoc property org-global-properties-fixed))))
15613 (ap (lambda (key)
15614 (when (re-search-forward
15615 (org-re-property key) (cdr range) t)
15616 (setq props
15617 (org-update-property-plist
15619 (if (match-end 3)
15620 (org-match-string-no-properties 3) "")
15621 props)))))
15622 val)
15623 (goto-char (car range))
15624 (funcall ap property)
15625 (goto-char (car range))
15626 (while (funcall ap (concat property "+")))
15627 (setq val (cdr (assoc property props)))
15628 (when val (if literal-nil val (org-not-nil val)))))))))))
15630 (defun org-property-or-variable-value (var &optional inherit)
15631 "Check if there is a property fixing the value of VAR.
15632 If yes, return this value. If not, return the current value of the variable."
15633 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15634 (if (and prop (stringp prop) (string-match "\\S-" prop))
15635 (read prop)
15636 (symbol-value var))))
15638 (defun org-entry-delete (pom property)
15639 "Delete the property PROPERTY from entry at point-or-marker POM."
15640 (unless (member property org-special-properties)
15641 (org-with-point-at pom
15642 (let ((range (org-get-property-block)))
15643 (if (and range
15644 (goto-char (car range))
15645 (re-search-forward
15646 (org-re-property property nil t)
15647 (cdr range) t))
15648 (progn
15649 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15650 (org-remove-empty-drawer-at (car range))
15652 nil)))))
15654 ;; Multi-values properties are properties that contain multiple values
15655 ;; These values are assumed to be single words, separated by whitespace.
15656 (defun org-entry-add-to-multivalued-property (pom property value)
15657 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15658 (let* ((old (org-entry-get pom property))
15659 (values (and old (org-split-string old "[ \t]"))))
15660 (setq value (org-entry-protect-space value))
15661 (unless (member value values)
15662 (setq values (append values (list value)))
15663 (org-entry-put pom property
15664 (mapconcat 'identity values " ")))))
15666 (defun org-entry-remove-from-multivalued-property (pom property value)
15667 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15668 (let* ((old (org-entry-get pom property))
15669 (values (and old (org-split-string old "[ \t]"))))
15670 (setq value (org-entry-protect-space value))
15671 (when (member value values)
15672 (setq values (delete value values))
15673 (org-entry-put pom property
15674 (mapconcat 'identity values " ")))))
15676 (defun org-entry-member-in-multivalued-property (pom property value)
15677 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15678 (let* ((old (org-entry-get pom property))
15679 (values (and old (org-split-string old "[ \t]"))))
15680 (setq value (org-entry-protect-space value))
15681 (member value values)))
15683 (defun org-entry-get-multivalued-property (pom property)
15684 "Return a list of values in a multivalued property."
15685 (let* ((value (org-entry-get pom property))
15686 (values (and value (org-split-string value "[ \t]"))))
15687 (mapcar 'org-entry-restore-space values)))
15689 (defun org-entry-put-multivalued-property (pom property &rest values)
15690 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15691 VALUES should be a list of strings. Spaces will be protected."
15692 (org-entry-put pom property
15693 (mapconcat 'org-entry-protect-space values " "))
15694 (let* ((value (org-entry-get pom property))
15695 (values (and value (org-split-string value "[ \t]"))))
15696 (mapcar 'org-entry-restore-space values)))
15698 (defun org-entry-protect-space (s)
15699 "Protect spaces and newline in string S."
15700 (while (string-match " " s)
15701 (setq s (replace-match "%20" t t s)))
15702 (while (string-match "\n" s)
15703 (setq s (replace-match "%0A" t t s)))
15706 (defun org-entry-restore-space (s)
15707 "Restore spaces and newline in string S."
15708 (while (string-match "%20" s)
15709 (setq s (replace-match " " t t s)))
15710 (while (string-match "%0A" s)
15711 (setq s (replace-match "\n" t t s)))
15714 (defvar org-entry-property-inherited-from (make-marker)
15715 "Marker pointing to the entry from where a property was inherited.
15716 Each call to `org-entry-get-with-inheritance' will set this marker to the
15717 location of the entry where the inheritance search matched. If there was
15718 no match, the marker will point nowhere.
15719 Note that also `org-entry-get' calls this function, if the INHERIT flag
15720 is set.")
15722 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15723 "Get PROPERTY of entry or content at point, search higher levels if needed.
15724 The search will stop at the first ancestor which has the property defined.
15725 If the value found is \"nil\", return nil to show that the property
15726 should be considered as undefined (this is the meaning of nil here).
15727 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15728 (move-marker org-entry-property-inherited-from nil)
15729 (let (tmp)
15730 (save-excursion
15731 (save-restriction
15732 (widen)
15733 (catch 'ex
15734 (while t
15735 (when (setq tmp (org-entry-get nil property nil literal-nil))
15736 (or (ignore-errors (org-back-to-heading t))
15737 (goto-char (point-min)))
15738 (move-marker org-entry-property-inherited-from (point))
15739 (throw 'ex tmp))
15740 (or (ignore-errors (org-up-heading-safe))
15741 (throw 'ex nil))))))
15742 (setq tmp (or tmp
15743 (cdr (assoc property org-file-properties))
15744 (cdr (assoc property org-global-properties))
15745 (cdr (assoc property org-global-properties-fixed))))
15746 (if literal-nil tmp (org-not-nil tmp))))
15748 (defvar org-property-changed-functions nil
15749 "Hook called when the value of a property has changed.
15750 Each hook function should accept two arguments, the name of the property
15751 and the new value.")
15753 (defun org-entry-put (pom property value)
15754 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15755 If the value is `nil', it is converted to the empty string.
15756 If it is not a string, an error is raised."
15757 (cond ((null value) (setq value ""))
15758 ((not (stringp value))
15759 (error "Properties values should be strings.")))
15760 (org-with-point-at pom
15761 (org-back-to-heading t)
15762 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15763 range)
15764 (cond
15765 ((equal property "TODO")
15766 (when (and (string-match "\\S-" value)
15767 (not (member value org-todo-keywords-1)))
15768 (user-error "\"%s\" is not a valid TODO state" value))
15769 (if (or (not value)
15770 (not (string-match "\\S-" value)))
15771 (setq value 'none))
15772 (org-todo value)
15773 (org-set-tags nil 'align))
15774 ((equal property "PRIORITY")
15775 (org-priority (if (and value (string-match "\\S-" value))
15776 (string-to-char value) ?\ ))
15777 (org-set-tags nil 'align))
15778 ((equal property "CLOCKSUM")
15779 (if (not (re-search-forward
15780 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15781 (error "Cannot find a clock log")
15782 (goto-char (- (match-end 1) 2))
15783 (cond
15784 ((eq value 'earlier) (org-timestamp-down))
15785 ((eq value 'later) (org-timestamp-up)))
15786 (org-clock-sum-current-item)))
15787 ((equal property "SCHEDULED")
15788 (if (re-search-forward org-scheduled-time-regexp end t)
15789 (cond
15790 ((eq value 'earlier) (org-timestamp-change -1 'day))
15791 ((eq value 'later) (org-timestamp-change 1 'day))
15792 (t (call-interactively 'org-schedule)))
15793 (call-interactively 'org-schedule)))
15794 ((equal property "DEADLINE")
15795 (if (re-search-forward org-deadline-time-regexp end t)
15796 (cond
15797 ((eq value 'earlier) (org-timestamp-change -1 'day))
15798 ((eq value 'later) (org-timestamp-change 1 'day))
15799 (t (call-interactively 'org-deadline)))
15800 (call-interactively 'org-deadline)))
15801 ((member property org-special-properties)
15802 (error "The %s property can not yet be set with `org-entry-put'"
15803 property))
15804 (t ; a non-special property
15805 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15806 (setq range (org-get-property-block beg 'force))
15807 (goto-char (car range))
15808 (if (re-search-forward
15809 (org-re-property property nil t) (cdr range) t)
15810 (progn
15811 (delete-region (match-beginning 0) (match-end 0))
15812 (goto-char (match-beginning 0)))
15813 (goto-char (cdr range))
15814 (insert "\n")
15815 (backward-char 1)
15816 (org-indent-line))
15817 (insert ":" property ":")
15818 (and value (insert " " value))
15819 (org-indent-line)))))
15820 (run-hook-with-args 'org-property-changed-functions property value)))
15822 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15823 "Get all property keys in the current buffer.
15824 With INCLUDE-SPECIALS, also list the special properties that reflect things
15825 like tags and TODO state.
15826 With INCLUDE-DEFAULTS, also include properties that has special meaning
15827 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15828 and others.
15829 With INCLUDE-COLUMNS, also include property names given in COLUMN
15830 formats in the current buffer."
15831 (let (rtn range cfmt s p)
15832 (save-excursion
15833 (save-restriction
15834 (widen)
15835 (goto-char (point-min))
15836 (while (re-search-forward org-property-start-re nil t)
15837 (catch 'cont
15838 (setq range (or (org-get-property-block)
15839 (if (y-or-n-p
15840 (format "Malformed drawer at %d, repair?" (point)))
15841 (org-get-property-block nil t)
15842 (throw 'cont nil))))
15843 (goto-char (car range))
15844 (while (re-search-forward org-property-re
15845 (cdr range) t)
15846 (add-to-list 'rtn (org-match-string-no-properties 2)))
15847 (outline-next-heading)))))
15849 (when include-specials
15850 (setq rtn (append org-special-properties rtn)))
15852 (when include-defaults
15853 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15854 (add-to-list 'rtn org-effort-property))
15856 (when include-columns
15857 (save-excursion
15858 (save-restriction
15859 (widen)
15860 (goto-char (point-min))
15861 (while (re-search-forward
15862 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15863 nil t)
15864 (setq cfmt (match-string 2) s 0)
15865 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15866 cfmt s)
15867 (setq s (match-end 0)
15868 p (match-string 1 cfmt))
15869 (unless (or (equal p "ITEM")
15870 (member p org-special-properties))
15871 (add-to-list 'rtn (match-string 1 cfmt))))))))
15873 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15875 (defun org-property-values (key)
15876 "Return a list of all values of property KEY in the current buffer."
15877 (save-excursion
15878 (save-restriction
15879 (widen)
15880 (goto-char (point-min))
15881 (let ((re (org-re-property key))
15882 values)
15883 (while (re-search-forward re nil t)
15884 (add-to-list 'values (org-trim (match-string 3))))
15885 (delete "" values)))))
15887 (defun org-insert-property-drawer ()
15888 "Insert a property drawer into the current entry."
15889 (org-back-to-heading t)
15890 (looking-at org-outline-regexp)
15891 (let ((indent (if org-adapt-indentation
15892 (- (match-end 0) (match-beginning 0))
15894 (beg (point))
15895 (re (concat "^[ \t]*" org-keyword-time-regexp))
15896 (org-clock-re (format "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|%s\\|:END:\\)"
15897 org-clock-string))
15898 (org-skip-line-list (list org-clock-string ":END:"))
15899 end hiddenp)
15900 (outline-next-heading)
15901 (setq end (point))
15902 (goto-char beg)
15903 (while (re-search-forward re end t))
15904 (setq hiddenp (outline-invisible-p))
15905 (end-of-line 1)
15906 (and (equal (char-after) ?\n) (forward-char 1))
15907 (while (looking-at org-clock-re)
15908 (if (member (match-string 1) org-skip-line-list)
15909 ;; just skip this line
15910 (beginning-of-line 2)
15911 ;; Drawer start, find the end
15912 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15913 (beginning-of-line 1)))
15914 (org-skip-over-state-notes)
15915 (skip-chars-backward " \t\n\r")
15916 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15917 (forward-char 1))
15918 (goto-char (point-at-eol))
15919 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15920 (beginning-of-line 0)
15921 (org-indent-to-column indent)
15922 (beginning-of-line 2)
15923 (org-indent-to-column indent)
15924 (beginning-of-line 0)
15925 (if hiddenp
15926 (save-excursion
15927 (org-back-to-heading t)
15928 (hide-entry))
15929 (org-flag-drawer t))))
15931 (defun org-insert-drawer (&optional arg drawer)
15932 "Insert a drawer at point.
15934 Optional argument DRAWER, when non-nil, is a string representing
15935 drawer's name. Otherwise, the user is prompted for a name.
15937 If a region is active, insert the drawer around that region
15938 instead.
15940 Point is left between drawer's boundaries."
15941 (interactive "P")
15942 (let* ((drawer (if arg "PROPERTIES"
15943 (or drawer (read-from-minibuffer "Drawer: ")))))
15944 (cond
15945 ;; With C-u, fall back on `org-insert-property-drawer'
15946 (arg (org-insert-property-drawer))
15948 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15949 (user-error "Invalid drawer name"))
15950 ;; With an active region, insert a drawer at point.
15951 ((not (org-region-active-p))
15952 (progn
15953 (unless (bolp) (insert "\n"))
15954 (insert (format ":%s:\n\n:END:\n" drawer))
15955 (forward-line -2)))
15956 ;; Otherwise, insert the drawer at point
15958 (let ((rbeg (region-beginning))
15959 (rend (copy-marker (region-end))))
15960 (unwind-protect
15961 (progn
15962 (goto-char rbeg)
15963 (beginning-of-line)
15964 (when (save-excursion
15965 (re-search-forward org-outline-regexp-bol rend t))
15966 (user-error "Drawers cannot contain headlines"))
15967 ;; Position point at the beginning of the first
15968 ;; non-blank line in region. Insert drawer's opening
15969 ;; there, then indent it.
15970 (org-skip-whitespace)
15971 (beginning-of-line)
15972 (insert ":" drawer ":\n")
15973 (forward-line -1)
15974 (indent-for-tab-command)
15975 ;; Move point to the beginning of the first blank line
15976 ;; after the last non-blank line in region. Insert
15977 ;; drawer's closing, then indent it.
15978 (goto-char rend)
15979 (skip-chars-backward " \r\t\n")
15980 (insert "\n:END:")
15981 (deactivate-mark t)
15982 (indent-for-tab-command)
15983 (unless (eolp) (insert "\n")))
15984 ;; Clear marker, whatever the outcome of insertion is.
15985 (set-marker rend nil)))))))
15987 (defvar org-property-set-functions-alist nil
15988 "Property set function alist.
15989 Each entry should have the following format:
15991 (PROPERTY . READ-FUNCTION)
15993 The read function will be called with the same argument as
15994 `org-completing-read'.")
15996 (defun org-set-property-function (property)
15997 "Get the function that should be used to set PROPERTY.
15998 This is computed according to `org-property-set-functions-alist'."
15999 (or (cdr (assoc property org-property-set-functions-alist))
16000 'org-completing-read))
16002 (defun org-read-property-value (property)
16003 "Read PROPERTY value from user."
16004 (let* ((completion-ignore-case t)
16005 (allowed (org-property-get-allowed-values nil property 'table))
16006 (cur (org-entry-get nil property))
16007 (prompt (concat property " value"
16008 (if (and cur (string-match "\\S-" cur))
16009 (concat " [" cur "]") "") ": "))
16010 (set-function (org-set-property-function property))
16011 (val (if allowed
16012 (funcall set-function prompt allowed nil
16013 (not (get-text-property 0 'org-unrestricted
16014 (caar allowed))))
16015 (let (org-completion-use-ido org-completion-use-iswitchb)
16016 (funcall set-function prompt
16017 (mapcar 'list (org-property-values property))
16018 nil nil "" nil cur)))))
16019 (org-trim val)))
16021 (defvar org-last-set-property nil)
16022 (defvar org-last-set-property-value nil)
16023 (defun org-read-property-name ()
16024 "Read a property name."
16025 (let* ((completion-ignore-case t)
16026 (keys (org-buffer-property-keys nil t t))
16027 (default-prop (or (save-excursion
16028 (save-match-data
16029 (beginning-of-line)
16030 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16031 (null (string= (match-string 1) "END"))
16032 (match-string 1))))
16033 org-last-set-property))
16034 (property (org-icompleting-read
16035 (concat "Property"
16036 (if default-prop (concat " [" default-prop "]") "")
16037 ": ")
16038 (mapcar 'list keys)
16039 nil nil nil nil
16040 default-prop)))
16041 (if (member property keys)
16042 property
16043 (or (cdr (assoc (downcase property)
16044 (mapcar (lambda (x) (cons (downcase x) x))
16045 keys)))
16046 property))))
16048 (defun org-set-property-and-value (use-last)
16049 "Allow to set [PROPERTY]: [value] direction from prompt.
16050 When use-default, don't even ask, just use the last
16051 \"[PROPERTY]: [value]\" string from the history."
16052 (interactive "P")
16053 (let* ((completion-ignore-case t)
16054 (pv (or (and use-last org-last-set-property-value)
16055 (org-completing-read
16056 "Enter a \"[Property]: [value]\" pair: "
16057 nil nil nil nil nil
16058 org-last-set-property-value)))
16059 prop val)
16060 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16061 (setq prop (match-string 1 pv)
16062 val (match-string 2 pv))
16063 (org-set-property prop val))))
16065 (defun org-set-property (property value)
16066 "In the current entry, set PROPERTY to VALUE.
16067 When called interactively, this will prompt for a property name, offering
16068 completion on existing and default properties. And then it will prompt
16069 for a value, offering completion either on allowed values (via an inherited
16070 xxx_ALL property) or on existing values in other instances of this property
16071 in the current file."
16072 (interactive (list nil nil))
16073 (let* ((property (or property (org-read-property-name)))
16074 (value (or value (org-read-property-value property)))
16075 (fn (cdr (assoc property org-properties-postprocess-alist))))
16076 (setq org-last-set-property property)
16077 (setq org-last-set-property-value (concat property ": " value))
16078 ;; Possibly postprocess the inserted value:
16079 (when fn (setq value (funcall fn value)))
16080 (unless (equal (org-entry-get nil property) value)
16081 (org-entry-put nil property value))))
16083 (defun org-delete-property (property)
16084 "In the current entry, delete PROPERTY."
16085 (interactive
16086 (let* ((completion-ignore-case t)
16087 (cat (org-entry-get (point) "CATEGORY"))
16088 (props0 (org-entry-properties nil 'standard))
16089 (props (if cat props0
16090 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16091 (prop (if (< 1 (length props))
16092 (org-icompleting-read "Property: " props nil t)
16093 (caar props))))
16094 (list prop)))
16095 (if (not property)
16096 (message "No property to delete in this entry")
16097 (org-entry-delete nil property)
16098 (message "Property \"%s\" deleted" property)))
16100 (defun org-delete-property-globally (property)
16101 "Remove PROPERTY globally, from all entries."
16102 (interactive
16103 (let* ((completion-ignore-case t)
16104 (prop (org-icompleting-read
16105 "Globally remove property: "
16106 (mapcar 'list (org-buffer-property-keys)))))
16107 (list prop)))
16108 (save-excursion
16109 (save-restriction
16110 (widen)
16111 (goto-char (point-min))
16112 (let ((cnt 0))
16113 (while (re-search-forward
16114 (org-re-property property)
16115 nil t)
16116 (setq cnt (1+ cnt))
16117 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16118 (message "Property \"%s\" removed from %d entries" property cnt)))))
16120 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16122 (defun org-compute-property-at-point ()
16123 "Compute the property at point.
16124 This looks for an enclosing column format, extracts the operator and
16125 then applies it to the property in the column format's scope."
16126 (interactive)
16127 (unless (org-at-property-p)
16128 (user-error "Not at a property"))
16129 (let ((prop (org-match-string-no-properties 2)))
16130 (org-columns-get-format-and-top-level)
16131 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16132 (user-error "No operator defined for property %s" prop))
16133 (org-columns-compute prop)))
16135 (defvar org-property-allowed-value-functions nil
16136 "Hook for functions supplying allowed values for a specific property.
16137 The functions must take a single argument, the name of the property, and
16138 return a flat list of allowed values. If \":ETC\" is one of
16139 the values, this means that these values are intended as defaults for
16140 completion, but that other values should be allowed too.
16141 The functions must return nil if they are not responsible for this
16142 property.")
16144 (defun org-property-get-allowed-values (pom property &optional table)
16145 "Get allowed values for the property PROPERTY.
16146 When TABLE is non-nil, return an alist that can directly be used for
16147 completion."
16148 (let (vals)
16149 (cond
16150 ((equal property "TODO")
16151 (setq vals (org-with-point-at pom
16152 (append org-todo-keywords-1 '("")))))
16153 ((equal property "PRIORITY")
16154 (let ((n org-lowest-priority))
16155 (while (>= n org-highest-priority)
16156 (push (char-to-string n) vals)
16157 (setq n (1- n)))))
16158 ((member property org-special-properties))
16159 ((setq vals (run-hook-with-args-until-success
16160 'org-property-allowed-value-functions property)))
16162 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16163 (when (and vals (string-match "\\S-" vals))
16164 (setq vals (car (read-from-string (concat "(" vals ")"))))
16165 (setq vals (mapcar (lambda (x)
16166 (cond ((stringp x) x)
16167 ((numberp x) (number-to-string x))
16168 ((symbolp x) (symbol-name x))
16169 (t "???")))
16170 vals)))))
16171 (when (member ":ETC" vals)
16172 (setq vals (remove ":ETC" vals))
16173 (org-add-props (car vals) '(org-unrestricted t)))
16174 (if table (mapcar 'list vals) vals)))
16176 (defun org-property-previous-allowed-value (&optional previous)
16177 "Switch to the next allowed value for this property."
16178 (interactive)
16179 (org-property-next-allowed-value t))
16181 (defun org-property-next-allowed-value (&optional previous)
16182 "Switch to the next allowed value for this property."
16183 (interactive)
16184 (unless (org-at-property-p)
16185 (user-error "Not at a property"))
16186 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16187 (key (match-string 2))
16188 (value (match-string 3))
16189 (allowed (or (org-property-get-allowed-values (point) key)
16190 (and (member value '("[ ]" "[-]" "[X]"))
16191 '("[ ]" "[X]"))))
16192 (heading (save-match-data (nth 4 (org-heading-components))))
16193 nval)
16194 (unless allowed
16195 (user-error "Allowed values for this property have not been defined"))
16196 (if previous (setq allowed (reverse allowed)))
16197 (if (member value allowed)
16198 (setq nval (car (cdr (member value allowed)))))
16199 (setq nval (or nval (car allowed)))
16200 (if (equal nval value)
16201 (user-error "Only one allowed value for this property"))
16202 (org-at-property-p)
16203 (replace-match (concat " :" key ": " nval) t t)
16204 (org-indent-line)
16205 (beginning-of-line 1)
16206 (skip-chars-forward " \t")
16207 (when (equal prop org-effort-property)
16208 (org-refresh-property
16209 '((effort . identity)
16210 (effort-minutes . org-duration-string-to-minutes))
16211 nval)
16212 (when (string= org-clock-current-task heading)
16213 (setq org-clock-effort nval)
16214 (org-clock-update-mode-line)))
16215 (run-hook-with-args 'org-property-changed-functions key nval)))
16217 (defun org-find-olp (path &optional this-buffer)
16218 "Return a marker pointing to the entry at outline path OLP.
16219 If anything goes wrong, throw an error.
16220 You can wrap this call to catch the error like this:
16222 (condition-case msg
16223 (org-mobile-locate-entry (match-string 4))
16224 (error (nth 1 msg)))
16226 The return value will then be either a string with the error message,
16227 or a marker if everything is OK.
16229 If THIS-BUFFER is set, the outline path does not contain a file,
16230 only headings."
16231 (let* ((file (if this-buffer buffer-file-name (pop path)))
16232 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16233 (level 1)
16234 (lmin 1)
16235 (lmax 1)
16236 limit re end found pos heading cnt flevel)
16237 (unless buffer (error "File not found :%s" file))
16238 (with-current-buffer buffer
16239 (save-excursion
16240 (save-restriction
16241 (widen)
16242 (setq limit (point-max))
16243 (goto-char (point-min))
16244 (while (setq heading (pop path))
16245 (setq re (format org-complex-heading-regexp-format
16246 (regexp-quote heading)))
16247 (setq cnt 0 pos (point))
16248 (while (re-search-forward re end t)
16249 (setq level (- (match-end 1) (match-beginning 1)))
16250 (if (and (>= level lmin) (<= level lmax))
16251 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16252 (when (= cnt 0) (error "Heading not found on level %d: %s"
16253 lmax heading))
16254 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16255 lmax heading))
16256 (goto-char found)
16257 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16258 (setq end (save-excursion (org-end-of-subtree t t))))
16259 (when (org-at-heading-p)
16260 (point-marker)))))))
16262 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16263 "Find node HEADING in BUFFER.
16264 Return a marker to the heading if it was found, or nil if not.
16265 If POS-ONLY is set, return just the position instead of a marker.
16267 The heading text must match exact, but it may have a TODO keyword,
16268 a priority cookie and tags in the standard locations."
16269 (with-current-buffer (or buffer (current-buffer))
16270 (save-excursion
16271 (save-restriction
16272 (widen)
16273 (goto-char (point-min))
16274 (let (case-fold-search)
16275 (if (re-search-forward
16276 (format org-complex-heading-regexp-format
16277 (regexp-quote heading)) nil t)
16278 (if pos-only
16279 (match-beginning 0)
16280 (move-marker (make-marker) (match-beginning 0)))))))))
16282 (defun org-find-exact-heading-in-directory (heading &optional dir)
16283 "Find Org node headline HEADING in all .org files in directory DIR.
16284 When the target headline is found, return a marker to this location."
16285 (let ((files (directory-files (or dir default-directory)
16286 t "\\`[^.#].*\\.org\\'"))
16287 file visiting m buffer)
16288 (catch 'found
16289 (while (setq file (pop files))
16290 (message "trying %s" file)
16291 (setq visiting (org-find-base-buffer-visiting file))
16292 (setq buffer (or visiting (find-file-noselect file)))
16293 (setq m (org-find-exact-headline-in-buffer
16294 heading buffer))
16295 (when (and (not m) (not visiting)) (kill-buffer buffer))
16296 (and m (throw 'found m))))))
16298 (defun org-find-entry-with-id (ident)
16299 "Locate the entry that contains the ID property with exact value IDENT.
16300 IDENT can be a string, a symbol or a number, this function will search for
16301 the string representation of it.
16302 Return the position where this entry starts, or nil if there is no such entry."
16303 (interactive "sID: ")
16304 (let ((id (cond
16305 ((stringp ident) ident)
16306 ((symbol-name ident) (symbol-name ident))
16307 ((numberp ident) (number-to-string ident))
16308 (t (error "IDENT %s must be a string, symbol or number" ident))))
16309 (case-fold-search nil))
16310 (save-excursion
16311 (save-restriction
16312 (widen)
16313 (goto-char (point-min))
16314 (when (re-search-forward
16315 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16316 nil t)
16317 (org-back-to-heading t)
16318 (point))))))
16320 ;;;; Timestamps
16322 (defvar org-last-changed-timestamp nil)
16323 (defvar org-last-inserted-timestamp nil
16324 "The last time stamp inserted with `org-insert-time-stamp'.")
16325 (defvar org-ts-what) ; dynamically scoped parameter
16327 (defun org-time-stamp (arg &optional inactive)
16328 "Prompt for a date/time and insert a time stamp.
16329 If the user specifies a time like HH:MM or if this command is
16330 called with at least one prefix argument, the time stamp contains
16331 the date and the time. Otherwise, only the date is be included.
16333 All parts of a date not specified by the user is filled in from
16334 the current date/time. So if you just press return without
16335 typing anything, the time stamp will represent the current
16336 date/time.
16338 If there is already a timestamp at the cursor, it will be
16339 modified.
16341 With two universal prefix arguments, insert an active timestamp
16342 with the current time without prompting the user.
16344 When called from lisp, the timestamp is inactive if INACTIVE is
16345 non-nil."
16346 (interactive "P")
16347 (let* ((ts nil)
16348 (default-time
16349 ;; Default time is either today, or, when entering a range,
16350 ;; the range start.
16351 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16352 (save-excursion
16353 (re-search-backward
16354 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16355 (- (point) 20) t)))
16356 (apply 'encode-time (org-parse-time-string (match-string 1)))
16357 (current-time)))
16358 (default-input (and ts (org-get-compact-tod ts)))
16359 (repeater (save-excursion
16360 (save-match-data
16361 (beginning-of-line)
16362 (when (re-search-forward
16363 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16364 (save-excursion (progn (end-of-line) (point))) t)
16365 (match-string 0)))))
16366 org-time-was-given org-end-time-was-given time)
16367 (cond
16368 ((and (org-at-timestamp-p t)
16369 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16370 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16371 (insert "--")
16372 (setq time (let ((this-command this-command))
16373 (org-read-date arg 'totime nil nil
16374 default-time default-input inactive)))
16375 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16376 ((org-at-timestamp-p t)
16377 (setq time (let ((this-command this-command))
16378 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16379 (when (org-at-timestamp-p t) ; just to get the match data
16380 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16381 (replace-match "")
16382 (setq org-last-changed-timestamp
16383 (org-insert-time-stamp
16384 time (or org-time-was-given arg)
16385 inactive nil nil (list org-end-time-was-given)))
16386 (when repeater (goto-char (1- (point))) (insert " " repeater)
16387 (setq org-last-changed-timestamp
16388 (concat (substring org-last-inserted-timestamp 0 -1)
16389 " " repeater ">"))))
16390 (message "Timestamp updated"))
16391 ((equal arg '(16))
16392 (org-insert-time-stamp (current-time) t inactive))
16394 (setq time (let ((this-command this-command))
16395 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16396 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16397 nil nil (list org-end-time-was-given))))))
16399 ;; FIXME: can we use this for something else, like computing time differences?
16400 (defun org-get-compact-tod (s)
16401 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16402 (let* ((t1 (match-string 1 s))
16403 (h1 (string-to-number (match-string 2 s)))
16404 (m1 (string-to-number (match-string 3 s)))
16405 (t2 (and (match-end 4) (match-string 5 s)))
16406 (h2 (and t2 (string-to-number (match-string 6 s))))
16407 (m2 (and t2 (string-to-number (match-string 7 s))))
16408 dh dm)
16409 (if (not t2)
16411 (setq dh (- h2 h1) dm (- m2 m1))
16412 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16413 (concat t1 "+" (number-to-string dh)
16414 (and (/= 0 dm) (format ":%02d" dm)))))))
16416 (defun org-time-stamp-inactive (&optional arg)
16417 "Insert an inactive time stamp.
16418 An inactive time stamp is enclosed in square brackets instead of angle
16419 brackets. It is inactive in the sense that it does not trigger agenda entries,
16420 does not link to the calendar and cannot be changed with the S-cursor keys.
16421 So these are more for recording a certain time/date."
16422 (interactive "P")
16423 (org-time-stamp arg 'inactive))
16425 (defvar org-date-ovl (make-overlay 1 1))
16426 (overlay-put org-date-ovl 'face 'org-date-selected)
16427 (org-detach-overlay org-date-ovl)
16429 (defvar org-ans1) ; dynamically scoped parameter
16430 (defvar org-ans2) ; dynamically scoped parameter
16432 (defvar org-plain-time-of-day-regexp) ; defined below
16434 (defvar org-overriding-default-time nil) ; dynamically scoped
16435 (defvar org-read-date-overlay nil)
16436 (defvar org-dcst nil) ; dynamically scoped
16437 (defvar org-read-date-history nil)
16438 (defvar org-read-date-final-answer nil)
16439 (defvar org-read-date-analyze-futurep nil)
16440 (defvar org-read-date-analyze-forced-year nil)
16441 (defvar org-read-date-inactive)
16443 (defvar org-read-date-minibuffer-local-map
16444 (let* ((org-replace-disputed-keys nil)
16445 (map (make-sparse-keymap)))
16446 (set-keymap-parent map minibuffer-local-map)
16447 (org-defkey map (kbd ".")
16448 (lambda () (interactive)
16449 ;; Are we at the beginning of the prompt?
16450 (if (looking-back "^[^:]+: ")
16451 (org-eval-in-calendar '(calendar-goto-today))
16452 (insert "."))))
16453 (org-defkey map (kbd "C-.")
16454 (lambda () (interactive)
16455 (org-eval-in-calendar '(calendar-goto-today))))
16456 (org-defkey map [(meta shift left)]
16457 (lambda () (interactive)
16458 (org-eval-in-calendar '(calendar-backward-month 1))))
16459 (org-defkey map [(meta shift right)]
16460 (lambda () (interactive)
16461 (org-eval-in-calendar '(calendar-forward-month 1))))
16462 (org-defkey map [(meta shift up)]
16463 (lambda () (interactive)
16464 (org-eval-in-calendar '(calendar-backward-year 1))))
16465 (org-defkey map [(meta shift down)]
16466 (lambda () (interactive)
16467 (org-eval-in-calendar '(calendar-forward-year 1))))
16468 (org-defkey map [?\e (shift left)]
16469 (lambda () (interactive)
16470 (org-eval-in-calendar '(calendar-backward-month 1))))
16471 (org-defkey map [?\e (shift right)]
16472 (lambda () (interactive)
16473 (org-eval-in-calendar '(calendar-forward-month 1))))
16474 (org-defkey map [?\e (shift up)]
16475 (lambda () (interactive)
16476 (org-eval-in-calendar '(calendar-backward-year 1))))
16477 (org-defkey map [?\e (shift down)]
16478 (lambda () (interactive)
16479 (org-eval-in-calendar '(calendar-forward-year 1))))
16480 (org-defkey map [(shift up)]
16481 (lambda () (interactive)
16482 (org-eval-in-calendar '(calendar-backward-week 1))))
16483 (org-defkey map [(shift down)]
16484 (lambda () (interactive)
16485 (org-eval-in-calendar '(calendar-forward-week 1))))
16486 (org-defkey map [(shift left)]
16487 (lambda () (interactive)
16488 (org-eval-in-calendar '(calendar-backward-day 1))))
16489 (org-defkey map [(shift right)]
16490 (lambda () (interactive)
16491 (org-eval-in-calendar '(calendar-forward-day 1))))
16492 (org-defkey map "!"
16493 (lambda () (interactive)
16494 (org-eval-in-calendar '(diary-view-entries))
16495 (message "")))
16496 (org-defkey map ">"
16497 (lambda () (interactive)
16498 (org-eval-in-calendar '(calendar-scroll-left 1))))
16499 (org-defkey map "<"
16500 (lambda () (interactive)
16501 (org-eval-in-calendar '(calendar-scroll-right 1))))
16502 (org-defkey map "\C-v"
16503 (lambda () (interactive)
16504 (org-eval-in-calendar
16505 '(calendar-scroll-left-three-months 1))))
16506 (org-defkey map "\M-v"
16507 (lambda () (interactive)
16508 (org-eval-in-calendar
16509 '(calendar-scroll-right-three-months 1))))
16510 map)
16511 "Keymap for minibuffer commands when using `org-read-date'.")
16513 (defvar org-def)
16514 (defvar org-defdecode)
16515 (defvar org-with-time)
16517 (defun org-read-date (&optional org-with-time to-time from-string prompt
16518 default-time default-input inactive)
16519 "Read a date, possibly a time, and make things smooth for the user.
16520 The prompt will suggest to enter an ISO date, but you can also enter anything
16521 which will at least partially be understood by `parse-time-string'.
16522 Unrecognized parts of the date will default to the current day, month, year,
16523 hour and minute. If this command is called to replace a timestamp at point,
16524 or to enter the second timestamp of a range, the default time is taken
16525 from the existing stamp. Furthermore, the command prefers the future,
16526 so if you are giving a date where the year is not given, and the day-month
16527 combination is already past in the current year, it will assume you
16528 mean next year. For details, see the manual. A few examples:
16530 3-2-5 --> 2003-02-05
16531 feb 15 --> currentyear-02-15
16532 2/15 --> currentyear-02-15
16533 sep 12 9 --> 2009-09-12
16534 12:45 --> today 12:45
16535 22 sept 0:34 --> currentyear-09-22 0:34
16536 12 --> currentyear-currentmonth-12
16537 Fri --> nearest Friday after today
16538 -Tue --> last Tuesday
16539 etc.
16541 Furthermore you can specify a relative date by giving, as the *first* thing
16542 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16543 change in days weeks, months, years.
16544 With a single plus or minus, the date is relative to today. With a double
16545 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16546 +4d --> four days from today
16547 +4 --> same as above
16548 +2w --> two weeks from today
16549 ++5 --> five days from default date
16551 The function understands only English month and weekday abbreviations.
16553 While prompting, a calendar is popped up - you can also select the
16554 date with the mouse (button 1). The calendar shows a period of three
16555 months. To scroll it to other months, use the keys `>' and `<'.
16556 If you don't like the calendar, turn it off with
16557 \(setq org-read-date-popup-calendar nil)
16559 With optional argument TO-TIME, the date will immediately be converted
16560 to an internal time.
16561 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16562 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16563 still enter a time, and this function will inform the calling routine
16564 about this change. The calling routine may then choose to change the
16565 format used to insert the time stamp into the buffer to include the time.
16566 With optional argument FROM-STRING, read from this string instead from
16567 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16568 the time/date that is used for everything that is not specified by the
16569 user."
16570 (require 'parse-time)
16571 (let* ((org-time-stamp-rounding-minutes
16572 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16573 (org-dcst org-display-custom-times)
16574 (ct (org-current-time))
16575 (org-def (or org-overriding-default-time default-time ct))
16576 (org-defdecode (decode-time org-def))
16577 (dummy (progn
16578 (when (< (nth 2 org-defdecode) org-extend-today-until)
16579 (setcar (nthcdr 2 org-defdecode) -1)
16580 (setcar (nthcdr 1 org-defdecode) 59)
16581 (setq org-def (apply 'encode-time org-defdecode)
16582 org-defdecode (decode-time org-def)))))
16583 (mouse-autoselect-window nil) ; Don't let the mouse jump
16584 (calendar-frame-setup nil)
16585 (calendar-setup nil)
16586 (calendar-move-hook nil)
16587 (calendar-view-diary-initially-flag nil)
16588 (calendar-view-holidays-initially-flag nil)
16589 (timestr (format-time-string
16590 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16591 (prompt (concat (if prompt (concat prompt " ") "")
16592 (format "Date+time [%s]: " timestr)))
16593 ans (org-ans0 "") org-ans1 org-ans2 final)
16595 (cond
16596 (from-string (setq ans from-string))
16597 (org-read-date-popup-calendar
16598 (save-excursion
16599 (save-window-excursion
16600 (calendar)
16601 (org-eval-in-calendar '(setq cursor-type nil) t)
16602 (unwind-protect
16603 (progn
16604 (calendar-forward-day (- (time-to-days org-def)
16605 (calendar-absolute-from-gregorian
16606 (calendar-current-date))))
16607 (org-eval-in-calendar nil t)
16608 (let* ((old-map (current-local-map))
16609 (map (copy-keymap calendar-mode-map))
16610 (minibuffer-local-map
16611 (copy-keymap org-read-date-minibuffer-local-map)))
16612 (org-defkey map (kbd "RET") 'org-calendar-select)
16613 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16614 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16615 (unwind-protect
16616 (progn
16617 (use-local-map map)
16618 (setq org-read-date-inactive inactive)
16619 (add-hook 'post-command-hook 'org-read-date-display)
16620 (setq org-ans0 (read-string prompt default-input
16621 'org-read-date-history nil))
16622 ;; org-ans0: from prompt
16623 ;; org-ans1: from mouse click
16624 ;; org-ans2: from calendar motion
16625 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16626 (remove-hook 'post-command-hook 'org-read-date-display)
16627 (use-local-map old-map)
16628 (when org-read-date-overlay
16629 (delete-overlay org-read-date-overlay)
16630 (setq org-read-date-overlay nil)))))
16631 (bury-buffer "*Calendar*")))))
16633 (t ; Naked prompt only
16634 (unwind-protect
16635 (setq ans (read-string prompt default-input
16636 'org-read-date-history timestr))
16637 (when org-read-date-overlay
16638 (delete-overlay org-read-date-overlay)
16639 (setq org-read-date-overlay nil)))))
16641 (setq final (org-read-date-analyze ans org-def org-defdecode))
16643 (when org-read-date-analyze-forced-year
16644 (message "Year was forced into %s"
16645 (if org-read-date-force-compatible-dates
16646 "compatible range (1970-2037)"
16647 "range representable on this machine"))
16648 (ding))
16650 ;; One round trip to get rid of 34th of August and stuff like that....
16651 (setq final (decode-time (apply 'encode-time final)))
16653 (setq org-read-date-final-answer ans)
16655 (if to-time
16656 (apply 'encode-time final)
16657 (if (and (boundp 'org-time-was-given) org-time-was-given)
16658 (format "%04d-%02d-%02d %02d:%02d"
16659 (nth 5 final) (nth 4 final) (nth 3 final)
16660 (nth 2 final) (nth 1 final))
16661 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16663 (defun org-read-date-display ()
16664 "Display the current date prompt interpretation in the minibuffer."
16665 (when org-read-date-display-live
16666 (when org-read-date-overlay
16667 (delete-overlay org-read-date-overlay))
16668 (when (minibufferp (current-buffer))
16669 (save-excursion
16670 (end-of-line 1)
16671 (while (not (equal (buffer-substring
16672 (max (point-min) (- (point) 4)) (point))
16673 " "))
16674 (insert " ")))
16675 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16676 " " (or org-ans1 org-ans2)))
16677 (org-end-time-was-given nil)
16678 (f (org-read-date-analyze ans org-def org-defdecode))
16679 (fmts (if org-dcst
16680 org-time-stamp-custom-formats
16681 org-time-stamp-formats))
16682 (fmt (if (or org-with-time
16683 (and (boundp 'org-time-was-given) org-time-was-given))
16684 (cdr fmts)
16685 (car fmts)))
16686 (txt (format-time-string fmt (apply 'encode-time f)))
16687 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16688 (txt (concat "=> " txt)))
16689 (when (and org-end-time-was-given
16690 (string-match org-plain-time-of-day-regexp txt))
16691 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16692 org-end-time-was-given
16693 (substring txt (match-end 0)))))
16694 (when org-read-date-analyze-futurep
16695 (setq txt (concat txt " (=>F)")))
16696 (setq org-read-date-overlay
16697 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16698 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16700 (defun org-read-date-analyze (ans org-def org-defdecode)
16701 "Analyze the combined answer of the date prompt."
16702 ;; FIXME: cleanup and comment
16703 (let ((nowdecode (decode-time (current-time)))
16704 delta deltan deltaw deltadef year month day
16705 hour minute second wday pm h2 m2 tl wday1
16706 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16707 (setq org-read-date-analyze-futurep nil
16708 org-read-date-analyze-forced-year nil)
16709 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16710 (setq ans "+0"))
16712 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16713 (setq ans (replace-match "" t t ans)
16714 deltan (car delta)
16715 deltaw (nth 1 delta)
16716 deltadef (nth 2 delta)))
16718 ;; Check if there is an iso week date in there. If yes, store the
16719 ;; info and postpone interpreting it until the rest of the parsing
16720 ;; is done.
16721 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16722 (setq iso-year (if (match-end 1)
16723 (org-small-year-to-year
16724 (string-to-number (match-string 1 ans))))
16725 iso-weekday (if (match-end 3)
16726 (string-to-number (match-string 3 ans)))
16727 iso-week (string-to-number (match-string 2 ans)))
16728 (setq ans (replace-match "" t t ans)))
16730 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16731 (when (string-match
16732 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16733 (setq year (if (match-end 2)
16734 (string-to-number (match-string 2 ans))
16735 (progn (setq kill-year t)
16736 (string-to-number (format-time-string "%Y"))))
16737 month (string-to-number (match-string 3 ans))
16738 day (string-to-number (match-string 4 ans)))
16739 (if (< year 100) (setq year (+ 2000 year)))
16740 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16741 t nil ans)))
16743 ;; Help matching dotted european dates
16744 (when (string-match
16745 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16746 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16747 (setq kill-year t)
16748 (string-to-number (format-time-string "%Y")))
16749 day (string-to-number (match-string 1 ans))
16750 month (string-to-number (match-string 2 ans))
16751 ans (replace-match (format "%04d-%02d-%02d" year month day)
16752 t nil ans)))
16754 ;; Help matching american dates, like 5/30 or 5/30/7
16755 (when (string-match
16756 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16757 (setq year (if (match-end 4)
16758 (string-to-number (match-string 4 ans))
16759 (progn (setq kill-year t)
16760 (string-to-number (format-time-string "%Y"))))
16761 month (string-to-number (match-string 1 ans))
16762 day (string-to-number (match-string 2 ans)))
16763 (if (< year 100) (setq year (+ 2000 year)))
16764 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16765 t nil ans)))
16766 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16767 ;; If there is a time with am/pm, and *no* time without it, we convert
16768 ;; so that matching will be successful.
16769 (loop for i from 1 to 2 do ; twice, for end time as well
16770 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16771 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16772 (setq hour (string-to-number (match-string 1 ans))
16773 minute (if (match-end 3)
16774 (string-to-number (match-string 3 ans))
16776 pm (equal ?p
16777 (string-to-char (downcase (match-string 4 ans)))))
16778 (if (and (= hour 12) (not pm))
16779 (setq hour 0)
16780 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16781 (setq ans (replace-match (format "%02d:%02d" hour minute)
16782 t t ans))))
16784 ;; Check if a time range is given as a duration
16785 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16786 (setq hour (string-to-number (match-string 1 ans))
16787 h2 (+ hour (string-to-number (match-string 3 ans)))
16788 minute (string-to-number (match-string 2 ans))
16789 m2 (+ minute (if (match-end 5) (string-to-number
16790 (match-string 5 ans))0)))
16791 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16792 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16793 t t ans)))
16795 ;; Check if there is a time range
16796 (when (boundp 'org-end-time-was-given)
16797 (setq org-time-was-given nil)
16798 (when (and (string-match org-plain-time-of-day-regexp ans)
16799 (match-end 8))
16800 (setq org-end-time-was-given (match-string 8 ans))
16801 (setq ans (concat (substring ans 0 (match-beginning 7))
16802 (substring ans (match-end 7))))))
16804 (setq tl (parse-time-string ans)
16805 day (or (nth 3 tl) (nth 3 org-defdecode))
16806 month (or (nth 4 tl)
16807 (if (and org-read-date-prefer-future
16808 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16809 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16810 (nth 4 org-defdecode)))
16811 year (or (and (not kill-year) (nth 5 tl))
16812 (if (and org-read-date-prefer-future
16813 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16814 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16815 (nth 5 org-defdecode)))
16816 hour (or (nth 2 tl) (nth 2 org-defdecode))
16817 minute (or (nth 1 tl) (nth 1 org-defdecode))
16818 second (or (nth 0 tl) 0)
16819 wday (nth 6 tl))
16821 (when (and (eq org-read-date-prefer-future 'time)
16822 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16823 (equal day (nth 3 nowdecode))
16824 (equal month (nth 4 nowdecode))
16825 (equal year (nth 5 nowdecode))
16826 (nth 2 tl)
16827 (or (< (nth 2 tl) (nth 2 nowdecode))
16828 (and (= (nth 2 tl) (nth 2 nowdecode))
16829 (nth 1 tl)
16830 (< (nth 1 tl) (nth 1 nowdecode)))))
16831 (setq day (1+ day)
16832 futurep t))
16834 ;; Special date definitions below
16835 (cond
16836 (iso-week
16837 ;; There was an iso week
16838 (require 'cal-iso)
16839 (setq futurep nil)
16840 (setq year (or iso-year year)
16841 day (or iso-weekday wday 1)
16842 wday nil ; to make sure that the trigger below does not match
16843 iso-date (calendar-gregorian-from-absolute
16844 (calendar-absolute-from-iso
16845 (list iso-week day year))))
16846 ; FIXME: Should we also push ISO weeks into the future?
16847 ; (when (and org-read-date-prefer-future
16848 ; (not iso-year)
16849 ; (< (calendar-absolute-from-gregorian iso-date)
16850 ; (time-to-days (current-time))))
16851 ; (setq year (1+ year)
16852 ; iso-date (calendar-gregorian-from-absolute
16853 ; (calendar-absolute-from-iso
16854 ; (list iso-week day year)))))
16855 (setq month (car iso-date)
16856 year (nth 2 iso-date)
16857 day (nth 1 iso-date)))
16858 (deltan
16859 (setq futurep nil)
16860 (unless deltadef
16861 (let ((now (decode-time (current-time))))
16862 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16863 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16864 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16865 ((equal deltaw "m") (setq month (+ month deltan)))
16866 ((equal deltaw "y") (setq year (+ year deltan)))))
16867 ((and wday (not (nth 3 tl)))
16868 ;; Weekday was given, but no day, so pick that day in the week
16869 ;; on or after the derived date.
16870 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16871 (unless (equal wday wday1)
16872 (setq day (+ day (% (- wday wday1 -7) 7))))))
16873 (if (and (boundp 'org-time-was-given)
16874 (nth 2 tl))
16875 (setq org-time-was-given t))
16876 (if (< year 100) (setq year (+ 2000 year)))
16877 ;; Check of the date is representable
16878 (if org-read-date-force-compatible-dates
16879 (progn
16880 (if (< year 1970)
16881 (setq year 1970 org-read-date-analyze-forced-year t))
16882 (if (> year 2037)
16883 (setq year 2037 org-read-date-analyze-forced-year t)))
16884 (condition-case nil
16885 (ignore (encode-time second minute hour day month year))
16886 (error
16887 (setq year (nth 5 org-defdecode))
16888 (setq org-read-date-analyze-forced-year t))))
16889 (setq org-read-date-analyze-futurep futurep)
16890 (list second minute hour day month year)))
16892 (defvar parse-time-weekdays)
16893 (defun org-read-date-get-relative (s today default)
16894 "Check string S for special relative date string.
16895 TODAY and DEFAULT are internal times, for today and for a default.
16896 Return shift list (N what def-flag)
16897 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16898 N is the number of WHATs to shift.
16899 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16900 the DEFAULT date rather than TODAY."
16901 (require 'parse-time)
16902 (when (and
16903 (string-match
16904 (concat
16905 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16906 "\\([0-9]+\\)?"
16907 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16908 "\\([ \t]\\|$\\)") s)
16909 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16910 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16911 (string-to-char (substring (match-string 1 s) -1))
16912 ?+))
16913 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16914 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16915 (what (if (match-end 3) (match-string 3 s) "d"))
16916 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16917 (date (if rel default today))
16918 (wday (nth 6 (decode-time date)))
16919 delta)
16920 (if wday1
16921 (progn
16922 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16923 (if (= delta 0) (setq delta 7))
16924 (if (= dir ?-)
16925 (progn
16926 (setq delta (- delta 7))
16927 (if (= delta 0) (setq delta -7))))
16928 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16929 (list delta "d" rel))
16930 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16932 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16933 "Turn a user-specified date into the internal representation.
16934 The internal representation needed by the calendar is (month day year).
16935 This is a wrapper to handle the brain-dead convention in calendar that
16936 user function argument order change dependent on argument order."
16937 (if (boundp 'calendar-date-style)
16938 (cond
16939 ((eq calendar-date-style 'american)
16940 (list arg1 arg2 arg3))
16941 ((eq calendar-date-style 'european)
16942 (list arg2 arg1 arg3))
16943 ((eq calendar-date-style 'iso)
16944 (list arg2 arg3 arg1)))
16945 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16946 (if (org-bound-and-true-p european-calendar-style)
16947 (list arg2 arg1 arg3)
16948 (list arg1 arg2 arg3)))))
16950 (defun org-eval-in-calendar (form &optional keepdate)
16951 "Eval FORM in the calendar window and return to current window.
16952 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16953 otherwise stick to the current value of `org-ans2'."
16954 (let ((sf (selected-frame))
16955 (sw (selected-window)))
16956 (select-window (get-buffer-window "*Calendar*" t))
16957 (eval form)
16958 (when (and (not keepdate) (calendar-cursor-to-date))
16959 (let* ((date (calendar-cursor-to-date))
16960 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16961 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16962 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16963 (select-window sw)
16964 (org-select-frame-set-input-focus sf)))
16966 (defun org-calendar-select ()
16967 "Return to `org-read-date' with the date currently selected.
16968 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16969 (interactive)
16970 (when (calendar-cursor-to-date)
16971 (let* ((date (calendar-cursor-to-date))
16972 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16973 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16974 (if (active-minibuffer-window) (exit-minibuffer))))
16976 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16977 "Insert a date stamp for the date given by the internal TIME.
16978 WITH-HM means use the stamp format that includes the time of the day.
16979 INACTIVE means use square brackets instead of angular ones, so that the
16980 stamp will not contribute to the agenda.
16981 PRE and POST are optional strings to be inserted before and after the
16982 stamp.
16983 The command returns the inserted time stamp."
16984 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16985 stamp)
16986 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16987 (insert-before-markers (or pre ""))
16988 (when (listp extra)
16989 (setq extra (car extra))
16990 (if (and (stringp extra)
16991 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16992 (setq extra (format "-%02d:%02d"
16993 (string-to-number (match-string 1 extra))
16994 (string-to-number (match-string 2 extra))))
16995 (setq extra nil)))
16996 (when extra
16997 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16998 (insert-before-markers (setq stamp (format-time-string fmt time)))
16999 (insert-before-markers (or post ""))
17000 (setq org-last-inserted-timestamp stamp)))
17002 (defun org-toggle-time-stamp-overlays ()
17003 "Toggle the use of custom time stamp formats."
17004 (interactive)
17005 (setq org-display-custom-times (not org-display-custom-times))
17006 (unless org-display-custom-times
17007 (let ((p (point-min)) (bmp (buffer-modified-p)))
17008 (while (setq p (next-single-property-change p 'display))
17009 (if (and (get-text-property p 'display)
17010 (eq (get-text-property p 'face) 'org-date))
17011 (remove-text-properties
17012 p (setq p (next-single-property-change p 'display))
17013 '(display t))))
17014 (set-buffer-modified-p bmp)))
17015 (if (featurep 'xemacs)
17016 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17017 (org-restart-font-lock)
17018 (setq org-table-may-need-update t)
17019 (if org-display-custom-times
17020 (message "Time stamps are overlaid with custom format")
17021 (message "Time stamp overlays removed")))
17023 (defun org-display-custom-time (beg end)
17024 "Overlay modified time stamp format over timestamp between BEG and END."
17025 (let* ((ts (buffer-substring beg end))
17026 t1 w1 with-hm tf time str w2 (off 0))
17027 (save-match-data
17028 (setq t1 (org-parse-time-string ts t))
17029 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17030 (setq off (- (match-end 0) (match-beginning 0)))))
17031 (setq end (- end off))
17032 (setq w1 (- end beg)
17033 with-hm (and (nth 1 t1) (nth 2 t1))
17034 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17035 time (org-fix-decoded-time t1)
17036 str (org-add-props
17037 (format-time-string
17038 (substring tf 1 -1) (apply 'encode-time time))
17039 nil 'mouse-face 'highlight)
17040 w2 (length str))
17041 (if (not (= w2 w1))
17042 (add-text-properties (1+ beg) (+ 2 beg)
17043 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17044 (if (featurep 'xemacs)
17045 (progn
17046 (put-text-property beg end 'invisible t)
17047 (put-text-property beg end 'end-glyph (make-glyph str)))
17048 (put-text-property beg end 'display str))))
17050 (defun org-translate-time (string)
17051 "Translate all timestamps in STRING to custom format.
17052 But do this only if the variable `org-display-custom-times' is set."
17053 (when org-display-custom-times
17054 (save-match-data
17055 (let* ((start 0)
17056 (re org-ts-regexp-both)
17057 t1 with-hm inactive tf time str beg end)
17058 (while (setq start (string-match re string start))
17059 (setq beg (match-beginning 0)
17060 end (match-end 0)
17061 t1 (save-match-data
17062 (org-parse-time-string (substring string beg end) t))
17063 with-hm (and (nth 1 t1) (nth 2 t1))
17064 inactive (equal (substring string beg (1+ beg)) "[")
17065 tf (funcall (if with-hm 'cdr 'car)
17066 org-time-stamp-custom-formats)
17067 time (org-fix-decoded-time t1)
17068 str (format-time-string
17069 (concat
17070 (if inactive "[" "<") (substring tf 1 -1)
17071 (if inactive "]" ">"))
17072 (apply 'encode-time time))
17073 string (replace-match str t t string)
17074 start (+ start (length str)))))))
17075 string)
17077 (defun org-fix-decoded-time (time)
17078 "Set 0 instead of nil for the first 6 elements of time.
17079 Don't touch the rest."
17080 (let ((n 0))
17081 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17083 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17085 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17086 "Difference between TIMESTAMP-STRING and now in days.
17087 If SECONDS is non-nil, return the difference in seconds."
17088 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17089 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17090 (funcall fdiff (current-time)))))
17092 (defun org-deadline-close (timestamp-string &optional ndays)
17093 "Is the time in TIMESTAMP-STRING close to the current date?"
17094 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17095 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17096 (not (org-entry-is-done-p))))
17098 (defun org-get-wdays (ts &optional delay zero-delay)
17099 "Get the deadline lead time appropriate for timestring TS.
17100 When DELAY is non-nil, get the delay time for scheduled items
17101 instead of the deadline lead time. When ZERO-DELAY is non-nil
17102 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17103 don't try to find the delay cookie in the scheduled timestamp."
17104 (let ((tv (if delay org-scheduled-delay-days
17105 org-deadline-warning-days)))
17106 (cond
17107 ((or (and delay (< tv 0))
17108 (and delay zero-delay (<= tv 0))
17109 (and (not delay) (<= tv 0)))
17110 ;; Enforce this value no matter what
17111 (- tv))
17112 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17113 ;; lead time is specified.
17114 (floor (* (string-to-number (match-string 1 ts))
17115 (cdr (assoc (match-string 2 ts)
17116 '(("d" . 1) ("w" . 7)
17117 ("m" . 30.4) ("y" . 365.25)
17118 ("h" . 0.041667)))))))
17119 ;; go for the default.
17120 (t tv))))
17122 (defun org-calendar-select-mouse (ev)
17123 "Return to `org-read-date' with the date currently selected.
17124 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17125 (interactive "e")
17126 (mouse-set-point ev)
17127 (when (calendar-cursor-to-date)
17128 (let* ((date (calendar-cursor-to-date))
17129 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17130 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17131 (if (active-minibuffer-window) (exit-minibuffer))))
17133 (defun org-check-deadlines (ndays)
17134 "Check if there are any deadlines due or past due.
17135 A deadline is considered due if it happens within `org-deadline-warning-days'
17136 days from today's date. If the deadline appears in an entry marked DONE,
17137 it is not shown. The prefix arg NDAYS can be used to test that many
17138 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17139 (interactive "P")
17140 (let* ((org-warn-days
17141 (cond
17142 ((equal ndays '(4)) 100000)
17143 (ndays (prefix-numeric-value ndays))
17144 (t (abs org-deadline-warning-days))))
17145 (case-fold-search nil)
17146 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17147 (callback
17148 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17150 (message "%d deadlines past-due or due within %d days"
17151 (org-occur regexp nil callback)
17152 org-warn-days)))
17154 (defsubst org-re-timestamp (type)
17155 "Return a regexp for timestamp TYPE.
17156 Allowed values for TYPE are:
17158 all: all timestamps
17159 active: only active timestamps (<...>)
17160 inactive: only inactive timestamps ([...])
17161 scheduled: only scheduled timestamps
17162 deadline: only deadline timestamps
17163 closed: only closed time-stamps
17165 When TYPE is nil, fall back on returning a regexp that matches
17166 both scheduled and deadline timestamps."
17167 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17168 ((eq type 'active) org-ts-regexp)
17169 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17170 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17171 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17172 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17173 ((eq type 'scheduled-or-deadline)
17174 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17176 (defun org-check-before-date (date)
17177 "Check if there are deadlines or scheduled entries before DATE."
17178 (interactive (list (org-read-date)))
17179 (let ((case-fold-search nil)
17180 (regexp (org-re-timestamp org-ts-type))
17181 (callback
17182 (lambda () (time-less-p
17183 (org-time-string-to-time (match-string 1))
17184 (org-time-string-to-time date)))))
17185 (message "%d entries before %s"
17186 (org-occur regexp nil callback) date)))
17188 (defun org-check-after-date (date)
17189 "Check if there are deadlines or scheduled entries after DATE."
17190 (interactive (list (org-read-date)))
17191 (let ((case-fold-search nil)
17192 (regexp (org-re-timestamp org-ts-type))
17193 (callback
17194 (lambda () (not
17195 (time-less-p
17196 (org-time-string-to-time (match-string 1))
17197 (org-time-string-to-time date))))))
17198 (message "%d entries after %s"
17199 (org-occur regexp nil callback) date)))
17201 (defun org-check-dates-range (start-date end-date)
17202 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17203 (interactive (list (org-read-date nil nil nil "Range starts")
17204 (org-read-date nil nil nil "Range end")))
17205 (let ((case-fold-search nil)
17206 (regexp (org-re-timestamp org-ts-type))
17207 (callback
17208 (lambda ()
17209 (let ((match (match-string 1)))
17210 (and
17211 (not (time-less-p
17212 (org-time-string-to-time match)
17213 (org-time-string-to-time start-date)))
17214 (time-less-p
17215 (org-time-string-to-time match)
17216 (org-time-string-to-time end-date)))))))
17217 (message "%d entries between %s and %s"
17218 (org-occur regexp nil callback) start-date end-date)))
17220 (defun org-evaluate-time-range (&optional to-buffer)
17221 "Evaluate a time range by computing the difference between start and end.
17222 Normally the result is just printed in the echo area, but with prefix arg
17223 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17224 If the time range is actually in a table, the result is inserted into the
17225 next column.
17226 For time difference computation, a year is assumed to be exactly 365
17227 days in order to avoid rounding problems."
17228 (interactive "P")
17230 (org-clock-update-time-maybe)
17231 (save-excursion
17232 (unless (org-at-date-range-p t)
17233 (goto-char (point-at-bol))
17234 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17235 (if (not (org-at-date-range-p t))
17236 (user-error "Not at a time-stamp range, and none found in current line")))
17237 (let* ((ts1 (match-string 1))
17238 (ts2 (match-string 2))
17239 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17240 (match-end (match-end 0))
17241 (time1 (org-time-string-to-time ts1))
17242 (time2 (org-time-string-to-time ts2))
17243 (t1 (org-float-time time1))
17244 (t2 (org-float-time time2))
17245 (diff (abs (- t2 t1)))
17246 (negative (< (- t2 t1) 0))
17247 ;; (ys (floor (* 365 24 60 60)))
17248 (ds (* 24 60 60))
17249 (hs (* 60 60))
17250 (fy "%dy %dd %02d:%02d")
17251 (fy1 "%dy %dd")
17252 (fd "%dd %02d:%02d")
17253 (fd1 "%dd")
17254 (fh "%02d:%02d")
17255 y d h m align)
17256 (if havetime
17257 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17259 d (floor (/ diff ds)) diff (mod diff ds)
17260 h (floor (/ diff hs)) diff (mod diff hs)
17261 m (floor (/ diff 60)))
17262 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17264 d (floor (+ (/ diff ds) 0.5))
17265 h 0 m 0))
17266 (if (not to-buffer)
17267 (message "%s" (org-make-tdiff-string y d h m))
17268 (if (org-at-table-p)
17269 (progn
17270 (goto-char match-end)
17271 (setq align t)
17272 (and (looking-at " *|") (goto-char (match-end 0))))
17273 (goto-char match-end))
17274 (if (looking-at
17275 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17276 (replace-match ""))
17277 (if negative (insert " -"))
17278 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17279 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17280 (insert " " (format fh h m))))
17281 (if align (org-table-align))
17282 (message "Time difference inserted")))))
17284 (defun org-make-tdiff-string (y d h m)
17285 (let ((fmt "")
17286 (l nil))
17287 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17288 l (push y l)))
17289 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17290 l (push d l)))
17291 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17292 l (push h l)))
17293 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17294 l (push m l)))
17295 (apply 'format fmt (nreverse l))))
17297 (defun org-time-string-to-time (s &optional buffer pos)
17298 "Convert a timestamp string into internal time."
17299 (condition-case errdata
17300 (apply 'encode-time (org-parse-time-string s))
17301 (error (error "Bad timestamp `%s'%s\nError was: %s"
17302 s (if (not (and buffer pos))
17304 (format " at %d in buffer `%s'" pos buffer))
17305 (cdr errdata)))))
17307 (defun org-time-string-to-seconds (s)
17308 "Convert a timestamp string to a number of seconds."
17309 (org-float-time (org-time-string-to-time s)))
17311 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17312 "Convert a time stamp to an absolute day number.
17313 If there is a specifier for a cyclic time stamp, get the closest
17314 date to DAYNR.
17315 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17316 The variable `date' is bound by the calendar when this is called."
17317 (cond
17318 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17319 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17320 daynr
17321 (+ daynr 1000)))
17322 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17323 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17324 (time-to-days (current-time))) (match-string 0 s)
17325 prefer show-all))
17326 (t (time-to-days
17327 (condition-case errdata
17328 (apply 'encode-time (org-parse-time-string s))
17329 (error (error "Bad timestamp `%s'%s\nError was: %s"
17330 s (if (not (and buffer pos))
17332 (format " at %d in buffer `%s'" pos buffer))
17333 (cdr errdata))))))))
17335 (defun org-days-to-iso-week (days)
17336 "Return the iso week number."
17337 (require 'cal-iso)
17338 (car (calendar-iso-from-absolute days)))
17340 (defun org-small-year-to-year (year)
17341 "Convert 2-digit years into 4-digit years.
17342 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17343 The year 2000 cannot be abbreviated. Any year larger than 99
17344 is returned unchanged."
17345 (if (< year 38)
17346 (setq year (+ 2000 year))
17347 (if (< year 100)
17348 (setq year (+ 1900 year))))
17349 year)
17351 (defun org-time-from-absolute (d)
17352 "Return the time corresponding to date D.
17353 D may be an absolute day number, or a calendar-type list (month day year)."
17354 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17355 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17357 (defun org-calendar-holiday ()
17358 "List of holidays, for Diary display in Org-mode."
17359 (require 'holidays)
17360 (let ((hl (funcall
17361 (if (fboundp 'calendar-check-holidays)
17362 'calendar-check-holidays 'check-calendar-holidays) date)))
17363 (if hl (mapconcat 'identity hl "; "))))
17365 (defun org-diary-sexp-entry (sexp entry date)
17366 "Process a SEXP diary ENTRY for DATE."
17367 (require 'diary-lib)
17368 (let ((result (if calendar-debug-sexp
17369 (let ((stack-trace-on-error t))
17370 (eval (car (read-from-string sexp))))
17371 (condition-case nil
17372 (eval (car (read-from-string sexp)))
17373 (error
17374 (beep)
17375 (message "Bad sexp at line %d in %s: %s"
17376 (org-current-line)
17377 (buffer-file-name) sexp)
17378 (sleep-for 2))))))
17379 (cond ((stringp result) (split-string result "; "))
17380 ((and (consp result)
17381 (not (consp (cdr result)))
17382 (stringp (cdr result))) (cdr result))
17383 ((and (consp result)
17384 (stringp (car result))) result)
17385 (result entry))))
17387 (defun org-diary-to-ical-string (frombuf)
17388 "Get iCalendar entries from diary entries in buffer FROMBUF.
17389 This uses the icalendar.el library."
17390 (let* ((tmpdir (if (featurep 'xemacs)
17391 (temp-directory)
17392 temporary-file-directory))
17393 (tmpfile (make-temp-name
17394 (expand-file-name "orgics" tmpdir)))
17395 buf rtn b e)
17396 (with-current-buffer frombuf
17397 (icalendar-export-region (point-min) (point-max) tmpfile)
17398 (setq buf (find-buffer-visiting tmpfile))
17399 (set-buffer buf)
17400 (goto-char (point-min))
17401 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17402 (setq b (match-beginning 0)))
17403 (goto-char (point-max))
17404 (if (re-search-backward "^END:VEVENT" nil t)
17405 (setq e (match-end 0)))
17406 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17407 (kill-buffer buf)
17408 (delete-file tmpfile)
17409 rtn))
17411 (defun org-closest-date (start current change prefer show-all)
17412 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17413 When PREFER is `past', return a date that is either CURRENT or past.
17414 When PREFER is `future', return a date that is either CURRENT or future.
17415 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17416 ;; Make the proper lists from the dates
17417 (catch 'exit
17418 (let ((a1 '(("h" . hour)
17419 ("d" . day)
17420 ("w" . week)
17421 ("m" . month)
17422 ("y" . year)))
17423 (shour (nth 2 (org-parse-time-string start)))
17424 dn dw sday cday n1 n2 n0
17425 d m y y1 y2 date1 date2 nmonths nm ny m2)
17427 (setq start (org-date-to-gregorian start)
17428 current (org-date-to-gregorian
17429 (if show-all
17430 current
17431 (time-to-days (current-time))))
17432 sday (calendar-absolute-from-gregorian start)
17433 cday (calendar-absolute-from-gregorian current))
17435 (if (<= cday sday) (throw 'exit sday))
17437 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17438 (setq dn (string-to-number (match-string 1 change))
17439 dw (cdr (assoc (match-string 2 change) a1)))
17440 (user-error "Invalid change specifier: %s" change))
17441 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17442 (cond
17443 ((eq dw 'hour)
17444 (let ((missing-hours
17445 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17446 dn)))
17447 (setq n1 (if (zerop missing-hours) cday
17448 (- cday (1+ (floor (/ missing-hours 24)))))
17449 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17450 ((eq dw 'day)
17451 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17452 n2 (+ n1 dn)))
17453 ((eq dw 'year)
17454 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17455 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17456 (setq date1 (list m d y1)
17457 n1 (calendar-absolute-from-gregorian date1)
17458 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17459 n2 (calendar-absolute-from-gregorian date2)))
17460 ((eq dw 'month)
17461 ;; approx number of month between the two dates
17462 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17463 ;; How often does dn fit in there?
17464 (setq d (nth 1 start) m (car start) y (nth 2 start)
17465 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17466 m (+ m nm)
17467 ny (floor (/ m 12))
17468 y (+ y ny)
17469 m (- m (* ny 12)))
17470 (while (> m 12) (setq m (- m 12) y (1+ y)))
17471 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17472 (setq m2 (+ m dn) y2 y)
17473 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17474 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17475 (while (<= n2 cday)
17476 (setq n1 n2 m m2 y y2)
17477 (setq m2 (+ m dn) y2 y)
17478 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17479 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17480 ;; Make sure n1 is the earlier date
17481 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17482 (if show-all
17483 (cond
17484 ((eq prefer 'past) (if (= cday n2) n2 n1))
17485 ((eq prefer 'future) (if (= cday n1) n1 n2))
17486 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17487 (cond
17488 ((eq prefer 'past) (if (= cday n2) n2 n1))
17489 ((eq prefer 'future) (if (= cday n1) n1 n2))
17490 (t (if (= cday n1) n1 n2)))))))
17492 (defun org-date-to-gregorian (date)
17493 "Turn any specification of DATE into a Gregorian date for the calendar."
17494 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17495 ((and (listp date) (= (length date) 3)) date)
17496 ((stringp date)
17497 (setq date (org-parse-time-string date))
17498 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17499 ((listp date)
17500 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17502 (defun org-parse-time-string (s &optional nodefault)
17503 "Parse the standard Org-mode time string.
17504 This should be a lot faster than the normal `parse-time-string'.
17505 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17506 hour and minute fields will be nil if not given."
17507 (cond ((string-match org-ts-regexp0 s)
17508 (list 0
17509 (if (or (match-beginning 8) (not nodefault))
17510 (string-to-number (or (match-string 8 s) "0")))
17511 (if (or (match-beginning 7) (not nodefault))
17512 (string-to-number (or (match-string 7 s) "0")))
17513 (string-to-number (match-string 4 s))
17514 (string-to-number (match-string 3 s))
17515 (string-to-number (match-string 2 s))
17516 nil nil nil))
17517 ((string-match "^<[^>]+>$" s)
17518 (decode-time (seconds-to-time (org-matcher-time s))))
17519 (t (error "Not a standard Org-mode time string: %s" s))))
17521 (defun org-timestamp-up (&optional arg)
17522 "Increase the date item at the cursor by one.
17523 If the cursor is on the year, change the year. If it is on the month,
17524 the day or the time, change that.
17525 With prefix ARG, change by that many units."
17526 (interactive "p")
17527 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17529 (defun org-timestamp-down (&optional arg)
17530 "Decrease the date item at the cursor by one.
17531 If the cursor is on the year, change the year. If it is on the month,
17532 the day or the time, change that.
17533 With prefix ARG, change by that many units."
17534 (interactive "p")
17535 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17537 (defun org-timestamp-up-day (&optional arg)
17538 "Increase the date in the time stamp by one day.
17539 With prefix ARG, change that many days."
17540 (interactive "p")
17541 (if (and (not (org-at-timestamp-p t))
17542 (org-at-heading-p))
17543 (org-todo 'up)
17544 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17546 (defun org-timestamp-down-day (&optional arg)
17547 "Decrease the date in the time stamp by one day.
17548 With prefix ARG, change that many days."
17549 (interactive "p")
17550 (if (and (not (org-at-timestamp-p t))
17551 (org-at-heading-p))
17552 (org-todo 'down)
17553 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17555 (defun org-at-timestamp-p (&optional inactive-ok)
17556 "Determine if the cursor is in or at a timestamp."
17557 (interactive)
17558 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17559 (pos (point))
17560 (ans (or (looking-at tsr)
17561 (save-excursion
17562 (skip-chars-backward "^[<\n\r\t")
17563 (if (> (point) (point-min)) (backward-char 1))
17564 (and (looking-at tsr)
17565 (> (- (match-end 0) pos) -1))))))
17566 (and ans
17567 (boundp 'org-ts-what)
17568 (setq org-ts-what
17569 (cond
17570 ((= pos (match-beginning 0)) 'bracket)
17571 ;; Point is considered to be "on the bracket" whether
17572 ;; it's really on it or right after it.
17573 ((= pos (1- (match-end 0))) 'bracket)
17574 ((= pos (match-end 0)) 'after)
17575 ((org-pos-in-match-range pos 2) 'year)
17576 ((org-pos-in-match-range pos 3) 'month)
17577 ((org-pos-in-match-range pos 7) 'hour)
17578 ((org-pos-in-match-range pos 8) 'minute)
17579 ((or (org-pos-in-match-range pos 4)
17580 (org-pos-in-match-range pos 5)) 'day)
17581 ((and (> pos (or (match-end 8) (match-end 5)))
17582 (< pos (match-end 0)))
17583 (- pos (or (match-end 8) (match-end 5))))
17584 (t 'day))))
17585 ans))
17587 (defun org-toggle-timestamp-type ()
17588 "Toggle the type (<active> or [inactive]) of a time stamp."
17589 (interactive)
17590 (when (org-at-timestamp-p t)
17591 (let ((beg (match-beginning 0)) (end (match-end 0))
17592 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17593 (save-excursion
17594 (goto-char beg)
17595 (while (re-search-forward "[][<>]" end t)
17596 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17597 t t)))
17598 (message "Timestamp is now %sactive"
17599 (if (equal (char-after beg) ?<) "" "in")))))
17601 (defun org-at-clock-log-p nil
17602 "Is the cursor on the clock log line?"
17603 (save-excursion
17604 (move-beginning-of-line 1)
17605 (looking-at org-clock-line-re)))
17607 (defvar org-clock-history) ; defined in org-clock.el
17608 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17609 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17610 "Change the date in the time stamp at point.
17611 The date will be changed by N times WHAT. WHAT can be `day', `month',
17612 `year', `minute', `second'. If WHAT is not given, the cursor position
17613 in the timestamp determines what will be changed.
17614 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17615 (let ((origin (point)) origin-cat
17616 with-hm inactive
17617 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17618 org-ts-what
17619 extra rem
17620 ts time time0 fixnext clrgx)
17621 (if (not (org-at-timestamp-p t))
17622 (user-error "Not at a timestamp"))
17623 (if (and (not what) (eq org-ts-what 'bracket))
17624 (org-toggle-timestamp-type)
17625 ;; Point isn't on brackets. Remember the part of the time-stamp
17626 ;; the point was in. Indeed, size of time-stamps may change,
17627 ;; but point must be kept in the same category nonetheless.
17628 (setq origin-cat org-ts-what)
17629 (if (and (not what) (not (eq org-ts-what 'day))
17630 org-display-custom-times
17631 (get-text-property (point) 'display)
17632 (not (get-text-property (1- (point)) 'display)))
17633 (setq org-ts-what 'day))
17634 (setq org-ts-what (or what org-ts-what)
17635 inactive (= (char-after (match-beginning 0)) ?\[)
17636 ts (match-string 0))
17637 (replace-match "")
17638 (when (string-match
17639 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17641 (setq extra (match-string 1 ts))
17642 (if suppress-tmp-delay
17643 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17644 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17645 (setq with-hm t))
17646 (setq time0 (org-parse-time-string ts))
17647 (when (and updown
17648 (eq org-ts-what 'minute)
17649 (not current-prefix-arg))
17650 ;; This looks like s-up and s-down. Change by one rounding step.
17651 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17652 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17653 (setcar (cdr time0) (+ (nth 1 time0)
17654 (if (> n 0) (- rem) (- dm rem))))))
17655 (setq time
17656 (encode-time (or (car time0) 0)
17657 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17658 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17659 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17660 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17661 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17662 (nthcdr 6 time0)))
17663 (when (and (member org-ts-what '(hour minute))
17664 extra
17665 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17666 (setq extra (org-modify-ts-extra
17667 extra
17668 (if (eq org-ts-what 'hour) 2 5)
17669 n dm)))
17670 (when (integerp org-ts-what)
17671 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17672 (if (eq what 'calendar)
17673 (let ((cal-date (org-get-date-from-calendar)))
17674 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17675 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17676 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17677 (setcar time0 (or (car time0) 0))
17678 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17679 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17680 (setq time (apply 'encode-time time0))))
17681 ;; Insert the new time-stamp, and ensure point stays in the same
17682 ;; category as before (i.e. not after the last position in that
17683 ;; category).
17684 (let ((pos (point)))
17685 ;; Stay before inserted string. `save-excursion' is of no use.
17686 (setq org-last-changed-timestamp
17687 (org-insert-time-stamp time with-hm inactive nil nil extra))
17688 (goto-char pos))
17689 (save-match-data
17690 (looking-at org-ts-regexp3)
17691 (goto-char (cond
17692 ;; `day' category ends before `hour' if any, or at
17693 ;; the end of the day name.
17694 ((eq origin-cat 'day)
17695 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17696 ((eq origin-cat 'hour) (min (match-end 7) origin))
17697 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17698 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17699 ;; `year' and `month' have both fixed size: point
17700 ;; couldn't have moved into another part.
17701 (t origin))))
17702 ;; Update clock if on a CLOCK line.
17703 (org-clock-update-time-maybe)
17704 ;; Maybe adjust the closest clock in `org-clock-history'
17705 (when org-clock-adjust-closest
17706 (if (not (and (org-at-clock-log-p)
17707 (< 1 (length (delq nil (mapcar 'marker-position
17708 org-clock-history))))))
17709 (message "No clock to adjust")
17710 (cond ((save-excursion ; fix previous clock?
17711 (re-search-backward org-ts-regexp0 nil t)
17712 (org-looking-back (concat org-clock-string " \\[")))
17713 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17714 ((save-excursion ; fix next clock?
17715 (re-search-backward org-ts-regexp0 nil t)
17716 (looking-at (concat org-ts-regexp0 "\\] =>")))
17717 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17718 (save-window-excursion
17719 ;; Find closest clock to point, adjust the previous/next one in history
17720 (let* ((p (save-excursion (org-back-to-heading t)))
17721 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17722 (clfixnth
17723 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17724 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17725 (if (not clfixpos)
17726 (message "No clock to adjust")
17727 (save-excursion
17728 (org-goto-marker-or-bmk clfixpos)
17729 (org-show-subtree)
17730 (when (re-search-forward clrgx nil t)
17731 (goto-char (match-beginning 1))
17732 (let (org-clock-adjust-closest)
17733 (org-timestamp-change n org-ts-what updown))
17734 (message "Clock adjusted in %s for heading: %s"
17735 (file-name-nondirectory (buffer-file-name))
17736 (org-get-heading t t)))))))))
17737 ;; Try to recenter the calendar window, if any.
17738 (if (and org-calendar-follow-timestamp-change
17739 (get-buffer-window "*Calendar*" t)
17740 (memq org-ts-what '(day month year)))
17741 (org-recenter-calendar (time-to-days time))))))
17743 (defun org-modify-ts-extra (s pos n dm)
17744 "Change the different parts of the lead-time and repeat fields in timestamp."
17745 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17746 ng h m new rem)
17747 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17748 (cond
17749 ((or (org-pos-in-match-range pos 2)
17750 (org-pos-in-match-range pos 3))
17751 (setq m (string-to-number (match-string 3 s))
17752 h (string-to-number (match-string 2 s)))
17753 (if (org-pos-in-match-range pos 2)
17754 (setq h (+ h n))
17755 (setq n (* dm (org-no-warnings (signum n))))
17756 (when (not (= 0 (setq rem (% m dm))))
17757 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17758 (setq m (+ m n)))
17759 (if (< m 0) (setq m (+ m 60) h (1- h)))
17760 (if (> m 59) (setq m (- m 60) h (1+ h)))
17761 (setq h (min 24 (max 0 h)))
17762 (setq ng 1 new (format "-%02d:%02d" h m)))
17763 ((org-pos-in-match-range pos 6)
17764 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17765 ((org-pos-in-match-range pos 5)
17766 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17768 ((org-pos-in-match-range pos 9)
17769 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17770 ((org-pos-in-match-range pos 8)
17771 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17773 (when ng
17774 (setq s (concat
17775 (substring s 0 (match-beginning ng))
17777 (substring s (match-end ng))))))
17780 (defun org-recenter-calendar (date)
17781 "If the calendar is visible, recenter it to DATE."
17782 (let ((cwin (get-buffer-window "*Calendar*" t)))
17783 (when cwin
17784 (let ((calendar-move-hook nil))
17785 (with-selected-window cwin
17786 (calendar-goto-date (if (listp date) date
17787 (calendar-gregorian-from-absolute date))))))))
17789 (defun org-goto-calendar (&optional arg)
17790 "Go to the Emacs calendar at the current date.
17791 If there is a time stamp in the current line, go to that date.
17792 A prefix ARG can be used to force the current date."
17793 (interactive "P")
17794 (let ((tsr org-ts-regexp) diff
17795 (calendar-move-hook nil)
17796 (calendar-view-holidays-initially-flag nil)
17797 (calendar-view-diary-initially-flag nil))
17798 (if (or (org-at-timestamp-p)
17799 (save-excursion
17800 (beginning-of-line 1)
17801 (looking-at (concat ".*" tsr))))
17802 (let ((d1 (time-to-days (current-time)))
17803 (d2 (time-to-days
17804 (org-time-string-to-time (match-string 1)))))
17805 (setq diff (- d2 d1))))
17806 (calendar)
17807 (calendar-goto-today)
17808 (if (and diff (not arg)) (calendar-forward-day diff))))
17810 (defun org-get-date-from-calendar ()
17811 "Return a list (month day year) of date at point in calendar."
17812 (with-current-buffer "*Calendar*"
17813 (save-match-data
17814 (calendar-cursor-to-date))))
17816 (defun org-date-from-calendar ()
17817 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17818 If there is already a time stamp at the cursor position, update it."
17819 (interactive)
17820 (if (org-at-timestamp-p t)
17821 (org-timestamp-change 0 'calendar)
17822 (let ((cal-date (org-get-date-from-calendar)))
17823 (org-insert-time-stamp
17824 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17826 (defcustom org-effort-durations
17827 `(("h" . 60)
17828 ("d" . ,(* 60 8))
17829 ("w" . ,(* 60 8 5))
17830 ("m" . ,(* 60 8 5 4))
17831 ("y" . ,(* 60 8 5 40)))
17832 "Conversion factor to minutes for an effort modifier.
17834 Each entry has the form (MODIFIER . MINUTES).
17836 In an effort string, a number followed by MODIFIER is multiplied
17837 by the specified number of MINUTES to obtain an effort in
17838 minutes.
17840 For example, if the value of this variable is ((\"hours\" . 60)), then an
17841 effort string \"2hours\" is equivalent to 120 minutes."
17842 :group 'org-agenda
17843 :version "24.1"
17844 :type '(alist :key-type (string :tag "Modifier")
17845 :value-type (number :tag "Minutes")))
17847 (defun org-minutes-to-clocksum-string (m)
17848 "Format number of minutes as a clocksum string.
17849 The format is determined by `org-time-clocksum-format',
17850 `org-time-clocksum-use-fractional' and
17851 `org-time-clocksum-fractional-format' and
17852 `org-time-clocksum-use-effort-durations'."
17853 (let ((clocksum "")
17854 (m (round m)) ; Don't allow fractions of minutes
17855 h d w mo y fmt n)
17856 (setq h (if org-time-clocksum-use-effort-durations
17857 (cdr (assoc "h" org-effort-durations)) 60)
17858 d (if org-time-clocksum-use-effort-durations
17859 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17860 w (if org-time-clocksum-use-effort-durations
17861 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17862 mo (if org-time-clocksum-use-effort-durations
17863 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17864 y (if org-time-clocksum-use-effort-durations
17865 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17866 ;; fractional format
17867 (if org-time-clocksum-use-fractional
17868 (cond
17869 ;; single format string
17870 ((stringp org-time-clocksum-fractional-format)
17871 (format org-time-clocksum-fractional-format (/ m (float h))))
17872 ;; choice of fractional formats for different time units
17873 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17874 (> (/ (truncate m) (* y d h)) 0))
17875 (format fmt (/ m (* y d (float h)))))
17876 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17877 (> (/ (truncate m) (* mo d h)) 0))
17878 (format fmt (/ m (* mo d (float h)))))
17879 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17880 (> (/ (truncate m) (* w d h)) 0))
17881 (format fmt (/ m (* w d (float h)))))
17882 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17883 (> (/ (truncate m) (* d h)) 0))
17884 (format fmt (/ m (* d (float h)))))
17885 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17886 (> (/ (truncate m) h) 0))
17887 (format fmt (/ m (float h))))
17888 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17889 (format fmt m))
17890 ;; fall back to smallest time unit with a format
17891 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17892 (format fmt (/ m (float h))))
17893 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17894 (format fmt (/ m (* d (float h)))))
17895 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17896 (format fmt (/ m (* w d (float h)))))
17897 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17898 (format fmt (/ m (* mo d (float h)))))
17899 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17900 (format fmt (/ m (* y d (float h))))))
17901 ;; standard (non-fractional) format, with single format string
17902 (if (stringp org-time-clocksum-format)
17903 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17904 ;; separate formats components
17905 (and (setq fmt (plist-get org-time-clocksum-format :years))
17906 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17907 (plist-get org-time-clocksum-format :require-years))
17908 (setq clocksum (concat clocksum (format fmt n))
17909 m (- m (* n y d h))))
17910 (and (setq fmt (plist-get org-time-clocksum-format :months))
17911 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17912 (plist-get org-time-clocksum-format :require-months))
17913 (setq clocksum (concat clocksum (format fmt n))
17914 m (- m (* n mo d h))))
17915 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17916 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17917 (plist-get org-time-clocksum-format :require-weeks))
17918 (setq clocksum (concat clocksum (format fmt n))
17919 m (- m (* n w d h))))
17920 (and (setq fmt (plist-get org-time-clocksum-format :days))
17921 (or (> (setq n (/ (truncate m) (* d h))) 0)
17922 (plist-get org-time-clocksum-format :require-days))
17923 (setq clocksum (concat clocksum (format fmt n))
17924 m (- m (* n d h))))
17925 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17926 (or (> (setq n (/ (truncate m) h)) 0)
17927 (plist-get org-time-clocksum-format :require-hours))
17928 (setq clocksum (concat clocksum (format fmt n))
17929 m (- m (* n h))))
17930 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17931 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17932 (setq clocksum (concat clocksum (format fmt m))))
17933 ;; return formatted time duration
17934 clocksum))))
17936 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17937 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17938 "Org mode version 8.0")
17940 (defun org-hours-to-clocksum-string (n)
17941 (org-minutes-to-clocksum-string (* n 60)))
17943 (defun org-hh:mm-string-to-minutes (s)
17944 "Convert a string H:MM to a number of minutes.
17945 If the string is just a number, interpret it as minutes.
17946 In fact, the first hh:mm or number in the string will be taken,
17947 there can be extra stuff in the string.
17948 If no number is found, the return value is 0."
17949 (cond
17950 ((integerp s) s)
17951 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17952 (+ (* (string-to-number (match-string 1 s)) 60)
17953 (string-to-number (match-string 2 s))))
17954 ((string-match "\\([0-9]+\\)" s)
17955 (string-to-number (match-string 1 s)))
17956 (t 0)))
17958 (defcustom org-image-actual-width t
17959 "Should we use the actual width of images when inlining them?
17961 When set to `t', always use the image width.
17963 When set to a number, use imagemagick (when available) to set
17964 the image's width to this value.
17966 When set to a number in a list, try to get the width from any
17967 #+ATTR.* keyword if it matches a width specification like
17969 #+ATTR_HTML: :width 300px
17971 and fall back on that number if none is found.
17973 When set to nil, try to get the width from an #+ATTR.* keyword
17974 and fall back on the original width if none is found.
17976 This requires Emacs >= 24.1, build with imagemagick support."
17977 :group 'org-appearance
17978 :version "24.4"
17979 :package-version '(Org . "8.0")
17980 :type '(choice
17981 (const :tag "Use the image width" t)
17982 (integer :tag "Use a number of pixels")
17983 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17984 (const :tag "Use #+ATTR* or don't resize" nil)))
17986 (defcustom org-agenda-inhibit-startup nil
17987 "Inhibit startup when preparing agenda buffers.
17988 When this variable is `t', the initialization of the Org agenda
17989 buffers is inhibited: e.g. the visibility state is not set, the
17990 tables are not re-aligned, etc."
17991 :type 'boolean
17992 :version "24.3"
17993 :group 'org-agenda)
17995 (define-obsolete-variable-alias
17996 'org-agenda-ignore-drawer-properties
17997 'org-agenda-ignore-properties "25.1")
17999 (defcustom org-agenda-ignore-properties nil
18000 "Avoid updating text properties when building the agenda.
18001 Properties are used to prepare buffers for effort estimates,
18002 appointments, statistics and subtree-local categories.
18003 If you don't use these in the agenda, you can add them to this
18004 list and agenda building will be a bit faster.
18005 The value is a list, with zero or more of the symbols `effort', `appt',
18006 `stats' or `category'."
18007 :type '(set :greedy t
18008 (const effort)
18009 (const appt)
18010 (const stats)
18011 (const category))
18012 :version "25.1"
18013 :package-version '(Org . "8.3")
18014 :group 'org-agenda)
18016 (defun org-duration-string-to-minutes (s &optional output-to-string)
18017 "Convert a duration string S to minutes.
18019 A bare number is interpreted as minutes, modifiers can be set by
18020 customizing `org-effort-durations' (which see).
18022 Entries containing a colon are interpreted as H:MM by
18023 `org-hh:mm-string-to-minutes'."
18024 (let ((result 0)
18025 (re (concat "\\([0-9.]+\\) *\\("
18026 (regexp-opt (mapcar 'car org-effort-durations))
18027 "\\)")))
18028 (while (string-match re s)
18029 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18030 (string-to-number (match-string 1 s))))
18031 (setq s (replace-match "" nil t s)))
18032 (setq result (floor result))
18033 (incf result (org-hh:mm-string-to-minutes s))
18034 (if output-to-string (number-to-string result) result)))
18036 ;;;; Files
18038 (defun org-save-all-org-buffers ()
18039 "Save all Org-mode buffers without user confirmation."
18040 (interactive)
18041 (message "Saving all Org-mode buffers...")
18042 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18043 (when (featurep 'org-id) (org-id-locations-save))
18044 (message "Saving all Org-mode buffers... done"))
18046 (defun org-revert-all-org-buffers ()
18047 "Revert all Org-mode buffers.
18048 Prompt for confirmation when there are unsaved changes.
18049 Be sure you know what you are doing before letting this function
18050 overwrite your changes.
18052 This function is useful in a setup where one tracks org files
18053 with a version control system, to revert on one machine after pulling
18054 changes from another. I believe the procedure must be like this:
18056 1. M-x org-save-all-org-buffers
18057 2. Pull changes from the other machine, resolve conflicts
18058 3. M-x org-revert-all-org-buffers"
18059 (interactive)
18060 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18061 (user-error "Abort"))
18062 (save-excursion
18063 (save-window-excursion
18064 (mapc
18065 (lambda (b)
18066 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18067 (with-current-buffer b buffer-file-name))
18068 (org-pop-to-buffer-same-window b)
18069 (revert-buffer t 'no-confirm)))
18070 (buffer-list))
18071 (when (and (featurep 'org-id) org-id-track-globally)
18072 (org-id-locations-load)))))
18074 ;;;; Agenda files
18076 ;;;###autoload
18077 (defun org-switchb (&optional arg)
18078 "Switch between Org buffers.
18079 With one prefix argument, restrict available buffers to files.
18080 With two prefix arguments, restrict available buffers to agenda files.
18082 Defaults to `iswitchb' for buffer name completion.
18083 Set `org-completion-use-ido' to make it use ido instead."
18084 (interactive "P")
18085 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18086 ((equal arg '(16)) (org-buffer-list 'agenda))
18087 (t (org-buffer-list))))
18088 (org-completion-use-iswitchb org-completion-use-iswitchb)
18089 (org-completion-use-ido org-completion-use-ido))
18090 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18091 (setq org-completion-use-iswitchb t))
18092 (org-pop-to-buffer-same-window
18093 (org-icompleting-read "Org buffer: "
18094 (mapcar 'list (mapcar 'buffer-name blist))
18095 nil t))))
18097 ;;; Define some older names previously used for this functionality
18098 ;;;###autoload
18099 (defalias 'org-ido-switchb 'org-switchb)
18100 ;;;###autoload
18101 (defalias 'org-iswitchb 'org-switchb)
18103 (defun org-buffer-list (&optional predicate exclude-tmp)
18104 "Return a list of Org buffers.
18105 PREDICATE can be `export', `files' or `agenda'.
18107 export restrict the list to Export buffers.
18108 files restrict the list to buffers visiting Org files.
18109 agenda restrict the list to buffers visiting agenda files.
18111 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18112 (let* ((bfn nil)
18113 (agenda-files (and (eq predicate 'agenda)
18114 (mapcar 'file-truename (org-agenda-files t))))
18115 (filter
18116 (cond
18117 ((eq predicate 'files)
18118 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18119 ((eq predicate 'export)
18120 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18121 ((eq predicate 'agenda)
18122 (lambda (b)
18123 (with-current-buffer b
18124 (and (derived-mode-p 'org-mode)
18125 (setq bfn (buffer-file-name b))
18126 (member (file-truename bfn) agenda-files)))))
18127 (t (lambda (b) (with-current-buffer b
18128 (or (derived-mode-p 'org-mode)
18129 (string-match "\*Org .*Export"
18130 (buffer-name b)))))))))
18131 (delq nil
18132 (mapcar
18133 (lambda(b)
18134 (if (and (funcall filter b)
18135 (or (not exclude-tmp)
18136 (not (string-match "tmp" (buffer-name b)))))
18138 nil))
18139 (buffer-list)))))
18141 (defun org-agenda-files (&optional unrestricted archives)
18142 "Get the list of agenda files.
18143 Optional UNRESTRICTED means return the full list even if a restriction
18144 is currently in place.
18145 When ARCHIVES is t, include all archive files that are really being
18146 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18147 `org-agenda-archives-mode' is t."
18148 (let ((files
18149 (cond
18150 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18151 ((stringp org-agenda-files) (org-read-agenda-file-list))
18152 ((listp org-agenda-files) org-agenda-files)
18153 (t (error "Invalid value of `org-agenda-files'")))))
18154 (setq files (apply 'append
18155 (mapcar (lambda (f)
18156 (if (file-directory-p f)
18157 (directory-files
18158 f t org-agenda-file-regexp)
18159 (list f)))
18160 files)))
18161 (when org-agenda-skip-unavailable-files
18162 (setq files (delq nil
18163 (mapcar (function
18164 (lambda (file)
18165 (and (file-readable-p file) file)))
18166 files))))
18167 (when (or (eq archives t)
18168 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18169 (setq files (org-add-archive-files files)))
18170 files))
18172 (defun org-agenda-file-p (&optional file)
18173 "Return non-nil, if FILE is an agenda file.
18174 If FILE is omitted, use the file associated with the current
18175 buffer."
18176 (let ((fname (or file (buffer-file-name))))
18177 (and fname
18178 (member (file-truename fname)
18179 (mapcar #'file-truename (org-agenda-files t))))))
18181 (defun org-edit-agenda-file-list ()
18182 "Edit the list of agenda files.
18183 Depending on setup, this either uses customize to edit the variable
18184 `org-agenda-files', or it visits the file that is holding the list. In the
18185 latter case, the buffer is set up in a way that saving it automatically kills
18186 the buffer and restores the previous window configuration."
18187 (interactive)
18188 (if (stringp org-agenda-files)
18189 (let ((cw (current-window-configuration)))
18190 (find-file org-agenda-files)
18191 (org-set-local 'org-window-configuration cw)
18192 (org-add-hook 'after-save-hook
18193 (lambda ()
18194 (set-window-configuration
18195 (prog1 org-window-configuration
18196 (kill-buffer (current-buffer))))
18197 (org-install-agenda-files-menu)
18198 (message "New agenda file list installed"))
18199 nil 'local)
18200 (message "%s" (substitute-command-keys
18201 "Edit list and finish with \\[save-buffer]")))
18202 (customize-variable 'org-agenda-files)))
18204 (defun org-store-new-agenda-file-list (list)
18205 "Set new value for the agenda file list and save it correctly."
18206 (if (stringp org-agenda-files)
18207 (let ((fe (org-read-agenda-file-list t)) b u)
18208 (while (setq b (find-buffer-visiting org-agenda-files))
18209 (kill-buffer b))
18210 (with-temp-file org-agenda-files
18211 (insert
18212 (mapconcat
18213 (lambda (f) ;; Keep un-expanded entries.
18214 (if (setq u (assoc f fe))
18215 (cdr u)
18217 list "\n")
18218 "\n")))
18219 (let ((org-mode-hook nil) (org-inhibit-startup t)
18220 (org-insert-mode-line-in-empty-file nil))
18221 (setq org-agenda-files list)
18222 (customize-save-variable 'org-agenda-files org-agenda-files))))
18224 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18225 "Read the list of agenda files from a file.
18226 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18227 filenames, used by `org-store-new-agenda-file-list' to write back
18228 un-expanded file names."
18229 (when (file-directory-p org-agenda-files)
18230 (error "`org-agenda-files' cannot be a single directory"))
18231 (when (stringp org-agenda-files)
18232 (with-temp-buffer
18233 (insert-file-contents org-agenda-files)
18234 (mapcar
18235 (lambda (f)
18236 (let ((e (expand-file-name (substitute-in-file-name f)
18237 org-directory)))
18238 (if pair-with-expansion
18239 (cons e f)
18240 e)))
18241 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18243 ;;;###autoload
18244 (defun org-cycle-agenda-files ()
18245 "Cycle through the files in `org-agenda-files'.
18246 If the current buffer visits an agenda file, find the next one in the list.
18247 If the current buffer does not, find the first agenda file."
18248 (interactive)
18249 (let* ((fs (org-agenda-files t))
18250 (files (append fs (list (car fs))))
18251 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18252 file)
18253 (unless files (user-error "No agenda files"))
18254 (catch 'exit
18255 (while (setq file (pop files))
18256 (if (equal (file-truename file) tcf)
18257 (when (car files)
18258 (find-file (car files))
18259 (throw 'exit t))))
18260 (find-file (car fs)))
18261 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18263 (defun org-agenda-file-to-front (&optional to-end)
18264 "Move/add the current file to the top of the agenda file list.
18265 If the file is not present in the list, it is added to the front. If it is
18266 present, it is moved there. With optional argument TO-END, add/move to the
18267 end of the list."
18268 (interactive "P")
18269 (let ((org-agenda-skip-unavailable-files nil)
18270 (file-alist (mapcar (lambda (x)
18271 (cons (file-truename x) x))
18272 (org-agenda-files t)))
18273 (ctf (file-truename
18274 (or buffer-file-name
18275 (user-error "Please save the current buffer to a file"))))
18276 x had)
18277 (setq x (assoc ctf file-alist) had x)
18279 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18280 (if to-end
18281 (setq file-alist (append (delq x file-alist) (list x)))
18282 (setq file-alist (cons x (delq x file-alist))))
18283 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18284 (org-install-agenda-files-menu)
18285 (message "File %s to %s of agenda file list"
18286 (if had "moved" "added") (if to-end "end" "front"))))
18288 (defun org-remove-file (&optional file)
18289 "Remove current file from the list of files in variable `org-agenda-files'.
18290 These are the files which are being checked for agenda entries.
18291 Optional argument FILE means use this file instead of the current."
18292 (interactive)
18293 (let* ((org-agenda-skip-unavailable-files nil)
18294 (file (or file buffer-file-name
18295 (user-error "Current buffer does not visit a file")))
18296 (true-file (file-truename file))
18297 (afile (abbreviate-file-name file))
18298 (files (delq nil (mapcar
18299 (lambda (x)
18300 (if (equal true-file
18301 (file-truename x))
18302 nil x))
18303 (org-agenda-files t)))))
18304 (if (not (= (length files) (length (org-agenda-files t))))
18305 (progn
18306 (org-store-new-agenda-file-list files)
18307 (org-install-agenda-files-menu)
18308 (message "Removed file: %s" afile))
18309 (message "File was not in list: %s (not removed)" afile))))
18311 (defun org-file-menu-entry (file)
18312 (vector file (list 'find-file file) t))
18314 (defun org-check-agenda-file (file)
18315 "Make sure FILE exists. If not, ask user what to do."
18316 (when (not (file-exists-p file))
18317 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18318 (abbreviate-file-name file))
18319 (let ((r (downcase (read-char-exclusive))))
18320 (cond
18321 ((equal r ?r)
18322 (org-remove-file file)
18323 (throw 'nextfile t))
18324 (t (user-error "Abort"))))))
18326 (defun org-get-agenda-file-buffer (file)
18327 "Get an agenda buffer visiting FILE.
18328 If the buffer needs to be created, add it to the list of buffers
18329 which might be released later."
18330 (let ((buf (org-find-base-buffer-visiting file)))
18331 (if buf
18332 buf ; just return it
18333 ;; Make a new buffer and remember it
18334 (setq buf (find-file-noselect file))
18335 (if buf (push buf org-agenda-new-buffers))
18336 buf)))
18338 (defun org-release-buffers (blist)
18339 "Release all buffers in list, asking the user for confirmation when needed.
18340 When a buffer is unmodified, it is just killed. When modified, it is saved
18341 \(if the user agrees) and then killed."
18342 (let (buf file)
18343 (while (setq buf (pop blist))
18344 (setq file (buffer-file-name buf))
18345 (when (and (buffer-modified-p buf)
18346 file
18347 (y-or-n-p (format "Save file %s? " file)))
18348 (with-current-buffer buf (save-buffer)))
18349 (kill-buffer buf))))
18351 (defun org-agenda-prepare-buffers (files)
18352 "Create buffers for all agenda files, protect archived trees and comments."
18353 (interactive)
18354 (let ((pa '(:org-archived t))
18355 (pc '(:org-comment t))
18356 (pall '(:org-archived t :org-comment t))
18357 (inhibit-read-only t)
18358 (org-inhibit-startup org-agenda-inhibit-startup)
18359 (rea (concat ":" org-archive-tag ":"))
18360 file re pos)
18361 (setq org-tag-alist-for-agenda nil
18362 org-tag-groups-alist-for-agenda nil)
18363 (save-excursion
18364 (save-restriction
18365 (while (setq file (pop files))
18366 (catch 'nextfile
18367 (if (bufferp file)
18368 (set-buffer file)
18369 (org-check-agenda-file file)
18370 (set-buffer (org-get-agenda-file-buffer file)))
18371 (widen)
18372 (org-set-regexps-and-options-for-tags)
18373 (setq pos (point))
18374 (goto-char (point-min))
18375 (let ((case-fold-search t))
18376 (when (search-forward "#+setupfile" nil t)
18377 ;; Don't set all regexps and options systematically as
18378 ;; this is only run for setting agenda tags from setup
18379 ;; file
18380 (org-set-regexps-and-options)))
18381 (or (memq 'category org-agenda-ignore-properties)
18382 (org-refresh-category-properties))
18383 (or (memq 'stats org-agenda-ignore-properties)
18384 (org-refresh-stats-properties))
18385 (or (memq 'effort org-agenda-ignore-properties)
18386 (org-refresh-effort-properties))
18387 (or (memq 'appt org-agenda-ignore-properties)
18388 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18389 (setq org-todo-keywords-for-agenda
18390 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18391 (setq org-done-keywords-for-agenda
18392 (append org-done-keywords-for-agenda org-done-keywords))
18393 (setq org-todo-keyword-alist-for-agenda
18394 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18395 (setq org-tag-alist-for-agenda
18396 (org-uniquify
18397 (append org-tag-alist-for-agenda
18398 org-tag-alist
18399 org-tag-persistent-alist)))
18400 (if org-group-tags
18401 (setq org-tag-groups-alist-for-agenda
18402 (org-uniquify-alist
18403 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18404 (org-with-silent-modifications
18405 (save-excursion
18406 (remove-text-properties (point-min) (point-max) pall)
18407 (when org-agenda-skip-archived-trees
18408 (goto-char (point-min))
18409 (while (re-search-forward rea nil t)
18410 (if (org-at-heading-p t)
18411 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18412 (goto-char (point-min))
18413 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18414 (while (re-search-forward re nil t)
18415 (when (save-match-data (org-in-commented-heading-p t))
18416 (add-text-properties
18417 (match-beginning 0) (org-end-of-subtree t) pc)))))
18418 (goto-char pos)))))
18419 (setq org-todo-keywords-for-agenda
18420 (org-uniquify org-todo-keywords-for-agenda))
18421 (setq org-todo-keyword-alist-for-agenda
18422 (org-uniquify org-todo-keyword-alist-for-agenda))))
18425 ;;;; CDLaTeX minor mode
18427 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18428 "Keymap for the minor `org-cdlatex-mode'.")
18430 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18431 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18432 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18433 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18434 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18436 (defvar org-cdlatex-texmathp-advice-is-done nil
18437 "Flag remembering if we have applied the advice to texmathp already.")
18439 (define-minor-mode org-cdlatex-mode
18440 "Toggle the minor `org-cdlatex-mode'.
18441 This mode supports entering LaTeX environment and math in LaTeX fragments
18442 in Org-mode.
18443 \\{org-cdlatex-mode-map}"
18444 nil " OCDL" nil
18445 (when org-cdlatex-mode
18446 (require 'cdlatex)
18447 (run-hooks 'cdlatex-mode-hook)
18448 (cdlatex-compute-tables))
18449 (unless org-cdlatex-texmathp-advice-is-done
18450 (setq org-cdlatex-texmathp-advice-is-done t)
18451 (defadvice texmathp (around org-math-always-on activate)
18452 "Always return t in org-mode buffers.
18453 This is because we want to insert math symbols without dollars even outside
18454 the LaTeX math segments. If Orgmode thinks that point is actually inside
18455 an embedded LaTeX fragment, let texmathp do its job.
18456 \\[org-cdlatex-mode-map]"
18457 (interactive)
18458 (let (p)
18459 (cond
18460 ((not (derived-mode-p 'org-mode)) ad-do-it)
18461 ((eq this-command 'cdlatex-math-symbol)
18462 (setq ad-return-value t
18463 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18465 (let ((p (org-inside-LaTeX-fragment-p)))
18466 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18467 (setq ad-return-value t
18468 texmathp-why '("Org-mode embedded math" . 0))
18469 (if p ad-do-it)))))))))
18471 (defun turn-on-org-cdlatex ()
18472 "Unconditionally turn on `org-cdlatex-mode'."
18473 (org-cdlatex-mode 1))
18475 (defun org-try-cdlatex-tab ()
18476 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18477 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18478 - inside a LaTeX fragment, or
18479 - after the first word in a line, where an abbreviation expansion could
18480 insert a LaTeX environment."
18481 (when org-cdlatex-mode
18482 (cond
18483 ;; Before any word on the line: No expansion possible.
18484 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18485 ;; Just after first word on the line: Expand it. Make sure it
18486 ;; cannot happen on headlines, though.
18487 ((save-excursion
18488 (skip-chars-backward "a-zA-Z0-9*")
18489 (skip-chars-backward " \t")
18490 (and (bolp) (not (org-at-heading-p))))
18491 (cdlatex-tab) t)
18492 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18494 (defun org-cdlatex-underscore-caret (&optional arg)
18495 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18496 Revert to the normal definition outside of these fragments."
18497 (interactive "P")
18498 (if (org-inside-LaTeX-fragment-p)
18499 (call-interactively 'cdlatex-sub-superscript)
18500 (let (org-cdlatex-mode)
18501 (call-interactively (key-binding (vector last-input-event))))))
18503 (defun org-cdlatex-math-modify (&optional arg)
18504 "Execute `cdlatex-math-modify' in LaTeX fragments.
18505 Revert to the normal definition outside of these fragments."
18506 (interactive "P")
18507 (if (org-inside-LaTeX-fragment-p)
18508 (call-interactively 'cdlatex-math-modify)
18509 (let (org-cdlatex-mode)
18510 (call-interactively (key-binding (vector last-input-event))))))
18512 (defun org-cdlatex-environment-indent (&optional environment item)
18513 "Execute `cdlatex-environment' and indent the inserted environment."
18514 (interactive)
18515 (cdlatex-environment environment item)
18516 (let ((element (org-element-at-point)))
18517 (org-indent-region (org-element-property :begin element)
18518 (org-element-property :end element))))
18521 ;;;; LaTeX fragments
18523 (defun org-inside-LaTeX-fragment-p ()
18524 "Test if point is inside a LaTeX fragment.
18525 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18526 sequence appearing also before point.
18527 Even though the matchers for math are configurable, this function assumes
18528 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18529 delimiters are skipped when they have been removed by customization.
18530 The return value is nil, or a cons cell with the delimiter and the
18531 position of this delimiter.
18533 This function does a reasonably good job, but can locally be fooled by
18534 for example currency specifications. For example it will assume being in
18535 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18536 fragments that are properly closed, but during editing, we have to live
18537 with the uncertainty caused by missing closing delimiters. This function
18538 looks only before point, not after."
18539 (catch 'exit
18540 (let ((pos (point))
18541 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18542 (lim (progn
18543 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18544 (point)))
18545 dd-on str (start 0) m re)
18546 (goto-char pos)
18547 (when dodollar
18548 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18549 re (nth 1 (assoc "$" org-latex-regexps)))
18550 (while (string-match re str start)
18551 (cond
18552 ((= (match-end 0) (length str))
18553 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18554 ((= (match-end 0) (- (length str) 5))
18555 (throw 'exit nil))
18556 (t (setq start (match-end 0))))))
18557 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18558 (goto-char pos)
18559 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18560 (and (match-beginning 2) (throw 'exit nil))
18561 ;; count $$
18562 (while (re-search-backward "\\$\\$" lim t)
18563 (setq dd-on (not dd-on)))
18564 (goto-char pos)
18565 (if dd-on (cons "$$" m))))))
18567 (defun org-inside-latex-macro-p ()
18568 "Is point inside a LaTeX macro or its arguments?"
18569 (save-match-data
18570 (org-in-regexp
18571 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18573 (defvar org-latex-fragment-image-overlays nil
18574 "List of overlays carrying the images of latex fragments.")
18575 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18577 (defun org-remove-latex-fragment-image-overlays ()
18578 "Remove all overlays with LaTeX fragment images in current buffer."
18579 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18580 (setq org-latex-fragment-image-overlays nil))
18582 (define-obsolete-function-alias
18583 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18584 (defun org-toggle-latex-fragment (&optional subtree)
18585 "Preview the LaTeX fragment at point, or all locally or globally.
18586 If the cursor is in a LaTeX fragment, create the image and overlay
18587 it over the source code. If there is no fragment at point, display
18588 all fragments in the current text, from one headline to the next. With
18589 prefix SUBTREE, display all fragments in the current subtree. With a
18590 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18591 the cursor is before the first headline,
18592 display all fragments in the buffer.
18593 The images can be removed again with \\[org-toggle-latex-fragment]."
18594 (interactive "P")
18595 (unless buffer-file-name
18596 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18597 (if org-latex-fragment-image-overlays
18598 (progn (org-remove-latex-fragment-image-overlays)
18599 (message "LaTeX fragments images removed"))
18600 (when (display-graphic-p)
18601 (org-remove-latex-fragment-image-overlays)
18602 (save-excursion
18603 (save-restriction
18604 (let (beg end at msg)
18605 (cond
18606 ((or (equal subtree '(16))
18607 (not (save-excursion
18608 (re-search-backward org-outline-regexp-bol nil t))))
18609 (setq beg (point-min) end (point-max)
18610 msg "Creating images for buffer...%s"))
18611 ((equal subtree '(4))
18612 (org-back-to-heading)
18613 (setq beg (point) end (org-end-of-subtree t)
18614 msg "Creating images for subtree...%s"))
18616 (if (setq at (org-inside-LaTeX-fragment-p))
18617 (goto-char (max (point-min) (- (cdr at) 2)))
18618 (org-back-to-heading))
18619 (setq beg (point) end (progn (outline-next-heading) (point))
18620 msg (if at "Creating image...%s"
18621 "Creating images for entry...%s"))))
18622 (message msg "")
18623 (narrow-to-region beg end)
18624 (goto-char beg)
18625 (org-format-latex
18626 (concat org-latex-preview-ltxpng-directory
18627 (file-name-sans-extension
18628 (file-name-nondirectory buffer-file-name)))
18629 default-directory 'overlays msg at 'forbuffer
18630 org-latex-create-formula-image-program)
18631 (message msg "done. Use `C-c C-x C-l' to remove images.")))))))
18633 (defun org-format-latex (prefix &optional dir overlays msg at
18634 forbuffer processing-type)
18635 "Replace LaTeX fragments with links to an image, and produce images.
18636 Some of the options can be changed using the variable
18637 `org-format-latex-options'."
18638 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18639 (let* ((prefixnodir (file-name-nondirectory prefix))
18640 (absprefix (expand-file-name prefix dir))
18641 (todir (file-name-directory absprefix))
18642 (opt org-format-latex-options)
18643 (optnew org-format-latex-options)
18644 (matchers (plist-get opt :matchers))
18645 (re-list org-latex-regexps)
18646 (cnt 0) txt hash link beg end re e checkdir
18647 string
18648 m n block-type block linkfile movefile ov)
18649 ;; Check the different regular expressions
18650 (while (setq e (pop re-list))
18651 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18652 block (if block-type "\n\n" ""))
18653 (when (member m matchers)
18654 (goto-char (point-min))
18655 (while (re-search-forward re nil t)
18656 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18657 (or (not overlays)
18658 (not (eq (get-char-property (match-beginning n)
18659 'org-overlay-type)
18660 'org-latex-overlay))))
18661 (cond
18662 ((eq processing-type 'verbatim))
18663 ((eq processing-type 'mathjax)
18664 ;; Prepare for MathJax processing.
18665 (setq string (match-string n))
18666 (when (member m '("$" "$1"))
18667 (save-excursion
18668 (delete-region (match-beginning n) (match-end n))
18669 (goto-char (match-beginning n))
18670 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18671 ((or (eq processing-type 'dvipng)
18672 (eq processing-type 'imagemagick))
18673 ;; Process to an image.
18674 (setq txt (match-string n)
18675 beg (match-beginning n) end (match-end n)
18676 cnt (1+ cnt))
18677 (let ((face (face-at-point))
18678 (fg (plist-get opt :foreground))
18679 (bg (plist-get opt :background))
18680 ;; Ensure full list is printed.
18681 print-length print-level)
18682 (when forbuffer
18683 ;; Get the colors from the face at point.
18684 (goto-char beg)
18685 (when (eq fg 'auto)
18686 (setq fg (face-attribute face :foreground nil 'default)))
18687 (when (eq bg 'auto)
18688 (setq bg (face-attribute face :background nil 'default)))
18689 (setq optnew (copy-sequence opt))
18690 (plist-put optnew :foreground fg)
18691 (plist-put optnew :background bg))
18692 (setq hash (sha1 (prin1-to-string
18693 (list org-format-latex-header
18694 org-latex-default-packages-alist
18695 org-latex-packages-alist
18696 org-format-latex-options
18697 forbuffer txt fg bg)))
18698 linkfile (format "%s_%s.png" prefix hash)
18699 movefile (format "%s_%s.png" absprefix hash)))
18700 (setq link (concat block "[[file:" linkfile "]]" block))
18701 (if msg (message msg cnt))
18702 (goto-char beg)
18703 (unless checkdir ; Ensure the directory exists.
18704 (setq checkdir t)
18705 (or (file-directory-p todir) (make-directory todir t)))
18706 (unless (file-exists-p movefile)
18707 (org-create-formula-image
18708 txt movefile optnew forbuffer processing-type))
18709 (if overlays
18710 (progn
18711 (mapc (lambda (o)
18712 (if (eq (overlay-get o 'org-overlay-type)
18713 'org-latex-overlay)
18714 (delete-overlay o)))
18715 (overlays-in beg end))
18716 (setq ov (make-overlay beg end))
18717 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18718 (if (featurep 'xemacs)
18719 (progn
18720 (overlay-put ov 'invisible t)
18721 (overlay-put
18722 ov 'end-glyph
18723 (make-glyph (vector 'png :file movefile))))
18724 (overlay-put
18725 ov 'display
18726 (list 'image :type 'png :file movefile :ascent 'center)))
18727 (push ov org-latex-fragment-image-overlays)
18728 (goto-char end))
18729 (delete-region beg end)
18730 (insert (org-add-props link
18731 (list 'org-latex-src
18732 (replace-regexp-in-string
18733 "\"" "" txt)
18734 'org-latex-src-embed-type
18735 (if block-type 'paragraph 'character))))))
18736 ((eq processing-type 'mathml)
18737 ;; Process to MathML
18738 (unless (save-match-data (org-format-latex-mathml-available-p))
18739 (user-error "LaTeX to MathML converter not configured"))
18740 (setq txt (match-string n)
18741 beg (match-beginning n) end (match-end n)
18742 cnt (1+ cnt))
18743 (if msg (message msg cnt))
18744 (goto-char beg)
18745 (delete-region beg end)
18746 (insert (org-format-latex-as-mathml
18747 txt block-type prefix dir)))
18749 (error "Unknown conversion type %s for LaTeX fragments"
18750 processing-type)))))))))
18752 (defun org-create-math-formula (latex-frag &optional mathml-file)
18753 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18754 Use `org-latex-to-mathml-convert-command'. If the conversion is
18755 sucessful, return the portion between \"<math...> </math>\"
18756 elements otherwise return nil. When MATHML-FILE is specified,
18757 write the results in to that file. When invoked as an
18758 interactive command, prompt for LATEX-FRAG, with initial value
18759 set to the current active region and echo the results for user
18760 inspection."
18761 (interactive (list (let ((frag (when (org-region-active-p)
18762 (buffer-substring-no-properties
18763 (region-beginning) (region-end)))))
18764 (read-string "LaTeX Fragment: " frag nil frag))))
18765 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18766 (let* ((tmp-in-file (file-relative-name
18767 (make-temp-name (expand-file-name "ltxmathml-in"))))
18768 (ignore (write-region latex-frag nil tmp-in-file))
18769 (tmp-out-file (file-relative-name
18770 (make-temp-name (expand-file-name "ltxmathml-out"))))
18771 (cmd (format-spec
18772 org-latex-to-mathml-convert-command
18773 `((?j . ,(shell-quote-argument
18774 (expand-file-name org-latex-to-mathml-jar-file)))
18775 (?I . ,(shell-quote-argument tmp-in-file))
18776 (?o . ,(shell-quote-argument tmp-out-file)))))
18777 mathml shell-command-output)
18778 (when (org-called-interactively-p 'any)
18779 (unless (org-format-latex-mathml-available-p)
18780 (user-error "LaTeX to MathML converter not configured")))
18781 (message "Running %s" cmd)
18782 (setq shell-command-output (shell-command-to-string cmd))
18783 (setq mathml
18784 (when (file-readable-p tmp-out-file)
18785 (with-current-buffer (find-file-noselect tmp-out-file t)
18786 (goto-char (point-min))
18787 (when (re-search-forward
18788 (concat
18789 (regexp-quote
18790 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18791 "\\(.\\|\n\\)*"
18792 (regexp-quote "</math>")) nil t)
18793 (prog1 (match-string 0) (kill-buffer))))))
18794 (cond
18795 (mathml
18796 (setq mathml
18797 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18798 (when mathml-file
18799 (write-region mathml nil mathml-file))
18800 (when (org-called-interactively-p 'any)
18801 (message mathml)))
18802 ((message "LaTeX to MathML conversion failed")
18803 (message shell-command-output)))
18804 (delete-file tmp-in-file)
18805 (when (file-exists-p tmp-out-file)
18806 (delete-file tmp-out-file))
18807 mathml))
18809 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18810 prefix &optional dir)
18811 "Use `org-create-math-formula' but check local cache first."
18812 (let* ((absprefix (expand-file-name prefix dir))
18813 (print-length nil) (print-level nil)
18814 (formula-id (concat
18815 "formula-"
18816 (sha1
18817 (prin1-to-string
18818 (list latex-frag
18819 org-latex-to-mathml-convert-command)))))
18820 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18821 (formula-cache-dir (file-name-directory formula-cache)))
18823 (unless (file-directory-p formula-cache-dir)
18824 (make-directory formula-cache-dir t))
18826 (unless (file-exists-p formula-cache)
18827 (org-create-math-formula latex-frag formula-cache))
18829 (if (file-exists-p formula-cache)
18830 ;; Successful conversion. Return the link to MathML file.
18831 (org-add-props
18832 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18833 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18834 'org-latex-src-embed-type (if latex-frag-type
18835 'paragraph 'character)))
18836 ;; Failed conversion. Return the LaTeX fragment verbatim
18837 latex-frag)))
18839 (defun org-create-formula-image (string tofile options buffer &optional type)
18840 "Create an image from LaTeX source using dvipng or convert.
18841 This function calls either `org-create-formula-image-with-dvipng'
18842 or `org-create-formula-image-with-imagemagick' depending on the
18843 value of `org-latex-create-formula-image-program' or on the value
18844 of the optional TYPE variable.
18846 Note: ultimately these two function should be combined as they
18847 share a good deal of logic."
18848 (org-check-external-command
18849 "latex" "needed to convert LaTeX fragments to images")
18850 (funcall
18851 (case (or type org-latex-create-formula-image-program)
18852 ('dvipng
18853 (org-check-external-command
18854 "dvipng" "needed to convert LaTeX fragments to images")
18855 'org-create-formula-image-with-dvipng)
18856 ('imagemagick
18857 (org-check-external-command
18858 "convert" "you need to install imagemagick")
18859 'org-create-formula-image-with-imagemagick)
18860 (t (error
18861 "Invalid value of `org-latex-create-formula-image-program'")))
18862 string tofile options buffer))
18864 (declare-function org-export-get-backend "ox" (name))
18865 (declare-function org-export--get-global-options "ox" (&optional backend))
18866 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18867 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18868 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18869 (defun org-create-formula--latex-header ()
18870 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18871 (let ((info (org-combine-plists (org-export--get-global-options
18872 (org-export-get-backend 'latex))
18873 (org-export--get-inbuffer-options
18874 (org-export-get-backend 'latex)))))
18875 (org-latex-guess-babel-language
18876 (org-latex-guess-inputenc
18877 (org-splice-latex-header
18878 org-format-latex-header
18879 org-latex-default-packages-alist
18880 org-latex-packages-alist t
18881 (plist-get info :latex-header)))
18882 info)))
18884 ;; This function borrows from Ganesh Swami's latex2png.el
18885 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18886 "This calls dvipng."
18887 (require 'ox-latex)
18888 (let* ((tmpdir (if (featurep 'xemacs)
18889 (temp-directory)
18890 temporary-file-directory))
18891 (texfilebase (make-temp-name
18892 (expand-file-name "orgtex" tmpdir)))
18893 (texfile (concat texfilebase ".tex"))
18894 (dvifile (concat texfilebase ".dvi"))
18895 (pngfile (concat texfilebase ".png"))
18896 (fnh (if (featurep 'xemacs)
18897 (font-height (face-font 'default))
18898 (face-attribute 'default :height nil)))
18899 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18900 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18901 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18902 "Black"))
18903 (bg (or (plist-get options (if buffer :background :html-background))
18904 "Transparent")))
18905 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18906 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18907 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18908 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18909 (let ((latex-header (org-create-formula--latex-header)))
18910 (with-temp-file texfile
18911 (insert latex-header)
18912 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18913 (let ((dir default-directory))
18914 (ignore-errors
18915 (cd tmpdir)
18916 (call-process "latex" nil nil nil texfile))
18917 (cd dir))
18918 (if (not (file-exists-p dvifile))
18919 (progn (message "Failed to create dvi file from %s" texfile) nil)
18920 (ignore-errors
18921 (if (featurep 'xemacs)
18922 (call-process "dvipng" nil nil nil
18923 "-fg" fg "-bg" bg
18924 "-T" "tight"
18925 "-o" pngfile
18926 dvifile)
18927 (call-process "dvipng" nil nil nil
18928 "-fg" fg "-bg" bg
18929 "-D" dpi
18930 ;;"-x" scale "-y" scale
18931 "-T" "tight"
18932 "-o" pngfile
18933 dvifile)))
18934 (if (not (file-exists-p pngfile))
18935 (if org-format-latex-signal-error
18936 (error "Failed to create png file from %s" texfile)
18937 (message "Failed to create png file from %s" texfile)
18938 nil)
18939 ;; Use the requested file name and clean up
18940 (copy-file pngfile tofile 'replace)
18941 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18942 (if (file-exists-p (concat texfilebase e))
18943 (delete-file (concat texfilebase e))))
18944 pngfile))))
18946 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18947 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18948 "This calls convert, which is included into imagemagick."
18949 (require 'ox-latex)
18950 (let* ((tmpdir (if (featurep 'xemacs)
18951 (temp-directory)
18952 temporary-file-directory))
18953 (texfilebase (make-temp-name
18954 (expand-file-name "orgtex" tmpdir)))
18955 (texfile (concat texfilebase ".tex"))
18956 (pdffile (concat texfilebase ".pdf"))
18957 (pngfile (concat texfilebase ".png"))
18958 (fnh (if (featurep 'xemacs)
18959 (font-height (face-font 'default))
18960 (face-attribute 'default :height nil)))
18961 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18962 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18963 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18964 "black"))
18965 (bg (or (plist-get options (if buffer :background :html-background))
18966 "white")))
18967 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18968 (setq fg (org-latex-color-format fg)))
18969 (if (eq bg 'default) (setq bg (org-latex-color :background))
18970 (setq bg (org-latex-color-format
18971 (if (string= bg "Transparent") "white" bg))))
18972 (let ((latex-header (org-create-formula--latex-header)))
18973 (with-temp-file texfile
18974 (insert latex-header)
18975 (insert "\n\\begin{document}\n"
18976 "\\definecolor{fg}{rgb}{" fg "}\n"
18977 "\\definecolor{bg}{rgb}{" bg "}\n"
18978 "\n\\pagecolor{bg}\n"
18979 "\n{\\color{fg}\n"
18980 string
18981 "\n}\n"
18982 "\n\\end{document}\n")))
18983 (org-latex-compile texfile t)
18984 (if (not (file-exists-p pdffile))
18985 (progn (message "Failed to create pdf file from %s" texfile) nil)
18986 (ignore-errors
18987 (if (featurep 'xemacs)
18988 (call-process "convert" nil nil nil
18989 "-density" "96"
18990 "-trim"
18991 "-antialias"
18992 pdffile
18993 "-quality" "100"
18994 ;; "-sharpen" "0x1.0"
18995 pngfile)
18996 (call-process "convert" nil nil nil
18997 "-density" dpi
18998 "-trim"
18999 "-antialias"
19000 pdffile
19001 "-quality" "100"
19002 ;; "-sharpen" "0x1.0"
19003 pngfile)))
19004 (if (not (file-exists-p pngfile))
19005 (if org-format-latex-signal-error
19006 (error "Failed to create png file from %s" texfile)
19007 (message "Failed to create png file from %s" texfile)
19008 nil)
19009 ;; Use the requested file name and clean up
19010 (copy-file pngfile tofile 'replace)
19011 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19012 (if (file-exists-p (concat texfilebase e))
19013 (delete-file (concat texfilebase e))))
19014 pngfile))))
19016 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19017 "Fill a LaTeX header template TPL.
19018 In the template, the following place holders will be recognized:
19020 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19021 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19022 [PACKAGES] \\usepackage statements for PKG
19023 [NO-PACKAGES] do not include PKG
19024 [EXTRA] the string EXTRA
19025 [NO-EXTRA] do not include EXTRA
19027 For backward compatibility, if both the positive and the negative place
19028 holder is missing, the positive one (without the \"NO-\") will be
19029 assumed to be present at the end of the template.
19030 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19031 EXTRA is a string.
19032 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19033 (let (rpl (end ""))
19034 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19035 (setq rpl (if (or (match-end 1) (not def-pkg))
19036 "" (org-latex-packages-to-string def-pkg snippets-p t))
19037 tpl (replace-match rpl t t tpl))
19038 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19040 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19041 (setq rpl (if (or (match-end 1) (not pkg))
19042 "" (org-latex-packages-to-string pkg snippets-p t))
19043 tpl (replace-match rpl t t tpl))
19044 (if pkg (setq end
19045 (concat end "\n"
19046 (org-latex-packages-to-string pkg snippets-p)))))
19048 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19049 (setq rpl (if (or (match-end 1) (not extra))
19050 "" (concat extra "\n"))
19051 tpl (replace-match rpl t t tpl))
19052 (if (and extra (string-match "\\S-" extra))
19053 (setq end (concat end "\n" extra))))
19055 (if (string-match "\\S-" end)
19056 (concat tpl "\n" end)
19057 tpl)))
19059 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19060 "Turn an alist of packages into a string with the \\usepackage macros."
19061 (setq pkg (mapconcat (lambda(p)
19062 (cond
19063 ((stringp p) p)
19064 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19065 (format "%% Package %s omitted" (cadr p)))
19066 ((equal "" (car p))
19067 (format "\\usepackage{%s}" (cadr p)))
19069 (format "\\usepackage[%s]{%s}"
19070 (car p) (cadr p)))))
19072 "\n"))
19073 (if newline (concat pkg "\n") pkg))
19075 (defun org-dvipng-color (attr)
19076 "Return a RGB color specification for dvipng."
19077 (apply 'format "rgb %s %s %s"
19078 (mapcar 'org-normalize-color
19079 (if (featurep 'xemacs)
19080 (color-rgb-components
19081 (face-property 'default
19082 (cond ((eq attr :foreground) 'foreground)
19083 ((eq attr :background) 'background))))
19084 (color-values (face-attribute 'default attr nil))))))
19086 (defun org-dvipng-color-format (color-name)
19087 "Convert COLOR-NAME to a RGB color value for dvipng."
19088 (apply 'format "rgb %s %s %s"
19089 (mapcar 'org-normalize-color
19090 (color-values color-name))))
19092 (defun org-latex-color (attr)
19093 "Return a RGB color for the LaTeX color package."
19094 (apply 'format "%s,%s,%s"
19095 (mapcar 'org-normalize-color
19096 (if (featurep 'xemacs)
19097 (color-rgb-components
19098 (face-property 'default
19099 (cond ((eq attr :foreground) 'foreground)
19100 ((eq attr :background) 'background))))
19101 (color-values (face-attribute 'default attr nil))))))
19103 (defun org-latex-color-format (color-name)
19104 "Convert COLOR-NAME to a RGB color value."
19105 (apply 'format "%s,%s,%s"
19106 (mapcar 'org-normalize-color
19107 (color-values color-name))))
19109 (defun org-normalize-color (value)
19110 "Return string to be used as color value for an RGB component."
19111 (format "%g" (/ value 65535.0)))
19115 ;; Image display
19117 (defvar org-inline-image-overlays nil)
19118 (make-variable-buffer-local 'org-inline-image-overlays)
19120 (defun org-toggle-inline-images (&optional include-linked)
19121 "Toggle the display of inline images.
19122 INCLUDE-LINKED is passed to `org-display-inline-images'."
19123 (interactive "P")
19124 (if org-inline-image-overlays
19125 (progn
19126 (org-remove-inline-images)
19127 (message "Inline image display turned off"))
19128 (org-display-inline-images include-linked)
19129 (if (and (org-called-interactively-p)
19130 org-inline-image-overlays)
19131 (message "%d images displayed inline"
19132 (length org-inline-image-overlays))
19133 (message "No images to display inline"))))
19135 (defun org-redisplay-inline-images ()
19136 "Refresh the display of inline images."
19137 (interactive)
19138 (if (not org-inline-image-overlays)
19139 (org-toggle-inline-images)
19140 (org-toggle-inline-images)
19141 (org-toggle-inline-images)))
19143 (defun org-display-inline-images (&optional include-linked refresh beg end)
19144 "Display inline images.
19146 An inline image is a link which follows either of these
19147 conventions:
19149 1. Its path is a file with an extension matching return value
19150 from `image-file-name-regexp' and it has no contents.
19152 2. Its description consists in a single link of the previous
19153 type.
19155 When optional argument INCLUDE-LINKED is non-nil, also links with
19156 a text description part will be inlined. This can be nice for
19157 a quick look at those images, but it does not reflect what
19158 exported files will look like.
19160 When optional argument REFRESH is non-nil, refresh existing
19161 images between BEG and END. This will create new image displays
19162 only if necessary. BEG and END default to the buffer
19163 boundaries."
19164 (interactive "P")
19165 (when (display-graphic-p)
19166 (unless refresh
19167 (org-remove-inline-images)
19168 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19169 (org-with-wide-buffer
19170 (goto-char (or beg (point-min)))
19171 (let ((case-fold-search t)
19172 (file-extension-re (org-image-file-name-regexp)))
19173 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19174 (let ((link (save-match-data (org-element-context))))
19175 ;; Check if we're at an inline image.
19176 (when (and (equal (org-element-property :type link) "file")
19177 (or include-linked
19178 (not (org-element-property :contents-begin link)))
19179 (let ((parent (org-element-property :parent link)))
19180 (or (not (eq (org-element-type parent) 'link))
19181 (not (cdr (org-element-contents parent)))))
19182 (org-string-match-p file-extension-re
19183 (org-element-property :path link)))
19184 (let ((file (expand-file-name (org-element-property :path link))))
19185 (when (file-exists-p file)
19186 (let ((width
19187 ;; Apply `org-image-actual-width' specifications.
19188 (cond
19189 ((not (image-type-available-p 'imagemagick)) nil)
19190 ((eq org-image-actual-width t) nil)
19191 ((listp org-image-actual-width)
19193 ;; First try to find a width among
19194 ;; attributes associated to the paragraph
19195 ;; containing link.
19196 (let ((paragraph
19197 (let ((e link))
19198 (while (and (setq e (org-element-property
19199 :parent e))
19200 (not (eq (org-element-type e)
19201 'paragraph))))
19202 e)))
19203 (when paragraph
19204 (save-excursion
19205 (goto-char (org-element-property :begin paragraph))
19206 (when
19207 (re-search-forward
19208 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19209 (org-element-property
19210 :post-affiliated paragraph)
19212 (string-to-number (match-string 1))))))
19213 ;; Otherwise, fall-back to provided number.
19214 (car org-image-actual-width)))
19215 ((numberp org-image-actual-width)
19216 org-image-actual-width)))
19217 (old (get-char-property-and-overlay
19218 (org-element-property :begin link)
19219 'org-image-overlay)))
19220 (if (and (car-safe old) refresh)
19221 (image-refresh (overlay-get (cdr old) 'display))
19222 (let ((image (create-image file
19223 (and width 'imagemagick)
19225 :width width)))
19226 (when image
19227 (let* ((link
19228 ;; If inline image is the description
19229 ;; of another link, be sure to
19230 ;; consider the latter as the one to
19231 ;; apply the overlay on.
19232 (let ((parent
19233 (org-element-property :parent link)))
19234 (if (eq (org-element-type parent) 'link)
19235 parent
19236 link)))
19237 (ov (make-overlay
19238 (org-element-property :begin link)
19239 (progn
19240 (goto-char
19241 (org-element-property :end link))
19242 (skip-chars-backward " \t")
19243 (point)))))
19244 (overlay-put ov 'display image)
19245 (overlay-put ov 'face 'default)
19246 (overlay-put ov 'org-image-overlay t)
19247 (overlay-put
19248 ov 'modification-hooks
19249 (list 'org-display-inline-remove-overlay))
19250 (push ov org-inline-image-overlays)))))))))))))))
19252 (define-obsolete-function-alias
19253 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19255 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19256 "Remove inline-display overlay if a corresponding region is modified."
19257 (let ((inhibit-modification-hooks t))
19258 (when (and ov after)
19259 (delete ov org-inline-image-overlays)
19260 (delete-overlay ov))))
19262 (defun org-remove-inline-images ()
19263 "Remove inline display of images."
19264 (interactive)
19265 (mapc 'delete-overlay org-inline-image-overlays)
19266 (setq org-inline-image-overlays nil))
19268 ;;;; Key bindings
19270 ;; Outline functions from `outline-mode-prefix-map'
19271 ;; that can be remapped in Org:
19272 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19273 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19274 (define-key org-mode-map [remap outline-forward-same-level]
19275 'org-forward-heading-same-level)
19276 (define-key org-mode-map [remap outline-backward-same-level]
19277 'org-backward-heading-same-level)
19278 (define-key org-mode-map [remap show-branches]
19279 'org-kill-note-or-show-branches)
19280 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19281 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19282 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19284 ;; Outline functions from `outline-mode-prefix-map' that can not
19285 ;; be remapped in Org:
19287 ;; - the column "key binding" shows whether the Outline function is still
19288 ;; available in Org mode on the same key that it has been bound to in
19289 ;; Outline mode:
19290 ;; - "overridden": key used for a different functionality in Org mode
19291 ;; - else: key still bound to the same Outline function in Org mode
19293 ;; | Outline function | key binding | Org replacement |
19294 ;; |------------------------------------+-------------+-----------------------|
19295 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19296 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19297 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19298 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19299 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19300 ;; | `show-entry' | overridden | no replacement |
19301 ;; | `show-children' | `C-c C-i' | visibility cycling |
19302 ;; | `show-branches' | `C-c C-k' | still same function |
19303 ;; | `show-subtree' | overridden | visibility cycling |
19304 ;; | `show-all' | overridden | no replacement |
19305 ;; | `hide-subtree' | overridden | visibility cycling |
19306 ;; | `hide-body' | overridden | no replacement |
19307 ;; | `hide-entry' | overridden | visibility cycling |
19308 ;; | `hide-leaves' | overridden | no replacement |
19309 ;; | `hide-sublevels' | overridden | no replacement |
19310 ;; | `hide-other' | overridden | no replacement |
19312 ;; Make `C-c C-x' a prefix key
19313 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19315 ;; TAB key with modifiers
19316 (org-defkey org-mode-map "\C-i" 'org-cycle)
19317 (org-defkey org-mode-map [(tab)] 'org-cycle)
19318 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19319 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19320 ;; The following line is necessary under Suse GNU/Linux
19321 (unless (featurep 'xemacs)
19322 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19323 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19324 (define-key org-mode-map [backtab] 'org-shifttab)
19326 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19327 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19328 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19330 ;; Cursor keys with modifiers
19331 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19332 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19333 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19334 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19336 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19337 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19338 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19339 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19340 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19341 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19343 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19344 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19345 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19346 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19348 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19349 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19350 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19351 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19353 ;; Babel keys
19354 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19355 (mapc (lambda (pair)
19356 (define-key org-babel-map (car pair) (cdr pair)))
19357 org-babel-key-bindings)
19359 ;;; Extra keys for tty access.
19360 ;; We only set them when really needed because otherwise the
19361 ;; menus don't show the simple keys
19363 (when (or org-use-extra-keys
19364 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19365 (not window-system))
19366 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19367 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19368 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19369 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19370 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19371 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19372 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19373 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19374 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19375 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19376 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19377 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19378 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19379 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19380 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19381 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19382 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19383 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19384 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19385 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19386 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19387 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19388 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19389 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19390 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19391 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19392 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19393 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19395 ;; All the other keys
19397 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19398 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19399 (if (boundp 'narrow-map)
19400 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19401 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19402 (if (boundp 'narrow-map)
19403 (org-defkey narrow-map "b" 'org-narrow-to-block)
19404 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19405 (if (boundp 'narrow-map)
19406 (org-defkey narrow-map "e" 'org-narrow-to-element)
19407 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19408 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19409 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19410 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19411 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19412 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19413 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19414 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19415 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19416 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19417 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19418 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19419 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19420 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19421 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19422 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19423 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19424 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19425 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19426 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19427 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19428 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19429 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19430 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19431 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19432 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19433 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19434 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19435 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19436 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19437 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19438 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19439 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19440 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19441 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19442 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19443 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19444 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19445 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19446 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19447 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19448 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19449 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19450 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19451 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19452 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19453 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19454 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19455 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19456 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19457 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19458 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19459 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19460 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19461 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19462 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19463 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19464 (org-defkey org-mode-map "\C-c^" 'org-sort)
19465 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19466 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19467 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19468 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19469 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19470 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19471 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19472 (org-defkey org-mode-map "\C-m" 'org-return)
19473 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19474 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19475 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19476 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19477 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19478 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19479 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19480 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19481 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19482 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19483 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19484 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19485 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19486 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19487 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19488 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19489 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19490 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19491 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19492 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19493 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19494 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19495 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19496 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19497 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19499 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19500 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19501 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19503 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19504 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19505 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19506 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19507 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19508 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19509 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19510 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19511 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19512 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19513 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19514 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19515 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19516 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19517 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19518 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19519 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19520 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19521 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19522 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19523 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19524 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19525 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19527 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19528 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19529 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19530 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19531 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19533 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19535 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19537 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19538 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19540 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19543 (when (featurep 'xemacs)
19544 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19547 (defconst org-speed-commands-default
19549 ("Outline Navigation")
19550 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19551 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19552 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19553 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19554 ("F" . org-next-block)
19555 ("B" . org-previous-block)
19556 ("u" . (org-speed-move-safe 'outline-up-heading))
19557 ("j" . org-goto)
19558 ("g" . (org-refile t))
19559 ("Outline Visibility")
19560 ("c" . org-cycle)
19561 ("C" . org-shifttab)
19562 (" " . org-display-outline-path)
19563 ("s" . org-narrow-to-subtree)
19564 ("=" . org-columns)
19565 ("Outline Structure Editing")
19566 ("U" . org-metaup)
19567 ("D" . org-metadown)
19568 ("r" . org-metaright)
19569 ("l" . org-metaleft)
19570 ("R" . org-shiftmetaright)
19571 ("L" . org-shiftmetaleft)
19572 ("i" . (progn (forward-char 1) (call-interactively
19573 'org-insert-heading-respect-content)))
19574 ("^" . org-sort)
19575 ("w" . org-refile)
19576 ("a" . org-archive-subtree-default-with-confirmation)
19577 ("@" . org-mark-subtree)
19578 ("#" . org-toggle-comment)
19579 ("Clock Commands")
19580 ("I" . org-clock-in)
19581 ("O" . org-clock-out)
19582 ("Meta Data Editing")
19583 ("t" . org-todo)
19584 ("," . (org-priority))
19585 ("0" . (org-priority ?\ ))
19586 ("1" . (org-priority ?A))
19587 ("2" . (org-priority ?B))
19588 ("3" . (org-priority ?C))
19589 (":" . org-set-tags-command)
19590 ("e" . org-set-effort)
19591 ("E" . org-inc-effort)
19592 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19593 (org-entry-put (point) "APPT_WARNTIME" m)))
19594 ("Agenda Views etc")
19595 ("v" . org-agenda)
19596 ("/" . org-sparse-tree)
19597 ("Misc")
19598 ("o" . org-open-at-point)
19599 ("?" . org-speed-command-help)
19600 ("<" . (org-agenda-set-restriction-lock 'subtree))
19601 (">" . (org-agenda-remove-restriction-lock))
19603 "The default speed commands.")
19605 (defun org-print-speed-command (e)
19606 (if (> (length (car e)) 1)
19607 (progn
19608 (princ "\n")
19609 (princ (car e))
19610 (princ "\n")
19611 (princ (make-string (length (car e)) ?-))
19612 (princ "\n"))
19613 (princ (car e))
19614 (princ " ")
19615 (if (symbolp (cdr e))
19616 (princ (symbol-name (cdr e)))
19617 (prin1 (cdr e)))
19618 (princ "\n")))
19620 (defun org-speed-command-help ()
19621 "Show the available speed commands."
19622 (interactive)
19623 (if (not org-use-speed-commands)
19624 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19625 (with-output-to-temp-buffer "*Help*"
19626 (princ "User-defined Speed commands\n===========================\n")
19627 (mapc 'org-print-speed-command org-speed-commands-user)
19628 (princ "\n")
19629 (princ "Built-in Speed commands\n=======================\n")
19630 (mapc 'org-print-speed-command org-speed-commands-default))
19631 (with-current-buffer "*Help*"
19632 (setq truncate-lines t))))
19634 (defun org-speed-move-safe (cmd)
19635 "Execute CMD, but make sure that the cursor always ends up in a headline.
19636 If not, return to the original position and throw an error."
19637 (interactive)
19638 (let ((pos (point)))
19639 (call-interactively cmd)
19640 (unless (and (bolp) (org-at-heading-p))
19641 (goto-char pos)
19642 (error "Boundary reached while executing %s" cmd))))
19644 (defvar org-self-insert-command-undo-counter 0)
19646 (defvar org-table-auto-blank-field) ; defined in org-table.el
19647 (defvar org-speed-command nil)
19649 (define-obsolete-function-alias
19650 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19652 (defun org-speed-command-activate (keys)
19653 "Hook for activating single-letter speed commands.
19654 `org-speed-commands-default' specifies a minimal command set.
19655 Use `org-speed-commands-user' for further customization."
19656 (when (or (and (bolp) (looking-at org-outline-regexp))
19657 (and (functionp org-use-speed-commands)
19658 (funcall org-use-speed-commands)))
19659 (cdr (assoc keys (append org-speed-commands-user
19660 org-speed-commands-default)))))
19662 (define-obsolete-function-alias
19663 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19665 (defun org-babel-speed-command-activate (keys)
19666 "Hook for activating single-letter code block commands."
19667 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19668 (cdr (assoc keys org-babel-key-bindings))))
19670 (defcustom org-speed-command-hook
19671 '(org-speed-command-default-hook org-babel-speed-command-hook)
19672 "Hook for activating speed commands at strategic locations.
19673 Hook functions are called in sequence until a valid handler is
19674 found.
19676 Each hook takes a single argument, a user-pressed command key
19677 which is also a `self-insert-command' from the global map.
19679 Within the hook, examine the cursor position and the command key
19680 and return nil or a valid handler as appropriate. Handler could
19681 be one of an interactive command, a function, or a form.
19683 Set `org-use-speed-commands' to non-nil value to enable this
19684 hook. The default setting is `org-speed-command-activate'."
19685 :group 'org-structure
19686 :version "24.1"
19687 :type 'hook)
19689 (defun org-self-insert-command (N)
19690 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19691 If the cursor is in a table looking at whitespace, the whitespace is
19692 overwritten, and the table is not marked as requiring realignment."
19693 (interactive "p")
19694 (org-check-before-invisible-edit 'insert)
19695 (cond
19696 ((and org-use-speed-commands
19697 (let ((kv (this-command-keys-vector)))
19698 (setq org-speed-command
19699 (run-hook-with-args-until-success
19700 'org-speed-command-hook
19701 (make-string 1 (aref kv (1- (length kv))))))))
19702 (cond
19703 ((commandp org-speed-command)
19704 (setq this-command org-speed-command)
19705 (call-interactively org-speed-command))
19706 ((functionp org-speed-command)
19707 (funcall org-speed-command))
19708 ((and org-speed-command (listp org-speed-command))
19709 (eval org-speed-command))
19710 (t (let (org-use-speed-commands)
19711 (call-interactively 'org-self-insert-command)))))
19712 ((and
19713 (org-table-p)
19714 (progn
19715 ;; check if we blank the field, and if that triggers align
19716 (and (featurep 'org-table) org-table-auto-blank-field
19717 (member last-command
19718 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas-expand))
19719 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19720 ;; got extra space, this field does not determine column width
19721 (let (org-table-may-need-update) (org-table-blank-field))
19722 ;; no extra space, this field may determine column width
19723 (org-table-blank-field)))
19725 (eq N 1)
19726 (looking-at "[^|\n]* |"))
19727 (let (org-table-may-need-update)
19728 (goto-char (1- (match-end 0)))
19729 (backward-delete-char 1)
19730 (goto-char (match-beginning 0))
19731 (self-insert-command N)))
19733 (setq org-table-may-need-update t)
19734 (self-insert-command N)
19735 (org-fix-tags-on-the-fly)
19736 (if org-self-insert-cluster-for-undo
19737 (if (not (eq last-command 'org-self-insert-command))
19738 (setq org-self-insert-command-undo-counter 1)
19739 (if (>= org-self-insert-command-undo-counter 20)
19740 (setq org-self-insert-command-undo-counter 1)
19741 (and (> org-self-insert-command-undo-counter 0)
19742 buffer-undo-list (listp buffer-undo-list)
19743 (not (cadr buffer-undo-list)) ; remove nil entry
19744 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19745 (setq org-self-insert-command-undo-counter
19746 (1+ org-self-insert-command-undo-counter))))))))
19748 (defun org-check-before-invisible-edit (kind)
19749 "Check is editing if kind KIND would be dangerous with invisible text around.
19750 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19751 ;; First, try to get out of here as quickly as possible, to reduce overhead
19752 (if (and org-catch-invisible-edits
19753 (or (not (boundp 'visible-mode)) (not visible-mode))
19754 (or (get-char-property (point) 'invisible)
19755 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19756 ;; OK, we need to take a closer look
19757 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19758 (invisible-before-point (if (bobp) nil (get-char-property
19759 (1- (point)) 'invisible)))
19760 (border-and-ok-direction
19762 ;; Check if we are acting predictably before invisible text
19763 (and invisible-at-point (not invisible-before-point)
19764 (memq kind '(insert delete-backward)))
19765 ;; Check if we are acting predictably after invisible text
19766 ;; This works not well, and I have turned it off. It seems
19767 ;; better to always show and stop after invisible text.
19768 ;; (and (not invisible-at-point) invisible-before-point
19769 ;; (memq kind '(insert delete)))
19771 (when (or (memq invisible-at-point '(outline org-hide-block t))
19772 (memq invisible-before-point '(outline org-hide-block t)))
19773 (if (eq org-catch-invisible-edits 'error)
19774 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19775 (if (and org-custom-properties-overlays
19776 (y-or-n-p "Display invisible properties in this buffer? "))
19777 (org-toggle-custom-properties-visibility)
19778 ;; Make the area visible
19779 (save-excursion
19780 (if invisible-before-point
19781 (goto-char (previous-single-char-property-change
19782 (point) 'invisible)))
19783 (show-subtree))
19784 (cond
19785 ((eq org-catch-invisible-edits 'show)
19786 ;; That's it, we do the edit after showing
19787 (message
19788 "Unfolding invisible region around point before editing")
19789 (sit-for 1))
19790 ((and (eq org-catch-invisible-edits 'smart)
19791 border-and-ok-direction)
19792 (message "Unfolding invisible region around point before editing"))
19794 ;; Don't do the edit, make the user repeat it in full visibility
19795 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19797 (defun org-fix-tags-on-the-fly ()
19798 (when (and (equal (char-after (point-at-bol)) ?*)
19799 (org-at-heading-p))
19800 (org-align-tags-here org-tags-column)))
19802 (defun org-delete-backward-char (N)
19803 "Like `delete-backward-char', insert whitespace at field end in tables.
19804 When deleting backwards, in tables this function will insert whitespace in
19805 front of the next \"|\" separator, to keep the table aligned. The table will
19806 still be marked for re-alignment if the field did fill the entire column,
19807 because, in this case the deletion might narrow the column."
19808 (interactive "p")
19809 (save-match-data
19810 (org-check-before-invisible-edit 'delete-backward)
19811 (if (and (org-table-p)
19812 (eq N 1)
19813 (string-match "|" (buffer-substring (point-at-bol) (point)))
19814 (looking-at ".*?|"))
19815 (let ((pos (point))
19816 (noalign (looking-at "[^|\n\r]* |"))
19817 (c org-table-may-need-update))
19818 (backward-delete-char N)
19819 (if (not overwrite-mode)
19820 (progn
19821 (skip-chars-forward "^|")
19822 (insert " ")
19823 (goto-char (1- pos))))
19824 ;; noalign: if there were two spaces at the end, this field
19825 ;; does not determine the width of the column.
19826 (if noalign (setq org-table-may-need-update c)))
19827 (backward-delete-char N)
19828 (org-fix-tags-on-the-fly))))
19830 (defun org-delete-char (N)
19831 "Like `delete-char', but insert whitespace at field end in tables.
19832 When deleting characters, in tables this function will insert whitespace in
19833 front of the next \"|\" separator, to keep the table aligned. The table will
19834 still be marked for re-alignment if the field did fill the entire column,
19835 because, in this case the deletion might narrow the column."
19836 (interactive "p")
19837 (save-match-data
19838 (org-check-before-invisible-edit 'delete)
19839 (if (and (org-table-p)
19840 (not (bolp))
19841 (not (= (char-after) ?|))
19842 (eq N 1))
19843 (if (looking-at ".*?|")
19844 (let ((pos (point))
19845 (noalign (looking-at "[^|\n\r]* |"))
19846 (c org-table-may-need-update))
19847 (replace-match
19848 (concat (substring (match-string 0) 1 -1) " |") nil t)
19849 (goto-char pos)
19850 ;; noalign: if there were two spaces at the end, this field
19851 ;; does not determine the width of the column.
19852 (if noalign (setq org-table-may-need-update c)))
19853 (delete-char N))
19854 (delete-char N)
19855 (org-fix-tags-on-the-fly))))
19857 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19858 (put 'org-self-insert-command 'delete-selection
19859 (lambda ()
19860 (not (run-hook-with-args-until-success
19861 'self-insert-uses-region-functions))))
19862 (put 'orgtbl-self-insert-command 'delete-selection
19863 (lambda ()
19864 (not (run-hook-with-args-until-success
19865 'self-insert-uses-region-functions))))
19866 (put 'org-delete-char 'delete-selection 'supersede)
19867 (put 'org-delete-backward-char 'delete-selection 'supersede)
19868 (put 'org-yank 'delete-selection 'yank)
19870 ;; Make `flyspell-mode' delay after some commands
19871 (put 'org-self-insert-command 'flyspell-delayed t)
19872 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19873 (put 'org-delete-char 'flyspell-delayed t)
19874 (put 'org-delete-backward-char 'flyspell-delayed t)
19876 ;; Make pabbrev-mode expand after org-mode commands
19877 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19878 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19880 (defun org-remap (map &rest commands)
19881 "In MAP, remap the functions given in COMMANDS.
19882 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19883 (let (new old)
19884 (while commands
19885 (setq old (pop commands) new (pop commands))
19886 (if (fboundp 'command-remapping)
19887 (org-defkey map (vector 'remap old) new)
19888 (substitute-key-definition old new map global-map)))))
19890 (defun org-transpose-words ()
19891 "Transpose words for Org.
19892 This uses the `org-mode-transpose-word-syntax-table' syntax
19893 table, which interprets characters in `org-emphasis-alist' as
19894 word constituents."
19895 (interactive)
19896 (with-syntax-table org-mode-transpose-word-syntax-table
19897 (call-interactively 'transpose-words)))
19898 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19900 (when (eq org-enable-table-editor 'optimized)
19901 ;; If the user wants maximum table support, we need to hijack
19902 ;; some standard editing functions
19903 (org-remap org-mode-map
19904 'self-insert-command 'org-self-insert-command
19905 'delete-char 'org-delete-char
19906 'delete-backward-char 'org-delete-backward-char)
19907 (org-defkey org-mode-map "|" 'org-force-self-insert))
19909 (defvar org-ctrl-c-ctrl-c-hook nil
19910 "Hook for functions attaching themselves to `C-c C-c'.
19912 This can be used to add additional functionality to the C-c C-c
19913 key which executes context-dependent commands. This hook is run
19914 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19915 run after the last test.
19917 Each function will be called with no arguments. The function
19918 must check if the context is appropriate for it to act. If yes,
19919 it should do its thing and then return a non-nil value. If the
19920 context is wrong, just do nothing and return nil.")
19922 (defvar org-ctrl-c-ctrl-c-final-hook nil
19923 "Hook for functions attaching themselves to `C-c C-c'.
19925 This can be used to add additional functionality to the C-c C-c
19926 key which executes context-dependent commands. This hook is run
19927 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19928 before the first test.
19930 Each function will be called with no arguments. The function
19931 must check if the context is appropriate for it to act. If yes,
19932 it should do its thing and then return a non-nil value. If the
19933 context is wrong, just do nothing and return nil.")
19935 (defvar org-tab-first-hook nil
19936 "Hook for functions to attach themselves to TAB.
19937 See `org-ctrl-c-ctrl-c-hook' for more information.
19938 This hook runs as the first action when TAB is pressed, even before
19939 `org-cycle' messes around with the `outline-regexp' to cater for
19940 inline tasks and plain list item folding.
19941 If any function in this hook returns t, any other actions that
19942 would have been caused by TAB (such as table field motion or visibility
19943 cycling) will not occur.")
19945 (defvar org-tab-after-check-for-table-hook nil
19946 "Hook for functions to attach themselves to TAB.
19947 See `org-ctrl-c-ctrl-c-hook' for more information.
19948 This hook runs after it has been established that the cursor is not in a
19949 table, but before checking if the cursor is in a headline or if global cycling
19950 should be done.
19951 If any function in this hook returns t, not other actions like visibility
19952 cycling will be done.")
19954 (defvar org-tab-after-check-for-cycling-hook nil
19955 "Hook for functions to attach themselves to TAB.
19956 See `org-ctrl-c-ctrl-c-hook' for more information.
19957 This hook runs after it has been established that not table field motion and
19958 not visibility should be done because of current context. This is probably
19959 the place where a package like yasnippets can hook in.")
19961 (defvar org-tab-before-tab-emulation-hook nil
19962 "Hook for functions to attach themselves to TAB.
19963 See `org-ctrl-c-ctrl-c-hook' for more information.
19964 This hook runs after every other options for TAB have been exhausted, but
19965 before indentation and \t insertion takes place.")
19967 (defvar org-metaleft-hook nil
19968 "Hook for functions attaching themselves to `M-left'.
19969 See `org-ctrl-c-ctrl-c-hook' for more information.")
19970 (defvar org-metaright-hook nil
19971 "Hook for functions attaching themselves to `M-right'.
19972 See `org-ctrl-c-ctrl-c-hook' for more information.")
19973 (defvar org-metaup-hook nil
19974 "Hook for functions attaching themselves to `M-up'.
19975 See `org-ctrl-c-ctrl-c-hook' for more information.")
19976 (defvar org-metadown-hook nil
19977 "Hook for functions attaching themselves to `M-down'.
19978 See `org-ctrl-c-ctrl-c-hook' for more information.")
19979 (defvar org-shiftmetaleft-hook nil
19980 "Hook for functions attaching themselves to `M-S-left'.
19981 See `org-ctrl-c-ctrl-c-hook' for more information.")
19982 (defvar org-shiftmetaright-hook nil
19983 "Hook for functions attaching themselves to `M-S-right'.
19984 See `org-ctrl-c-ctrl-c-hook' for more information.")
19985 (defvar org-shiftmetaup-hook nil
19986 "Hook for functions attaching themselves to `M-S-up'.
19987 See `org-ctrl-c-ctrl-c-hook' for more information.")
19988 (defvar org-shiftmetadown-hook nil
19989 "Hook for functions attaching themselves to `M-S-down'.
19990 See `org-ctrl-c-ctrl-c-hook' for more information.")
19991 (defvar org-metareturn-hook nil
19992 "Hook for functions attaching themselves to `M-RET'.
19993 See `org-ctrl-c-ctrl-c-hook' for more information.")
19994 (defvar org-shiftup-hook nil
19995 "Hook for functions attaching themselves to `S-up'.
19996 See `org-ctrl-c-ctrl-c-hook' for more information.")
19997 (defvar org-shiftup-final-hook nil
19998 "Hook for functions attaching themselves to `S-up'.
19999 This one runs after all other options except shift-select have been excluded.
20000 See `org-ctrl-c-ctrl-c-hook' for more information.")
20001 (defvar org-shiftdown-hook nil
20002 "Hook for functions attaching themselves to `S-down'.
20003 See `org-ctrl-c-ctrl-c-hook' for more information.")
20004 (defvar org-shiftdown-final-hook nil
20005 "Hook for functions attaching themselves to `S-down'.
20006 This one runs after all other options except shift-select have been excluded.
20007 See `org-ctrl-c-ctrl-c-hook' for more information.")
20008 (defvar org-shiftleft-hook nil
20009 "Hook for functions attaching themselves to `S-left'.
20010 See `org-ctrl-c-ctrl-c-hook' for more information.")
20011 (defvar org-shiftleft-final-hook nil
20012 "Hook for functions attaching themselves to `S-left'.
20013 This one runs after all other options except shift-select have been excluded.
20014 See `org-ctrl-c-ctrl-c-hook' for more information.")
20015 (defvar org-shiftright-hook nil
20016 "Hook for functions attaching themselves to `S-right'.
20017 See `org-ctrl-c-ctrl-c-hook' for more information.")
20018 (defvar org-shiftright-final-hook nil
20019 "Hook for functions attaching themselves to `S-right'.
20020 This one runs after all other options except shift-select have been excluded.
20021 See `org-ctrl-c-ctrl-c-hook' for more information.")
20023 (defun org-modifier-cursor-error ()
20024 "Throw an error, a modified cursor command was applied in wrong context."
20025 (user-error "This command is active in special context like tables, headlines or items"))
20027 (defun org-shiftselect-error ()
20028 "Throw an error because Shift-Cursor command was applied in wrong context."
20029 (if (and (boundp 'shift-select-mode) shift-select-mode)
20030 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20031 (user-error "This command works only in special context like headlines or timestamps")))
20033 (defun org-call-for-shift-select (cmd)
20034 (let ((this-command-keys-shift-translated t))
20035 (call-interactively cmd)))
20037 (defun org-shifttab (&optional arg)
20038 "Global visibility cycling or move to previous table field.
20039 Call `org-table-previous-field' within a table.
20040 When ARG is nil, cycle globally through visibility states.
20041 When ARG is a numeric prefix, show contents of this level."
20042 (interactive "P")
20043 (cond
20044 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20045 ((integerp arg)
20046 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20047 (message "Content view to level: %d" arg)
20048 (org-content (prefix-numeric-value arg2))
20049 (org-cycle-show-empty-lines t)
20050 (setq org-cycle-global-status 'overview)))
20051 (t (call-interactively 'org-global-cycle))))
20053 (defun org-shiftmetaleft ()
20054 "Promote subtree or delete table column.
20055 Calls `org-promote-subtree', `org-outdent-item-tree', or
20056 `org-table-delete-column', depending on context. See the
20057 individual commands for more information."
20058 (interactive)
20059 (cond
20060 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20061 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20062 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20063 ((if (not (org-region-active-p)) (org-at-item-p)
20064 (save-excursion (goto-char (region-beginning))
20065 (org-at-item-p)))
20066 (call-interactively 'org-outdent-item-tree))
20067 (t (org-modifier-cursor-error))))
20069 (defun org-shiftmetaright ()
20070 "Demote subtree or insert table column.
20071 Calls `org-demote-subtree', `org-indent-item-tree', or
20072 `org-table-insert-column', depending on context. See the
20073 individual commands for more information."
20074 (interactive)
20075 (cond
20076 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20077 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20078 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20079 ((if (not (org-region-active-p)) (org-at-item-p)
20080 (save-excursion (goto-char (region-beginning))
20081 (org-at-item-p)))
20082 (call-interactively 'org-indent-item-tree))
20083 (t (org-modifier-cursor-error))))
20085 (defun org-shiftmetaup (&optional arg)
20086 "Drag the line at point up.
20087 In a table, kill the current row.
20088 On a clock timestamp, update the value of the timestamp like `S-<up>'
20089 but also adjust the previous clocked item in the clock history.
20090 Everywhere else, drag the line at point up."
20091 (interactive "P")
20092 (cond
20093 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20094 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20095 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20096 (call-interactively 'org-timestamp-up)))
20097 (t (call-interactively 'org-drag-line-backward))))
20099 (defun org-shiftmetadown (&optional arg)
20100 "Drag the line at point down.
20101 In a table, insert an empty row at the current line.
20102 On a clock timestamp, update the value of the timestamp like `S-<down>'
20103 but also adjust the previous clocked item in the clock history.
20104 Everywhere else, drag the line at point down."
20105 (interactive "P")
20106 (cond
20107 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20108 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20109 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20110 (call-interactively 'org-timestamp-down)))
20111 (t (call-interactively 'org-drag-line-forward))))
20113 (defsubst org-hidden-tree-error ()
20114 (user-error
20115 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20117 (defun org-metaleft (&optional arg)
20118 "Promote heading or move table column to left.
20119 Calls `org-do-promote' or `org-table-move-column', depending on context.
20120 With no specific context, calls the Emacs default `backward-word'.
20121 See the individual commands for more information."
20122 (interactive "P")
20123 (cond
20124 ((run-hook-with-args-until-success 'org-metaleft-hook))
20125 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20126 ((org-with-limited-levels
20127 (or (org-at-heading-p)
20128 (and (org-region-active-p)
20129 (save-excursion
20130 (goto-char (region-beginning))
20131 (org-at-heading-p)))))
20132 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20133 (call-interactively 'org-do-promote))
20134 ;; At an inline task.
20135 ((org-at-heading-p)
20136 (call-interactively 'org-inlinetask-promote))
20137 ((or (org-at-item-p)
20138 (and (org-region-active-p)
20139 (save-excursion
20140 (goto-char (region-beginning))
20141 (org-at-item-p))))
20142 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20143 (call-interactively 'org-outdent-item))
20144 (t (call-interactively 'backward-word))))
20146 (defun org-metaright (&optional arg)
20147 "Demote a subtree, a list item or move table column to right.
20148 In front of a drawer or a block keyword, indent it correctly.
20149 With no specific context, calls the Emacs default `forward-word'.
20150 See the individual commands for more information."
20151 (interactive "P")
20152 (cond
20153 ((run-hook-with-args-until-success 'org-metaright-hook))
20154 ((org-at-table-p) (call-interactively 'org-table-move-column))
20155 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20156 ((org-at-block-p) (call-interactively 'org-indent-block))
20157 ((org-with-limited-levels
20158 (or (org-at-heading-p)
20159 (and (org-region-active-p)
20160 (save-excursion
20161 (goto-char (region-beginning))
20162 (org-at-heading-p)))))
20163 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20164 (call-interactively 'org-do-demote))
20165 ;; At an inline task.
20166 ((org-at-heading-p)
20167 (call-interactively 'org-inlinetask-demote))
20168 ((or (org-at-item-p)
20169 (and (org-region-active-p)
20170 (save-excursion
20171 (goto-char (region-beginning))
20172 (org-at-item-p))))
20173 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20174 (call-interactively 'org-indent-item))
20175 (t (call-interactively 'forward-word))))
20177 (defun org-check-for-hidden (what)
20178 "Check if there are hidden headlines/items in the current visual line.
20179 WHAT can be either `headlines' or `items'. If the current line is
20180 an outline or item heading and it has a folded subtree below it,
20181 this function returns t, nil otherwise."
20182 (let ((re (cond
20183 ((eq what 'headlines) org-outline-regexp-bol)
20184 ((eq what 'items) (org-item-beginning-re))
20185 (t (error "This should not happen"))))
20186 beg end)
20187 (save-excursion
20188 (catch 'exit
20189 (unless (org-region-active-p)
20190 (setq beg (point-at-bol))
20191 (beginning-of-line 2)
20192 (while (and (not (eobp)) ;; this is like `next-line'
20193 (get-char-property (1- (point)) 'invisible))
20194 (beginning-of-line 2))
20195 (setq end (point))
20196 (goto-char beg)
20197 (goto-char (point-at-eol))
20198 (setq end (max end (point)))
20199 (while (re-search-forward re end t)
20200 (if (get-char-property (match-beginning 0) 'invisible)
20201 (throw 'exit t))))
20202 nil))))
20204 (defun org-metaup (&optional arg)
20205 "Move subtree up or move table row up.
20206 Calls `org-move-subtree-up' or `org-table-move-row' or
20207 `org-move-item-up', depending on context. See the individual commands
20208 for more information."
20209 (interactive "P")
20210 (cond
20211 ((run-hook-with-args-until-success 'org-metaup-hook))
20212 ((org-region-active-p)
20213 (let* ((a (min (region-beginning) (region-end)))
20214 (b (1- (max (region-beginning) (region-end))))
20215 (c (save-excursion (goto-char a)
20216 (move-beginning-of-line 0)))
20217 (d (save-excursion (goto-char a)
20218 (move-end-of-line 0) (point))))
20219 (transpose-regions a b c d)
20220 (goto-char c)))
20221 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20222 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20223 ((org-at-item-p) (call-interactively 'org-move-item-up))
20224 (t (org-drag-element-backward))))
20226 (defun org-metadown (&optional arg)
20227 "Move subtree down or move table row down.
20228 Calls `org-move-subtree-down' or `org-table-move-row' or
20229 `org-move-item-down', depending on context. See the individual
20230 commands for more information."
20231 (interactive "P")
20232 (cond
20233 ((run-hook-with-args-until-success 'org-metadown-hook))
20234 ((org-region-active-p)
20235 (let* ((a (min (region-beginning) (region-end)))
20236 (b (max (region-beginning) (region-end)))
20237 (c (save-excursion (goto-char b)
20238 (move-beginning-of-line 1)))
20239 (d (save-excursion (goto-char b)
20240 (move-end-of-line 1) (1+ (point)))))
20241 (transpose-regions a b c d)
20242 (goto-char d)))
20243 ((org-at-table-p) (call-interactively 'org-table-move-row))
20244 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20245 ((org-at-item-p) (call-interactively 'org-move-item-down))
20246 (t (org-drag-element-forward))))
20248 (defun org-shiftup (&optional arg)
20249 "Increase item in timestamp or increase priority of current headline.
20250 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20251 depending on context. See the individual commands for more information."
20252 (interactive "P")
20253 (cond
20254 ((run-hook-with-args-until-success 'org-shiftup-hook))
20255 ((and org-support-shift-select (org-region-active-p))
20256 (org-call-for-shift-select 'previous-line))
20257 ((org-at-timestamp-p t)
20258 (call-interactively (if org-edit-timestamp-down-means-later
20259 'org-timestamp-down 'org-timestamp-up)))
20260 ((and (not (eq org-support-shift-select 'always))
20261 org-enable-priority-commands
20262 (org-at-heading-p))
20263 (call-interactively 'org-priority-up))
20264 ((and (not org-support-shift-select) (org-at-item-p))
20265 (call-interactively 'org-previous-item))
20266 ((org-clocktable-try-shift 'up arg))
20267 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20268 (org-support-shift-select
20269 (org-call-for-shift-select 'previous-line))
20270 (t (org-shiftselect-error))))
20272 (defun org-shiftdown (&optional arg)
20273 "Decrease item in timestamp or decrease priority of current headline.
20274 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20275 depending on context. See the individual commands for more information."
20276 (interactive "P")
20277 (cond
20278 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20279 ((and org-support-shift-select (org-region-active-p))
20280 (org-call-for-shift-select 'next-line))
20281 ((org-at-timestamp-p t)
20282 (call-interactively (if org-edit-timestamp-down-means-later
20283 'org-timestamp-up 'org-timestamp-down)))
20284 ((and (not (eq org-support-shift-select 'always))
20285 org-enable-priority-commands
20286 (org-at-heading-p))
20287 (call-interactively 'org-priority-down))
20288 ((and (not org-support-shift-select) (org-at-item-p))
20289 (call-interactively 'org-next-item))
20290 ((org-clocktable-try-shift 'down arg))
20291 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20292 (org-support-shift-select
20293 (org-call-for-shift-select 'next-line))
20294 (t (org-shiftselect-error))))
20296 (defun org-shiftright (&optional arg)
20297 "Cycle the thing at point or in the current line, depending on context.
20298 Depending on context, this does one of the following:
20300 - switch a timestamp at point one day into the future
20301 - on a headline, switch to the next TODO keyword.
20302 - on an item, switch entire list to the next bullet type
20303 - on a property line, switch to the next allowed value
20304 - on a clocktable definition line, move time block into the future"
20305 (interactive "P")
20306 (cond
20307 ((run-hook-with-args-until-success 'org-shiftright-hook))
20308 ((and org-support-shift-select (org-region-active-p))
20309 (org-call-for-shift-select 'forward-char))
20310 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20311 ((and (not (eq org-support-shift-select 'always))
20312 (org-at-heading-p))
20313 (let ((org-inhibit-logging
20314 (not org-treat-S-cursor-todo-selection-as-state-change))
20315 (org-inhibit-blocking
20316 (not org-treat-S-cursor-todo-selection-as-state-change)))
20317 (org-call-with-arg 'org-todo 'right)))
20318 ((or (and org-support-shift-select
20319 (not (eq org-support-shift-select 'always))
20320 (org-at-item-bullet-p))
20321 (and (not org-support-shift-select) (org-at-item-p)))
20322 (org-call-with-arg 'org-cycle-list-bullet nil))
20323 ((and (not (eq org-support-shift-select 'always))
20324 (org-at-property-p))
20325 (call-interactively 'org-property-next-allowed-value))
20326 ((org-clocktable-try-shift 'right arg))
20327 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20328 (org-support-shift-select
20329 (org-call-for-shift-select 'forward-char))
20330 (t (org-shiftselect-error))))
20332 (defun org-shiftleft (&optional arg)
20333 "Cycle the thing at point or in the current line, depending on context.
20334 Depending on context, this does one of the following:
20336 - switch a timestamp at point one day into the past
20337 - on a headline, switch to the previous TODO keyword.
20338 - on an item, switch entire list to the previous bullet type
20339 - on a property line, switch to the previous allowed value
20340 - on a clocktable definition line, move time block into the past"
20341 (interactive "P")
20342 (cond
20343 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20344 ((and org-support-shift-select (org-region-active-p))
20345 (org-call-for-shift-select 'backward-char))
20346 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20347 ((and (not (eq org-support-shift-select 'always))
20348 (org-at-heading-p))
20349 (let ((org-inhibit-logging
20350 (not org-treat-S-cursor-todo-selection-as-state-change))
20351 (org-inhibit-blocking
20352 (not org-treat-S-cursor-todo-selection-as-state-change)))
20353 (org-call-with-arg 'org-todo 'left)))
20354 ((or (and org-support-shift-select
20355 (not (eq org-support-shift-select 'always))
20356 (org-at-item-bullet-p))
20357 (and (not org-support-shift-select) (org-at-item-p)))
20358 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20359 ((and (not (eq org-support-shift-select 'always))
20360 (org-at-property-p))
20361 (call-interactively 'org-property-previous-allowed-value))
20362 ((org-clocktable-try-shift 'left arg))
20363 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20364 (org-support-shift-select
20365 (org-call-for-shift-select 'backward-char))
20366 (t (org-shiftselect-error))))
20368 (defun org-shiftcontrolright ()
20369 "Switch to next TODO set."
20370 (interactive)
20371 (cond
20372 ((and org-support-shift-select (org-region-active-p))
20373 (org-call-for-shift-select 'forward-word))
20374 ((and (not (eq org-support-shift-select 'always))
20375 (org-at-heading-p))
20376 (org-call-with-arg 'org-todo 'nextset))
20377 (org-support-shift-select
20378 (org-call-for-shift-select 'forward-word))
20379 (t (org-shiftselect-error))))
20381 (defun org-shiftcontrolleft ()
20382 "Switch to previous TODO set."
20383 (interactive)
20384 (cond
20385 ((and org-support-shift-select (org-region-active-p))
20386 (org-call-for-shift-select 'backward-word))
20387 ((and (not (eq org-support-shift-select 'always))
20388 (org-at-heading-p))
20389 (org-call-with-arg 'org-todo 'previousset))
20390 (org-support-shift-select
20391 (org-call-for-shift-select 'backward-word))
20392 (t (org-shiftselect-error))))
20394 (defun org-shiftcontrolup (&optional n)
20395 "Change timestamps synchronously up in CLOCK log lines.
20396 Optional argument N tells to change by that many units."
20397 (interactive "P")
20398 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20399 (let (org-support-shift-select)
20400 (org-clock-timestamps-up n))
20401 (user-error "Not at a clock log")))
20403 (defun org-shiftcontroldown (&optional n)
20404 "Change timestamps synchronously down in CLOCK log lines.
20405 Optional argument N tells to change by that many units."
20406 (interactive "P")
20407 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20408 (let (org-support-shift-select)
20409 (org-clock-timestamps-down n))
20410 (user-error "Not at a clock log")))
20412 (defun org-increase-number-at-point (&optional inc)
20413 "Increment the number at point.
20414 With an optional prefix numeric argument INC, increment using
20415 this numeric value."
20416 (interactive "p")
20417 (if (not (number-at-point))
20418 (user-error "Not on a number")
20419 (unless inc (setq inc 1))
20420 (let ((pos (point))
20421 (beg (skip-chars-backward "-+^/*0-9eE."))
20422 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20423 (setq nap (buffer-substring-no-properties
20424 (+ pos beg) (+ pos beg end)))
20425 (delete-region (+ pos beg) (+ pos beg end))
20426 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20427 (when (org-at-table-p)
20428 (org-table-align)
20429 (org-table-end-of-field 1))))
20431 (defun org-decrease-number-at-point (&optional inc)
20432 "Decrement the number at point.
20433 With an optional prefix numeric argument INC, decrement using
20434 this numeric value."
20435 (interactive "p")
20436 (org-increase-number-at-point (- inc)))
20438 (defun org-ctrl-c-ret ()
20439 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20440 (interactive)
20441 (cond
20442 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20443 (t (call-interactively 'org-insert-heading))))
20445 (defun org-find-visible ()
20446 (let ((s (point)))
20447 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20448 (get-char-property s 'invisible)))
20450 (defun org-find-invisible ()
20451 (let ((s (point)))
20452 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20453 (not (get-char-property s 'invisible))))
20456 (defun org-copy-visible (beg end)
20457 "Copy the visible parts of the region."
20458 (interactive "r")
20459 (let (snippets s)
20460 (save-excursion
20461 (save-restriction
20462 (narrow-to-region beg end)
20463 (setq s (goto-char (point-min)))
20464 (while (not (= (point) (point-max)))
20465 (goto-char (org-find-invisible))
20466 (push (buffer-substring s (point)) snippets)
20467 (setq s (goto-char (org-find-visible))))))
20468 (kill-new (apply 'concat (nreverse snippets)))))
20470 (defun org-copy-special ()
20471 "Copy region in table or copy current subtree.
20472 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20473 See the individual commands for more information."
20474 (interactive)
20475 (call-interactively
20476 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20478 (defun org-cut-special ()
20479 "Cut region in table or cut current subtree.
20480 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20481 See the individual commands for more information."
20482 (interactive)
20483 (call-interactively
20484 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20486 (defun org-paste-special (arg)
20487 "Paste rectangular region into table, or past subtree relative to level.
20488 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20489 See the individual commands for more information."
20490 (interactive "P")
20491 (if (org-at-table-p)
20492 (org-table-paste-rectangle)
20493 (org-paste-subtree arg)))
20495 (defsubst org-in-fixed-width-region-p ()
20496 "Is point in a fixed-width region?"
20497 (save-match-data
20498 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20500 (defun org-edit-special (&optional arg)
20501 "Call a special editor for the element at point.
20502 When at a table, call the formula editor with `org-table-edit-formulas'.
20503 When in a source code block, call `org-edit-src-code'.
20504 When in a fixed-width region, call `org-edit-fixed-width-region'.
20505 When at an #+INCLUDE keyword, visit the included file.
20506 On a link, call `ffap' to visit the link at point.
20507 Otherwise, return a user error."
20508 (interactive "P")
20509 (let ((element (org-element-at-point)))
20510 (assert (not buffer-read-only) nil
20511 "Buffer is read-only: %s" (buffer-name))
20512 (case (org-element-type element)
20513 (src-block
20514 (if (not arg) (org-edit-src-code)
20515 (let* ((info (org-babel-get-src-block-info))
20516 (lang (nth 0 info))
20517 (params (nth 2 info))
20518 (session (cdr (assq :session params))))
20519 (if (not session) (org-edit-src-code)
20520 ;; At a src-block with a session and function called with
20521 ;; an ARG: switch to the buffer related to the inferior
20522 ;; process.
20523 (switch-to-buffer
20524 (funcall (intern (concat "org-babel-prep-session:" lang))
20525 session params))))))
20526 (keyword
20527 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20528 (org-open-link-from-string
20529 (format "[[%s]]"
20530 (expand-file-name
20531 (let ((value (org-element-property :value element)))
20532 (cond ((not (org-string-nw-p value))
20533 (user-error "No file to edit"))
20534 ((string-match "\\`\"\\(.*?\\)\"" value)
20535 (match-string 1 value))
20536 ((string-match "\\`[^ \t\"]\\S-*" value)
20537 (match-string 0 value))
20538 (t (user-error "No valid file specified")))))))
20539 (user-error "No special environment to edit here")))
20540 (table
20541 (if (eq (org-element-property :type element) 'table.el)
20542 (org-edit-src-code)
20543 (call-interactively 'org-table-edit-formulas)))
20544 ;; Only Org tables contain `table-row' type elements.
20545 (table-row (call-interactively 'org-table-edit-formulas))
20546 ((example-block export-block) (org-edit-src-code))
20547 (fixed-width (org-edit-fixed-width-region))
20548 (otherwise
20549 ;; No notable element at point. Though, we may be at a link,
20550 ;; which is an object. Thus, scan deeper.
20551 (if (eq (org-element-type (org-element-context element)) 'link)
20552 (call-interactively 'ffap)
20553 (user-error "No special environment to edit here"))))))
20555 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20556 (defun org-ctrl-c-ctrl-c (&optional arg)
20557 "Set tags in headline, or update according to changed information at point.
20559 This command does many different things, depending on context:
20561 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20562 this is what we do.
20564 - If the cursor is on a statistics cookie, update it.
20566 - If the cursor is in a headline, prompt for tags and insert them
20567 into the current line, aligned to `org-tags-column'. When called
20568 with prefix arg, realign all tags in the current buffer.
20570 - If the cursor is in one of the special #+KEYWORD lines, this
20571 triggers scanning the buffer for these lines and updating the
20572 information.
20574 - If the cursor is inside a table, realign the table. This command
20575 works even if the automatic table editor has been turned off.
20577 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20578 the entire table.
20580 - If the cursor is at a footnote reference or definition, jump to
20581 the corresponding definition or references, respectively.
20583 - If the cursor is a the beginning of a dynamic block, update it.
20585 - If the current buffer is a capture buffer, close note and file it.
20587 - If the cursor is on a <<<target>>>, update radio targets and
20588 corresponding links in this buffer.
20590 - If the cursor is on a numbered item in a plain list, renumber the
20591 ordered list.
20593 - If the cursor is on a checkbox, toggle it.
20595 - If the cursor is on a code block, evaluate it. The variable
20596 `org-confirm-babel-evaluate' can be used to control prompting
20597 before code block evaluation, by default every code block
20598 evaluation requires confirmation. Code block evaluation can be
20599 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20600 (interactive "P")
20601 (cond
20602 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20603 org-occur-highlights)
20604 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20605 (org-remove-occur-highlights)
20606 (message "Temporary highlights/overlays removed from current buffer"))
20607 ((and (local-variable-p 'org-finish-function (current-buffer))
20608 (fboundp org-finish-function))
20609 (funcall org-finish-function))
20610 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20612 (let* ((context (org-element-context)) (type (org-element-type context)))
20613 ;; Test if point is within a blank line.
20614 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20615 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20616 (user-error "C-c C-c can do nothing useful at this location"))
20617 (case type
20618 ;; When at a link, act according to the parent instead.
20619 (link (setq context (org-element-property :parent context))
20620 (setq type (org-element-type context)))
20621 ;; Unsupported object types: refer to the first supported
20622 ;; element or object containing it.
20623 ((bold code entity export-snippet inline-babel-call inline-src-block
20624 italic latex-fragment line-break macro strike-through subscript
20625 superscript underline verbatim)
20626 (while (and (setq context (org-element-property :parent context))
20627 (not (memq (setq type (org-element-type context))
20628 '(radio-target paragraph verse-block
20629 table-cell)))))))
20630 ;; For convenience: at the first line of a paragraph on the
20631 ;; same line as an item, apply function on that item instead.
20632 (when (eq type 'paragraph)
20633 (let ((parent (org-element-property :parent context)))
20634 (when (and (eq (org-element-type parent) 'item)
20635 (= (point-at-bol) (org-element-property :begin parent)))
20636 (setq context parent type 'item))))
20637 ;; Act according to type of element or object at point.
20638 (case type
20639 (clock (org-clock-update-time-maybe))
20640 (dynamic-block
20641 (save-excursion
20642 (goto-char (org-element-property :post-affiliated context))
20643 (org-update-dblock)))
20644 (footnote-definition
20645 (goto-char (org-element-property :post-affiliated context))
20646 (call-interactively 'org-footnote-action))
20647 (footnote-reference (call-interactively 'org-footnote-action))
20648 ((headline inlinetask)
20649 (save-excursion (goto-char (org-element-property :begin context))
20650 (call-interactively 'org-set-tags)))
20651 (item
20652 ;; At an item: a double C-u set checkbox to "[-]"
20653 ;; unconditionally, whereas a single one will toggle its
20654 ;; presence. Without an universal argument, if the item
20655 ;; has a checkbox, toggle it. Otherwise repair the list.
20656 (let* ((box (org-element-property :checkbox context))
20657 (struct (org-element-property :structure context))
20658 (old-struct (copy-tree struct))
20659 (parents (org-list-parents-alist struct))
20660 (prevs (org-list-prevs-alist struct))
20661 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20662 (org-list-set-checkbox
20663 (org-element-property :begin context) struct
20664 (cond ((equal arg '(16)) "[-]")
20665 ((and (not box) (equal arg '(4))) "[ ]")
20666 ((or (not box) (equal arg '(4))) nil)
20667 ((eq box 'on) "[ ]")
20668 (t "[X]")))
20669 ;; Mimic `org-list-write-struct' but with grabbing
20670 ;; a return value from `org-list-struct-fix-box'.
20671 (org-list-struct-fix-ind struct parents 2)
20672 (org-list-struct-fix-item-end struct)
20673 (org-list-struct-fix-bul struct prevs)
20674 (org-list-struct-fix-ind struct parents)
20675 (let ((block-item
20676 (org-list-struct-fix-box struct parents prevs orderedp)))
20677 (if (and box (equal struct old-struct))
20678 (if (equal arg '(16))
20679 (message "Checkboxes already reset")
20680 (user-error "Cannot toggle this checkbox: %s"
20681 (if (eq box 'on)
20682 "all subitems checked"
20683 "unchecked subitems")))
20684 (org-list-struct-apply-struct struct old-struct)
20685 (org-update-checkbox-count-maybe))
20686 (when block-item
20687 (message "Checkboxes were removed due to empty box at line %d"
20688 (org-current-line block-item))))))
20689 (keyword
20690 (let ((org-inhibit-startup-visibility-stuff t)
20691 (org-startup-align-all-tables nil))
20692 (when (boundp 'org-table-coordinate-overlays)
20693 (mapc 'delete-overlay org-table-coordinate-overlays)
20694 (setq org-table-coordinate-overlays nil))
20695 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20696 (message "Local setup has been refreshed"))
20697 (plain-list
20698 ;; At a plain list, with a double C-u argument, set
20699 ;; checkboxes of each item to "[-]", whereas a single one
20700 ;; will toggle their presence according to the state of the
20701 ;; first item in the list. Without an argument, repair the
20702 ;; list.
20703 (let* ((begin (org-element-property :contents-begin context))
20704 (beginm (move-marker (make-marker) begin))
20705 (struct (org-element-property :structure context))
20706 (old-struct (copy-tree struct))
20707 (first-box (save-excursion
20708 (goto-char begin)
20709 (looking-at org-list-full-item-re)
20710 (match-string-no-properties 3)))
20711 (new-box (cond ((equal arg '(16)) "[-]")
20712 ((equal arg '(4)) (unless first-box "[ ]"))
20713 ((equal first-box "[X]") "[ ]")
20714 (t "[X]"))))
20715 (cond
20716 (arg
20717 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20718 (org-list-get-all-items
20719 begin struct (org-list-prevs-alist struct))))
20720 ((and first-box (eq (point) begin))
20721 ;; For convenience, when point is at bol on the first
20722 ;; item of the list and no argument is provided, simply
20723 ;; toggle checkbox of that item, if any.
20724 (org-list-set-checkbox begin struct new-box)))
20725 (org-list-write-struct
20726 struct (org-list-parents-alist struct) old-struct)
20727 (org-update-checkbox-count-maybe)
20728 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20729 ((property-drawer node-property)
20730 (call-interactively 'org-property-action))
20731 ((radio-target target)
20732 (call-interactively 'org-update-radio-target-regexp))
20733 (statistics-cookie
20734 (call-interactively 'org-update-statistics-cookies))
20735 ((table table-cell table-row)
20736 ;; At a table, recalculate every field and align it. Also
20737 ;; send the table if necessary. If the table has
20738 ;; a `table.el' type, just give up. At a table row or
20739 ;; cell, maybe recalculate line but always align table.
20740 (if (eq (org-element-property :type context) 'table.el)
20741 (message "Use C-c ' to edit table.el tables")
20742 (let ((org-enable-table-editor t))
20743 (if (or (eq type 'table)
20744 ;; Check if point is at a TBLFM line.
20745 (and (eq type 'table-row)
20746 (= (point) (org-element-property :end context))))
20747 (save-excursion
20748 (if (org-at-TBLFM-p)
20749 (progn (require 'org-table)
20750 (org-table-calc-current-TBLFM))
20751 (goto-char (org-element-property :contents-begin context))
20752 (org-call-with-arg 'org-table-recalculate (or arg t))
20753 (orgtbl-send-table 'maybe)))
20754 (org-table-maybe-eval-formula)
20755 (cond (arg (call-interactively 'org-table-recalculate))
20756 ((org-table-maybe-recalculate-line))
20757 (t (org-table-align)))))))
20758 (timestamp (org-timestamp-change 0 'day))
20759 (otherwise
20760 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20761 (user-error
20762 "C-c C-c can do nothing useful at this location")))))))))
20764 (defun org-mode-restart ()
20765 (interactive)
20766 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20767 (funcall major-mode)
20768 (hack-local-variables)
20769 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20770 (org-indent-mode -1)))
20771 (message "%s restarted" major-mode))
20773 (defun org-kill-note-or-show-branches ()
20774 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20775 (interactive)
20776 (if (not org-finish-function)
20777 (progn
20778 (hide-subtree)
20779 (call-interactively 'show-branches))
20780 (let ((org-note-abort t))
20781 (funcall org-finish-function))))
20783 (defun org-open-line (n)
20784 "Insert a new row in tables, call `open-line' elsewhere.
20785 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20786 (interactive "*p")
20787 (cond
20788 ((not org-special-ctrl-o)
20789 (open-line n))
20790 ((org-at-table-p)
20791 (org-table-insert-row))
20793 (open-line n))))
20795 (defun org-return (&optional indent)
20796 "Goto next table row or insert a newline.
20797 Calls `org-table-next-row' or `newline', depending on context.
20798 See the individual commands for more information."
20799 (interactive)
20800 (let (org-ts-what)
20801 (cond
20802 ((or (bobp) (org-in-src-block-p))
20803 (if indent (newline-and-indent) (newline)))
20804 ((org-at-table-p)
20805 (org-table-justify-field-maybe)
20806 (call-interactively 'org-table-next-row))
20807 ;; when `newline-and-indent' is called within a list, make sure
20808 ;; text moved stays inside the item.
20809 ((and (org-in-item-p) indent)
20810 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20811 (progn
20812 (save-match-data (newline))
20813 (org-indent-line-to (length (match-string 0))))
20814 (let ((ind (org-get-indentation)))
20815 (newline)
20816 (if (org-looking-back org-list-end-re)
20817 (org-indent-line)
20818 (org-indent-line-to ind)))))
20819 ((and org-return-follows-link
20820 (org-at-timestamp-p t)
20821 (not (eq org-ts-what 'after)))
20822 (org-follow-timestamp-link))
20823 ((and org-return-follows-link
20824 (let ((tprop (get-text-property (point) 'face)))
20825 (or (eq tprop 'org-link)
20826 (and (listp tprop) (memq 'org-link tprop)))))
20827 (call-interactively 'org-open-at-point))
20828 ((and (org-at-heading-p)
20829 (looking-at
20830 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20831 (org-show-entry)
20832 (end-of-line 1)
20833 (newline))
20834 (t (if indent (newline-and-indent) (newline))))))
20836 (defun org-return-indent ()
20837 "Goto next table row or insert a newline and indent.
20838 Calls `org-table-next-row' or `newline-and-indent', depending on
20839 context. See the individual commands for more information."
20840 (interactive)
20841 (org-return t))
20843 (defun org-ctrl-c-star ()
20844 "Compute table, or change heading status of lines.
20845 Calls `org-table-recalculate' or `org-toggle-heading',
20846 depending on context."
20847 (interactive)
20848 (cond
20849 ((org-at-table-p)
20850 (call-interactively 'org-table-recalculate))
20852 ;; Convert all lines in region to list items
20853 (call-interactively 'org-toggle-heading))))
20855 (defun org-ctrl-c-minus ()
20856 "Insert separator line in table or modify bullet status of line.
20857 Also turns a plain line or a region of lines into list items.
20858 Calls `org-table-insert-hline', `org-toggle-item', or
20859 `org-cycle-list-bullet', depending on context."
20860 (interactive)
20861 (cond
20862 ((org-at-table-p)
20863 (call-interactively 'org-table-insert-hline))
20864 ((org-region-active-p)
20865 (call-interactively 'org-toggle-item))
20866 ((org-in-item-p)
20867 (call-interactively 'org-cycle-list-bullet))
20869 (call-interactively 'org-toggle-item))))
20871 (defun org-toggle-item (arg)
20872 "Convert headings or normal lines to items, items to normal lines.
20873 If there is no active region, only the current line is considered.
20875 If the first non blank line in the region is a headline, convert
20876 all headlines to items, shifting text accordingly.
20878 If it is an item, convert all items to normal lines.
20880 If it is normal text, change region into a list of items.
20881 With a prefix argument ARG, change the region in a single item."
20882 (interactive "P")
20883 (let ((shift-text
20884 (function
20885 ;; Shift text in current section to IND, from point to END.
20886 ;; The function leaves point to END line.
20887 (lambda (ind end)
20888 (let ((min-i 1000) (end (copy-marker end)))
20889 ;; First determine the minimum indentation (MIN-I) of
20890 ;; the text.
20891 (save-excursion
20892 (catch 'exit
20893 (while (< (point) end)
20894 (let ((i (org-get-indentation)))
20895 (cond
20896 ;; Skip blank lines and inline tasks.
20897 ((looking-at "^[ \t]*$"))
20898 ((looking-at org-outline-regexp-bol))
20899 ;; We can't find less than 0 indentation.
20900 ((zerop i) (throw 'exit (setq min-i 0)))
20901 ((< i min-i) (setq min-i i))))
20902 (forward-line))))
20903 ;; Then indent each line so that a line indented to
20904 ;; MIN-I becomes indented to IND. Ignore blank lines
20905 ;; and inline tasks in the process.
20906 (let ((delta (- ind min-i)))
20907 (while (< (point) end)
20908 (unless (or (looking-at "^[ \t]*$")
20909 (looking-at org-outline-regexp-bol))
20910 (org-indent-line-to (+ (org-get-indentation) delta)))
20911 (forward-line)))))))
20912 (skip-blanks
20913 (function
20914 ;; Return beginning of first non-blank line, starting from
20915 ;; line at POS.
20916 (lambda (pos)
20917 (save-excursion
20918 (goto-char pos)
20919 (skip-chars-forward " \r\t\n")
20920 (point-at-bol)))))
20921 beg end)
20922 ;; Determine boundaries of changes.
20923 (if (org-region-active-p)
20924 (setq beg (funcall skip-blanks (region-beginning))
20925 end (copy-marker (region-end)))
20926 (setq beg (funcall skip-blanks (point-at-bol))
20927 end (copy-marker (point-at-eol))))
20928 ;; Depending on the starting line, choose an action on the text
20929 ;; between BEG and END.
20930 (org-with-limited-levels
20931 (save-excursion
20932 (goto-char beg)
20933 (cond
20934 ;; Case 1. Start at an item: de-itemize. Note that it only
20935 ;; happens when a region is active: `org-ctrl-c-minus'
20936 ;; would call `org-cycle-list-bullet' otherwise.
20937 ((org-at-item-p)
20938 (while (< (point) end)
20939 (when (org-at-item-p)
20940 (skip-chars-forward " \t")
20941 (delete-region (point) (match-end 0)))
20942 (forward-line)))
20943 ;; Case 2. Start at an heading: convert to items.
20944 ((org-at-heading-p)
20945 (let* ((bul (org-list-bullet-string "-"))
20946 (bul-len (length bul))
20947 (done (org-entry-is-done-p))
20948 (todo (org-entry-is-todo-p))
20949 ;; Indentation of the first heading. It should be
20950 ;; relative to the indentation of its parent, if any.
20951 (start-ind (save-excursion
20952 (cond
20953 ((not org-adapt-indentation) 0)
20954 ((not (outline-previous-heading)) 0)
20955 (t (length (match-string 0))))))
20956 ;; Level of first heading. Further headings will be
20957 ;; compared to it to determine hierarchy in the list.
20958 (ref-level (org-reduced-level (org-outline-level))))
20959 (when (or done todo) (org-todo ""))
20960 (while (< (point) end)
20961 (let* ((level (org-reduced-level (org-outline-level)))
20962 (delta (max 0 (- level ref-level))))
20963 ;; If current headline is less indented than the first
20964 ;; one, set it as reference, in order to preserve
20965 ;; subtrees.
20966 (when (< level ref-level) (setq ref-level level))
20967 (replace-match bul t t)
20968 (org-indent-line-to (+ start-ind (* delta bul-len)))
20969 (when (or done todo)
20970 (let* ((struct (org-list-struct))
20971 (old (copy-tree struct)))
20972 (org-list-set-checkbox (line-beginning-position)
20973 struct
20974 (if done "[X]" "[ ]"))
20975 (org-list-write-struct struct
20976 (org-list-parents-alist struct)
20977 old)))
20978 ;; Ensure all text down to END (or SECTION-END) belongs
20979 ;; to the newly created item.
20980 (let ((section-end (save-excursion
20981 (or (outline-next-heading) (point)))))
20982 (forward-line)
20983 (funcall shift-text
20984 (+ start-ind (* (1+ delta) bul-len))
20985 (min end section-end)))))))
20986 ;; Case 3. Normal line with ARG: make the first line of region
20987 ;; an item, and shift indentation of others lines to
20988 ;; set them as item's body.
20989 (arg (let* ((bul (org-list-bullet-string "-"))
20990 (bul-len (length bul))
20991 (ref-ind (org-get-indentation)))
20992 (skip-chars-forward " \t")
20993 (insert bul)
20994 (forward-line)
20995 (while (< (point) end)
20996 ;; Ensure that lines less indented than first one
20997 ;; still get included in item body.
20998 (funcall shift-text
20999 (+ ref-ind bul-len)
21000 (min end (save-excursion (or (outline-next-heading)
21001 (point)))))
21002 (forward-line))))
21003 ;; Case 4. Normal line without ARG: turn each non-item line
21004 ;; into an item.
21006 (while (< (point) end)
21007 (unless (or (org-at-heading-p) (org-at-item-p))
21008 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21009 (replace-match
21010 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21011 (forward-line))))))))
21013 (defun org-toggle-heading (&optional nstars)
21014 "Convert headings to normal text, or items or text to headings.
21015 If there is no active region, only convert the current line.
21017 With a \\[universal-argument] prefix, convert the whole list at
21018 point into heading.
21020 In a region:
21022 - If the first non blank line is a headline, remove the stars
21023 from all headlines in the region.
21025 - If it is a normal line, turn each and every normal line (i.e.,
21026 not an heading or an item) in the region into headings. If you
21027 want to convert only the first line of this region, use one
21028 universal prefix argument.
21030 - If it is a plain list item, turn all plain list items into headings.
21032 When converting a line into a heading, the number of stars is chosen
21033 such that the lines become children of the current entry. However,
21034 when a numeric prefix argument is given, its value determines the
21035 number of stars to add."
21036 (interactive "P")
21037 (let ((skip-blanks
21038 (function
21039 ;; Return beginning of first non-blank line, starting from
21040 ;; line at POS.
21041 (lambda (pos)
21042 (save-excursion
21043 (goto-char pos)
21044 (while (org-at-comment-p) (forward-line))
21045 (skip-chars-forward " \r\t\n")
21046 (point-at-bol)))))
21047 beg end toggled)
21048 ;; Determine boundaries of changes. If a universal prefix has
21049 ;; been given, put the list in a region. If region ends at a bol,
21050 ;; do not consider the last line to be in the region.
21052 (when (and current-prefix-arg (org-at-item-p))
21053 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21054 (org-mark-element))
21056 (if (org-region-active-p)
21057 (setq beg (funcall skip-blanks (region-beginning))
21058 end (copy-marker (save-excursion
21059 (goto-char (region-end))
21060 (if (bolp) (point) (point-at-eol)))))
21061 (setq beg (funcall skip-blanks (point-at-bol))
21062 end (copy-marker (point-at-eol))))
21063 ;; Ensure inline tasks don't count as headings.
21064 (org-with-limited-levels
21065 (save-excursion
21066 (goto-char beg)
21067 (cond
21068 ;; Case 1. Started at an heading: de-star headings.
21069 ((org-at-heading-p)
21070 (while (< (point) end)
21071 (when (org-at-heading-p t)
21072 (looking-at org-outline-regexp) (replace-match "")
21073 (setq toggled t))
21074 (forward-line)))
21075 ;; Case 2. Started at an item: change items into headlines.
21076 ;; One star will be added by `org-list-to-subtree'.
21077 ((org-at-item-p)
21078 (let* ((stars (make-string
21079 ;; subtract the star that will be added again by
21080 ;; `org-list-to-subtree'
21081 (if (numberp nstars) (1- nstars)
21082 (or (org-current-level) 0))
21083 ?*))
21084 (add-stars
21085 (cond (nstars "") ; stars from prefix only
21086 ((equal stars "") "") ; before first heading
21087 (org-odd-levels-only "*") ; inside heading, odd
21088 (t "")))) ; inside heading, oddeven
21089 (while (< (point) end)
21090 (when (org-at-item-p)
21091 ;; Pay attention to cases when region ends before list.
21092 (let* ((struct (org-list-struct))
21093 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21094 (save-restriction
21095 (narrow-to-region (point) list-end)
21096 (insert
21097 (org-list-to-subtree
21098 (org-list-parse-list t)
21099 '(:istart (concat stars add-stars (funcall get-stars depth))
21100 :icount (concat stars add-stars (funcall get-stars depth)))))))
21101 (setq toggled t))
21102 (forward-line))))
21103 ;; Case 3. Started at normal text: make every line an heading,
21104 ;; skipping headlines and items.
21105 (t (let* ((stars
21106 (make-string
21107 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21108 (add-stars
21109 (cond (nstars "") ; stars from prefix only
21110 ((equal stars "") "*") ; before first heading
21111 (org-odd-levels-only "**") ; inside heading, odd
21112 (t "*"))) ; inside heading, oddeven
21113 (rpl (concat stars add-stars " "))
21114 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21115 (while (< (point) (if (equal nstars '(4)) lend end))
21116 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21117 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21118 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21119 (forward-line)))))))
21120 (unless toggled (message "Cannot toggle heading from here"))))
21122 (defun org-meta-return (&optional arg)
21123 "Insert a new heading or wrap a region in a table.
21124 Calls `org-insert-heading' or `org-table-wrap-region', depending
21125 on context. See the individual commands for more information."
21126 (interactive "P")
21127 (org-check-before-invisible-edit 'insert)
21128 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21129 (let* ((element (org-element-at-point))
21130 (type (org-element-type element)))
21131 (when (eq type 'table-row)
21132 (setq element (org-element-property :parent element))
21133 (setq type 'table))
21134 (if (and (eq type 'table)
21135 (eq (org-element-property :type element) 'org)
21136 (>= (point) (org-element-property :contents-begin element))
21137 (< (point) (org-element-property :contents-end element)))
21138 (call-interactively 'org-table-wrap-region)
21139 (call-interactively 'org-insert-heading)))))
21141 ;;; Menu entries
21143 (defsubst org-in-subtree-not-table-p ()
21144 "Are we in a subtree and not in a table?"
21145 (and (not (org-before-first-heading-p))
21146 (not (org-at-table-p))))
21148 ;; Define the Org-mode menus
21149 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21150 '("Tbl"
21151 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21152 ["Next Field" org-cycle (org-at-table-p)]
21153 ["Previous Field" org-shifttab (org-at-table-p)]
21154 ["Next Row" org-return (org-at-table-p)]
21155 "--"
21156 ["Blank Field" org-table-blank-field (org-at-table-p)]
21157 ["Edit Field" org-table-edit-field (org-at-table-p)]
21158 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21159 "--"
21160 ("Column"
21161 ["Move Column Left" org-metaleft (org-at-table-p)]
21162 ["Move Column Right" org-metaright (org-at-table-p)]
21163 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21164 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21165 ("Row"
21166 ["Move Row Up" org-metaup (org-at-table-p)]
21167 ["Move Row Down" org-metadown (org-at-table-p)]
21168 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21169 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21170 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21171 "--"
21172 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21173 ("Rectangle"
21174 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21175 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21176 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21177 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21178 "--"
21179 ("Calculate"
21180 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21181 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21182 ["Edit Formulas" org-edit-special (org-at-table-p)]
21183 "--"
21184 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21185 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21186 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21187 "--"
21188 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21189 "--"
21190 ["Sum Column/Rectangle" org-table-sum
21191 (or (org-at-table-p) (org-region-active-p))]
21192 ["Which Column?" org-table-current-column (org-at-table-p)])
21193 ["Debug Formulas"
21194 org-table-toggle-formula-debugger
21195 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21196 ["Show Col/Row Numbers"
21197 org-table-toggle-coordinate-overlays
21198 :style toggle
21199 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21200 "--"
21201 ["Create" org-table-create (and (not (org-at-table-p))
21202 org-enable-table-editor)]
21203 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21204 ["Import from File" org-table-import (not (org-at-table-p))]
21205 ["Export to File" org-table-export (org-at-table-p)]
21206 "--"
21207 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21208 "--"
21209 ("Plot"
21210 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21211 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21213 (easy-menu-define org-org-menu org-mode-map "Org menu"
21214 '("Org"
21215 ("Show/Hide"
21216 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21217 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21218 ["Sparse Tree..." org-sparse-tree t]
21219 ["Reveal Context" org-reveal t]
21220 ["Show All" show-all t]
21221 "--"
21222 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21223 "--"
21224 ["New Heading" org-insert-heading t]
21225 ("Navigate Headings"
21226 ["Up" outline-up-heading t]
21227 ["Next" outline-next-visible-heading t]
21228 ["Previous" outline-previous-visible-heading t]
21229 ["Next Same Level" outline-forward-same-level t]
21230 ["Previous Same Level" outline-backward-same-level t]
21231 "--"
21232 ["Jump" org-goto t])
21233 ("Edit Structure"
21234 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21235 "--"
21236 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21237 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21238 "--"
21239 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21240 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21241 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21242 "--"
21243 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21244 "--"
21245 ["Copy visible text" org-copy-visible t]
21246 "--"
21247 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21248 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21249 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21250 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21251 "--"
21252 ["Sort Region/Children" org-sort t]
21253 "--"
21254 ["Convert to odd levels" org-convert-to-odd-levels t]
21255 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21256 ("Editing"
21257 ["Emphasis..." org-emphasize t]
21258 ["Edit Source Example" org-edit-special t]
21259 "--"
21260 ["Footnote new/jump" org-footnote-action t]
21261 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21262 ("Archive"
21263 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21264 "--"
21265 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21266 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21267 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21269 "--"
21270 ("Hyperlinks"
21271 ["Store Link (Global)" org-store-link t]
21272 ["Find existing link to here" org-occur-link-in-agenda-files t]
21273 ["Insert Link" org-insert-link t]
21274 ["Follow Link" org-open-at-point t]
21275 "--"
21276 ["Next link" org-next-link t]
21277 ["Previous link" org-previous-link t]
21278 "--"
21279 ["Descriptive Links"
21280 org-toggle-link-display
21281 :style radio
21282 :selected org-descriptive-links
21284 ["Literal Links"
21285 org-toggle-link-display
21286 :style radio
21287 :selected (not org-descriptive-links)])
21288 "--"
21289 ("TODO Lists"
21290 ["TODO/DONE/-" org-todo t]
21291 ("Select keyword"
21292 ["Next keyword" org-shiftright (org-at-heading-p)]
21293 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21294 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21295 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21296 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21297 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21298 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21299 "--"
21300 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21301 :selected org-enforce-todo-dependencies :style toggle :active t]
21302 "Settings for tree at point"
21303 ["Do Children sequentially" org-toggle-ordered-property :style radio
21304 :selected (org-entry-get nil "ORDERED")
21305 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21306 ["Do Children parallel" org-toggle-ordered-property :style radio
21307 :selected (not (org-entry-get nil "ORDERED"))
21308 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21309 "--"
21310 ["Set Priority" org-priority t]
21311 ["Priority Up" org-shiftup t]
21312 ["Priority Down" org-shiftdown t]
21313 "--"
21314 ["Get news from all feeds" org-feed-update-all t]
21315 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21316 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21317 ("TAGS and Properties"
21318 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21319 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21320 "--"
21321 ["Set property" org-set-property (not (org-before-first-heading-p))]
21322 ["Column view of properties" org-columns t]
21323 ["Insert Column View DBlock" org-insert-columns-dblock t])
21324 ("Dates and Scheduling"
21325 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21326 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21327 ("Change Date"
21328 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21329 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21330 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21331 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21332 ["Compute Time Range" org-evaluate-time-range t]
21333 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21334 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21335 "--"
21336 ["Custom time format" org-toggle-time-stamp-overlays
21337 :style radio :selected org-display-custom-times]
21338 "--"
21339 ["Goto Calendar" org-goto-calendar t]
21340 ["Date from Calendar" org-date-from-calendar t]
21341 "--"
21342 ["Start/Restart Timer" org-timer-start t]
21343 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21344 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21345 ["Insert Timer String" org-timer t]
21346 ["Insert Timer Item" org-timer-item t])
21347 ("Logging work"
21348 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21349 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21350 ["Clock out" org-clock-out t]
21351 ["Clock cancel" org-clock-cancel t]
21352 "--"
21353 ["Mark as default task" org-clock-mark-default-task t]
21354 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21355 ["Goto running clock" org-clock-goto t]
21356 "--"
21357 ["Display times" org-clock-display t]
21358 ["Create clock table" org-clock-report t]
21359 "--"
21360 ["Record DONE time"
21361 (progn (setq org-log-done (not org-log-done))
21362 (message "Switching to %s will %s record a timestamp"
21363 (car org-done-keywords)
21364 (if org-log-done "automatically" "not")))
21365 :style toggle :selected org-log-done])
21366 "--"
21367 ["Agenda Command..." org-agenda t]
21368 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21369 ("File List for Agenda")
21370 ("Special views current file"
21371 ["TODO Tree" org-show-todo-tree t]
21372 ["Check Deadlines" org-check-deadlines t]
21373 ["Timeline" org-timeline t]
21374 ["Tags/Property tree" org-match-sparse-tree t])
21375 "--"
21376 ["Export/Publish..." org-export-dispatch t]
21377 ("LaTeX"
21378 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21379 :selected org-cdlatex-mode]
21380 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21381 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21382 ["Modify math symbol" org-cdlatex-math-modify
21383 (org-inside-LaTeX-fragment-p)]
21384 ["Insert citation" org-reftex-citation t]
21385 "--"
21386 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21387 "--"
21388 ("MobileOrg"
21389 ["Push Files and Views" org-mobile-push t]
21390 ["Get Captured and Flagged" org-mobile-pull t]
21391 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21392 "--"
21393 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21394 "--"
21395 ("Documentation"
21396 ["Show Version" org-version t]
21397 ["Info Documentation" org-info t])
21398 ("Customize"
21399 ["Browse Org Group" org-customize t]
21400 "--"
21401 ["Expand This Menu" org-create-customize-menu
21402 (fboundp 'customize-menu-create)])
21403 ["Send bug report" org-submit-bug-report t]
21404 "--"
21405 ("Refresh/Reload"
21406 ["Refresh setup current buffer" org-mode-restart t]
21407 ["Reload Org (after update)" org-reload t]
21408 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21411 (defun org-info (&optional node)
21412 "Read documentation for Org-mode in the info system.
21413 With optional NODE, go directly to that node."
21414 (interactive)
21415 (info (format "(org)%s" (or node ""))))
21417 ;;;###autoload
21418 (defun org-submit-bug-report ()
21419 "Submit a bug report on Org-mode via mail.
21421 Don't hesitate to report any problems or inaccurate documentation.
21423 If you don't have setup sending mail from (X)Emacs, please copy the
21424 output buffer into your mail program, as it gives us important
21425 information about your Org-mode version and configuration."
21426 (interactive)
21427 (require 'reporter)
21428 (org-load-modules-maybe)
21429 (org-require-autoloaded-modules)
21430 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21431 (reporter-submit-bug-report
21432 "emacs-orgmode@gnu.org"
21433 (org-version nil 'full)
21434 (let (list)
21435 (save-window-excursion
21436 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21437 (delete-other-windows)
21438 (erase-buffer)
21439 (insert "You are about to submit a bug report to the Org-mode mailing list.
21441 We would like to add your full Org-mode and Outline configuration to the
21442 bug report. This greatly simplifies the work of the maintainer and
21443 other experts on the mailing list.
21445 HOWEVER, some variables you have customized may contain private
21446 information. The names of customers, colleagues, or friends, might
21447 appear in the form of file names, tags, todo states, or search strings.
21448 If you answer yes to the prompt, you might want to check and remove
21449 such private information before sending the email.")
21450 (add-text-properties (point-min) (point-max) '(face org-warning))
21451 (when (yes-or-no-p "Include your Org-mode configuration ")
21452 (mapatoms
21453 (lambda (v)
21454 (and (boundp v)
21455 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21456 (or (and (symbol-value v)
21457 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21458 (and
21459 (get v 'custom-type) (get v 'standard-value)
21460 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21461 (push v list)))))
21462 (kill-buffer (get-buffer "*Warn about privacy*"))
21463 list))
21464 nil nil
21465 "Remember to cover the basics, that is, what you expected to happen and
21466 what in fact did happen. You don't know how to make a good report? See
21468 http://orgmode.org/manual/Feedback.html#Feedback
21470 Your bug report will be posted to the Org-mode mailing list.
21471 ------------------------------------------------------------------------")
21472 (save-excursion
21473 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21474 (replace-match "\\1Bug: \\3 [\\2]")))))
21477 (defun org-install-agenda-files-menu ()
21478 (let ((bl (buffer-list)))
21479 (save-excursion
21480 (while bl
21481 (set-buffer (pop bl))
21482 (if (derived-mode-p 'org-mode) (setq bl nil)))
21483 (when (derived-mode-p 'org-mode)
21484 (easy-menu-change
21485 '("Org") "File List for Agenda"
21486 (append
21487 (list
21488 ["Edit File List" (org-edit-agenda-file-list) t]
21489 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21490 ["Remove Current File from List" org-remove-file t]
21491 ["Cycle through agenda files" org-cycle-agenda-files t]
21492 ["Occur in all agenda files" org-occur-in-agenda-files t]
21493 "--")
21494 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21496 ;;;; Documentation
21498 (defun org-require-autoloaded-modules ()
21499 (interactive)
21500 (mapc 'require
21501 '(org-agenda org-archive org-attach org-clock org-colview org-id
21502 org-table org-timer)))
21504 ;;;###autoload
21505 (defun org-reload (&optional uncompiled)
21506 "Reload all org lisp files.
21507 With prefix arg UNCOMPILED, load the uncompiled versions."
21508 (interactive "P")
21509 (require 'loadhist)
21510 (let* ((org-dir (org-find-library-dir "org"))
21511 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21512 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21513 (remove-re (mapconcat 'identity
21514 (mapcar (lambda (f) (concat "^" f "$"))
21515 (list (if (featurep 'xemacs)
21516 "org-colview"
21517 "org-colview-xemacs")
21518 "org" "org-loaddefs" "org-version"))
21519 "\\|"))
21520 (feats (delete-dups
21521 (mapcar 'file-name-sans-extension
21522 (mapcar 'file-name-nondirectory
21523 (delq nil
21524 (mapcar 'feature-file
21525 features))))))
21526 (lfeat (append
21527 (sort
21528 (setq feats
21529 (delq nil (mapcar
21530 (lambda (f)
21531 (if (and (string-match feature-re f)
21532 (not (string-match remove-re f)))
21533 f nil))
21534 feats)))
21535 'string-lessp)
21536 (list "org-version" "org")))
21537 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21538 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21539 load-uncore load-misses)
21540 (setq load-misses
21541 (delq 't
21542 (mapcar (lambda (f)
21543 (or (org-load-noerror-mustsuffix (concat org-dir f))
21544 (and (string= org-dir contrib-dir)
21545 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21546 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21547 (add-to-list 'load-uncore f 'append)
21550 lfeat)))
21551 (if load-uncore
21552 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21553 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21554 (if load-misses
21555 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21556 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21557 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21559 ;;;###autoload
21560 (defun org-customize ()
21561 "Call the customize function with org as argument."
21562 (interactive)
21563 (org-load-modules-maybe)
21564 (org-require-autoloaded-modules)
21565 (customize-browse 'org))
21567 (defun org-create-customize-menu ()
21568 "Create a full customization menu for Org-mode, insert it into the menu."
21569 (interactive)
21570 (org-load-modules-maybe)
21571 (org-require-autoloaded-modules)
21572 (if (fboundp 'customize-menu-create)
21573 (progn
21574 (easy-menu-change
21575 '("Org") "Customize"
21576 `(["Browse Org group" org-customize t]
21577 "--"
21578 ,(customize-menu-create 'org)
21579 ["Set" Custom-set t]
21580 ["Save" Custom-save t]
21581 ["Reset to Current" Custom-reset-current t]
21582 ["Reset to Saved" Custom-reset-saved t]
21583 ["Reset to Standard Settings" Custom-reset-standard t]))
21584 (message "\"Org\"-menu now contains full customization menu"))
21585 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21587 ;;;; Miscellaneous stuff
21589 ;;; Generally useful functions
21591 (defsubst org-get-at-eol (property n)
21592 "Get text property PROPERTY at the end of line less N characters."
21593 (get-text-property (- (point-at-eol) n) property))
21595 (defun org-find-text-property-in-string (prop s)
21596 "Return the first non-nil value of property PROP in string S."
21597 (or (get-text-property 0 prop s)
21598 (get-text-property (or (next-single-property-change 0 prop s) 0)
21599 prop s)))
21601 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21602 "Display the given MESSAGE as a warning."
21603 (if (fboundp 'display-warning)
21604 (display-warning 'org message
21605 (if (featurep 'xemacs) 'warning :warning))
21606 (let ((buf (get-buffer-create "*Org warnings*")))
21607 (with-current-buffer buf
21608 (goto-char (point-max))
21609 (insert "Warning (Org): " message)
21610 (unless (bolp)
21611 (newline)))
21612 (display-buffer buf)
21613 (sit-for 0))))
21615 (defun org-eval (form)
21616 "Eval FORM and return result."
21617 (condition-case error
21618 (eval form)
21619 (error (format "%%![Error: %s]" error))))
21621 (defun org-in-clocktable-p ()
21622 "Check if the cursor is in a clocktable."
21623 (let ((pos (point)) start)
21624 (save-excursion
21625 (end-of-line 1)
21626 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21627 (setq start (match-beginning 0))
21628 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21629 (>= (match-end 0) pos)
21630 start))))
21632 (defun org-in-verbatim-emphasis ()
21633 (save-match-data
21634 (and (org-in-regexp org-emph-re 2)
21635 (>= (point) (match-beginning 3))
21636 (<= (point) (match-end 4))
21637 (member (match-string 3) '("=" "~")))))
21639 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21640 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21641 (if (and marker (marker-buffer marker)
21642 (buffer-live-p (marker-buffer marker)))
21643 (progn
21644 (org-pop-to-buffer-same-window (marker-buffer marker))
21645 (if (or (> marker (point-max)) (< marker (point-min)))
21646 (widen))
21647 (goto-char marker)
21648 (org-show-context 'org-goto))
21649 (if bookmark
21650 (bookmark-jump bookmark)
21651 (error "Cannot find location"))))
21653 (defun org-quote-csv-field (s)
21654 "Quote field for inclusion in CSV material."
21655 (if (string-match "[\",]" s)
21656 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21659 (defun org-force-self-insert (N)
21660 "Needed to enforce self-insert under remapping."
21661 (interactive "p")
21662 (self-insert-command N))
21664 (defun org-string-width (s)
21665 "Compute width of string, ignoring invisible characters.
21666 This ignores character with invisibility property `org-link', and also
21667 characters with property `org-cwidth', because these will become invisible
21668 upon the next fontification round."
21669 (let (b l)
21670 (when (or (eq t buffer-invisibility-spec)
21671 (assq 'org-link buffer-invisibility-spec))
21672 (while (setq b (text-property-any 0 (length s)
21673 'invisible 'org-link s))
21674 (setq s (concat (substring s 0 b)
21675 (substring s (or (next-single-property-change
21676 b 'invisible s) (length s)))))))
21677 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21678 (setq s (concat (substring s 0 b)
21679 (substring s (or (next-single-property-change
21680 b 'org-cwidth s) (length s))))))
21681 (setq l (string-width s) b -1)
21682 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21683 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21686 (defun org-shorten-string (s maxlength)
21687 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21688 If the string is shorter or has length MAXLENGTH, just return the
21689 original string. If it is longer, the functions finds a space in the
21690 string, breaks this string off at that locations and adds three dots
21691 as ellipsis. Including the ellipsis, the string will not be longer
21692 than MAXLENGTH. If finding a good breaking point in the string does
21693 not work, the string is just chopped off in the middle of a word
21694 if necessary."
21695 (if (<= (length s) maxlength)
21697 (let* ((n (max (- maxlength 4) 1))
21698 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21699 (if (string-match re s)
21700 (concat (match-string 1 s) "...")
21701 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21703 (defun org-get-indentation (&optional line)
21704 "Get the indentation of the current line, interpreting tabs.
21705 When LINE is given, assume it represents a line and compute its indentation."
21706 (if line
21707 (if (string-match "^ *" (org-remove-tabs line))
21708 (match-end 0))
21709 (save-excursion
21710 (beginning-of-line 1)
21711 (skip-chars-forward " \t")
21712 (current-column))))
21714 (defun org-get-string-indentation (s)
21715 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21716 (let ((n -1) (i 0) (w tab-width) c)
21717 (catch 'exit
21718 (while (< (setq n (1+ n)) (length s))
21719 (setq c (aref s n))
21720 (cond ((= c ?\ ) (setq i (1+ i)))
21721 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21722 (t (throw 'exit t)))))
21725 (defun org-remove-tabs (s &optional width)
21726 "Replace tabulators in S with spaces.
21727 Assumes that s is a single line, starting in column 0."
21728 (setq width (or width tab-width))
21729 (while (string-match "\t" s)
21730 (setq s (replace-match
21731 (make-string
21732 (- (* width (/ (+ (match-beginning 0) width) width))
21733 (match-beginning 0)) ?\ )
21734 t t s)))
21737 (defun org-fix-indentation (line ind)
21738 "Fix indentation in LINE.
21739 IND is a cons cell with target and minimum indentation.
21740 If the current indentation in LINE is smaller than the minimum,
21741 leave it alone. If it is larger than ind, set it to the target."
21742 (let* ((l (org-remove-tabs line))
21743 (i (org-get-indentation l))
21744 (i1 (car ind)) (i2 (cdr ind)))
21745 (if (>= i i2) (setq l (substring line i2)))
21746 (if (> i1 0)
21747 (concat (make-string i1 ?\ ) l)
21748 l)))
21750 (defun org-remove-indentation (code &optional n)
21751 "Remove the maximum common indentation from the lines in CODE.
21752 N may optionally be the number of spaces to remove."
21753 (with-temp-buffer
21754 (insert code)
21755 (org-do-remove-indentation n)
21756 (buffer-string)))
21758 (defun org-do-remove-indentation (&optional n)
21759 "Remove the maximum common indentation from the buffer."
21760 (untabify (point-min) (point-max))
21761 (let ((min 10000) re)
21762 (if n
21763 (setq min n)
21764 (goto-char (point-min))
21765 (while (re-search-forward "^ *[^ \n]" nil t)
21766 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21767 (unless (or (= min 0) (= min 10000))
21768 (setq re (format "^ \\{%d\\}" min))
21769 (goto-char (point-min))
21770 (while (re-search-forward re nil t)
21771 (replace-match "")
21772 (end-of-line 1))
21773 min)))
21775 (defun org-fill-template (template alist)
21776 "Find each %key of ALIST in TEMPLATE and replace it."
21777 (let ((case-fold-search nil)
21778 entry key value)
21779 (setq alist (sort (copy-sequence alist)
21780 (lambda (a b) (< (length (car a)) (length (car b))))))
21781 (while (setq entry (pop alist))
21782 (setq template
21783 (replace-regexp-in-string
21784 (concat "%" (regexp-quote (car entry)))
21785 (or (cdr entry) "") template t t)))
21786 template))
21788 (defun org-base-buffer (buffer)
21789 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21790 (if (not buffer)
21791 buffer
21792 (or (buffer-base-buffer buffer)
21793 buffer)))
21795 (defun org-wrap (string &optional width lines)
21796 "Wrap string to either a number of lines, or a width in characters.
21797 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21798 that costs. If there is a word longer than WIDTH, the text is actually
21799 wrapped to the length of that word.
21800 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21801 many lines, whatever width that takes.
21802 The return value is a list of lines, without newlines at the end."
21803 (let* ((words (org-split-string string "[ \t\n]+"))
21804 (maxword (apply 'max (mapcar 'org-string-width words)))
21805 w ll)
21806 (cond (width
21807 (org-do-wrap words (max maxword width)))
21808 (lines
21809 (setq w maxword)
21810 (setq ll (org-do-wrap words maxword))
21811 (if (<= (length ll) lines)
21813 (setq ll words)
21814 (while (> (length ll) lines)
21815 (setq w (1+ w))
21816 (setq ll (org-do-wrap words w)))
21817 ll))
21818 (t (error "Cannot wrap this")))))
21820 (defun org-do-wrap (words width)
21821 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21822 (let (lines line)
21823 (while words
21824 (setq line (pop words))
21825 (while (and words (< (+ (length line) (length (car words))) width))
21826 (setq line (concat line " " (pop words))))
21827 (setq lines (push line lines)))
21828 (nreverse lines)))
21830 (defun org-split-string (string &optional separators)
21831 "Splits STRING into substrings at SEPARATORS.
21832 No empty strings are returned if there are matches at the beginning
21833 and end of string."
21834 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21835 (start 0)
21836 notfirst
21837 (list nil))
21838 (while (and (string-match rexp string
21839 (if (and notfirst
21840 (= start (match-beginning 0))
21841 (< start (length string)))
21842 (1+ start) start))
21843 (< (match-beginning 0) (length string)))
21844 (setq notfirst t)
21845 (or (eq (match-beginning 0) 0)
21846 (and (eq (match-beginning 0) (match-end 0))
21847 (eq (match-beginning 0) start))
21848 (setq list
21849 (cons (substring string start (match-beginning 0))
21850 list)))
21851 (setq start (match-end 0)))
21852 (or (eq start (length string))
21853 (setq list
21854 (cons (substring string start)
21855 list)))
21856 (nreverse list)))
21858 (defun org-quote-vert (s)
21859 "Replace \"|\" with \"\\vert\"."
21860 (while (string-match "|" s)
21861 (setq s (replace-match "\\vert" t t s)))
21864 (defun org-uuidgen-p (s)
21865 "Is S an ID created by UUIDGEN?"
21866 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21868 (defun org-in-src-block-p (&optional inside)
21869 "Whether point is in a code source block.
21870 When INSIDE is non-nil, don't consider we are within a src block
21871 when point is at #+BEGIN_SRC or #+END_SRC."
21872 (let ((case-fold-search t) ov)
21873 (or (and (eq (get-char-property (point) 'src-block) t))
21874 (and (not inside)
21875 (save-match-data
21876 (save-excursion
21877 (beginning-of-line)
21878 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21880 (defun org-context ()
21881 "Return a list of contexts of the current cursor position.
21882 If several contexts apply, all are returned.
21883 Each context entry is a list with a symbol naming the context, and
21884 two positions indicating start and end of the context. Possible
21885 contexts are:
21887 :headline anywhere in a headline
21888 :headline-stars on the leading stars in a headline
21889 :todo-keyword on a TODO keyword (including DONE) in a headline
21890 :tags on the TAGS in a headline
21891 :priority on the priority cookie in a headline
21892 :item on the first line of a plain list item
21893 :item-bullet on the bullet/number of a plain list item
21894 :checkbox on the checkbox in a plain list item
21895 :table in an org-mode table
21896 :table-special on a special filed in a table
21897 :table-table in a table.el table
21898 :clocktable in a clocktable
21899 :src-block in a source block
21900 :link on a hyperlink
21901 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21902 :target on a <<target>>
21903 :radio-target on a <<<radio-target>>>
21904 :latex-fragment on a LaTeX fragment
21905 :latex-preview on a LaTeX fragment with overlaid preview image
21907 This function expects the position to be visible because it uses font-lock
21908 faces as a help to recognize the following contexts: :table-special, :link,
21909 and :keyword."
21910 (let* ((f (get-text-property (point) 'face))
21911 (faces (if (listp f) f (list f)))
21912 (case-fold-search t)
21913 (p (point)) clist o)
21914 ;; First the large context
21915 (cond
21916 ((org-at-heading-p t)
21917 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21918 (when (progn
21919 (beginning-of-line 1)
21920 (looking-at org-todo-line-tags-regexp))
21921 (push (org-point-in-group p 1 :headline-stars) clist)
21922 (push (org-point-in-group p 2 :todo-keyword) clist)
21923 (push (org-point-in-group p 4 :tags) clist))
21924 (goto-char p)
21925 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21926 (if (looking-at "\\[#[A-Z0-9]\\]")
21927 (push (org-point-in-group p 0 :priority) clist)))
21929 ((org-at-item-p)
21930 (push (org-point-in-group p 2 :item-bullet) clist)
21931 (push (list :item (point-at-bol)
21932 (save-excursion (org-end-of-item) (point)))
21933 clist)
21934 (and (org-at-item-checkbox-p)
21935 (push (org-point-in-group p 0 :checkbox) clist)))
21937 ((org-at-table-p)
21938 (push (list :table (org-table-begin) (org-table-end)) clist)
21939 (if (memq 'org-formula faces)
21940 (push (list :table-special
21941 (previous-single-property-change p 'face)
21942 (next-single-property-change p 'face)) clist)))
21943 ((org-at-table-p 'any)
21944 (push (list :table-table) clist)))
21945 (goto-char p)
21947 (let ((case-fold-search t))
21948 ;; New the "medium" contexts: clocktables, source blocks
21949 (cond ((org-in-clocktable-p)
21950 (push (list :clocktable
21951 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21952 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21953 (match-beginning 1))
21954 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21955 (match-end 0))) clist))
21956 ((org-in-src-block-p)
21957 (push (list :src-block
21958 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21959 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21960 (match-beginning 1))
21961 (and (search-forward "#+END_SRC" nil t)
21962 (match-beginning 0))) clist))))
21963 (goto-char p)
21965 ;; Now the small context
21966 (cond
21967 ((org-at-timestamp-p)
21968 (push (org-point-in-group p 0 :timestamp) clist))
21969 ((memq 'org-link faces)
21970 (push (list :link
21971 (previous-single-property-change p 'face)
21972 (next-single-property-change p 'face)) clist))
21973 ((memq 'org-special-keyword faces)
21974 (push (list :keyword
21975 (previous-single-property-change p 'face)
21976 (next-single-property-change p 'face)) clist))
21977 ((org-at-target-p)
21978 (push (org-point-in-group p 0 :target) clist)
21979 (goto-char (1- (match-beginning 0)))
21980 (if (looking-at org-radio-target-regexp)
21981 (push (org-point-in-group p 0 :radio-target) clist))
21982 (goto-char p))
21983 ((setq o (car (delq nil
21984 (mapcar
21985 (lambda (x)
21986 (if (memq x org-latex-fragment-image-overlays) x))
21987 (overlays-at (point))))))
21988 (push (list :latex-fragment
21989 (overlay-start o) (overlay-end o)) clist)
21990 (push (list :latex-preview
21991 (overlay-start o) (overlay-end o)) clist))
21992 ((org-inside-LaTeX-fragment-p)
21993 ;; FIXME: positions wrong.
21994 (push (list :latex-fragment (point) (point)) clist)))
21996 (setq clist (nreverse (delq nil clist)))
21997 clist))
21999 ;; FIXME: Compare with at-regexp-p Do we need both?
22000 (defun org-in-regexp (re &optional nlines visually)
22001 "Check if point is inside a match of regexp.
22002 Normally only the current line is checked, but you can include NLINES extra
22003 lines both before and after point into the search.
22004 If VISUALLY is set, require that the cursor is not after the match but
22005 really on, so that the block visually is on the match."
22006 (catch 'exit
22007 (let ((pos (point))
22008 (eol (point-at-eol (+ 1 (or nlines 0))))
22009 (inc (if visually 1 0)))
22010 (save-excursion
22011 (beginning-of-line (- 1 (or nlines 0)))
22012 (while (re-search-forward re eol t)
22013 (if (and (<= (match-beginning 0) pos)
22014 (>= (+ inc (match-end 0)) pos))
22015 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
22017 (defun org-at-regexp-p (regexp)
22018 "Is point inside a match of REGEXP in the current line?"
22019 (catch 'exit
22020 (save-excursion
22021 (let ((pos (point)) (end (point-at-eol)))
22022 (beginning-of-line 1)
22023 (while (re-search-forward regexp end t)
22024 (if (and (<= (match-beginning 0) pos)
22025 (>= (match-end 0) pos))
22026 (throw 'exit t)))
22027 nil))))
22029 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22030 "Non-nil when point is between matches of START-RE and END-RE.
22032 Also return a non-nil value when point is on one of the matches.
22034 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22035 buffer positions. Default values are the positions of headlines
22036 surrounding the point.
22038 The functions returns a cons cell whose car (resp. cdr) is the
22039 position before START-RE (resp. after END-RE)."
22040 (save-match-data
22041 (let ((pos (point))
22042 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22043 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22044 beg end)
22045 (save-excursion
22046 ;; Point is on a block when on START-RE or if START-RE can be
22047 ;; found before it...
22048 (and (or (org-at-regexp-p start-re)
22049 (re-search-backward start-re limit-up t))
22050 (setq beg (match-beginning 0))
22051 ;; ... and END-RE after it...
22052 (goto-char (match-end 0))
22053 (re-search-forward end-re limit-down t)
22054 (> (setq end (match-end 0)) pos)
22055 ;; ... without another START-RE in-between.
22056 (goto-char (match-beginning 0))
22057 (not (re-search-backward start-re (1+ beg) t))
22058 ;; Return value.
22059 (cons beg end))))))
22061 (defun org-in-block-p (names)
22062 "Non-nil when point belongs to a block whose name belongs to NAMES.
22064 NAMES is a list of strings containing names of blocks.
22066 Return first block name matched, or nil. Beware that in case of
22067 nested blocks, the returned name may not belong to the closest
22068 block from point."
22069 (save-match-data
22070 (catch 'exit
22071 (let ((case-fold-search t)
22072 (lim-up (save-excursion (outline-previous-heading)))
22073 (lim-down (save-excursion (outline-next-heading))))
22074 (mapc (lambda (name)
22075 (let ((n (regexp-quote name)))
22076 (when (org-between-regexps-p
22077 (concat "^[ \t]*#\\+begin_" n)
22078 (concat "^[ \t]*#\\+end_" n)
22079 lim-up lim-down)
22080 (throw 'exit n))))
22081 names))
22082 nil)))
22084 (defun org-in-drawer-p ()
22085 "Non-nil if point is within a drawer.
22086 If point is within a drawer, return it, as parsed data."
22087 (let ((element (save-match-data (org-element-at-point))))
22088 (while (and element (not (memq (org-element-type element)
22089 '(drawer property-drawer))))
22090 (setq element (org-element-property :parent element)))
22091 element))
22093 (defun org-occur-in-agenda-files (regexp &optional nlines)
22094 "Call `multi-occur' with buffers for all agenda files."
22095 (interactive "sOrg-files matching: \np")
22096 (let* ((files (org-agenda-files))
22097 (tnames (mapcar 'file-truename files))
22098 (extra org-agenda-text-search-extra-files)
22100 (when (eq (car extra) 'agenda-archives)
22101 (setq extra (cdr extra))
22102 (setq files (org-add-archive-files files)))
22103 (while (setq f (pop extra))
22104 (unless (member (file-truename f) tnames)
22105 (add-to-list 'files f 'append)
22106 (add-to-list 'tnames (file-truename f) 'append)))
22107 (multi-occur
22108 (mapcar (lambda (x)
22109 (with-current-buffer
22110 (or (get-file-buffer x) (find-file-noselect x))
22111 (widen)
22112 (current-buffer)))
22113 files)
22114 regexp)))
22116 (if (boundp 'occur-mode-find-occurrence-hook)
22117 ;; Emacs 23
22118 (add-hook 'occur-mode-find-occurrence-hook
22119 (lambda ()
22120 (when (derived-mode-p 'org-mode)
22121 (org-reveal))))
22122 ;; Emacs 22
22123 (defadvice occur-mode-goto-occurrence
22124 (after org-occur-reveal activate)
22125 (and (derived-mode-p 'org-mode) (org-reveal)))
22126 (defadvice occur-mode-goto-occurrence-other-window
22127 (after org-occur-reveal activate)
22128 (and (derived-mode-p 'org-mode) (org-reveal)))
22129 (defadvice occur-mode-display-occurrence
22130 (after org-occur-reveal activate)
22131 (when (derived-mode-p 'org-mode)
22132 (let ((pos (occur-mode-find-occurrence)))
22133 (with-current-buffer (marker-buffer pos)
22134 (save-excursion
22135 (goto-char pos)
22136 (org-reveal)))))))
22138 (defun org-occur-link-in-agenda-files ()
22139 "Create a link and search for it in the agendas.
22140 The link is not stored in `org-stored-links', it is just created
22141 for the search purpose."
22142 (interactive)
22143 (let ((link (condition-case nil
22144 (org-store-link nil)
22145 (error "Unable to create a link to here"))))
22146 (org-occur-in-agenda-files (regexp-quote link))))
22148 (defun org-reverse-string (string)
22149 "Return the reverse of STRING."
22150 (apply 'string (reverse (string-to-list string))))
22152 ;; defsubst org-uniquify must be defined before first use
22154 (defun org-uniquify-alist (alist)
22155 "Merge elements of ALIST with the same key.
22157 For example, in this alist:
22159 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22160 => '((a 1 3) (b 2))
22162 merge (a 1) and (a 3) into (a 1 3).
22164 The function returns the new ALIST."
22165 (let (rtn)
22166 (mapc
22167 (lambda (e)
22168 (let (n)
22169 (if (not (assoc (car e) rtn))
22170 (push e rtn)
22171 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22172 (setq rtn (assq-delete-all (car e) rtn))
22173 (push n rtn))))
22174 alist)
22175 rtn))
22177 (defun org-delete-all (elts list)
22178 "Remove all elements in ELTS from LIST."
22179 (while elts
22180 (setq list (delete (pop elts) list)))
22181 list)
22183 (defun org-count (cl-item cl-seq)
22184 "Count the number of occurrences of ITEM in SEQ.
22185 Taken from `count' in cl-seq.el with all keyword arguments removed."
22186 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22187 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22188 (while (< cl-start cl-end)
22189 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22190 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22191 (setq cl-start (1+ cl-start)))
22192 cl-count))
22194 (defun org-remove-if (predicate seq)
22195 "Remove everything from SEQ that fulfills PREDICATE."
22196 (let (res e)
22197 (while seq
22198 (setq e (pop seq))
22199 (if (not (funcall predicate e)) (push e res)))
22200 (nreverse res)))
22202 (defun org-remove-if-not (predicate seq)
22203 "Remove everything from SEQ that does not fulfill PREDICATE."
22204 (let (res e)
22205 (while seq
22206 (setq e (pop seq))
22207 (if (funcall predicate e) (push e res)))
22208 (nreverse res)))
22210 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22211 "Reduce two-argument FUNCTION across SEQ.
22212 Taken from `reduce' in cl-seq.el with all keyword arguments but
22213 \":initial-value\" removed."
22214 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22215 (cadr (memq :initial-value cl-keys)))
22216 (cl-seq (pop cl-seq))
22217 (t (funcall cl-func)))))
22218 (while cl-seq
22219 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22220 cl-accum))
22222 (defun org-every (pred seq)
22223 "Return true if PREDICATE is true of every element of SEQ.
22224 Adapted from `every' in cl.el."
22225 (catch 'org-every
22226 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22229 (defun org-some (pred seq)
22230 "Return true if PREDICATE is true of any element of SEQ.
22231 Adapted from `some' in cl.el."
22232 (catch 'org-some
22233 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22234 nil))
22236 (defun org-back-over-empty-lines ()
22237 "Move backwards over whitespace, to the beginning of the first empty line.
22238 Returns the number of empty lines passed."
22239 (let ((pos (point)))
22240 (if (cdr (assoc 'heading org-blank-before-new-entry))
22241 (skip-chars-backward " \t\n\r")
22242 (unless (eobp)
22243 (forward-line -1)))
22244 (beginning-of-line 2)
22245 (goto-char (min (point) pos))
22246 (count-lines (point) pos)))
22248 (defun org-skip-whitespace ()
22249 (skip-chars-forward " \t\n\r"))
22251 (defun org-point-in-group (point group &optional context)
22252 "Check if POINT is in match-group GROUP.
22253 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22254 match. If the match group does not exist or point is not inside it,
22255 return nil."
22256 (and (match-beginning group)
22257 (>= point (match-beginning group))
22258 (<= point (match-end group))
22259 (if context
22260 (list context (match-beginning group) (match-end group))
22261 t)))
22263 (defun org-switch-to-buffer-other-window (&rest args)
22264 "Switch to buffer in a second window on the current frame.
22265 In particular, do not allow pop-up frames.
22266 Returns the newly created buffer."
22267 (org-no-popups
22268 (apply 'switch-to-buffer-other-window args)))
22270 (defun org-combine-plists (&rest plists)
22271 "Create a single property list from all plists in PLISTS.
22272 The process starts by copying the first list, and then setting properties
22273 from the other lists. Settings in the last list are the most significant
22274 ones and overrule settings in the other lists."
22275 (let ((rtn (copy-sequence (pop plists)))
22276 p v ls)
22277 (while plists
22278 (setq ls (pop plists))
22279 (while ls
22280 (setq p (pop ls) v (pop ls))
22281 (setq rtn (plist-put rtn p v))))
22282 rtn))
22284 (defun org-replace-escapes (string table)
22285 "Replace %-escapes in STRING with values in TABLE.
22286 TABLE is an association list with keys like \"%a\" and string values.
22287 The sequences in STRING may contain normal field width and padding information,
22288 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22289 so values can contain further %-escapes if they are define later in TABLE."
22290 (let ((tbl (copy-alist table))
22291 (case-fold-search nil)
22292 (pchg 0)
22293 e re rpl)
22294 (while (setq e (pop tbl))
22295 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22296 (when (and (cdr e) (string-match re (cdr e)))
22297 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22298 (safe "SREF"))
22299 (add-text-properties 0 3 (list 'sref sref) safe)
22300 (setcdr e (replace-match safe t t (cdr e)))))
22301 (while (string-match re string)
22302 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22303 (cdr e)))
22304 (setq string (replace-match rpl t t string))))
22305 (while (setq pchg (next-property-change pchg string))
22306 (let ((sref (get-text-property pchg 'sref string)))
22307 (when (and sref (string-match "SREF" string pchg))
22308 (setq string (replace-match sref t t string)))))
22309 string))
22311 (defun org-sublist (list start end)
22312 "Return a section of LIST, from START to END.
22313 Counting starts at 1."
22314 (let (rtn (c start))
22315 (setq list (nthcdr (1- start) list))
22316 (while (and list (<= c end))
22317 (push (pop list) rtn)
22318 (setq c (1+ c)))
22319 (nreverse rtn)))
22321 (defun org-find-base-buffer-visiting (file)
22322 "Like `find-buffer-visiting' but always return the base buffer and
22323 not an indirect buffer."
22324 (let ((buf (or (get-file-buffer file)
22325 (find-buffer-visiting file))))
22326 (if buf
22327 (or (buffer-base-buffer buf) buf)
22328 nil)))
22330 (defun org-image-file-name-regexp (&optional extensions)
22331 "Return regexp matching the file names of images.
22332 If EXTENSIONS is given, only match these."
22333 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22334 (image-file-name-regexp)
22335 (let ((image-file-name-extensions
22336 (or extensions
22337 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22338 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22339 (concat "\\."
22340 (regexp-opt (nconc (mapcar 'upcase
22341 image-file-name-extensions)
22342 image-file-name-extensions)
22344 "\\'"))))
22346 (defun org-file-image-p (file &optional extensions)
22347 "Return non-nil if FILE is an image."
22348 (save-match-data
22349 (string-match (org-image-file-name-regexp extensions) file)))
22351 (defun org-get-cursor-date (&optional with-time)
22352 "Return the date at cursor in as a time.
22353 This works in the calendar and in the agenda, anywhere else it just
22354 returns the current time.
22355 If WITH-TIME is non-nil, returns the time of the event at point (in
22356 the agenda) or the current time of the day."
22357 (let (date day defd tp tm hod mod)
22358 (when with-time
22359 (setq tp (get-text-property (point) 'time))
22360 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22361 (setq hod (string-to-number (match-string 1 tp))
22362 mod (string-to-number (match-string 2 tp))))
22363 (or tp (setq hod (nth 2 (decode-time (current-time)))
22364 mod (nth 1 (decode-time (current-time))))))
22365 (cond
22366 ((eq major-mode 'calendar-mode)
22367 (setq date (calendar-cursor-to-date)
22368 defd (encode-time 0 (or mod 0) (or hod 0)
22369 (nth 1 date) (nth 0 date) (nth 2 date))))
22370 ((eq major-mode 'org-agenda-mode)
22371 (setq day (get-text-property (point) 'day))
22372 (if day
22373 (setq date (calendar-gregorian-from-absolute day)
22374 defd (encode-time 0 (or mod 0) (or hod 0)
22375 (nth 1 date) (nth 0 date) (nth 2 date))))))
22376 (or defd (current-time))))
22378 (defun org-mark-subtree (&optional up)
22379 "Mark the current subtree.
22380 This puts point at the start of the current subtree, and mark at
22381 the end. If a numeric prefix UP is given, move up into the
22382 hierarchy of headlines by UP levels before marking the subtree."
22383 (interactive "P")
22384 (org-with-limited-levels
22385 (cond ((org-at-heading-p) (beginning-of-line))
22386 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22387 (t (outline-previous-visible-heading 1))))
22388 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22389 (if (org-called-interactively-p 'any)
22390 (call-interactively 'org-mark-element)
22391 (org-mark-element)))
22394 ;;; Indentation
22396 (defun org--get-expected-indentation (element contentsp)
22397 "Expected indentation column for current line, according to ELEMENT.
22398 ELEMENT is an element containing point. CONTENTSP is non-nil
22399 when indentation is to be computed according to contents of
22400 ELEMENT."
22401 (let ((type (org-element-type element))
22402 (start (org-element-property :begin element)))
22403 (org-with-wide-buffer
22404 (cond
22405 (contentsp
22406 (case type
22407 (footnote-definition 0)
22408 ((headline inlinetask nil)
22409 (if (not org-adapt-indentation) 0
22410 (let ((level (org-current-level)))
22411 (if level (1+ level) 0))))
22412 (item
22413 (org-list-item-body-column
22414 (org-element-property :post-affiliated element)))
22415 (plain-list
22416 (save-excursion
22417 (goto-char (org-element-property :post-affiliated element))
22418 (org-get-indentation)))
22419 (otherwise
22420 (goto-char start)
22421 (org-get-indentation))))
22422 ((memq type '(headline inlinetask nil))
22423 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22424 (org--get-expected-indentation element t)
22426 ((eq type 'footnote-definition) 0)
22427 ;; First paragraph of a footnote definition or an item.
22428 ;; Indent like parent.
22429 ((< (line-beginning-position) start)
22430 (org--get-expected-indentation
22431 (org-element-property :parent element) t))
22432 ;; At first line: indent according to previous sibling, if any,
22433 ;; ignoring footnote definitions and inline tasks, or parent's
22434 ;; contents.
22435 ((= (line-beginning-position) start)
22436 (catch 'exit
22437 (while t
22438 (if (= (point-min) start) (throw 'exit 0)
22439 (goto-char (1- start))
22440 (let* ((previous (org-element-at-point))
22441 (parent previous))
22442 (while (and parent (<= (org-element-property :end parent) start))
22443 (setq previous parent
22444 parent (org-element-property :parent parent)))
22445 (cond
22446 ((not previous) (throw 'exit 0))
22447 ((> (org-element-property :end previous) start)
22448 (throw 'exit (org--get-expected-indentation previous t)))
22449 ((memq (org-element-type previous)
22450 '(footnote-definition inlinetask))
22451 (setq start (org-element-property :begin previous)))
22452 (t (goto-char (org-element-property :begin previous))
22453 (throw 'exit
22454 (if (bolp) (org-get-indentation)
22455 ;; At first paragraph in an item or
22456 ;; a footnote definition.
22457 (org--get-expected-indentation
22458 (org-element-property :parent previous) t))))))))))
22459 ;; Otherwise, move to the first non-blank line above.
22461 (beginning-of-line)
22462 (let ((pos (point)))
22463 (skip-chars-backward " \r\t\n")
22464 (cond
22465 ;; Two blank lines end a footnote definition or a plain
22466 ;; list. When we indent an empty line after them, the
22467 ;; containing list or footnote definition is over, so it
22468 ;; qualifies as a previous sibling. Therefore, we indent
22469 ;; like its first line.
22470 ((and (memq type '(footnote-definition plain-list))
22471 (> (count-lines (point) pos) 2))
22472 (goto-char start)
22473 (org-get-indentation))
22474 ;; Line above is the first one of a paragraph at the
22475 ;; beginning of an item or a footnote definition. Indent
22476 ;; like parent.
22477 ((< (line-beginning-position) start)
22478 (org--get-expected-indentation
22479 (org-element-property :parent element) t))
22480 ;; POS is after contents in a greater element. Indent like
22481 ;; the beginning of the element.
22483 ;; As a special case, if point is at the end of a footnote
22484 ;; definition or an item, indent like the very last element
22485 ;; within.
22486 ((let ((cend (org-element-property :contents-end element)))
22487 (and cend (<= cend pos)))
22488 (if (memq type '(footnote-definition item plain-list))
22489 (org--get-expected-indentation (org-element-at-point) nil)
22490 (goto-char start)
22491 (org-get-indentation)))
22492 ;; In any other case, indent like the current line.
22493 (t (org-get-indentation)))))))))
22495 (defun org--align-node-property ()
22496 "Align node property at point.
22497 Alignment is done according to `org-property-format', which see."
22498 (when (save-excursion
22499 (beginning-of-line)
22500 (looking-at org-property-re))
22501 (replace-match
22502 (concat (match-string 4)
22503 (org-trim
22504 (format org-property-format (match-string 1) (match-string 3))))
22505 t t)))
22507 (defun org-indent-line ()
22508 "Indent line depending on context.
22510 Indentation is done according to the following rules:
22512 - Footnote definitions, headlines and inline tasks have to
22513 start at column 0.
22515 - On the very first line of an element, consider, in order, the
22516 next rules until one matches:
22518 1. If there's a sibling element before, ignoring footnote
22519 definitions and inline tasks, indent like its first line.
22521 2. If element has a parent, indent like its contents. More
22522 precisely, if parent is an item, indent after the
22523 description part, if any, or the bullet (see
22524 ``org-list-description-max-indent'). Else, indent like
22525 parent's first line.
22527 3. Otherwise, indent relatively to current level, if
22528 `org-adapt-indentation' is non-nil, or to left margin.
22530 - On a blank line at the end of a plain list, an item, or
22531 a footnote definition, indent like the very last element
22532 within.
22534 - In the code part of a source block, use language major mode
22535 to indent current line if `org-src-tab-acts-natively' is
22536 non-nil. If it is nil, do nothing.
22538 - Otherwise, indent like the first non-blank line above.
22540 The function doesn't indent an item as it could break the whole
22541 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22542 \\[org-shiftmetaright].
22544 Also align node properties according to `org-property-format'."
22545 (interactive)
22546 (cond
22547 (orgstruct-is-++
22548 (let ((indent-line-function
22549 (cadadr (assq 'indent-line-function org-fb-vars))))
22550 (indent-according-to-mode)))
22551 ((org-at-heading-p) 'noindent)
22553 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22554 (type (org-element-type element)))
22555 (cond ((and (memq type '(plain-list item))
22556 (= (line-beginning-position)
22557 (org-element-property :post-affiliated element)))
22558 'noindent)
22559 ((and (eq type 'src-block)
22560 org-src-tab-acts-natively
22561 (> (line-beginning-position)
22562 (org-element-property :post-affiliated element))
22563 (< (line-beginning-position)
22564 (org-with-wide-buffer
22565 (goto-char (org-element-property :end element))
22566 (skip-chars-backward " \r\t\n")
22567 (line-beginning-position))))
22568 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22569 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))))
22571 (let ((column (org--get-expected-indentation element nil)))
22572 ;; Preserve current column.
22573 (if (<= (current-column) (current-indentation))
22574 (org-indent-line-to column)
22575 (save-excursion (org-indent-line-to column))))
22576 ;; Align node property. Also preserve current column.
22577 (when (eq type 'node-property)
22578 (let ((column (current-column)))
22579 (org--align-node-property)
22580 (org-move-to-column column)))))))))
22582 (defun org-indent-region (start end)
22583 "Indent each non-blank line in the region.
22584 Called from a program, START and END specify the region to
22585 indent. The function will not indent contents of example blocks,
22586 verse blocks and export blocks as leading white spaces are
22587 assumed to be significant there."
22588 (interactive "r")
22589 (save-excursion
22590 (goto-char start)
22591 (skip-chars-forward " \r\t\n")
22592 (unless (eobp) (beginning-of-line))
22593 (let ((indent-to
22594 (lambda (ind pos)
22595 ;; Set IND as indentation for all lines between point and
22596 ;; POS or END, whichever comes first. Blank lines are
22597 ;; ignored. Leave point after POS once done.
22598 (let ((limit (copy-marker (min end pos))))
22599 (while (< (point) limit)
22600 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22601 (forward-line))
22602 (set-marker limit nil))))
22603 (end (copy-marker end)))
22604 (while (< (point) end)
22605 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22606 (let* ((element (org-element-at-point))
22607 (type (org-element-type element))
22608 (element-end (copy-marker (org-element-property :end element)))
22609 (ind (org--get-expected-indentation element nil)))
22610 (cond
22611 ((or (memq type '(paragraph table table-row))
22612 (not (or (org-element-property :contents-begin element)
22613 (memq type
22614 '(example-block export-block src-block)))))
22615 ;; Elements here are indented as a single block. Also
22616 ;; align node properties.
22617 (when (eq type 'node-property)
22618 (org--align-node-property)
22619 (beginning-of-line))
22620 (funcall indent-to ind element-end))
22622 ;; Elements in this category consist of three parts:
22623 ;; before the contents, the contents, and after the
22624 ;; contents. The contents are treated specially,
22625 ;; according to the element type, or not indented at
22626 ;; all. Other parts are indented as a single block.
22627 (let* ((post (copy-marker
22628 (org-element-property :post-affiliated element)))
22629 (cbeg
22630 (copy-marker
22631 (cond
22632 ((not (org-element-property :contents-begin element))
22633 ;; Fake contents for source blocks.
22634 (org-with-wide-buffer
22635 (goto-char post)
22636 (forward-line)
22637 (point)))
22638 ((memq type '(footnote-definition item plain-list))
22639 ;; Contents in these elements could start on
22640 ;; the same line as the beginning of the
22641 ;; element. Make sure we start indenting
22642 ;; from the second line.
22643 (org-with-wide-buffer
22644 (goto-char post)
22645 (end-of-line)
22646 (skip-chars-forward " \r\t\n")
22647 (if (eobp) (point) (line-beginning-position))))
22648 (t (org-element-property :contents-begin element)))))
22649 (cend (copy-marker
22650 (or (org-element-property :contents-end element)
22651 ;; Fake contents for source blocks.
22652 (org-with-wide-buffer
22653 (goto-char element-end)
22654 (skip-chars-backward " \r\t\n")
22655 (line-beginning-position))))))
22656 ;; Do not change items indentation individually as it
22657 ;; might break the list as a whole. On the other
22658 ;; hand, when at a plain list, indent it as a whole.
22659 (cond ((eq type 'plain-list)
22660 (let ((offset (- ind (org-get-indentation))))
22661 (unless (zerop offset)
22662 (indent-rigidly (org-element-property :begin element)
22663 (org-element-property :end element)
22664 offset))
22665 (goto-char cbeg)))
22666 ((eq type 'item) (goto-char cbeg))
22667 (t (funcall indent-to ind cbeg)))
22668 (when (< (point) end)
22669 (case type
22670 ((example-block export-block verse-block))
22671 (src-block
22672 ;; In a source block, indent source code
22673 ;; according to language major mode, but only if
22674 ;; `org-src-tab-acts-natively' is non-nil.
22675 (when (and (< (point) end) org-src-tab-acts-natively)
22676 (ignore-errors
22677 (let (org-src-strip-leading-and-trailing-blank-lines
22678 ;; Region boundaries in edit buffer.
22679 (start (1+ (- (point) cbeg)))
22680 (end (- (min cend end) cbeg)))
22681 (org-babel-do-in-edit-buffer
22682 (indent-region start end))))))
22683 (t (org-indent-region (point) (min cend end))))
22684 (goto-char (min cend end))
22685 (when (< (point) end) (funcall indent-to ind element-end)))
22686 (set-marker post nil)
22687 (set-marker cbeg nil)
22688 (set-marker cend nil))))
22689 (set-marker element-end nil))))
22690 (set-marker end nil))))
22692 (defun org-indent-drawer ()
22693 "Indent the drawer at point."
22694 (interactive)
22695 (unless (save-excursion
22696 (beginning-of-line)
22697 (org-looking-at-p org-drawer-regexp))
22698 (user-error "Not at a drawer"))
22699 (let ((element (org-element-at-point)))
22700 (unless (memq (org-element-type element) '(drawer property-drawer))
22701 (user-error "Not at a drawer"))
22702 (org-with-wide-buffer
22703 (org-indent-region (org-element-property :begin element)
22704 (org-element-property :end element))))
22705 (message "Drawer at point indented"))
22707 (defun org-indent-block ()
22708 "Indent the block at point."
22709 (interactive)
22710 (unless (save-excursion
22711 (beginning-of-line)
22712 (let ((case-fold-search t))
22713 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22714 (user-error "Not at a block"))
22715 (let ((element (org-element-at-point)))
22716 (unless (memq (org-element-type element)
22717 '(comment-block center-block dynamic-block example-block
22718 export-block quote-block special-block
22719 src-block verse-block))
22720 (user-error "Not at a block"))
22721 (org-with-wide-buffer
22722 (org-indent-region (org-element-property :begin element)
22723 (org-element-property :end element))))
22724 (message "Block at point indented"))
22727 ;;; Filling
22729 ;; We use our own fill-paragraph and auto-fill functions.
22731 ;; `org-fill-paragraph' relies on adaptive filling and context
22732 ;; checking. Appropriate `fill-prefix' is computed with
22733 ;; `org-adaptive-fill-function'.
22735 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22736 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22737 ;; `org-adaptive-fill-function' value. Internally,
22738 ;; `org-comment-line-break-function' breaks the line.
22740 ;; `org-setup-filling' installs filling and auto-filling related
22741 ;; variables during `org-mode' initialization.
22743 (defvar org-element-paragraph-separate) ; org-element.el
22744 (defun org-setup-filling ()
22745 (require 'org-element)
22746 ;; Prevent auto-fill from inserting unwanted new items.
22747 (when (boundp 'fill-nobreak-predicate)
22748 (org-set-local
22749 'fill-nobreak-predicate
22750 (org-uniquify
22751 (append fill-nobreak-predicate
22752 '(org-fill-line-break-nobreak-p
22753 org-fill-paragraph-with-timestamp-nobreak-p)))))
22754 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22755 (org-set-local 'paragraph-start paragraph-ending)
22756 (org-set-local 'paragraph-separate paragraph-ending))
22757 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22758 (org-set-local 'auto-fill-inhibit-regexp nil)
22759 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22760 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22761 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22763 (defun org-fill-line-break-nobreak-p ()
22764 "Non-nil when a new line at point would create an Org line break."
22765 (save-excursion
22766 (skip-chars-backward "[ \t]")
22767 (skip-chars-backward "\\\\")
22768 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22770 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22771 "Non-nil when a new line at point would split a timestamp."
22772 (and (org-at-timestamp-p t)
22773 (not (looking-at org-ts-regexp-both))))
22775 (declare-function message-in-body-p "message" ())
22776 (defvar orgtbl-line-start-regexp) ; From org-table.el
22777 (defun org-adaptive-fill-function ()
22778 "Compute a fill prefix for the current line.
22779 Return fill prefix, as a string, or nil if current line isn't
22780 meant to be filled. For convenience, if `adaptive-fill-regexp'
22781 matches in paragraphs or comments, use it."
22782 (catch 'exit
22783 (when (derived-mode-p 'message-mode)
22784 (save-excursion
22785 (beginning-of-line)
22786 (cond ((or (not (message-in-body-p))
22787 (looking-at orgtbl-line-start-regexp))
22788 (throw 'exit nil))
22789 ((looking-at message-cite-prefix-regexp)
22790 (throw 'exit (match-string-no-properties 0)))
22791 ((looking-at org-outline-regexp)
22792 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22793 (org-with-wide-buffer
22794 (unless (org-at-heading-p)
22795 (let* ((p (line-beginning-position))
22796 (element (save-excursion
22797 (beginning-of-line)
22798 (org-element-at-point)))
22799 (type (org-element-type element))
22800 (post-affiliated (org-element-property :post-affiliated element)))
22801 (unless (< p post-affiliated)
22802 (case type
22803 (comment
22804 (save-excursion
22805 (beginning-of-line)
22806 (looking-at "[ \t]*")
22807 (concat (match-string 0) "# ")))
22808 (footnote-definition "")
22809 ((item plain-list)
22810 (make-string (org-list-item-body-column post-affiliated) ?\s))
22811 (paragraph
22812 ;; Fill prefix is usually the same as the current line,
22813 ;; unless the paragraph is at the beginning of an item.
22814 (let ((parent (org-element-property :parent element)))
22815 (save-excursion
22816 (beginning-of-line)
22817 (cond ((eq (org-element-type parent) 'item)
22818 (make-string (org-list-item-body-column
22819 (org-element-property :begin parent))
22820 ?\s))
22821 ((and adaptive-fill-regexp
22822 ;; Locally disable
22823 ;; `adaptive-fill-function' to let
22824 ;; `fill-context-prefix' handle
22825 ;; `adaptive-fill-regexp' variable.
22826 (let (adaptive-fill-function)
22827 (fill-context-prefix
22828 post-affiliated
22829 (org-element-property :end element)))))
22830 ((looking-at "[ \t]+") (match-string 0))
22831 (t "")))))
22832 (comment-block
22833 ;; Only fill contents if P is within block boundaries.
22834 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22835 (forward-line)
22836 (point)))
22837 (cend (save-excursion
22838 (goto-char (org-element-property :end element))
22839 (skip-chars-backward " \r\t\n")
22840 (line-beginning-position))))
22841 (when (and (>= p cbeg) (< p cend))
22842 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22843 (match-string 0)
22844 "")))))))))))
22846 (declare-function message-goto-body "message" ())
22847 (defvar message-cite-prefix-regexp) ; From message.el
22848 (defun org-fill-paragraph (&optional justify)
22849 "Fill element at point, when applicable.
22851 This function only applies to comment blocks, comments, example
22852 blocks and paragraphs. Also, as a special case, re-align table
22853 when point is at one.
22855 If JUSTIFY is non-nil (interactively, with prefix argument),
22856 justify as well. If `sentence-end-double-space' is non-nil, then
22857 period followed by one space does not end a sentence, so don't
22858 break a line there. The variable `fill-column' controls the
22859 width for filling.
22861 For convenience, when point is at a plain list, an item or
22862 a footnote definition, try to fill the first paragraph within."
22863 (interactive)
22864 (if (and (derived-mode-p 'message-mode)
22865 (or (not (message-in-body-p))
22866 (save-excursion (move-beginning-of-line 1)
22867 (looking-at message-cite-prefix-regexp))))
22868 ;; First ensure filling is correct in message-mode.
22869 (let ((fill-paragraph-function
22870 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22871 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22872 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22873 (paragraph-separate
22874 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22875 (fill-paragraph nil))
22876 (with-syntax-table org-mode-transpose-word-syntax-table
22877 ;; Move to end of line in order to get the first paragraph
22878 ;; within a plain list or a footnote definition.
22879 (let ((element (save-excursion
22880 (end-of-line)
22881 (or (ignore-errors (org-element-at-point))
22882 (user-error "An element cannot be parsed line %d"
22883 (line-number-at-pos (point)))))))
22884 ;; First check if point is in a blank line at the beginning of
22885 ;; the buffer. In that case, ignore filling.
22886 (case (org-element-type element)
22887 ;; Use major mode filling function is src blocks.
22888 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22889 ;; Align Org tables, leave table.el tables as-is.
22890 (table-row (org-table-align) t)
22891 (table
22892 (when (eq (org-element-property :type element) 'org)
22893 (save-excursion
22894 (goto-char (org-element-property :post-affiliated element))
22895 (org-table-align)))
22897 (paragraph
22898 ;; Paragraphs may contain `line-break' type objects.
22899 (let ((beg (max (point-min)
22900 (org-element-property :contents-begin element)))
22901 (end (min (point-max)
22902 (org-element-property :contents-end element))))
22903 ;; Do nothing if point is at an affiliated keyword.
22904 (if (< (line-end-position) beg) t
22905 (when (derived-mode-p 'message-mode)
22906 ;; In `message-mode', do not fill following citation
22907 ;; in current paragraph nor text before message body.
22908 (let ((body-start (save-excursion (message-goto-body))))
22909 (when body-start (setq beg (max body-start beg))))
22910 (when (save-excursion
22911 (re-search-forward
22912 (concat "^" message-cite-prefix-regexp) end t))
22913 (setq end (match-beginning 0))))
22914 ;; Fill paragraph, taking line breaks into account.
22915 (save-excursion
22916 (goto-char beg)
22917 (let ((cuts (list beg)))
22918 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22919 (when (eq 'line-break
22920 (org-element-type
22921 (save-excursion (backward-char)
22922 (org-element-context))))
22923 (push (point) cuts)))
22924 (dolist (c (delq end cuts))
22925 (fill-region-as-paragraph c end justify)
22926 (setq end c))))
22927 t)))
22928 ;; Contents of `comment-block' type elements should be
22929 ;; filled as plain text, but only if point is within block
22930 ;; markers.
22931 (comment-block
22932 (let* ((case-fold-search t)
22933 (beg (save-excursion
22934 (goto-char (org-element-property :begin element))
22935 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22936 (forward-line)
22937 (point)))
22938 (end (save-excursion
22939 (goto-char (org-element-property :end element))
22940 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22941 (line-beginning-position))))
22942 (if (or (< (point) beg) (> (point) end)) t
22943 (fill-region-as-paragraph
22944 (save-excursion (end-of-line)
22945 (re-search-backward "^[ \t]*$" beg 'move)
22946 (line-beginning-position))
22947 (save-excursion (beginning-of-line)
22948 (re-search-forward "^[ \t]*$" end 'move)
22949 (line-beginning-position))
22950 justify))))
22951 ;; Fill comments.
22952 (comment
22953 (let ((begin (org-element-property :post-affiliated element))
22954 (end (org-element-property :end element)))
22955 (when (and (>= (point) begin) (<= (point) end))
22956 (let ((begin (save-excursion
22957 (end-of-line)
22958 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22959 (progn (forward-line) (point))
22960 begin)))
22961 (end (save-excursion
22962 (end-of-line)
22963 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22964 (1- (line-beginning-position))
22965 (skip-chars-backward " \r\t\n")
22966 (line-end-position)))))
22967 ;; Do not fill comments when at a blank line.
22968 (when (> end begin)
22969 (let ((fill-prefix
22970 (save-excursion
22971 (beginning-of-line)
22972 (looking-at "[ \t]*#")
22973 (let ((comment-prefix (match-string 0)))
22974 (goto-char (match-end 0))
22975 (if (looking-at adaptive-fill-regexp)
22976 (concat comment-prefix (match-string 0))
22977 (concat comment-prefix " "))))))
22978 (save-excursion
22979 (fill-region-as-paragraph begin end justify))))))
22981 ;; Ignore every other element.
22982 (otherwise t))))))
22984 (defun org-auto-fill-function ()
22985 "Auto-fill function."
22986 ;; Check if auto-filling is meaningful.
22987 (let ((fc (current-fill-column)))
22988 (when (and fc (> (current-column) fc))
22989 (let* ((fill-prefix (org-adaptive-fill-function))
22990 ;; Enforce empty fill prefix, if required. Otherwise, it
22991 ;; will be computed again.
22992 (adaptive-fill-mode (not (equal fill-prefix ""))))
22993 (when fill-prefix (do-auto-fill))))))
22995 (defun org-comment-line-break-function (&optional soft)
22996 "Break line at point and indent, continuing comment if within one.
22997 The inserted newline is marked hard if variable
22998 `use-hard-newlines' is true, unless optional argument SOFT is
22999 non-nil."
23000 (if soft (insert-and-inherit ?\n) (newline 1))
23001 (save-excursion (forward-char -1) (delete-horizontal-space))
23002 (delete-horizontal-space)
23003 (indent-to-left-margin)
23004 (insert-before-markers-and-inherit fill-prefix))
23007 ;;; Fixed Width Areas
23009 (defun org-toggle-fixed-width ()
23010 "Toggle fixed-width markup.
23012 Add or remove fixed-width markup on current line, whenever it
23013 makes sense. Return an error otherwise.
23015 If a region is active and if it contains only fixed-width areas
23016 or blank lines, remove all fixed-width markup in it. If the
23017 region contains anything else, convert all non-fixed-width lines
23018 to fixed-width ones.
23020 Blank lines at the end of the region are ignored unless the
23021 region only contains such lines."
23022 (interactive)
23023 (if (not (org-region-active-p))
23024 ;; No region:
23026 ;; Remove fixed width marker only in a fixed-with element.
23028 ;; Add fixed width maker in paragraphs, in blank lines after
23029 ;; elements or at the beginning of a headline or an inlinetask,
23030 ;; and before any one-line elements (e.g., a clock).
23031 (progn
23032 (beginning-of-line)
23033 (let* ((element (org-element-at-point))
23034 (type (org-element-type element)))
23035 (cond
23036 ((and (eq type 'fixed-width)
23037 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23038 (replace-match
23039 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23040 ((and (memq type '(babel-call clock comment diary-sexp headline
23041 horizontal-rule keyword paragraph
23042 planning))
23043 (<= (org-element-property :post-affiliated element) (point)))
23044 (skip-chars-forward " \t")
23045 (insert ": "))
23046 ((and (org-looking-at-p "[ \t]*$")
23047 (or (eq type 'inlinetask)
23048 (save-excursion
23049 (skip-chars-forward " \r\t\n")
23050 (<= (org-element-property :end element) (point)))))
23051 (delete-region (point) (line-end-position))
23052 (org-indent-line)
23053 (insert ": "))
23054 (t (user-error "Cannot insert a fixed-width line here")))))
23055 ;; Region active.
23056 (let* ((begin (save-excursion
23057 (goto-char (region-beginning))
23058 (line-beginning-position)))
23059 (end (copy-marker
23060 (save-excursion
23061 (goto-char (region-end))
23062 (unless (eolp) (beginning-of-line))
23063 (if (save-excursion (re-search-backward "\\S-" begin t))
23064 (progn (skip-chars-backward " \r\t\n") (point))
23065 (point)))))
23066 (all-fixed-width-p
23067 (catch 'not-all-p
23068 (save-excursion
23069 (goto-char begin)
23070 (skip-chars-forward " \r\t\n")
23071 (when (eobp) (throw 'not-all-p nil))
23072 (while (< (point) end)
23073 (let ((element (org-element-at-point)))
23074 (if (eq (org-element-type element) 'fixed-width)
23075 (goto-char (org-element-property :end element))
23076 (throw 'not-all-p nil))))
23077 t))))
23078 (if all-fixed-width-p
23079 (save-excursion
23080 (goto-char begin)
23081 (while (< (point) end)
23082 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23083 (replace-match
23084 "" nil nil nil
23085 (if (= (line-end-position) (match-end 0)) 0 1)))
23086 (forward-line)))
23087 (let ((min-ind (point-max)))
23088 ;; Find minimum indentation across all lines.
23089 (save-excursion
23090 (goto-char begin)
23091 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23092 (setq min-ind 0)
23093 (catch 'zerop
23094 (while (< (point) end)
23095 (unless (org-looking-at-p "[ \t]*$")
23096 (let ((ind (org-get-indentation)))
23097 (setq min-ind (min min-ind ind))
23098 (when (zerop ind) (throw 'zerop t))))
23099 (forward-line)))))
23100 ;; Loop over all lines and add fixed-width markup everywhere
23101 ;; but in fixed-width lines.
23102 (save-excursion
23103 (goto-char begin)
23104 (while (< (point) end)
23105 (cond
23106 ((org-at-heading-p)
23107 (insert ": ")
23108 (forward-line)
23109 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23110 (insert ":")
23111 (forward-line)))
23112 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23113 (let* ((element (org-element-at-point))
23114 (element-end (org-element-property :end element)))
23115 (if (eq (org-element-type element) 'fixed-width)
23116 (progn (goto-char element-end)
23117 (skip-chars-backward " \r\t\n")
23118 (forward-line))
23119 (let ((limit (min end element-end)))
23120 (while (< (point) limit)
23121 (org-move-to-column min-ind t)
23122 (insert ": ")
23123 (forward-line))))))
23125 (org-move-to-column min-ind t)
23126 (insert ": ")
23127 (forward-line)))))))
23128 (set-marker end nil))))
23131 ;;; Comments
23133 ;; Org comments syntax is quite complex. It requires the entire line
23134 ;; to be just a comment. Also, even with the right syntax at the
23135 ;; beginning of line, some some elements (i.e. verse-block or
23136 ;; example-block) don't accept comments. Usual Emacs comment commands
23137 ;; cannot cope with those requirements. Therefore, Org replaces them.
23139 ;; Org still relies on `comment-dwim', but cannot trust
23140 ;; `comment-only-p'. So, `comment-region-function' and
23141 ;; `uncomment-region-function' both point
23142 ;; to`org-comment-or-uncomment-region'. Eventually,
23143 ;; `org-insert-comment' takes care of insertion of comments at the
23144 ;; beginning of line.
23146 ;; `org-setup-comments-handling' install comments related variables
23147 ;; during `org-mode' initialization.
23149 (defun org-setup-comments-handling ()
23150 (interactive)
23151 (org-set-local 'comment-use-syntax nil)
23152 (org-set-local 'comment-start "# ")
23153 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23154 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23155 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23156 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23158 (defun org-insert-comment ()
23159 "Insert an empty comment above current line.
23160 If the line is empty, insert comment at its beginning. When
23161 point is within a source block, comment according to the related
23162 major mode."
23163 (if (let ((element (org-element-at-point)))
23164 (and (eq (org-element-type element) 'src-block)
23165 (< (save-excursion
23166 (goto-char (org-element-property :post-affiliated element))
23167 (line-end-position))
23168 (point))
23169 (> (save-excursion
23170 (goto-char (org-element-property :end element))
23171 (skip-chars-backward " \r\t\n")
23172 (line-beginning-position))
23173 (point))))
23174 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23175 (beginning-of-line)
23176 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23177 (open-line 1))
23178 (org-indent-line)
23179 (insert "# ")))
23181 (defvar comment-empty-lines) ; From newcomment.el.
23182 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23183 "Comment or uncomment each non-blank line in the region.
23184 Uncomment each non-blank line between BEG and END if it only
23185 contains commented lines. Otherwise, comment them. If region is
23186 strictly within a source block, use appropriate comment syntax."
23187 (if (let ((element (org-element-at-point)))
23188 (and (eq (org-element-type element) 'src-block)
23189 (< (save-excursion
23190 (goto-char (org-element-property :post-affiliated element))
23191 (line-end-position))
23192 beg)
23193 (>= (save-excursion
23194 (goto-char (org-element-property :end element))
23195 (skip-chars-backward " \r\t\n")
23196 (line-beginning-position))
23197 end)))
23198 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23199 (save-restriction
23200 ;; Restrict region
23201 (narrow-to-region (save-excursion (goto-char beg)
23202 (skip-chars-forward " \r\t\n" end)
23203 (line-beginning-position))
23204 (save-excursion (goto-char end)
23205 (skip-chars-backward " \r\t\n" beg)
23206 (line-end-position)))
23207 (let ((uncommentp
23208 ;; UNCOMMENTP is non-nil when every non blank line between
23209 ;; BEG and END is a comment.
23210 (save-excursion
23211 (goto-char (point-min))
23212 (while (and (not (eobp))
23213 (let ((element (org-element-at-point)))
23214 (and (eq (org-element-type element) 'comment)
23215 (goto-char (min (point-max)
23216 (org-element-property
23217 :end element)))))))
23218 (eobp))))
23219 (if uncommentp
23220 ;; Only blank lines and comments in region: uncomment it.
23221 (save-excursion
23222 (goto-char (point-min))
23223 (while (not (eobp))
23224 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23225 (replace-match "" nil nil nil 1))
23226 (forward-line)))
23227 ;; Comment each line in region.
23228 (let ((min-indent (point-max)))
23229 ;; First find the minimum indentation across all lines.
23230 (save-excursion
23231 (goto-char (point-min))
23232 (while (and (not (eobp)) (not (zerop min-indent)))
23233 (unless (looking-at "[ \t]*$")
23234 (setq min-indent (min min-indent (current-indentation))))
23235 (forward-line)))
23236 ;; Then loop over all lines.
23237 (save-excursion
23238 (goto-char (point-min))
23239 (while (not (eobp))
23240 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23241 ;; Don't get fooled by invisible text (e.g. link path)
23242 ;; when moving to column MIN-INDENT.
23243 (let ((buffer-invisibility-spec nil))
23244 (org-move-to-column min-indent t))
23245 (insert comment-start))
23246 (forward-line)))))))))
23248 (defun org-comment-dwim (arg)
23249 "Call `comment-dwim' within a source edit buffer if needed."
23250 (interactive "*P")
23251 (if (org-in-src-block-p)
23252 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23253 (call-interactively 'comment-dwim)))
23256 ;;; Planning
23258 ;; This section contains tools to operate on timestamp objects, as
23259 ;; returned by, e.g. `org-element-context'.
23261 (defun org-timestamp-has-time-p (timestamp)
23262 "Non-nil when TIMESTAMP has a time specified."
23263 (org-element-property :hour-start timestamp))
23265 (defun org-timestamp-format (timestamp format &optional end utc)
23266 "Format a TIMESTAMP element into a string.
23268 FORMAT is a format specifier to be passed to
23269 `format-time-string'.
23271 When optional argument END is non-nil, use end of date-range or
23272 time-range, if possible.
23274 When optional argument UTC is non-nil, time will be expressed as
23275 Universal Time."
23276 (format-time-string
23277 format
23278 (apply 'encode-time
23279 (cons 0
23280 (mapcar
23281 (lambda (prop) (or (org-element-property prop timestamp) 0))
23282 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23283 '(:minute-start :hour-start :day-start :month-start
23284 :year-start)))))
23285 utc))
23287 (defun org-timestamp-split-range (timestamp &optional end)
23288 "Extract a timestamp object from a date or time range.
23290 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23291 the end of the range. Otherwise, extract its start.
23293 Return a new timestamp object sharing the same parent as
23294 TIMESTAMP."
23295 (let ((type (org-element-property :type timestamp)))
23296 (if (memq type '(active inactive diary)) timestamp
23297 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23298 ;; Set new type.
23299 (org-element-put-property
23300 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23301 ;; Copy start properties over end properties if END is
23302 ;; non-nil. Otherwise, copy end properties over `start' ones.
23303 (let ((p-alist '((:minute-start . :minute-end)
23304 (:hour-start . :hour-end)
23305 (:day-start . :day-end)
23306 (:month-start . :month-end)
23307 (:year-start . :year-end))))
23308 (dolist (p-cell p-alist)
23309 (org-element-put-property
23310 split-ts
23311 (funcall (if end 'car 'cdr) p-cell)
23312 (org-element-property
23313 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23314 ;; Eventually refresh `:raw-value'.
23315 (org-element-put-property split-ts :raw-value nil)
23316 (org-element-put-property
23317 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23319 (defun org-timestamp-translate (timestamp &optional boundary)
23320 "Apply `org-translate-time' on a TIMESTAMP object.
23321 When optional argument BOUNDARY is non-nil, it is either the
23322 symbol `start' or `end'. In this case, only translate the
23323 starting or ending part of TIMESTAMP if it is a date or time
23324 range. Otherwise, translate both parts."
23325 (if (and (not boundary)
23326 (memq (org-element-property :type timestamp)
23327 '(active-range inactive-range)))
23328 (concat
23329 (org-translate-time
23330 (org-element-property :raw-value
23331 (org-timestamp-split-range timestamp)))
23332 "--"
23333 (org-translate-time
23334 (org-element-property :raw-value
23335 (org-timestamp-split-range timestamp t))))
23336 (org-translate-time
23337 (org-element-property
23338 :raw-value
23339 (if (not boundary) timestamp
23340 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23344 ;;; Other stuff.
23346 (defun org-reftex-citation ()
23347 "Use reftex-citation to insert a citation into the buffer.
23348 This looks for a line like
23350 #+BIBLIOGRAPHY: foo plain option:-d
23352 and derives from it that foo.bib is the bibliography file relevant
23353 for this document. It then installs the necessary environment for RefTeX
23354 to work in this buffer and calls `reftex-citation' to insert a citation
23355 into the buffer.
23357 Export of such citations to both LaTeX and HTML is handled by the contributed
23358 package ox-bibtex by Taru Karttunen."
23359 (interactive)
23360 (let ((reftex-docstruct-symbol 'rds)
23361 (reftex-cite-format "\\cite{%l}")
23362 rds bib)
23363 (save-excursion
23364 (save-restriction
23365 (widen)
23366 (let ((case-fold-search t)
23367 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23368 (if (not (save-excursion
23369 (or (re-search-forward re nil t)
23370 (re-search-backward re nil t))))
23371 (user-error "No bibliography defined in file")
23372 (setq bib (concat (match-string 1) ".bib")
23373 rds (list (list 'bib bib)))))))
23374 (call-interactively 'reftex-citation)))
23376 ;;;; Functions extending outline functionality
23378 (defun org-beginning-of-line (&optional arg)
23379 "Go to the beginning of the current line. If that is invisible, continue
23380 to a visible line beginning. This makes the function of C-a more intuitive.
23381 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23382 first attempt, and only move to after the tags when the cursor is already
23383 beyond the end of the headline."
23384 (interactive "P")
23385 (let ((pos (point))
23386 (special (if (consp org-special-ctrl-a/e)
23387 (car org-special-ctrl-a/e)
23388 org-special-ctrl-a/e))
23389 deactivate-mark refpos)
23390 (if (org-bound-and-true-p visual-line-mode)
23391 (beginning-of-visual-line 1)
23392 (beginning-of-line 1))
23393 (if (and arg (fboundp 'move-beginning-of-line))
23394 (call-interactively 'move-beginning-of-line)
23395 (if (bobp)
23397 (backward-char 1)
23398 (if (org-truely-invisible-p)
23399 (while (and (not (bobp)) (org-truely-invisible-p))
23400 (backward-char 1)
23401 (beginning-of-line 1))
23402 (forward-char 1))))
23403 (when special
23404 (cond
23405 ((and (looking-at org-complex-heading-regexp)
23406 (= (char-after (match-end 1)) ?\ ))
23407 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23408 (point-at-eol)))
23409 (goto-char
23410 (if (eq special t)
23411 (cond ((> pos refpos) refpos)
23412 ((= pos (point)) refpos)
23413 (t (point)))
23414 (cond ((> pos (point)) (point))
23415 ((not (eq last-command this-command)) (point))
23416 (t refpos)))))
23417 ((org-at-item-p)
23418 ;; Being at an item and not looking at an the item means point
23419 ;; was previously moved to beginning of a visual line, which
23420 ;; doesn't contain the item. Therefore, do nothing special,
23421 ;; just stay here.
23422 (when (looking-at org-list-full-item-re)
23423 ;; Set special position at first white space character after
23424 ;; bullet, and check-box, if any.
23425 (let ((after-bullet
23426 (let ((box (match-end 3)))
23427 (if (not box) (match-end 1)
23428 (let ((after (char-after box)))
23429 (if (and after (= after ? )) (1+ box) box))))))
23430 ;; Special case: Move point to special position when
23431 ;; currently after it or at beginning of line.
23432 (if (eq special t)
23433 (when (or (> pos after-bullet) (= (point) pos))
23434 (goto-char after-bullet))
23435 ;; Reversed case: Move point to special position when
23436 ;; point was already at beginning of line and command is
23437 ;; repeated.
23438 (when (and (= (point) pos) (eq last-command this-command))
23439 (goto-char after-bullet))))))))
23440 (org-no-warnings
23441 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23442 (setq disable-point-adjustment
23443 (or (not (invisible-p (point)))
23444 (not (invisible-p (max (point-min) (1- (point))))))))
23446 (defun org-end-of-line (&optional arg)
23447 "Go to the end of the line.
23448 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23449 tags on the first attempt, and only move to after the tags when
23450 the cursor is already beyond the end of the headline."
23451 (interactive "P")
23452 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23453 org-special-ctrl-a/e))
23454 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23455 'end-of-visual-line)
23456 ((fboundp 'move-end-of-line) 'move-end-of-line)
23457 (t 'end-of-line)))
23458 deactivate-mark)
23459 (if (or (not special) arg) (call-interactively move-fun)
23460 (let* ((element (save-excursion (beginning-of-line)
23461 (org-element-at-point)))
23462 (type (org-element-type element)))
23463 (cond
23464 ((memq type '(headline inlinetask))
23465 (let ((pos (point)))
23466 (beginning-of-line 1)
23467 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23468 (if (eq special t)
23469 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23470 (goto-char (match-beginning 1))
23471 (goto-char (match-end 0)))
23472 (if (or (< pos (match-end 0))
23473 (not (eq this-command last-command)))
23474 (goto-char (match-end 0))
23475 (goto-char (match-beginning 1))))
23476 (call-interactively move-fun))))
23477 ((outline-invisible-p (line-end-position))
23478 ;; If element is hidden, `move-end-of-line' would put point
23479 ;; after it. Use `end-of-line' to stay on current line.
23480 (call-interactively 'end-of-line))
23481 (t (call-interactively move-fun)))))
23482 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23483 (setq disable-point-adjustment
23484 (or (not (invisible-p (point)))
23485 (not (invisible-p (max (point-min) (1- (point))))))))
23487 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23488 (define-key org-mode-map "\C-e" 'org-end-of-line)
23490 (defun org-backward-sentence (&optional arg)
23491 "Go to beginning of sentence, or beginning of table field.
23492 This will call `backward-sentence' or `org-table-beginning-of-field',
23493 depending on context."
23494 (interactive "P")
23495 (cond
23496 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23497 (t (call-interactively 'backward-sentence))))
23499 (defun org-forward-sentence (&optional arg)
23500 "Go to end of sentence, or end of table field.
23501 This will call `forward-sentence' or `org-table-end-of-field',
23502 depending on context."
23503 (interactive "P")
23504 (cond
23505 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23506 (t (call-interactively 'forward-sentence))))
23508 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23509 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23511 (defun org-kill-line (&optional arg)
23512 "Kill line, to tags or end of line."
23513 (interactive "P")
23514 (cond
23515 ((or (not org-special-ctrl-k)
23516 (bolp)
23517 (not (org-at-heading-p)))
23518 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23519 org-ctrl-k-protect-subtree)
23520 (if (or (eq org-ctrl-k-protect-subtree 'error)
23521 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23522 (user-error "C-k aborted as it would kill a hidden subtree")))
23523 (call-interactively
23524 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23525 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23526 (kill-region (point) (match-beginning 1))
23527 (org-set-tags nil t))
23528 (t (kill-region (point) (point-at-eol)))))
23530 (define-key org-mode-map "\C-k" 'org-kill-line)
23532 (defun org-yank (&optional arg)
23533 "Yank. If the kill is a subtree, treat it specially.
23534 This command will look at the current kill and check if is a single
23535 subtree, or a series of subtrees[1]. If it passes the test, and if the
23536 cursor is at the beginning of a line or after the stars of a currently
23537 empty headline, then the yank is handled specially. How exactly depends
23538 on the value of the following variables, both set by default.
23540 `org-yank-folded-subtrees'
23541 When set, the subtree(s) will be folded after insertion, but only
23542 if doing so would now swallow text after the yanked text.
23544 `org-yank-adjusted-subtrees'
23545 When set, the subtree will be promoted or demoted in order to
23546 fit into the local outline tree structure, which means that the
23547 level will be adjusted so that it becomes the smaller one of the
23548 two *visible* surrounding headings.
23550 Any prefix to this command will cause `yank' to be called directly with
23551 no special treatment. In particular, a simple \\[universal-argument] prefix \
23552 will just
23553 plainly yank the text as it is.
23555 \[1] The test checks if the first non-white line is a heading
23556 and if there are no other headings with fewer stars."
23557 (interactive "P")
23558 (org-yank-generic 'yank arg))
23560 (defun org-yank-generic (command arg)
23561 "Perform some yank-like command.
23563 This function implements the behavior described in the `org-yank'
23564 documentation. However, it has been generalized to work for any
23565 interactive command with similar behavior."
23567 ;; pretend to be command COMMAND
23568 (setq this-command command)
23570 (if arg
23571 (call-interactively command)
23573 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23574 (and (org-kill-is-subtree-p)
23575 (or (bolp)
23576 (and (looking-at "[ \t]*$")
23577 (string-match
23578 "\\`\\*+\\'"
23579 (buffer-substring (point-at-bol) (point)))))))
23580 swallowp)
23581 (cond
23582 ((and subtreep org-yank-folded-subtrees)
23583 (let ((beg (point))
23584 end)
23585 (if (and subtreep org-yank-adjusted-subtrees)
23586 (org-paste-subtree nil nil 'for-yank)
23587 (call-interactively command))
23589 (setq end (point))
23590 (goto-char beg)
23591 (when (and (bolp) subtreep
23592 (not (setq swallowp
23593 (org-yank-folding-would-swallow-text beg end))))
23594 (org-with-limited-levels
23595 (or (looking-at org-outline-regexp)
23596 (re-search-forward org-outline-regexp-bol end t))
23597 (while (and (< (point) end) (looking-at org-outline-regexp))
23598 (hide-subtree)
23599 (org-cycle-show-empty-lines 'folded)
23600 (condition-case nil
23601 (outline-forward-same-level 1)
23602 (error (goto-char end))))))
23603 (when swallowp
23604 (message
23605 "Inserted text not folded because that would swallow text"))
23607 (goto-char end)
23608 (skip-chars-forward " \t\n\r")
23609 (beginning-of-line 1)
23610 (push-mark beg 'nomsg)))
23611 ((and subtreep org-yank-adjusted-subtrees)
23612 (let ((beg (point-at-bol)))
23613 (org-paste-subtree nil nil 'for-yank)
23614 (push-mark beg 'nomsg)))
23616 (call-interactively command))))))
23618 (defun org-yank-folding-would-swallow-text (beg end)
23619 "Would hide-subtree at BEG swallow any text after END?"
23620 (let (level)
23621 (org-with-limited-levels
23622 (save-excursion
23623 (goto-char beg)
23624 (when (or (looking-at org-outline-regexp)
23625 (re-search-forward org-outline-regexp-bol end t))
23626 (setq level (org-outline-level)))
23627 (goto-char end)
23628 (skip-chars-forward " \t\r\n\v\f")
23629 (if (or (eobp)
23630 (and (bolp) (looking-at org-outline-regexp)
23631 (<= (org-outline-level) level)))
23632 nil ; Nothing would be swallowed
23633 t))))) ; something would swallow
23635 (define-key org-mode-map "\C-y" 'org-yank)
23637 (defun org-truely-invisible-p ()
23638 "Check if point is at a character currently not visible.
23639 This version does not only check the character property, but also
23640 `visible-mode'."
23641 ;; Early versions of noutline don't have `outline-invisible-p'.
23642 (if (org-bound-and-true-p visible-mode)
23644 (outline-invisible-p)))
23646 (defun org-invisible-p2 ()
23647 "Check if point is at a character currently not visible."
23648 (save-excursion
23649 (if (and (eolp) (not (bobp))) (backward-char 1))
23650 ;; Early versions of noutline don't have `outline-invisible-p'.
23651 (outline-invisible-p)))
23653 (defun org-back-to-heading (&optional invisible-ok)
23654 "Call `outline-back-to-heading', but provide a better error message."
23655 (condition-case nil
23656 (outline-back-to-heading invisible-ok)
23657 (error (error "Before first headline at position %d in buffer %s"
23658 (point) (current-buffer)))))
23660 (defun org-before-first-heading-p ()
23661 "Before first heading?"
23662 (save-excursion
23663 (end-of-line)
23664 (null (re-search-backward org-outline-regexp-bol nil t))))
23666 (defun org-at-heading-p (&optional ignored)
23667 (outline-on-heading-p t))
23668 ;; Compatibility alias with Org versions < 7.8.03
23669 (defalias 'org-on-heading-p 'org-at-heading-p)
23671 (defun org-in-commented-heading-p (&optional no-inheritance)
23672 "Non-nil if point is under a commented heading.
23673 This function also checks ancestors of the current headline,
23674 unless optional argument NO-INHERITANCE is non-nil."
23675 (cond
23676 ((org-before-first-heading-p) nil)
23677 ((let ((headline (nth 4 (org-heading-components))))
23678 (and headline
23679 (let ((case-fold-search nil))
23680 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23681 headline)))))
23682 (no-inheritance nil)
23684 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23686 (defun org-at-comment-p nil
23687 "Is cursor in a commented line?"
23688 (save-excursion
23689 (save-match-data
23690 (beginning-of-line)
23691 (looking-at "^[ \t]*# "))))
23693 (defun org-at-drawer-p nil
23694 "Is cursor at a drawer keyword?"
23695 (save-excursion
23696 (move-beginning-of-line 1)
23697 (looking-at org-drawer-regexp)))
23699 (defun org-at-block-p nil
23700 "Is cursor at a block keyword?"
23701 (save-excursion
23702 (move-beginning-of-line 1)
23703 (looking-at org-block-regexp)))
23705 (defun org-point-at-end-of-empty-headline ()
23706 "If point is at the end of an empty headline, return t, else nil.
23707 If the heading only contains a TODO keyword, it is still still considered
23708 empty."
23709 (and (looking-at "[ \t]*$")
23710 (when org-todo-line-regexp
23711 (save-excursion
23712 (beginning-of-line 1)
23713 (let ((case-fold-search nil))
23714 (looking-at org-todo-line-regexp)
23715 (string= (match-string 3) ""))))))
23717 (defun org-at-heading-or-item-p ()
23718 (or (org-at-heading-p) (org-at-item-p)))
23720 (defun org-at-target-p ()
23721 (or (org-in-regexp org-radio-target-regexp)
23722 (org-in-regexp org-target-regexp)))
23723 ;; Compatibility alias with Org versions < 7.8.03
23724 (defalias 'org-on-target-p 'org-at-target-p)
23726 (defun org-up-heading-all (arg)
23727 "Move to the heading line of which the present line is a subheading.
23728 This function considers both visible and invisible heading lines.
23729 With argument, move up ARG levels."
23730 (if (fboundp 'outline-up-heading-all)
23731 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23732 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23734 (defun org-up-heading-safe ()
23735 "Move to the heading line of which the present line is a subheading.
23736 This version will not throw an error. It will return the level of the
23737 headline found, or nil if no higher level is found.
23739 Also, this function will be a lot faster than `outline-up-heading',
23740 because it relies on stars being the outline starters. This can really
23741 make a significant difference in outlines with very many siblings."
23742 (when (ignore-errors (org-back-to-heading t))
23743 (let ((level-up (1- (funcall outline-level))))
23744 (and (> level-up 0)
23745 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23746 (funcall outline-level)))))
23748 (defun org-first-sibling-p ()
23749 "Is this heading the first child of its parents?"
23750 (interactive)
23751 (let ((re org-outline-regexp-bol)
23752 level l)
23753 (unless (org-at-heading-p t)
23754 (user-error "Not at a heading"))
23755 (setq level (funcall outline-level))
23756 (save-excursion
23757 (if (not (re-search-backward re nil t))
23759 (setq l (funcall outline-level))
23760 (< l level)))))
23762 (defun org-goto-sibling (&optional previous)
23763 "Goto the next sibling, even if it is invisible.
23764 When PREVIOUS is set, go to the previous sibling instead. Returns t
23765 when a sibling was found. When none is found, return nil and don't
23766 move point."
23767 (let ((fun (if previous 're-search-backward 're-search-forward))
23768 (pos (point))
23769 (re org-outline-regexp-bol)
23770 level l)
23771 (when (ignore-errors (org-back-to-heading t))
23772 (setq level (funcall outline-level))
23773 (catch 'exit
23774 (or previous (forward-char 1))
23775 (while (funcall fun re nil t)
23776 (setq l (funcall outline-level))
23777 (when (< l level) (goto-char pos) (throw 'exit nil))
23778 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23779 (goto-char pos)
23780 nil))))
23782 (defun org-show-siblings ()
23783 "Show all siblings of the current headline."
23784 (save-excursion
23785 (while (org-goto-sibling) (org-flag-heading nil)))
23786 (save-excursion
23787 (while (org-goto-sibling 'previous)
23788 (org-flag-heading nil))))
23790 (defun org-goto-first-child ()
23791 "Goto the first child, even if it is invisible.
23792 Return t when a child was found. Otherwise don't move point and
23793 return nil."
23794 (let (level (pos (point)) (re org-outline-regexp-bol))
23795 (when (ignore-errors (org-back-to-heading t))
23796 (setq level (outline-level))
23797 (forward-char 1)
23798 (if (and (re-search-forward re nil t) (> (outline-level) level))
23799 (progn (goto-char (match-beginning 0)) t)
23800 (goto-char pos) nil))))
23802 (defun org-show-hidden-entry ()
23803 "Show an entry where even the heading is hidden."
23804 (save-excursion
23805 (org-show-entry)))
23807 (defun org-flag-heading (flag &optional entry)
23808 "Flag the current heading. FLAG non-nil means make invisible.
23809 When ENTRY is non-nil, show the entire entry."
23810 (save-excursion
23811 (org-back-to-heading t)
23812 ;; Check if we should show the entire entry
23813 (if entry
23814 (progn
23815 (org-show-entry)
23816 (save-excursion
23817 (and (outline-next-heading)
23818 (org-flag-heading nil))))
23819 (outline-flag-region (max (point-min) (1- (point)))
23820 (save-excursion (outline-end-of-heading) (point))
23821 flag))))
23823 (defun org-get-next-sibling ()
23824 "Move to next heading of the same level, and return point.
23825 If there is no such heading, return nil.
23826 This is like outline-next-sibling, but invisible headings are ok."
23827 (let ((level (funcall outline-level)))
23828 (outline-next-heading)
23829 (while (and (not (eobp)) (> (funcall outline-level) level))
23830 (outline-next-heading))
23831 (if (or (eobp) (< (funcall outline-level) level))
23833 (point))))
23835 (defun org-get-last-sibling ()
23836 "Move to previous heading of the same level, and return point.
23837 If there is no such heading, return nil."
23838 (let ((opoint (point))
23839 (level (funcall outline-level)))
23840 (outline-previous-heading)
23841 (when (and (/= (point) opoint) (outline-on-heading-p t))
23842 (while (and (> (funcall outline-level) level)
23843 (not (bobp)))
23844 (outline-previous-heading))
23845 (if (< (funcall outline-level) level)
23847 (point)))))
23849 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23850 "Goto to the end of a subtree."
23851 ;; This contains an exact copy of the original function, but it uses
23852 ;; `org-back-to-heading', to make it work also in invisible
23853 ;; trees. And is uses an invisible-ok argument.
23854 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23855 ;; Furthermore, when used inside Org, finding the end of a large subtree
23856 ;; with many children and grandchildren etc, this can be much faster
23857 ;; than the outline version.
23858 (org-back-to-heading invisible-ok)
23859 (let ((first t)
23860 (level (funcall outline-level)))
23861 (if (and (derived-mode-p 'org-mode) (< level 1000))
23862 ;; A true heading (not a plain list item), in Org-mode
23863 ;; This means we can easily find the end by looking
23864 ;; only for the right number of stars. Using a regexp to do
23865 ;; this is so much faster than using a Lisp loop.
23866 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23867 (forward-char 1)
23868 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23869 ;; something else, do it the slow way
23870 (while (and (not (eobp))
23871 (or first (> (funcall outline-level) level)))
23872 (setq first nil)
23873 (outline-next-heading)))
23874 (unless to-heading
23875 (if (memq (preceding-char) '(?\n ?\^M))
23876 (progn
23877 ;; Go to end of line before heading
23878 (forward-char -1)
23879 (if (memq (preceding-char) '(?\n ?\^M))
23880 ;; leave blank line before heading
23881 (forward-char -1))))))
23882 (point))
23884 (defun org-end-of-meta-data-and-drawers ()
23885 "Jump to the first text after meta data and drawers in the current entry.
23886 This will move over empty lines, lines with planning time stamps,
23887 clocking lines, and drawers."
23888 (org-back-to-heading t)
23889 (let ((end (save-excursion (outline-next-heading) (point)))
23890 (re (concat "\\(" org-drawer-regexp "\\)"
23891 "\\|" "[ \t]*" org-keyword-time-regexp)))
23892 (forward-line 1)
23893 (while (re-search-forward re end t)
23894 (if (not (match-end 1))
23895 ;; empty or planning line
23896 (forward-line 1)
23897 ;; a drawer, find the end
23898 (re-search-forward "^[ \t]*:END:" end 'move)
23899 (forward-line 1)))
23900 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23901 (point)))
23903 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23904 "Move forward to the ARG'th subheading at same level as this one.
23905 Stop at the first and last subheadings of a superior heading.
23906 Normally this only looks at visible headings, but when INVISIBLE-OK is
23907 non-nil it will also look at invisible ones."
23908 (interactive "p")
23909 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23910 (if (and arg (< arg 0))
23911 (goto-char (point-min))
23912 (outline-next-heading))
23913 (org-at-heading-p)
23914 (let ((level (- (match-end 0) (match-beginning 0) 1))
23915 (f (if (and arg (< arg 0))
23916 're-search-backward
23917 're-search-forward))
23918 (count (if arg (abs arg) 1))
23919 (result (point)))
23920 (while (and (prog1 (> count 0)
23921 (forward-char (if (and arg (< arg 0)) -1 1)))
23922 (funcall f org-outline-regexp-bol nil 'move))
23923 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23924 (cond ((< l level) (setq count 0))
23925 ((and (= l level)
23926 (or invisible-ok
23927 (progn
23928 (goto-char (line-beginning-position))
23929 (not (outline-invisible-p)))))
23930 (setq count (1- count))
23931 (when (eq l level)
23932 (setq result (point)))))))
23933 (goto-char result))
23934 (beginning-of-line 1)))
23936 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23937 "Move backward to the ARG'th subheading at same level as this one.
23938 Stop at the first and last subheadings of a superior heading."
23939 (interactive "p")
23940 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23942 (defun org-next-block (arg &optional backward block-regexp)
23943 "Jump to the next block.
23944 With a prefix argument ARG, jump forward ARG many source blocks.
23945 When BACKWARD is non-nil, jump to the previous block.
23946 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23947 (interactive "p")
23948 (let ((re (or block-regexp org-block-regexp))
23949 (re-search-fn (or (and backward 're-search-backward)
23950 're-search-forward)))
23951 (if (looking-at re) (forward-char 1))
23952 (condition-case nil
23953 (funcall re-search-fn re nil nil arg)
23954 (error (user-error "No %s code blocks"
23955 (if backward "previous" "further" ))))
23956 (goto-char (match-beginning 0)) (org-show-context)))
23958 (defun org-previous-block (arg &optional block-regexp)
23959 "Jump to the previous block.
23960 With a prefix argument ARG, jump backward ARG many source blocks.
23961 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23962 (interactive "p")
23963 (org-next-block arg t block-regexp))
23965 (defun org-forward-paragraph ()
23966 "Move forward to beginning of next paragraph or equivalent.
23968 The function moves point to the beginning of the next visible
23969 structural element, which can be a paragraph, a table, a list
23970 item, etc. It also provides some special moves for convenience:
23972 - On an affiliated keyword, jump to the beginning of the
23973 relative element.
23974 - On an item or a footnote definition, move to the second
23975 element inside, if any.
23976 - On a table or a property drawer, jump after it.
23977 - On a verse or source block, stop after blank lines."
23978 (interactive)
23979 (when (eobp) (user-error "Cannot move further down"))
23980 (let* ((deactivate-mark nil)
23981 (element (org-element-at-point))
23982 (type (org-element-type element))
23983 (post-affiliated (org-element-property :post-affiliated element))
23984 (contents-begin (org-element-property :contents-begin element))
23985 (contents-end (org-element-property :contents-end element))
23986 (end (let ((end (org-element-property :end element)) (parent element))
23987 (while (and (setq parent (org-element-property :parent parent))
23988 (= (org-element-property :contents-end parent) end))
23989 (setq end (org-element-property :end parent)))
23990 end)))
23991 (cond ((not element)
23992 (skip-chars-forward " \r\t\n")
23993 (or (eobp) (beginning-of-line)))
23994 ;; On affiliated keywords, move to element's beginning.
23995 ((< (point) post-affiliated)
23996 (goto-char post-affiliated))
23997 ;; At a table row, move to the end of the table. Similarly,
23998 ;; at a node property, move to the end of the property
23999 ;; drawer.
24000 ((memq type '(node-property table-row))
24001 (goto-char (org-element-property
24002 :end (org-element-property :parent element))))
24003 ((memq type '(property-drawer table)) (goto-char end))
24004 ;; Consider blank lines as separators in verse and source
24005 ;; blocks to ease editing.
24006 ((memq type '(src-block verse-block))
24007 (when (eq type 'src-block)
24008 (setq contents-end
24009 (save-excursion (goto-char end)
24010 (skip-chars-backward " \r\t\n")
24011 (line-beginning-position))))
24012 (beginning-of-line)
24013 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24014 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24015 (goto-char end)
24016 (skip-chars-forward " \r\t\n")
24017 (if (= (point) contents-end) (goto-char end)
24018 (beginning-of-line))))
24019 ;; With no contents, just skip element.
24020 ((not contents-begin) (goto-char end))
24021 ;; If contents are invisible, skip the element altogether.
24022 ((outline-invisible-p (line-end-position))
24023 (case type
24024 (headline
24025 (org-with-limited-levels (outline-next-visible-heading 1)))
24026 ;; At a plain list, make sure we move to the next item
24027 ;; instead of skipping the whole list.
24028 (plain-list (forward-char)
24029 (org-forward-paragraph))
24030 (otherwise (goto-char end))))
24031 ((>= (point) contents-end) (goto-char end))
24032 ((>= (point) contents-begin)
24033 ;; This can only happen on paragraphs and plain lists.
24034 (case type
24035 (paragraph (goto-char end))
24036 ;; At a plain list, try to move to second element in
24037 ;; first item, if possible.
24038 (plain-list (end-of-line)
24039 (org-forward-paragraph))))
24040 ;; When contents start on the middle of a line (e.g. in
24041 ;; items and footnote definitions), try to reach first
24042 ;; element starting after current line.
24043 ((> (line-end-position) contents-begin)
24044 (end-of-line)
24045 (org-forward-paragraph))
24046 (t (goto-char contents-begin)))))
24048 (defun org-backward-paragraph ()
24049 "Move backward to start of previous paragraph or equivalent.
24051 The function moves point to the beginning of the current
24052 structural element, which can be a paragraph, a table, a list
24053 item, etc., or to the beginning of the previous visible one if
24054 point is already there. It also provides some special moves for
24055 convenience:
24057 - On an affiliated keyword, jump to the first one.
24058 - On a table or a property drawer, move to its beginning.
24059 - On a verse or source block, stop before blank lines."
24060 (interactive)
24061 (when (bobp) (user-error "Cannot move further up"))
24062 (let* ((deactivate-mark nil)
24063 (element (org-element-at-point))
24064 (type (org-element-type element))
24065 (contents-begin (org-element-property :contents-begin element))
24066 (contents-end (org-element-property :contents-end element))
24067 (post-affiliated (org-element-property :post-affiliated element))
24068 (begin (org-element-property :begin element)))
24069 (cond
24070 ((not element) (goto-char (point-min)))
24071 ((= (point) begin)
24072 (backward-char)
24073 (org-backward-paragraph))
24074 ((<= (point) post-affiliated) (goto-char begin))
24075 ((memq type '(node-property table-row))
24076 (goto-char (org-element-property
24077 :post-affiliated (org-element-property :parent element))))
24078 ((memq type '(property-drawer table)) (goto-char begin))
24079 ((memq type '(src-block verse-block))
24080 (when (eq type 'src-block)
24081 (setq contents-begin
24082 (save-excursion (goto-char begin) (forward-line) (point))))
24083 (if (= (point) contents-begin) (goto-char post-affiliated)
24084 ;; Inside a verse block, see blank lines as paragraph
24085 ;; separators.
24086 (let ((origin (point)))
24087 (skip-chars-backward " \r\t\n" contents-begin)
24088 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24089 (skip-chars-forward " \r\t\n" origin)
24090 (if (= (point) origin) (goto-char contents-begin)
24091 (beginning-of-line))))))
24092 ((not contents-begin) (goto-char (or post-affiliated begin)))
24093 ((eq type 'paragraph)
24094 (goto-char contents-begin)
24095 ;; When at first paragraph in an item or a footnote definition,
24096 ;; move directly to beginning of line.
24097 (let ((parent-contents
24098 (org-element-property
24099 :contents-begin (org-element-property :parent element))))
24100 (when (and parent-contents (= parent-contents contents-begin))
24101 (beginning-of-line))))
24102 ;; At the end of a greater element, move to the beginning of the
24103 ;; last element within.
24104 ((>= (point) contents-end)
24105 (goto-char (1- contents-end))
24106 (org-backward-paragraph))
24107 (t (goto-char (or post-affiliated begin))))
24108 ;; Ensure we never leave point invisible.
24109 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24111 (defun org-forward-element ()
24112 "Move forward by one element.
24113 Move to the next element at the same level, when possible."
24114 (interactive)
24115 (cond ((eobp) (user-error "Cannot move further down"))
24116 ((org-with-limited-levels (org-at-heading-p))
24117 (let ((origin (point)))
24118 (goto-char (org-end-of-subtree nil t))
24119 (unless (org-with-limited-levels (org-at-heading-p))
24120 (goto-char origin)
24121 (user-error "Cannot move further down"))))
24123 (let* ((elem (org-element-at-point))
24124 (end (org-element-property :end elem))
24125 (parent (org-element-property :parent elem)))
24126 (cond ((and parent (= (org-element-property :contents-end parent) end))
24127 (goto-char (org-element-property :end parent)))
24128 ((integer-or-marker-p end) (goto-char end))
24129 (t (message "No element at point")))))))
24131 (defun org-backward-element ()
24132 "Move backward by one element.
24133 Move to the previous element at the same level, when possible."
24134 (interactive)
24135 (cond ((bobp) (user-error "Cannot move further up"))
24136 ((org-with-limited-levels (org-at-heading-p))
24137 ;; At a headline, move to the previous one, if any, or stay
24138 ;; here.
24139 (let ((origin (point)))
24140 (org-with-limited-levels (org-backward-heading-same-level 1))
24141 ;; When current headline has no sibling above, move to its
24142 ;; parent.
24143 (when (= (point) origin)
24144 (or (org-with-limited-levels (org-up-heading-safe))
24145 (progn (goto-char origin)
24146 (user-error "Cannot move further up"))))))
24148 (let* ((elem (org-element-at-point))
24149 (beg (org-element-property :begin elem)))
24150 (cond
24151 ;; Move to beginning of current element if point isn't
24152 ;; there already.
24153 ((null beg) (message "No element at point"))
24154 ((/= (point) beg) (goto-char beg))
24155 (t (goto-char beg)
24156 (skip-chars-backward " \r\t\n")
24157 (unless (bobp)
24158 (let ((prev (org-element-at-point)))
24159 (goto-char (org-element-property :begin prev))
24160 (while (and (setq prev (org-element-property :parent prev))
24161 (<= (org-element-property :end prev) beg))
24162 (goto-char (org-element-property :begin prev)))))))))))
24164 (defun org-up-element ()
24165 "Move to upper element."
24166 (interactive)
24167 (if (org-with-limited-levels (org-at-heading-p))
24168 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24169 (let* ((elem (org-element-at-point))
24170 (parent (org-element-property :parent elem)))
24171 (if parent (goto-char (org-element-property :begin parent))
24172 (if (org-with-limited-levels (org-before-first-heading-p))
24173 (user-error "No surrounding element")
24174 (org-with-limited-levels (org-back-to-heading)))))))
24176 (defvar org-element-greater-elements)
24177 (defun org-down-element ()
24178 "Move to inner element."
24179 (interactive)
24180 (let ((element (org-element-at-point)))
24181 (cond
24182 ((memq (org-element-type element) '(plain-list table))
24183 (goto-char (org-element-property :contents-begin element))
24184 (forward-char))
24185 ((memq (org-element-type element) org-element-greater-elements)
24186 ;; If contents are hidden, first disclose them.
24187 (when (outline-invisible-p (line-end-position)) (org-cycle))
24188 (goto-char (or (org-element-property :contents-begin element)
24189 (user-error "No content for this element"))))
24190 (t (user-error "No inner element")))))
24192 (defun org-drag-element-backward ()
24193 "Move backward element at point."
24194 (interactive)
24195 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24196 (let* ((elem (org-element-at-point))
24197 (prev-elem
24198 (save-excursion
24199 (goto-char (org-element-property :begin elem))
24200 (skip-chars-backward " \r\t\n")
24201 (unless (bobp)
24202 (let* ((beg (org-element-property :begin elem))
24203 (prev (org-element-at-point))
24204 (up prev))
24205 (while (and (setq up (org-element-property :parent up))
24206 (<= (org-element-property :end up) beg))
24207 (setq prev up))
24208 prev)))))
24209 ;; Error out if no previous element or previous element is
24210 ;; a parent of the current one.
24211 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24212 (user-error "Cannot drag element backward")
24213 (let ((pos (point)))
24214 (org-element-swap-A-B prev-elem elem)
24215 (goto-char (+ (org-element-property :begin prev-elem)
24216 (- pos (org-element-property :begin elem)))))))))
24218 (defun org-drag-element-forward ()
24219 "Move forward element at point."
24220 (interactive)
24221 (let* ((pos (point))
24222 (elem (org-element-at-point)))
24223 (when (= (point-max) (org-element-property :end elem))
24224 (user-error "Cannot drag element forward"))
24225 (goto-char (org-element-property :end elem))
24226 (let ((next-elem (org-element-at-point)))
24227 (when (or (org-element-nested-p elem next-elem)
24228 (and (eq (org-element-type next-elem) 'headline)
24229 (not (eq (org-element-type elem) 'headline))))
24230 (goto-char pos)
24231 (user-error "Cannot drag element forward"))
24232 ;; Compute new position of point: it's shifted by NEXT-ELEM
24233 ;; body's length (without final blanks) and by the length of
24234 ;; blanks between ELEM and NEXT-ELEM.
24235 (let ((size-next (- (save-excursion
24236 (goto-char (org-element-property :end next-elem))
24237 (skip-chars-backward " \r\t\n")
24238 (forward-line)
24239 ;; Small correction if buffer doesn't end
24240 ;; with a newline character.
24241 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24242 (org-element-property :begin next-elem)))
24243 (size-blank (- (org-element-property :end elem)
24244 (save-excursion
24245 (goto-char (org-element-property :end elem))
24246 (skip-chars-backward " \r\t\n")
24247 (forward-line)
24248 (point)))))
24249 (org-element-swap-A-B elem next-elem)
24250 (goto-char (+ pos size-next size-blank))))))
24252 (defun org-drag-line-forward (arg)
24253 "Drag the line at point ARG lines forward."
24254 (interactive "p")
24255 (dotimes (n (abs arg))
24256 (let ((c (current-column)))
24257 (if (< 0 arg)
24258 (progn
24259 (beginning-of-line 2)
24260 (transpose-lines 1)
24261 (beginning-of-line 0))
24262 (transpose-lines 1)
24263 (beginning-of-line -1))
24264 (org-move-to-column c))))
24266 (defun org-drag-line-backward (arg)
24267 "Drag the line at point ARG lines backward."
24268 (interactive "p")
24269 (org-drag-line-forward (- arg)))
24271 (defun org-mark-element ()
24272 "Put point at beginning of this element, mark at end.
24274 Interactively, if this command is repeated or (in Transient Mark
24275 mode) if the mark is active, it marks the next element after the
24276 ones already marked."
24277 (interactive)
24278 (let (deactivate-mark)
24279 (if (and (org-called-interactively-p 'any)
24280 (or (and (eq last-command this-command) (mark t))
24281 (and transient-mark-mode mark-active)))
24282 (set-mark
24283 (save-excursion
24284 (goto-char (mark))
24285 (goto-char (org-element-property :end (org-element-at-point)))))
24286 (let ((element (org-element-at-point)))
24287 (end-of-line)
24288 (push-mark (org-element-property :end element) t t)
24289 (goto-char (org-element-property :begin element))))))
24291 (defun org-narrow-to-element ()
24292 "Narrow buffer to current element."
24293 (interactive)
24294 (let ((elem (org-element-at-point)))
24295 (cond
24296 ((eq (car elem) 'headline)
24297 (narrow-to-region
24298 (org-element-property :begin elem)
24299 (org-element-property :end elem)))
24300 ((memq (car elem) org-element-greater-elements)
24301 (narrow-to-region
24302 (org-element-property :contents-begin elem)
24303 (org-element-property :contents-end elem)))
24305 (narrow-to-region
24306 (org-element-property :begin elem)
24307 (org-element-property :end elem))))))
24309 (defun org-transpose-element ()
24310 "Transpose current and previous elements, keeping blank lines between.
24311 Point is moved after both elements."
24312 (interactive)
24313 (org-skip-whitespace)
24314 (let ((end (org-element-property :end (org-element-at-point))))
24315 (org-drag-element-backward)
24316 (goto-char end)))
24318 (defun org-unindent-buffer ()
24319 "Un-indent the visible part of the buffer.
24320 Relative indentation (between items, inside blocks, etc.) isn't
24321 modified."
24322 (interactive)
24323 (unless (eq major-mode 'org-mode)
24324 (user-error "Cannot un-indent a buffer not in Org mode"))
24325 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24326 unindent-tree ; For byte-compiler.
24327 (unindent-tree
24328 (function
24329 (lambda (contents)
24330 (mapc
24331 (lambda (element)
24332 (if (memq (org-element-type element) '(headline section))
24333 (funcall unindent-tree (org-element-contents element))
24334 (save-excursion
24335 (save-restriction
24336 (narrow-to-region
24337 (org-element-property :begin element)
24338 (org-element-property :end element))
24339 (org-do-remove-indentation)))))
24340 (reverse contents))))))
24341 (funcall unindent-tree (org-element-contents parse-tree))))
24343 (defun org-show-subtree ()
24344 "Show everything after this heading at deeper levels."
24345 (interactive)
24346 (outline-flag-region
24347 (point)
24348 (save-excursion
24349 (org-end-of-subtree t t))
24350 nil))
24352 (defun org-show-entry ()
24353 "Show the body directly following this heading.
24354 Show the heading too, if it is currently invisible."
24355 (interactive)
24356 (save-excursion
24357 (ignore-errors
24358 (org-back-to-heading t)
24359 (outline-flag-region
24360 (max (point-min) (1- (point)))
24361 (save-excursion
24362 (if (re-search-forward
24363 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24364 (match-beginning 1)
24365 (point-max)))
24366 nil)
24367 (org-cycle-hide-drawers 'children))))
24369 (defun org-make-options-regexp (kwds &optional extra)
24370 "Make a regular expression for keyword lines."
24371 (concat
24372 "^[ \t]*#\\+\\("
24373 (mapconcat 'regexp-quote kwds "\\|")
24374 (if extra (concat "\\|" extra))
24375 "\\):[ \t]*\\(.*\\)"))
24377 ;; Make isearch reveal the necessary context
24378 (defun org-isearch-end ()
24379 "Reveal context after isearch exits."
24380 (when isearch-success ; only if search was successful
24381 (if (featurep 'xemacs)
24382 ;; Under XEmacs, the hook is run in the correct place,
24383 ;; we directly show the context.
24384 (org-show-context 'isearch)
24385 ;; In Emacs the hook runs *before* restoring the overlays.
24386 ;; So we have to use a one-time post-command-hook to do this.
24387 ;; (Emacs 22 has a special variable, see function `org-mode')
24388 (unless (and (boundp 'isearch-mode-end-hook-quit)
24389 isearch-mode-end-hook-quit)
24390 ;; Only when the isearch was not quitted.
24391 (org-add-hook 'post-command-hook 'org-isearch-post-command
24392 'append 'local)))))
24394 (defun org-isearch-post-command ()
24395 "Remove self from hook, and show context."
24396 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24397 (org-show-context 'isearch))
24400 ;;;; Integration with and fixes for other packages
24402 ;;; Imenu support
24404 (defvar org-imenu-markers nil
24405 "All markers currently used by Imenu.")
24406 (make-variable-buffer-local 'org-imenu-markers)
24408 (defun org-imenu-new-marker (&optional pos)
24409 "Return a new marker for use by Imenu, and remember the marker."
24410 (let ((m (make-marker)))
24411 (move-marker m (or pos (point)))
24412 (push m org-imenu-markers)
24415 (defun org-imenu-get-tree ()
24416 "Produce the index for Imenu."
24417 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24418 (setq org-imenu-markers nil)
24419 (let* ((n org-imenu-depth)
24420 (re (concat "^" (org-get-limited-outline-regexp)))
24421 (subs (make-vector (1+ n) nil))
24422 (last-level 0)
24423 m level head0 head)
24424 (save-excursion
24425 (save-restriction
24426 (widen)
24427 (goto-char (point-max))
24428 (while (re-search-backward re nil t)
24429 (setq level (org-reduced-level (funcall outline-level)))
24430 (when (and (<= level n)
24431 (looking-at org-complex-heading-regexp)
24432 (setq head0 (org-match-string-no-properties 4)))
24433 (setq head (org-link-display-format head0)
24434 m (org-imenu-new-marker))
24435 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24436 (if (>= level last-level)
24437 (push (cons head m) (aref subs level))
24438 (push (cons head (aref subs (1+ level))) (aref subs level))
24439 (loop for i from (1+ level) to n do (aset subs i nil)))
24440 (setq last-level level)))))
24441 (aref subs 1)))
24443 (eval-after-load "imenu"
24444 '(progn
24445 (add-hook 'imenu-after-jump-hook
24446 (lambda ()
24447 (if (derived-mode-p 'org-mode)
24448 (org-show-context 'org-goto))))))
24450 (defun org-link-display-format (link)
24451 "Replace a link with its the description.
24452 If there is no description, use the link target."
24453 (save-match-data
24454 (if (string-match org-bracket-link-analytic-regexp link)
24455 (replace-match (if (match-end 5)
24456 (match-string 5 link)
24457 (concat (match-string 1 link)
24458 (match-string 3 link)))
24459 nil t link)
24460 link)))
24462 (defun org-toggle-link-display ()
24463 "Toggle the literal or descriptive display of links."
24464 (interactive)
24465 (if org-descriptive-links
24466 (progn (org-remove-from-invisibility-spec '(org-link))
24467 (org-restart-font-lock)
24468 (setq org-descriptive-links nil))
24469 (progn (add-to-invisibility-spec '(org-link))
24470 (org-restart-font-lock)
24471 (setq org-descriptive-links t))))
24473 ;; Speedbar support
24475 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24476 "Overlay marking the agenda restriction line in speedbar.")
24477 (overlay-put org-speedbar-restriction-lock-overlay
24478 'face 'org-agenda-restriction-lock)
24479 (overlay-put org-speedbar-restriction-lock-overlay
24480 'help-echo "Agendas are currently limited to this item.")
24481 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24483 (defun org-speedbar-set-agenda-restriction ()
24484 "Restrict future agenda commands to the location at point in speedbar.
24485 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24486 (interactive)
24487 (require 'org-agenda)
24488 (let (p m tp np dir txt)
24489 (cond
24490 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24491 'org-imenu t))
24492 (setq m (get-text-property p 'org-imenu-marker))
24493 (with-current-buffer (marker-buffer m)
24494 (goto-char m)
24495 (org-agenda-set-restriction-lock 'subtree)))
24496 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24497 'speedbar-function 'speedbar-find-file))
24498 (setq tp (previous-single-property-change
24499 (1+ p) 'speedbar-function)
24500 np (next-single-property-change
24501 tp 'speedbar-function)
24502 dir (speedbar-line-directory)
24503 txt (buffer-substring-no-properties (or tp (point-min))
24504 (or np (point-max))))
24505 (with-current-buffer (find-file-noselect
24506 (let ((default-directory dir))
24507 (expand-file-name txt)))
24508 (unless (derived-mode-p 'org-mode)
24509 (user-error "Cannot restrict to non-Org-mode file"))
24510 (org-agenda-set-restriction-lock 'file)))
24511 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24512 (move-overlay org-speedbar-restriction-lock-overlay
24513 (point-at-bol) (point-at-eol))
24514 (setq current-prefix-arg nil)
24515 (org-agenda-maybe-redo)))
24517 (defvar speedbar-file-key-map)
24518 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24519 (eval-after-load "speedbar"
24520 '(progn
24521 (speedbar-add-supported-extension ".org")
24522 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24523 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24524 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24525 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24526 (add-hook 'speedbar-visiting-tag-hook
24527 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24529 ;;; Fixes and Hacks for problems with other packages
24531 (defun org--flyspell-object-check-p (element)
24532 "Non-nil when Flyspell can check object at point.
24533 ELEMENT is the element at point."
24534 (let ((object (save-excursion
24535 (when (org-looking-at-p "\\>") (backward-char))
24536 (org-element-context element))))
24537 (case (org-element-type object)
24538 ;; Prevent checks in links due to keybinding conflict with
24539 ;; Flyspell.
24540 ((code entity export-snippet inline-babel-call
24541 inline-src-block line-break latex-fragment link macro
24542 statistics-cookie target timestamp verbatim)
24543 nil)
24544 (footnote-reference
24545 ;; Only in inline footnotes, within the definition.
24546 (and (eq (org-element-property :type object) 'inline)
24547 (< (save-excursion
24548 (goto-char (org-element-property :begin object))
24549 (search-forward ":" nil t 2))
24550 (point))))
24551 (otherwise t))))
24553 (defun org-mode-flyspell-verify ()
24554 "Function used for `flyspell-generic-check-word-predicate'."
24555 (if (org-at-heading-p)
24556 ;; At a headline or an inlinetask, check title only. This is
24557 ;; faster than relying on `org-element-at-point'.
24558 (and (save-excursion (beginning-of-line)
24559 (and (let ((case-fold-search t))
24560 (not (looking-at "\\*+ END[ \t]*$")))
24561 (looking-at org-complex-heading-regexp)))
24562 (match-beginning 4)
24563 (>= (point) (match-beginning 4))
24564 (or (not (match-beginning 5))
24565 (< (point) (match-beginning 5))))
24566 (let* ((element (org-element-at-point))
24567 (post-affiliated (org-element-property :post-affiliated element)))
24568 (cond
24569 ;; Ignore checks in all affiliated keywords but captions.
24570 ((< (point) post-affiliated)
24571 (and (save-excursion
24572 (beginning-of-line)
24573 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24574 (> (point) (match-end 0))
24575 (org--flyspell-object-check-p element)))
24576 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24577 ((and org-log-into-drawer
24578 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24579 (parent element))
24580 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24581 (setq parent (org-element-property :parent parent)))
24582 (and parent
24583 (eq (compare-strings
24584 log nil nil
24585 (org-element-property :drawer-name parent) nil nil t)
24586 t))))
24587 nil)
24589 (case (org-element-type element)
24590 ((comment quote-section) t)
24591 (comment-block
24592 ;; Allow checks between block markers, not on them.
24593 (and (> (line-beginning-position) post-affiliated)
24594 (save-excursion
24595 (end-of-line)
24596 (skip-chars-forward " \r\t\n")
24597 (< (point) (org-element-property :end element)))))
24598 ;; Arbitrary list of keywords where checks are meaningful.
24599 ;; Make sure point is on the value part of the element.
24600 (keyword
24601 (and (member (org-element-property :key element)
24602 '("DESCRIPTION" "TITLE"))
24603 (< (save-excursion
24604 (beginning-of-line) (search-forward ":") (point))
24605 (point))))
24606 ;; Check is globally allowed in paragraphs verse blocks and
24607 ;; table rows (after affiliated keywords) but some objects
24608 ;; must not be affected.
24609 ((paragraph table-row verse-block)
24610 (let ((cbeg (org-element-property :contents-begin element))
24611 (cend (org-element-property :contents-end element)))
24612 (and cbeg (>= (point) cbeg) (< (point) cend)
24613 (org--flyspell-object-check-p element))))))))))
24614 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24616 (defun org-remove-flyspell-overlays-in (beg end)
24617 "Remove flyspell overlays in region."
24618 (and (org-bound-and-true-p flyspell-mode)
24619 (fboundp 'flyspell-delete-region-overlays)
24620 (flyspell-delete-region-overlays beg end)))
24622 (defvar flyspell-delayed-commands)
24623 (eval-after-load "flyspell"
24624 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24626 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24627 (eval-after-load "bookmark"
24628 '(if (boundp 'bookmark-after-jump-hook)
24629 ;; We can use the hook
24630 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24631 ;; Hook not available, use advice
24632 (defadvice bookmark-jump (after org-make-visible activate)
24633 "Make the position visible."
24634 (org-bookmark-jump-unhide))))
24636 ;; Make sure saveplace shows the location if it was hidden
24637 (eval-after-load "saveplace"
24638 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24639 "Make the position visible."
24640 (org-bookmark-jump-unhide)))
24642 ;; Make sure ecb shows the location if it was hidden
24643 (eval-after-load "ecb"
24644 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24645 "Make hierarchy visible when jumping into location from ECB tree buffer."
24646 (if (derived-mode-p 'org-mode)
24647 (org-show-context))))
24649 (defun org-bookmark-jump-unhide ()
24650 "Unhide the current position, to show the bookmark location."
24651 (and (derived-mode-p 'org-mode)
24652 (or (outline-invisible-p)
24653 (save-excursion (goto-char (max (point-min) (1- (point))))
24654 (outline-invisible-p)))
24655 (org-show-context 'bookmark-jump)))
24657 (defun org-mark-jump-unhide ()
24658 "Make the point visible with `org-show-context' after jumping to the mark."
24659 (when (and (derived-mode-p 'org-mode)
24660 (outline-invisible-p))
24661 (org-show-context 'mark-goto)))
24663 (eval-after-load "simple"
24664 '(defadvice pop-to-mark-command (after org-make-visible activate)
24665 "Make the point visible with `org-show-context'."
24666 (org-mark-jump-unhide)))
24668 (eval-after-load "simple"
24669 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24670 "Make the point visible with `org-show-context'."
24671 (org-mark-jump-unhide)))
24673 (eval-after-load "simple"
24674 '(defadvice pop-global-mark (after org-make-visible activate)
24675 "Make the point visible with `org-show-context'."
24676 (org-mark-jump-unhide)))
24678 ;; Make session.el ignore our circular variable
24679 (defvar session-globals-exclude)
24680 (eval-after-load "session"
24681 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24683 ;;;; Finish up
24685 (provide 'org)
24687 (run-hooks 'org-load-hook)
24689 ;;; org.el ends here