Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob634f2f569dd96ea172d060a2d850c38fa9deb43e
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 "\\(" org-property-start-re "\\)[^\000]*?\\("
424 org-property-end-re "\\)\n?")
425 "Matches an entire property drawer.")
427 (defconst org-clock-drawer-re
428 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
429 org-clock-drawer-end-re "\\)\n?")
430 "Matches an entire clock drawer.")
432 ;;;; Headline
434 (defconst org-heading-keyword-regexp-format
435 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
436 "Printf format for a regexp matching a headline with some keyword.
437 This regexp will match the headline of any node which has the
438 exact keyword that is put into the format. The keyword isn't in
439 any group by default, but the stars and the body are.")
441 (defconst org-heading-keyword-maybe-regexp-format
442 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
443 "Printf format for a regexp matching a headline, possibly with some keyword.
444 This regexp can match any headline with the specified keyword, or
445 without a keyword. The keyword isn't in any group by default,
446 but the stars and the body are.")
448 (defconst org-archive-tag "ARCHIVE"
449 "The tag that marks a subtree as archived.
450 An archived subtree does not open during visibility cycling, and does
451 not contribute to the agenda listings.")
453 (defconst org-comment-string "COMMENT"
454 "Entries starting with this keyword will never be exported.
455 An entry can be toggled between COMMENT and normal with
456 \\[org-toggle-comment].")
459 ;;;; LaTeX Environments and Fragments
461 (defconst org-latex-regexps
462 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
463 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
464 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
465 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
466 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
467 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
468 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
469 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
470 "Regular expressions for matching embedded LaTeX.")
472 ;;;; Node Property
474 (defconst org-effort-property "Effort"
475 "The property that is being used to keep track of effort estimates.
476 Effort estimates given in this property need to have the format H:MM.")
478 ;;;; Table
480 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
481 "Detect an org-type or table-type table.")
483 (defconst org-table-line-regexp "^[ \t]*|"
484 "Detect an org-type table line.")
486 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
487 "Detect an org-type table line.")
489 (defconst org-table-hline-regexp "^[ \t]*|-"
490 "Detect an org-type table hline.")
492 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
493 "Detect a table-type table hline.")
495 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
496 "Detect the first line outside a table when searching from within it.
497 This works for both table types.")
499 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
500 "Detect a #+TBLFM line.")
502 ;;;; Timestamp
504 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
505 "Regular expression for fast time stamp matching.")
507 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
508 "Regular expression for fast time stamp matching.")
510 (defconst org-ts-regexp0
511 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
512 "Regular expression matching time strings for analysis.
513 This one does not require the space after the date, so it can be used
514 on a string that terminates immediately after the date.")
516 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
517 "Regular expression matching time strings for analysis.")
519 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
520 "Regular expression matching time stamps, with groups.")
522 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
523 "Regular expression matching time stamps (also [..]), with groups.")
525 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
526 "Regular expression matching a time stamp range.")
528 (defconst org-tr-regexp-both
529 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
530 "Regular expression matching a time stamp range.")
532 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
533 org-ts-regexp "\\)?")
534 "Regular expression matching a time stamp or time stamp range.")
536 (defconst org-tsr-regexp-both
537 (concat org-ts-regexp-both "\\(--?-?"
538 org-ts-regexp-both "\\)?")
539 "Regular expression matching a time stamp or time stamp range.
540 The time stamps may be either active or inactive.")
542 (defconst org-repeat-re
543 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
544 "Regular expression for specifying repeated events.
545 After a match, group 1 contains the repeat expression.")
547 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
548 "Formats for `format-time-string' which are used for time stamps.")
551 ;;; The custom variables
553 (defgroup org nil
554 "Outline-based notes management and organizer."
555 :tag "Org"
556 :group 'outlines
557 :group 'calendar)
559 (defcustom org-mode-hook nil
560 "Mode hook for Org-mode, run after the mode was turned on."
561 :group 'org
562 :type 'hook)
564 (defcustom org-load-hook nil
565 "Hook that is run after org.el has been loaded."
566 :group 'org
567 :type 'hook)
569 (defcustom org-log-buffer-setup-hook nil
570 "Hook that is run after an Org log buffer is created."
571 :group 'org
572 :version "24.1"
573 :type 'hook)
575 (defvar org-modules) ; defined below
576 (defvar org-modules-loaded nil
577 "Have the modules been loaded already?")
579 (defun org-load-modules-maybe (&optional force)
580 "Load all extensions listed in `org-modules'."
581 (when (or force (not org-modules-loaded))
582 (mapc (lambda (ext)
583 (condition-case nil (require ext)
584 (error (message "Problems while trying to load feature `%s'" ext))))
585 org-modules)
586 (setq org-modules-loaded t)))
588 (defun org-set-modules (var value)
589 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
590 (set var value)
591 (when (featurep 'org)
592 (org-load-modules-maybe 'force)
593 (org-element-cache-reset 'all)))
595 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
596 "Modules that should always be loaded together with org.el.
598 If a description starts with <C>, the file is not part of Emacs
599 and loading it will require that you have downloaded and properly
600 installed the Org mode distribution.
602 You can also use this system to load external packages (i.e. neither Org
603 core modules, nor modules from the CONTRIB directory). Just add symbols
604 to the end of the list. If the package is called org-xyz.el, then you need
605 to add the symbol `xyz', and the package must have a call to:
607 \(provide 'org-xyz)
609 For export specific modules, see also `org-export-backends'."
610 :group 'org
611 :set 'org-set-modules
612 :version "24.4"
613 :package-version '(Org . "8.0")
614 :type
615 '(set :greedy t
616 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
617 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
618 (const :tag " crypt: Encryption of subtrees" org-crypt)
619 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
620 (const :tag " docview: Links to doc-view buffers" org-docview)
621 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
622 (const :tag " habit: Track your consistency with habits" org-habit)
623 (const :tag " id: Global IDs for identifying entries" org-id)
624 (const :tag " info: Links to Info nodes" org-info)
625 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
626 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
627 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
628 (const :tag " mouse: Additional mouse support" org-mouse)
629 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
630 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
631 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
633 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
634 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
635 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
636 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
637 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
638 (const :tag "C collector: Collect properties into tables" org-collector)
639 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
640 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
641 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
642 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
643 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
644 (const :tag "C eval: Include command output as text" org-eval)
645 (const :tag "C eww: Store link to url of eww" org-eww)
646 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
647 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
648 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
649 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
650 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
651 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
652 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
653 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
654 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
655 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
656 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
657 (const :tag "C mew: Links to Mew folders/messages" org-mew)
658 (const :tag "C mtags: Support for muse-like tags" org-mtags)
659 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
660 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
661 (const :tag "C registry: A registry for Org-mode links" org-registry)
662 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
663 (const :tag "C secretary: Team management with org-mode" org-secretary)
664 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
665 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
666 (const :tag "C track: Keep up with Org-mode development" org-track)
667 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
668 (const :tag "C vm: Links to VM folders/messages" org-vm)
669 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
670 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
671 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
673 (defvar org-export--registered-backends) ; From ox.el.
674 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
675 (declare-function org-export-backend-name "ox" (backend))
676 (defcustom org-export-backends '(ascii html icalendar latex)
677 "List of export back-ends that should be always available.
679 If a description starts with <C>, the file is not part of Emacs
680 and loading it will require that you have downloaded and properly
681 installed the Org mode distribution.
683 Unlike to `org-modules', libraries in this list will not be
684 loaded along with Org, but only once the export framework is
685 needed.
687 This variable needs to be set before org.el is loaded. If you
688 need to make a change while Emacs is running, use the customize
689 interface or run the following code, where VAL stands for the new
690 value of the variable, after updating it:
692 \(progn
693 \(setq org-export--registered-backends
694 \(org-remove-if-not
695 \(lambda (backend)
696 \(let ((name (org-export-backend-name backend)))
697 \(or (memq name val)
698 \(catch 'parentp
699 \(dolist (b val)
700 \(and (org-export-derived-backend-p b name)
701 \(throw 'parentp t)))))))
702 org-export--registered-backends))
703 \(let ((new-list (mapcar 'org-export-backend-name
704 org-export--registered-backends)))
705 \(dolist (backend val)
706 \(cond
707 \((not (load (format \"ox-%s\" backend) t t))
708 \(message \"Problems while trying to load export back-end `%s'\"
709 backend))
710 \((not (memq backend new-list)) (push backend new-list))))
711 \(set-default 'org-export-backends new-list)))
713 Adding a back-end to this list will also pull the back-end it
714 depends on, if any."
715 :group 'org
716 :group 'org-export
717 :version "24.4"
718 :package-version '(Org . "8.0")
719 :initialize 'custom-initialize-set
720 :set (lambda (var val)
721 (if (not (featurep 'ox)) (set-default var val)
722 ;; Any back-end not required anymore (not present in VAL and not
723 ;; a parent of any back-end in the new value) is removed from the
724 ;; list of registered back-ends.
725 (setq org-export--registered-backends
726 (org-remove-if-not
727 (lambda (backend)
728 (let ((name (org-export-backend-name backend)))
729 (or (memq name val)
730 (catch 'parentp
731 (dolist (b val)
732 (and (org-export-derived-backend-p b name)
733 (throw 'parentp t)))))))
734 org-export--registered-backends))
735 ;; Now build NEW-LIST of both new back-ends and required
736 ;; parents.
737 (let ((new-list (mapcar 'org-export-backend-name
738 org-export--registered-backends)))
739 (dolist (backend val)
740 (cond
741 ((not (load (format "ox-%s" backend) t t))
742 (message "Problems while trying to load export back-end `%s'"
743 backend))
744 ((not (memq backend new-list)) (push backend new-list))))
745 ;; Set VAR to that list with fixed dependencies.
746 (set-default var new-list))))
747 :type '(set :greedy t
748 (const :tag " ascii Export buffer to ASCII format" ascii)
749 (const :tag " beamer Export buffer to Beamer presentation" beamer)
750 (const :tag " html Export buffer to HTML format" html)
751 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
752 (const :tag " latex Export buffer to LaTeX format" latex)
753 (const :tag " man Export buffer to MAN format" man)
754 (const :tag " md Export buffer to Markdown format" md)
755 (const :tag " odt Export buffer to ODT format" odt)
756 (const :tag " org Export buffer to Org format" org)
757 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
758 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
759 (const :tag "C deck Export buffer to deck.js presentations" deck)
760 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
761 (const :tag "C groff Export buffer to Groff format" groff)
762 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
763 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
764 (const :tag "C s5 Export buffer to s5 presentations" s5)
765 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
767 (eval-after-load 'ox
768 '(mapc
769 (lambda (backend)
770 (condition-case nil (require (intern (format "ox-%s" backend)))
771 (error (message "Problems while trying to load export back-end `%s'"
772 backend))))
773 org-export-backends))
775 (defcustom org-support-shift-select nil
776 "Non-nil means make shift-cursor commands select text when possible.
778 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
779 start selecting a region, or enlarge regions started in this way.
780 In Org-mode, in special contexts, these same keys are used for
781 other purposes, important enough to compete with shift selection.
782 Org tries to balance these needs by supporting `shift-select-mode'
783 outside these special contexts, under control of this variable.
785 The default of this variable is nil, to avoid confusing behavior. Shifted
786 cursor keys will then execute Org commands in the following contexts:
787 - on a headline, changing TODO state (left/right) and priority (up/down)
788 - on a time stamp, changing the time
789 - in a plain list item, changing the bullet type
790 - in a property definition line, switching between allowed values
791 - in the BEGIN line of a clock table (changing the time block).
792 Outside these contexts, the commands will throw an error.
794 When this variable is t and the cursor is not in a special
795 context, Org-mode will support shift-selection for making and
796 enlarging regions. To make this more effective, the bullet
797 cycling will no longer happen anywhere in an item line, but only
798 if the cursor is exactly on the bullet.
800 If you set this variable to the symbol `always', then the keys
801 will not be special in headlines, property lines, and item lines,
802 to make shift selection work there as well. If this is what you
803 want, you can use the following alternative commands: `C-c C-t'
804 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
805 can be used to switch TODO sets, `C-c -' to cycle item bullet
806 types, and properties can be edited by hand or in column view.
808 However, when the cursor is on a timestamp, shift-cursor commands
809 will still edit the time stamp - this is just too good to give up.
811 XEmacs user should have this variable set to nil, because
812 `shift-select-mode' is in Emacs 23 or later only."
813 :group 'org
814 :type '(choice
815 (const :tag "Never" nil)
816 (const :tag "When outside special context" t)
817 (const :tag "Everywhere except timestamps" always)))
819 (defcustom org-loop-over-headlines-in-active-region nil
820 "Shall some commands act upon headlines in the active region?
822 When set to `t', some commands will be performed in all headlines
823 within the active region.
825 When set to `start-level', some commands will be performed in all
826 headlines within the active region, provided that these headlines
827 are of the same level than the first one.
829 When set to a string, those commands will be performed on the
830 matching headlines within the active region. Such string must be
831 a tags/property/todo match as it is used in the agenda tags view.
833 The list of commands is: `org-schedule', `org-deadline',
834 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
835 `org-archive-to-archive-sibling'. The archiving commands skip
836 already archived entries."
837 :type '(choice (const :tag "Don't loop" nil)
838 (const :tag "All headlines in active region" t)
839 (const :tag "In active region, headlines at the same level than the first one" start-level)
840 (string :tag "Tags/Property/Todo matcher"))
841 :version "24.1"
842 :group 'org-todo
843 :group 'org-archive)
845 (defgroup org-startup nil
846 "Options concerning startup of Org-mode."
847 :tag "Org Startup"
848 :group 'org)
850 (defcustom org-startup-folded t
851 "Non-nil means entering Org-mode will switch to OVERVIEW.
852 This can also be configured on a per-file basis by adding one of
853 the following lines anywhere in the buffer:
855 #+STARTUP: fold (or `overview', this is equivalent)
856 #+STARTUP: nofold (or `showall', this is equivalent)
857 #+STARTUP: content
858 #+STARTUP: showeverything
860 By default, this option is ignored when Org opens agenda files
861 for the first time. If you want the agenda to honor the startup
862 option, set `org-agenda-inhibit-startup' to nil."
863 :group 'org-startup
864 :type '(choice
865 (const :tag "nofold: show all" nil)
866 (const :tag "fold: overview" t)
867 (const :tag "content: all headlines" content)
868 (const :tag "show everything, even drawers" showeverything)))
870 (defcustom org-startup-truncated t
871 "Non-nil means entering Org-mode will set `truncate-lines'.
872 This is useful since some lines containing links can be very long and
873 uninteresting. Also tables look terrible when wrapped."
874 :group 'org-startup
875 :type 'boolean)
877 (defcustom org-startup-indented nil
878 "Non-nil means turn on `org-indent-mode' on startup.
879 This can also be configured on a per-file basis by adding one of
880 the following lines anywhere in the buffer:
882 #+STARTUP: indent
883 #+STARTUP: noindent"
884 :group 'org-structure
885 :type '(choice
886 (const :tag "Not" nil)
887 (const :tag "Globally (slow on startup in large files)" t)))
889 (defcustom org-use-sub-superscripts t
890 "Non-nil means interpret \"_\" and \"^\" for display.
892 If you want to control how Org exports those characters, see
893 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
894 used to be an alias for `org-export-with-sub-superscripts' in
895 Org <8.0, it is not anymore.
897 When this option is turned on, you can use TeX-like syntax for
898 sub- and superscripts within the buffer. Several characters after
899 \"_\" or \"^\" will be considered as a single item - so grouping
900 with {} is normally not needed. For example, the following things
901 will be parsed as single sub- or superscripts:
903 10^24 or 10^tau several digits will be considered 1 item.
904 10^-12 or 10^-tau a leading sign with digits or a word
905 x^2-y^3 will be read as x^2 - y^3, because items are
906 terminated by almost any nonword/nondigit char.
907 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
909 Still, ambiguity is possible. So when in doubt, use {} to enclose
910 the sub/superscript. If you set this variable to the symbol `{}',
911 the braces are *required* in order to trigger interpretations as
912 sub/superscript. This can be helpful in documents that need \"_\"
913 frequently in plain text."
914 :group 'org-startup
915 :version "24.4"
916 :package-version '(Org . "8.0")
917 :type '(choice
918 (const :tag "Always interpret" t)
919 (const :tag "Only with braces" {})
920 (const :tag "Never interpret" nil)))
922 (defcustom org-startup-with-beamer-mode nil
923 "Non-nil means turn on `org-beamer-mode' on startup.
924 This can also be configured on a per-file basis by adding one of
925 the following lines anywhere in the buffer:
927 #+STARTUP: beamer"
928 :group 'org-startup
929 :version "24.1"
930 :type 'boolean)
932 (defcustom org-startup-align-all-tables nil
933 "Non-nil means align all tables when visiting a file.
934 This is useful when the column width in tables is forced with <N> cookies
935 in table fields. Such tables will look correct only after the first re-align.
936 This can also be configured on a per-file basis by adding one of
937 the following lines anywhere in the buffer:
938 #+STARTUP: align
939 #+STARTUP: noalign"
940 :group 'org-startup
941 :type 'boolean)
943 (defcustom org-startup-with-inline-images nil
944 "Non-nil means show inline images when loading a new Org file.
945 This can also be configured on a per-file basis by adding one of
946 the following lines anywhere in the buffer:
947 #+STARTUP: inlineimages
948 #+STARTUP: noinlineimages"
949 :group 'org-startup
950 :version "24.1"
951 :type 'boolean)
953 (defcustom org-startup-with-latex-preview nil
954 "Non-nil means preview LaTeX fragments when loading a new Org file.
956 This can also be configured on a per-file basis by adding one of
957 the following lines anywhere in the buffer:
958 #+STARTUP: latexpreview
959 #+STARTUP: nolatexpreview"
960 :group 'org-startup
961 :version "24.4"
962 :package-version '(Org . "8.0")
963 :type 'boolean)
965 (defcustom org-insert-mode-line-in-empty-file nil
966 "Non-nil means insert the first line setting Org-mode in empty files.
967 When the function `org-mode' is called interactively in an empty file, this
968 normally means that the file name does not automatically trigger Org-mode.
969 To ensure that the file will always be in Org-mode in the future, a
970 line enforcing Org-mode will be inserted into the buffer, if this option
971 has been set."
972 :group 'org-startup
973 :type 'boolean)
975 (defcustom org-replace-disputed-keys nil
976 "Non-nil means use alternative key bindings for some keys.
977 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
978 These keys are also used by other packages like shift-selection-mode'
979 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
980 If you want to use Org-mode together with one of these other modes,
981 or more generally if you would like to move some Org-mode commands to
982 other keys, set this variable and configure the keys with the variable
983 `org-disputed-keys'.
985 This option is only relevant at load-time of Org-mode, and must be set
986 *before* org.el is loaded. Changing it requires a restart of Emacs to
987 become effective."
988 :group 'org-startup
989 :type 'boolean)
991 (defcustom org-use-extra-keys nil
992 "Non-nil means use extra key sequence definitions for certain commands.
993 This happens automatically if you run XEmacs or if `window-system'
994 is nil. This variable lets you do the same manually. You must
995 set it before loading org.
997 Example: on Carbon Emacs 22 running graphically, with an external
998 keyboard on a Powerbook, the default way of setting M-left might
999 not work for either Alt or ESC. Setting this variable will make
1000 it work for ESC."
1001 :group 'org-startup
1002 :type 'boolean)
1004 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1006 (defcustom org-disputed-keys
1007 '(([(shift up)] . [(meta p)])
1008 ([(shift down)] . [(meta n)])
1009 ([(shift left)] . [(meta -)])
1010 ([(shift right)] . [(meta +)])
1011 ([(control shift right)] . [(meta shift +)])
1012 ([(control shift left)] . [(meta shift -)]))
1013 "Keys for which Org-mode and other modes compete.
1014 This is an alist, cars are the default keys, second element specifies
1015 the alternative to use when `org-replace-disputed-keys' is t.
1017 Keys can be specified in any syntax supported by `define-key'.
1018 The value of this option takes effect only at Org-mode's startup,
1019 therefore you'll have to restart Emacs to apply it after changing."
1020 :group 'org-startup
1021 :type 'alist)
1023 (defun org-key (key)
1024 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1025 Or return the original if not disputed.
1026 Also apply the translations defined in `org-xemacs-key-equivalents'."
1027 (when org-replace-disputed-keys
1028 (let* ((nkey (key-description key))
1029 (x (org-find-if (lambda (x)
1030 (equal (key-description (car x)) nkey))
1031 org-disputed-keys)))
1032 (setq key (if x (cdr x) key))))
1033 (when (featurep 'xemacs)
1034 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1035 key)
1037 (defun org-find-if (predicate seq)
1038 (catch 'exit
1039 (while seq
1040 (if (funcall predicate (car seq))
1041 (throw 'exit (car seq))
1042 (pop seq)))))
1044 (defun org-defkey (keymap key def)
1045 "Define a key, possibly translated, as returned by `org-key'."
1046 (define-key keymap (org-key key) def))
1048 (defcustom org-ellipsis nil
1049 "The ellipsis to use in the Org-mode outline.
1050 When nil, just use the standard three dots.
1051 When a string, use that string instead.
1052 When a face, use the standard 3 dots, but with the specified face.
1053 The change affects only Org-mode (which will then use its own display table).
1054 Changing this requires executing \\[org-mode] in a buffer to become
1055 effective."
1056 :group 'org-startup
1057 :type '(choice (const :tag "Default" nil)
1058 (face :tag "Face" :value org-warning)
1059 (string :tag "String" :value "...#")))
1061 (defvar org-display-table nil
1062 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1064 (defgroup org-keywords nil
1065 "Keywords in Org-mode."
1066 :tag "Org Keywords"
1067 :group 'org)
1069 (defcustom org-closed-keep-when-no-todo nil
1070 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1071 :group 'org-todo
1072 :group 'org-keywords
1073 :version "24.4"
1074 :package-version '(Org . "8.0")
1075 :type 'boolean)
1077 (defgroup org-structure nil
1078 "Options concerning the general structure of Org-mode files."
1079 :tag "Org Structure"
1080 :group 'org)
1082 (defgroup org-reveal-location nil
1083 "Options about how to make context of a location visible."
1084 :tag "Org Reveal Location"
1085 :group 'org-structure)
1087 (defconst org-context-choice
1088 '(choice
1089 (const :tag "Always" t)
1090 (const :tag "Never" nil)
1091 (repeat :greedy t :tag "Individual contexts"
1092 (cons
1093 (choice :tag "Context"
1094 (const agenda)
1095 (const org-goto)
1096 (const occur-tree)
1097 (const tags-tree)
1098 (const link-search)
1099 (const mark-goto)
1100 (const bookmark-jump)
1101 (const isearch)
1102 (const default))
1103 (boolean))))
1104 "Contexts for the reveal options.")
1106 (defcustom org-show-hierarchy-above '((default . t))
1107 "Non-nil means show full hierarchy when revealing a location.
1108 Org-mode often shows locations in an org-mode file which might have
1109 been invisible before. When this is set, the hierarchy of headings
1110 above the exposed location is shown.
1111 Turning this off for example for sparse trees makes them very compact.
1112 Instead of t, this can also be an alist specifying this option for different
1113 contexts. Valid contexts are
1114 agenda when exposing an entry from the agenda
1115 org-goto when using the command `org-goto' on key C-c C-j
1116 occur-tree when using the command `org-occur' on key C-c /
1117 tags-tree when constructing a sparse tree based on tags matches
1118 link-search when exposing search matches associated with a link
1119 mark-goto when exposing the jump goal of a mark
1120 bookmark-jump when exposing a bookmark location
1121 isearch when exiting from an incremental search
1122 default default for all contexts not set explicitly"
1123 :group 'org-reveal-location
1124 :type org-context-choice)
1126 (defcustom org-show-following-heading '((default . nil))
1127 "Non-nil means show following heading when revealing a location.
1128 Org-mode often shows locations in an org-mode file which might have
1129 been invisible before. When this is set, the heading following the
1130 match is shown.
1131 Turning this off for example for sparse trees makes them very compact,
1132 but makes it harder to edit the location of the match. In such a case,
1133 use the command \\[org-reveal] to show more context.
1134 Instead of t, this can also be an alist specifying this option for different
1135 contexts. See `org-show-hierarchy-above' for valid contexts."
1136 :group 'org-reveal-location
1137 :type org-context-choice)
1139 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1140 "Non-nil means show all sibling heading when revealing a location.
1141 Org-mode often shows locations in an org-mode file which might have
1142 been invisible before. When this is set, the sibling of the current entry
1143 heading are all made visible. If `org-show-hierarchy-above' is t,
1144 the same happens on each level of the hierarchy above the current entry.
1146 By default this is on for the isearch context, off for all other contexts.
1147 Turning this off for example for sparse trees makes them very compact,
1148 but makes it harder to edit the location of the match. In such a case,
1149 use the command \\[org-reveal] to show more context.
1150 Instead of t, this can also be an alist specifying this option for different
1151 contexts. See `org-show-hierarchy-above' for valid contexts."
1152 :group 'org-reveal-location
1153 :type org-context-choice
1154 :version "24.4"
1155 :package-version '(Org . "8.0"))
1157 (defcustom org-show-entry-below '((default . nil))
1158 "Non-nil means show the entry below a headline when revealing a location.
1159 Org-mode often shows locations in an org-mode file which might have
1160 been invisible before. When this is set, the text below the headline that is
1161 exposed is also shown.
1163 By default this is off for all contexts.
1164 Instead of t, this can also be an alist specifying this option for different
1165 contexts. See `org-show-hierarchy-above' for valid contexts."
1166 :group 'org-reveal-location
1167 :type org-context-choice)
1169 (defcustom org-indirect-buffer-display 'other-window
1170 "How should indirect tree buffers be displayed?
1171 This applies to indirect buffers created with the commands
1172 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1173 Valid values are:
1174 current-window Display in the current window
1175 other-window Just display in another window.
1176 dedicated-frame Create one new frame, and re-use it each time.
1177 new-frame Make a new frame each time. Note that in this case
1178 previously-made indirect buffers are kept, and you need to
1179 kill these buffers yourself."
1180 :group 'org-structure
1181 :group 'org-agenda-windows
1182 :type '(choice
1183 (const :tag "In current window" current-window)
1184 (const :tag "In current frame, other window" other-window)
1185 (const :tag "Each time a new frame" new-frame)
1186 (const :tag "One dedicated frame" dedicated-frame)))
1188 (defcustom org-use-speed-commands nil
1189 "Non-nil means activate single letter commands at beginning of a headline.
1190 This may also be a function to test for appropriate locations where speed
1191 commands should be active.
1193 For example, to activate speed commands when the point is on any
1194 star at the beginning of the headline, you can do this:
1196 (setq org-use-speed-commands
1197 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1198 :group 'org-structure
1199 :type '(choice
1200 (const :tag "Never" nil)
1201 (const :tag "At beginning of headline stars" t)
1202 (function)))
1204 (defcustom org-speed-commands-user nil
1205 "Alist of additional speed commands.
1206 This list will be checked before `org-speed-commands-default'
1207 when the variable `org-use-speed-commands' is non-nil
1208 and when the cursor is at the beginning of a headline.
1209 The car if each entry is a string with a single letter, which must
1210 be assigned to `self-insert-command' in the global map.
1211 The cdr is either a command to be called interactively, a function
1212 to be called, or a form to be evaluated.
1213 An entry that is just a list with a single string will be interpreted
1214 as a descriptive headline that will be added when listing the speed
1215 commands in the Help buffer using the `?' speed command."
1216 :group 'org-structure
1217 :type '(repeat :value ("k" . ignore)
1218 (choice :value ("k" . ignore)
1219 (list :tag "Descriptive Headline" (string :tag "Headline"))
1220 (cons :tag "Letter and Command"
1221 (string :tag "Command letter")
1222 (choice
1223 (function)
1224 (sexp))))))
1226 (defcustom org-bookmark-names-plist
1227 '(:last-capture "org-capture-last-stored"
1228 :last-refile "org-refile-last-stored"
1229 :last-capture-marker "org-capture-last-stored-marker")
1230 "Names for bookmarks automatically set by some Org commands.
1231 This can provide strings as names for a number of bookmarks Org sets
1232 automatically. The following keys are currently implemented:
1233 :last-capture
1234 :last-capture-marker
1235 :last-refile
1236 When a key does not show up in the property list, the corresponding bookmark
1237 is not set."
1238 :group 'org-structure
1239 :type 'plist)
1241 (defgroup org-cycle nil
1242 "Options concerning visibility cycling in Org-mode."
1243 :tag "Org Cycle"
1244 :group 'org-structure)
1246 (defcustom org-cycle-skip-children-state-if-no-children t
1247 "Non-nil means skip CHILDREN state in entries that don't have any."
1248 :group 'org-cycle
1249 :type 'boolean)
1251 (defcustom org-cycle-max-level nil
1252 "Maximum level which should still be subject to visibility cycling.
1253 Levels higher than this will, for cycling, be treated as text, not a headline.
1254 When `org-odd-levels-only' is set, a value of N in this variable actually
1255 means 2N-1 stars as the limiting headline.
1256 When nil, cycle all levels.
1257 Note that the limiting level of cycling is also influenced by
1258 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1259 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1260 than its value."
1261 :group 'org-cycle
1262 :type '(choice
1263 (const :tag "No limit" nil)
1264 (integer :tag "Maximum level")))
1266 (defcustom org-hide-block-startup nil
1267 "Non-nil means entering Org-mode will fold all blocks.
1268 This can also be set in on a per-file basis with
1270 #+STARTUP: hideblocks
1271 #+STARTUP: showblocks"
1272 :group 'org-startup
1273 :group 'org-cycle
1274 :type 'boolean)
1276 (defcustom org-cycle-global-at-bob nil
1277 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1278 This makes it possible to do global cycling without having to use S-TAB or
1279 \\[universal-argument] TAB. For this special case to work, the first line
1280 of the buffer must not be a headline -- it may be empty or some other text.
1281 When used in this way, `org-cycle-hook' is disabled temporarily to make
1282 sure the cursor stays at the beginning of the buffer. When this option is
1283 nil, don't do anything special at the beginning of the buffer."
1284 :group 'org-cycle
1285 :type 'boolean)
1287 (defcustom org-cycle-level-after-item/entry-creation t
1288 "Non-nil means cycle entry level or item indentation in new empty entries.
1290 When the cursor is at the end of an empty headline, i.e., with only stars
1291 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1292 and then all possible ancestor states, before returning to the original state.
1293 This makes data entry extremely fast: M-RET to create a new headline,
1294 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1296 When the cursor is at the end of an empty plain list item, one TAB will
1297 make it a subitem, two or more tabs will back up to make this an item
1298 higher up in the item hierarchy."
1299 :group 'org-cycle
1300 :type 'boolean)
1302 (defcustom org-cycle-emulate-tab t
1303 "Where should `org-cycle' emulate TAB.
1304 nil Never
1305 white Only in completely white lines
1306 whitestart Only at the beginning of lines, before the first non-white char
1307 t Everywhere except in headlines
1308 exc-hl-bol Everywhere except at the start of a headline
1309 If TAB is used in a place where it does not emulate TAB, the current subtree
1310 visibility is cycled."
1311 :group 'org-cycle
1312 :type '(choice (const :tag "Never" nil)
1313 (const :tag "Only in completely white lines" white)
1314 (const :tag "Before first char in a line" whitestart)
1315 (const :tag "Everywhere except in headlines" t)
1316 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1318 (defcustom org-cycle-separator-lines 2
1319 "Number of empty lines needed to keep an empty line between collapsed trees.
1320 If you leave an empty line between the end of a subtree and the following
1321 headline, this empty line is hidden when the subtree is folded.
1322 Org-mode will leave (exactly) one empty line visible if the number of
1323 empty lines is equal or larger to the number given in this variable.
1324 So the default 2 means at least 2 empty lines after the end of a subtree
1325 are needed to produce free space between a collapsed subtree and the
1326 following headline.
1328 If the number is negative, and the number of empty lines is at least -N,
1329 all empty lines are shown.
1331 Special case: when 0, never leave empty lines in collapsed view."
1332 :group 'org-cycle
1333 :type 'integer)
1334 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1336 (defcustom org-pre-cycle-hook nil
1337 "Hook that is run before visibility cycling is happening.
1338 The function(s) in this hook must accept a single argument which indicates
1339 the new state that will be set right after running this hook. The
1340 argument is a symbol. Before a global state change, it can have the values
1341 `overview', `content', or `all'. Before a local state change, it can have
1342 the values `folded', `children', or `subtree'."
1343 :group 'org-cycle
1344 :type 'hook)
1346 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1347 org-cycle-hide-drawers
1348 org-cycle-hide-inline-tasks
1349 org-cycle-show-empty-lines
1350 org-optimize-window-after-visibility-change)
1351 "Hook that is run after `org-cycle' has changed the buffer visibility.
1352 The function(s) in this hook must accept a single argument which indicates
1353 the new state that was set by the most recent `org-cycle' command. The
1354 argument is a symbol. After a global state change, it can have the values
1355 `overview', `contents', or `all'. After a local state change, it can have
1356 the values `folded', `children', or `subtree'."
1357 :group 'org-cycle
1358 :type 'hook)
1360 (defgroup org-edit-structure nil
1361 "Options concerning structure editing in Org-mode."
1362 :tag "Org Edit Structure"
1363 :group 'org-structure)
1365 (defcustom org-odd-levels-only nil
1366 "Non-nil means skip even levels and only use odd levels for the outline.
1367 This has the effect that two stars are being added/taken away in
1368 promotion/demotion commands. It also influences how levels are
1369 handled by the exporters.
1370 Changing it requires restart of `font-lock-mode' to become effective
1371 for fontification also in regions already fontified.
1372 You may also set this on a per-file basis by adding one of the following
1373 lines to the buffer:
1375 #+STARTUP: odd
1376 #+STARTUP: oddeven"
1377 :group 'org-edit-structure
1378 :group 'org-appearance
1379 :type 'boolean)
1381 (defcustom org-adapt-indentation t
1382 "Non-nil means adapt indentation to outline node level.
1384 When this variable is set, Org assumes that you write outlines by
1385 indenting text in each node to align with the headline (after the stars).
1386 The following issues are influenced by this variable:
1388 - When this is set and the *entire* text in an entry is indented, the
1389 indentation is increased by one space in a demotion command, and
1390 decreased by one in a promotion command. If any line in the entry
1391 body starts with text at column 0, indentation is not changed at all.
1393 - Property drawers and planning information is inserted indented when
1394 this variable s set. When nil, they will not be indented.
1396 - TAB indents a line relative to context. The lines below a headline
1397 will be indented when this variable is set.
1399 Note that this is all about true indentation, by adding and removing
1400 space characters. See also `org-indent.el' which does level-dependent
1401 indentation in a virtual way, i.e. at display time in Emacs."
1402 :group 'org-edit-structure
1403 :type 'boolean)
1405 (defcustom org-special-ctrl-a/e nil
1406 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1408 When t, `C-a' will bring back the cursor to the beginning of the
1409 headline text, i.e. after the stars and after a possible TODO
1410 keyword. In an item, this will be the position after bullet and
1411 check-box, if any. When the cursor is already at that position,
1412 another `C-a' will bring it to the beginning of the line.
1414 `C-e' will jump to the end of the headline, ignoring the presence
1415 of tags in the headline. A second `C-e' will then jump to the
1416 true end of the line, after any tags. This also means that, when
1417 this variable is non-nil, `C-e' also will never jump beyond the
1418 end of the heading of a folded section, i.e. not after the
1419 ellipses.
1421 When set to the symbol `reversed', the first `C-a' or `C-e' works
1422 normally, going to the true line boundary first. Only a directly
1423 following, identical keypress will bring the cursor to the
1424 special positions.
1426 This may also be a cons cell where the behavior for `C-a' and
1427 `C-e' is set separately."
1428 :group 'org-edit-structure
1429 :type '(choice
1430 (const :tag "off" nil)
1431 (const :tag "on: after stars/bullet and before tags first" t)
1432 (const :tag "reversed: true line boundary first" reversed)
1433 (cons :tag "Set C-a and C-e separately"
1434 (choice :tag "Special C-a"
1435 (const :tag "off" nil)
1436 (const :tag "on: after stars/bullet first" t)
1437 (const :tag "reversed: before stars/bullet first" reversed))
1438 (choice :tag "Special C-e"
1439 (const :tag "off" nil)
1440 (const :tag "on: before tags first" t)
1441 (const :tag "reversed: after tags first" reversed)))))
1442 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1444 (defcustom org-special-ctrl-k nil
1445 "Non-nil means `C-k' will behave specially in headlines.
1446 When nil, `C-k' will call the default `kill-line' command.
1447 When t, the following will happen while the cursor is in the headline:
1449 - When the cursor is at the beginning of a headline, kill the entire
1450 line and possible the folded subtree below the line.
1451 - When in the middle of the headline text, kill the headline up to the tags.
1452 - When after the headline text, kill the tags."
1453 :group 'org-edit-structure
1454 :type 'boolean)
1456 (defcustom org-ctrl-k-protect-subtree nil
1457 "Non-nil means, do not delete a hidden subtree with C-k.
1458 When set to the symbol `error', simply throw an error when C-k is
1459 used to kill (part-of) a headline that has hidden text behind it.
1460 Any other non-nil value will result in a query to the user, if it is
1461 OK to kill that hidden subtree. When nil, kill without remorse."
1462 :group 'org-edit-structure
1463 :version "24.1"
1464 :type '(choice
1465 (const :tag "Do not protect hidden subtrees" nil)
1466 (const :tag "Protect hidden subtrees with a security query" t)
1467 (const :tag "Never kill a hidden subtree with C-k" error)))
1469 (defcustom org-special-ctrl-o t
1470 "Non-nil means, make `C-o' insert a row in tables."
1471 :group 'org-edit-structure
1472 :type 'boolean)
1474 (defcustom org-catch-invisible-edits nil
1475 "Check if in invisible region before inserting or deleting a character.
1476 Valid values are:
1478 nil Do not check, so just do invisible edits.
1479 error Throw an error and do nothing.
1480 show Make point visible, and do the requested edit.
1481 show-and-error Make point visible, then throw an error and abort the edit.
1482 smart Make point visible, and do insertion/deletion if it is
1483 adjacent to visible text and the change feels predictable.
1484 Never delete a previously invisible character or add in the
1485 middle or right after an invisible region. Basically, this
1486 allows insertion and backward-delete right before ellipses.
1487 FIXME: maybe in this case we should not even show?"
1488 :group 'org-edit-structure
1489 :version "24.1"
1490 :type '(choice
1491 (const :tag "Do not check" nil)
1492 (const :tag "Throw error when trying to edit" error)
1493 (const :tag "Unhide, but do not do the edit" show-and-error)
1494 (const :tag "Show invisible part and do the edit" show)
1495 (const :tag "Be smart and do the right thing" smart)))
1497 (defcustom org-yank-folded-subtrees t
1498 "Non-nil means when yanking subtrees, fold them.
1499 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1500 it starts with a heading and all other headings in it are either children
1501 or siblings, then fold all the subtrees. However, do this only if no
1502 text after the yank would be swallowed into a folded tree by this action."
1503 :group 'org-edit-structure
1504 :type 'boolean)
1506 (defcustom org-yank-adjusted-subtrees nil
1507 "Non-nil means when yanking subtrees, adjust the level.
1508 With this setting, `org-paste-subtree' is used to insert the subtree, see
1509 this function for details."
1510 :group 'org-edit-structure
1511 :type 'boolean)
1513 (defcustom org-M-RET-may-split-line '((default . t))
1514 "Non-nil means M-RET will split the line at the cursor position.
1515 When nil, it will go to the end of the line before making a
1516 new line.
1517 You may also set this option in a different way for different
1518 contexts. Valid contexts are:
1520 headline when creating a new headline
1521 item when creating a new item
1522 table in a table field
1523 default the value to be used for all contexts not explicitly
1524 customized"
1525 :group 'org-structure
1526 :group 'org-table
1527 :type '(choice
1528 (const :tag "Always" t)
1529 (const :tag "Never" nil)
1530 (repeat :greedy t :tag "Individual contexts"
1531 (cons
1532 (choice :tag "Context"
1533 (const headline)
1534 (const item)
1535 (const table)
1536 (const default))
1537 (boolean)))))
1540 (defcustom org-insert-heading-respect-content nil
1541 "Non-nil means insert new headings after the current subtree.
1542 When nil, the new heading is created directly after the current line.
1543 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1544 this variable on for the duration of the command."
1545 :group 'org-structure
1546 :type 'boolean)
1548 (defcustom org-blank-before-new-entry '((heading . auto)
1549 (plain-list-item . auto))
1550 "Should `org-insert-heading' leave a blank line before new heading/item?
1551 The value is an alist, with `heading' and `plain-list-item' as CAR,
1552 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1553 which case Org will look at the surrounding headings/items and try to
1554 make an intelligent decision whether to insert a blank line or not.
1556 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1557 the setting here is ignored and no empty line is inserted to avoid breaking
1558 the list structure."
1559 :group 'org-edit-structure
1560 :type '(list
1561 (cons (const heading)
1562 (choice (const :tag "Never" nil)
1563 (const :tag "Always" t)
1564 (const :tag "Auto" auto)))
1565 (cons (const plain-list-item)
1566 (choice (const :tag "Never" nil)
1567 (const :tag "Always" t)
1568 (const :tag "Auto" auto)))))
1570 (defcustom org-insert-heading-hook nil
1571 "Hook being run after inserting a new heading."
1572 :group 'org-edit-structure
1573 :type 'hook)
1575 (defcustom org-enable-fixed-width-editor t
1576 "Non-nil means lines starting with \":\" are treated as fixed-width.
1577 This currently only means they are never auto-wrapped.
1578 When nil, such lines will be treated like ordinary lines."
1579 :group 'org-edit-structure
1580 :type 'boolean)
1582 (defcustom org-goto-auto-isearch t
1583 "Non-nil means typing characters in `org-goto' starts incremental search.
1584 When nil, you can use these keybindings to navigate the buffer:
1586 q Quit the org-goto interface
1587 n Go to the next visible heading
1588 p Go to the previous visible heading
1589 f Go one heading forward on same level
1590 b Go one heading backward on same level
1591 u Go one heading up"
1592 :group 'org-edit-structure
1593 :type 'boolean)
1595 (defgroup org-sparse-trees nil
1596 "Options concerning sparse trees in Org-mode."
1597 :tag "Org Sparse Trees"
1598 :group 'org-structure)
1600 (defcustom org-highlight-sparse-tree-matches t
1601 "Non-nil means highlight all matches that define a sparse tree.
1602 The highlights will automatically disappear the next time the buffer is
1603 changed by an edit command."
1604 :group 'org-sparse-trees
1605 :type 'boolean)
1607 (defcustom org-remove-highlights-with-change t
1608 "Non-nil means any change to the buffer will remove temporary highlights.
1609 Such highlights are created by `org-occur' and `org-clock-display'.
1610 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1611 The highlights created by `org-toggle-latex-fragment' always need
1612 `C-c C-x C-l' to be removed."
1613 :group 'org-sparse-trees
1614 :group 'org-time
1615 :type 'boolean)
1618 (defcustom org-occur-hook '(org-first-headline-recenter)
1619 "Hook that is run after `org-occur' has constructed a sparse tree.
1620 This can be used to recenter the window to show as much of the structure
1621 as possible."
1622 :group 'org-sparse-trees
1623 :type 'hook)
1625 (defgroup org-imenu-and-speedbar nil
1626 "Options concerning imenu and speedbar in Org-mode."
1627 :tag "Org Imenu and Speedbar"
1628 :group 'org-structure)
1630 (defcustom org-imenu-depth 2
1631 "The maximum level for Imenu access to Org-mode headlines.
1632 This also applied for speedbar access."
1633 :group 'org-imenu-and-speedbar
1634 :type 'integer)
1636 (defgroup org-table nil
1637 "Options concerning tables in Org-mode."
1638 :tag "Org Table"
1639 :group 'org)
1641 (defcustom org-enable-table-editor 'optimized
1642 "Non-nil means lines starting with \"|\" are handled by the table editor.
1643 When nil, such lines will be treated like ordinary lines.
1645 When equal to the symbol `optimized', the table editor will be optimized to
1646 do the following:
1647 - Automatic overwrite mode in front of whitespace in table fields.
1648 This makes the structure of the table stay in tact as long as the edited
1649 field does not exceed the column width.
1650 - Minimize the number of realigns. Normally, the table is aligned each time
1651 TAB or RET are pressed to move to another field. With optimization this
1652 happens only if changes to a field might have changed the column width.
1653 Optimization requires replacing the functions `self-insert-command',
1654 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1655 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1656 very good at guessing when a re-align will be necessary, but you can always
1657 force one with \\[org-ctrl-c-ctrl-c].
1659 If you would like to use the optimized version in Org-mode, but the
1660 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1662 This variable can be used to turn on and off the table editor during a session,
1663 but in order to toggle optimization, a restart is required.
1665 See also the variable `org-table-auto-blank-field'."
1666 :group 'org-table
1667 :type '(choice
1668 (const :tag "off" nil)
1669 (const :tag "on" t)
1670 (const :tag "on, optimized" optimized)))
1672 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1673 (version<= emacs-version "24.1"))
1674 "Non-nil means cluster self-insert commands for undo when possible.
1675 If this is set, then, like in the Emacs command loop, 20 consecutive
1676 characters will be undone together.
1677 This is configurable, because there is some impact on typing performance."
1678 :group 'org-table
1679 :type 'boolean)
1681 (defcustom org-table-tab-recognizes-table.el t
1682 "Non-nil means TAB will automatically notice a table.el table.
1683 When it sees such a table, it moves point into it and - if necessary -
1684 calls `table-recognize-table'."
1685 :group 'org-table-editing
1686 :type 'boolean)
1688 (defgroup org-link nil
1689 "Options concerning links in Org-mode."
1690 :tag "Org Link"
1691 :group 'org)
1693 (defvar org-link-abbrev-alist-local nil
1694 "Buffer-local version of `org-link-abbrev-alist', which see.
1695 The value of this is taken from the #+LINK lines.")
1696 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1698 (defcustom org-link-abbrev-alist nil
1699 "Alist of link abbreviations.
1700 The car of each element is a string, to be replaced at the start of a link.
1701 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1702 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1704 [[linkkey:tag][description]]
1706 The 'linkkey' must be a word word, starting with a letter, followed
1707 by letters, numbers, '-' or '_'.
1709 If REPLACE is a string, the tag will simply be appended to create the link.
1710 If the string contains \"%s\", the tag will be inserted there. If the string
1711 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1712 at that point (see the function `url-hexify-string'). If the string contains
1713 the specifier \"%(my-function)\", then the custom function `my-function' will
1714 be invoked: this function takes the tag as its only argument and must return
1715 a string.
1717 REPLACE may also be a function that will be called with the tag as the
1718 only argument to create the link, which should be returned as a string.
1720 See the manual for examples."
1721 :group 'org-link
1722 :type '(repeat
1723 (cons
1724 (string :tag "Protocol")
1725 (choice
1726 (string :tag "Format")
1727 (function)))))
1729 (defcustom org-descriptive-links t
1730 "Non-nil means Org will display descriptive links.
1731 E.g. [[http://orgmode.org][Org website]] will be displayed as
1732 \"Org Website\", hiding the link itself and just displaying its
1733 description. When set to `nil', Org will display the full links
1734 literally.
1736 You can interactively set the value of this variable by calling
1737 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1738 :group 'org-link
1739 :type 'boolean)
1741 (defcustom org-link-file-path-type 'adaptive
1742 "How the path name in file links should be stored.
1743 Valid values are:
1745 relative Relative to the current directory, i.e. the directory of the file
1746 into which the link is being inserted.
1747 absolute Absolute path, if possible with ~ for home directory.
1748 noabbrev Absolute path, no abbreviation of home directory.
1749 adaptive Use relative path for files in the current directory and sub-
1750 directories of it. For other files, use an absolute path."
1751 :group 'org-link
1752 :type '(choice
1753 (const relative)
1754 (const absolute)
1755 (const noabbrev)
1756 (const adaptive)))
1758 (defvaralias 'org-activate-links 'org-highlight-links)
1759 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1760 "Types of links that should be highlighted in Org-mode files.
1762 This is a list of symbols, each one of them leading to the
1763 highlighting of a certain link type.
1765 You can still open links that are not highlighted.
1767 In principle, it does not hurt to turn on highlighting for all
1768 link types. There may be a small gain when turning off unused
1769 link types. The types are:
1771 bracket The recommended [[link][description]] or [[link]] links with hiding.
1772 angle Links in angular brackets that may contain whitespace like
1773 <bbdb:Carsten Dominik>.
1774 plain Plain links in normal text, no whitespace, like http://google.com.
1775 radio Text that is matched by a radio target, see manual for details.
1776 tag Tag settings in a headline (link to tag search).
1777 date Time stamps (link to calendar).
1778 footnote Footnote labels.
1780 If you set this variable during an Emacs session, use `org-mode-restart'
1781 in the Org buffer so that the change takes effect."
1782 :group 'org-link
1783 :group 'org-appearance
1784 :type '(set :greedy t
1785 (const :tag "Double bracket links" bracket)
1786 (const :tag "Angular bracket links" angle)
1787 (const :tag "Plain text links" plain)
1788 (const :tag "Radio target matches" radio)
1789 (const :tag "Tags" tag)
1790 (const :tag "Timestamps" date)
1791 (const :tag "Footnotes" footnote)))
1793 (defcustom org-make-link-description-function nil
1794 "Function to use for generating link descriptions from links.
1795 When nil, the link location will be used. This function must take
1796 two parameters: the first one is the link, the second one is the
1797 description generated by `org-insert-link'. The function should
1798 return the description to use."
1799 :group 'org-link
1800 :type '(choice (const nil) (function)))
1802 (defgroup org-link-store nil
1803 "Options concerning storing links in Org-mode."
1804 :tag "Org Store Link"
1805 :group 'org-link)
1807 (defcustom org-url-hexify-p t
1808 "When non-nil, hexify URL when creating a link."
1809 :type 'boolean
1810 :version "24.3"
1811 :group 'org-link-store)
1813 (defcustom org-email-link-description-format "Email %c: %.30s"
1814 "Format of the description part of a link to an email or usenet message.
1815 The following %-escapes will be replaced by corresponding information:
1817 %F full \"From\" field
1818 %f name, taken from \"From\" field, address if no name
1819 %T full \"To\" field
1820 %t first name in \"To\" field, address if no name
1821 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1822 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1823 %s subject
1824 %d date
1825 %m message-id.
1827 You may use normal field width specification between the % and the letter.
1828 This is for example useful to limit the length of the subject.
1830 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1831 :group 'org-link-store
1832 :type 'string)
1834 (defcustom org-from-is-user-regexp
1835 (let (r1 r2)
1836 (when (and user-mail-address (not (string= user-mail-address "")))
1837 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1838 (when (and user-full-name (not (string= user-full-name "")))
1839 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1840 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1841 "Regexp matched against the \"From:\" header of an email or usenet message.
1842 It should match if the message is from the user him/herself."
1843 :group 'org-link-store
1844 :type 'regexp)
1846 (defcustom org-context-in-file-links t
1847 "Non-nil means file links from `org-store-link' contain context.
1848 A search string will be added to the file name with :: as separator and
1849 used to find the context when the link is activated by the command
1850 `org-open-at-point'. When this option is t, the entire active region
1851 will be placed in the search string of the file link. If set to a
1852 positive integer, only the first n lines of context will be stored.
1854 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1855 negates this setting for the duration of the command."
1856 :group 'org-link-store
1857 :type '(choice boolean integer))
1859 (defcustom org-keep-stored-link-after-insertion nil
1860 "Non-nil means keep link in list for entire session.
1862 The command `org-store-link' adds a link pointing to the current
1863 location to an internal list. These links accumulate during a session.
1864 The command `org-insert-link' can be used to insert links into any
1865 Org-mode file (offering completion for all stored links). When this
1866 option is nil, every link which has been inserted once using \\[org-insert-link]
1867 will be removed from the list, to make completing the unused links
1868 more efficient."
1869 :group 'org-link-store
1870 :type 'boolean)
1872 (defgroup org-link-follow nil
1873 "Options concerning following links in Org-mode."
1874 :tag "Org Follow Link"
1875 :group 'org-link)
1877 (defcustom org-link-translation-function nil
1878 "Function to translate links with different syntax to Org syntax.
1879 This can be used to translate links created for example by the Planner
1880 or emacs-wiki packages to Org syntax.
1881 The function must accept two parameters, a TYPE containing the link
1882 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1883 which is everything after the link protocol. It should return a cons
1884 with possibly modified values of type and path.
1885 Org contains a function for this, so if you set this variable to
1886 `org-translate-link-from-planner', you should be able follow many
1887 links created by planner."
1888 :group 'org-link-follow
1889 :type '(choice (const nil) (function)))
1891 (defcustom org-follow-link-hook nil
1892 "Hook that is run after a link has been followed."
1893 :group 'org-link-follow
1894 :type 'hook)
1896 (defcustom org-tab-follows-link nil
1897 "Non-nil means on links TAB will follow the link.
1898 Needs to be set before org.el is loaded.
1899 This really should not be used, it does not make sense, and the
1900 implementation is bad."
1901 :group 'org-link-follow
1902 :type 'boolean)
1904 (defcustom org-return-follows-link nil
1905 "Non-nil means on links RET will follow the link.
1906 In tables, the special behavior of RET has precedence."
1907 :group 'org-link-follow
1908 :type 'boolean)
1910 (defcustom org-mouse-1-follows-link
1911 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1912 "Non-nil means mouse-1 on a link will follow the link.
1913 A longer mouse click will still set point. Does not work on XEmacs.
1914 Needs to be set before org.el is loaded."
1915 :group 'org-link-follow
1916 :version "24.4"
1917 :package-version '(Org . "8.3")
1918 :type '(choice
1919 (const :tag "A double click follows the link" double)
1920 (const :tag "Unconditionally follow the link with mouse-1" t)
1921 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1923 (defcustom org-mark-ring-length 4
1924 "Number of different positions to be recorded in the ring.
1925 Changing this requires a restart of Emacs to work correctly."
1926 :group 'org-link-follow
1927 :type 'integer)
1929 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1930 "Non-nil means internal links in Org files must exactly match a headline.
1931 When nil, the link search tries to match a phrase with all words
1932 in the search text."
1933 :group 'org-link-follow
1934 :version "24.1"
1935 :type '(choice
1936 (const :tag "Use fuzzy text search" nil)
1937 (const :tag "Match only exact headline" t)
1938 (const :tag "Match exact headline or query to create it"
1939 query-to-create)))
1941 (defcustom org-link-frame-setup
1942 '((vm . vm-visit-folder-other-frame)
1943 (vm-imap . vm-visit-imap-folder-other-frame)
1944 (gnus . org-gnus-no-new-news)
1945 (file . find-file-other-window)
1946 (wl . wl-other-frame))
1947 "Setup the frame configuration for following links.
1948 When following a link with Emacs, it may often be useful to display
1949 this link in another window or frame. This variable can be used to
1950 set this up for the different types of links.
1951 For VM, use any of
1952 `vm-visit-folder'
1953 `vm-visit-folder-other-window'
1954 `vm-visit-folder-other-frame'
1955 For Gnus, use any of
1956 `gnus'
1957 `gnus-other-frame'
1958 `org-gnus-no-new-news'
1959 For FILE, use any of
1960 `find-file'
1961 `find-file-other-window'
1962 `find-file-other-frame'
1963 For Wanderlust use any of
1964 `wl'
1965 `wl-other-frame'
1966 For the calendar, use the variable `calendar-setup'.
1967 For BBDB, it is currently only possible to display the matches in
1968 another window."
1969 :group 'org-link-follow
1970 :type '(list
1971 (cons (const vm)
1972 (choice
1973 (const vm-visit-folder)
1974 (const vm-visit-folder-other-window)
1975 (const vm-visit-folder-other-frame)))
1976 (cons (const vm-imap)
1977 (choice
1978 (const vm-visit-imap-folder)
1979 (const vm-visit-imap-folder-other-window)
1980 (const vm-visit-imap-folder-other-frame)))
1981 (cons (const gnus)
1982 (choice
1983 (const gnus)
1984 (const gnus-other-frame)
1985 (const org-gnus-no-new-news)))
1986 (cons (const file)
1987 (choice
1988 (const find-file)
1989 (const find-file-other-window)
1990 (const find-file-other-frame)))
1991 (cons (const wl)
1992 (choice
1993 (const wl)
1994 (const wl-other-frame)))))
1996 (defcustom org-display-internal-link-with-indirect-buffer nil
1997 "Non-nil means use indirect buffer to display infile links.
1998 Activating internal links (from one location in a file to another location
1999 in the same file) normally just jumps to the location. When the link is
2000 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2001 is displayed in
2002 another window. When this option is set, the other window actually displays
2003 an indirect buffer clone of the current buffer, to avoid any visibility
2004 changes to the current buffer."
2005 :group 'org-link-follow
2006 :type 'boolean)
2008 (defcustom org-open-non-existing-files nil
2009 "Non-nil means `org-open-file' will open non-existing files.
2010 When nil, an error will be generated.
2011 This variable applies only to external applications because they
2012 might choke on non-existing files. If the link is to a file that
2013 will be opened in Emacs, the variable is ignored."
2014 :group 'org-link-follow
2015 :type 'boolean)
2017 (defcustom org-open-directory-means-index-dot-org nil
2018 "Non-nil means a link to a directory really means to index.org.
2019 When nil, following a directory link will run dired or open a finder/explorer
2020 window on that directory."
2021 :group 'org-link-follow
2022 :type 'boolean)
2024 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2025 "Non-nil means ask for confirmation before executing shell links.
2026 Shell links can be dangerous: just think about a link
2028 [[shell:rm -rf ~/*][Google Search]]
2030 This link would show up in your Org-mode document as \"Google Search\",
2031 but really it would remove your entire home directory.
2032 Therefore we advise against setting this variable to nil.
2033 Just change it to `y-or-n-p' if you want to confirm with a
2034 single keystroke rather than having to type \"yes\"."
2035 :group 'org-link-follow
2036 :type '(choice
2037 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2038 (const :tag "with y-or-n (faster)" y-or-n-p)
2039 (const :tag "no confirmation (dangerous)" nil)))
2040 (put 'org-confirm-shell-link-function
2041 'safe-local-variable
2042 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2044 (defcustom org-confirm-shell-link-not-regexp ""
2045 "A regexp to skip confirmation for shell links."
2046 :group 'org-link-follow
2047 :version "24.1"
2048 :type 'regexp)
2050 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2051 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2052 Elisp links can be dangerous: just think about a link
2054 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2056 This link would show up in your Org-mode document as \"Google Search\",
2057 but really it would remove your entire home directory.
2058 Therefore we advise against setting this variable to nil.
2059 Just change it to `y-or-n-p' if you want to confirm with a
2060 single keystroke rather than having to type \"yes\"."
2061 :group 'org-link-follow
2062 :type '(choice
2063 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2064 (const :tag "with y-or-n (faster)" y-or-n-p)
2065 (const :tag "no confirmation (dangerous)" nil)))
2066 (put 'org-confirm-shell-link-function
2067 'safe-local-variable
2068 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2070 (defcustom org-confirm-elisp-link-not-regexp ""
2071 "A regexp to skip confirmation for Elisp links."
2072 :group 'org-link-follow
2073 :version "24.1"
2074 :type 'regexp)
2076 (defconst org-file-apps-defaults-gnu
2077 '((remote . emacs)
2078 (system . mailcap)
2079 (t . mailcap))
2080 "Default file applications on a UNIX or GNU/Linux system.
2081 See `org-file-apps'.")
2083 (defconst org-file-apps-defaults-macosx
2084 '((remote . emacs)
2085 (t . "open %s")
2086 (system . "open %s")
2087 ("ps.gz" . "gv %s")
2088 ("eps.gz" . "gv %s")
2089 ("dvi" . "xdvi %s")
2090 ("fig" . "xfig %s"))
2091 "Default file applications on a MacOS X system.
2092 The system \"open\" is known as a default, but we use X11 applications
2093 for some files for which the OS does not have a good default.
2094 See `org-file-apps'.")
2096 (defconst org-file-apps-defaults-windowsnt
2097 (list
2098 '(remote . emacs)
2099 (cons t
2100 (list (if (featurep 'xemacs)
2101 'mswindows-shell-execute
2102 'w32-shell-execute)
2103 "open" 'file))
2104 (cons 'system
2105 (list (if (featurep 'xemacs)
2106 'mswindows-shell-execute
2107 'w32-shell-execute)
2108 "open" 'file)))
2109 "Default file applications on a Windows NT system.
2110 The system \"open\" is used for most files.
2111 See `org-file-apps'.")
2113 (defcustom org-file-apps
2114 '((auto-mode . emacs)
2115 ("\\.mm\\'" . default)
2116 ("\\.x?html?\\'" . default)
2117 ("\\.pdf\\'" . default))
2118 "External applications for opening `file:path' items in a document.
2119 Org-mode uses system defaults for different file types, but
2120 you can use this variable to set the application for a given file
2121 extension. The entries in this list are cons cells where the car identifies
2122 files and the cdr the corresponding command. Possible values for the
2123 file identifier are
2124 \"string\" A string as a file identifier can be interpreted in different
2125 ways, depending on its contents:
2127 - Alphanumeric characters only:
2128 Match links with this file extension.
2129 Example: (\"pdf\" . \"evince %s\")
2130 to open PDFs with evince.
2132 - Regular expression: Match links where the
2133 filename matches the regexp. If you want to
2134 use groups here, use shy groups.
2136 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2137 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2138 to open *.html and *.xhtml with firefox.
2140 - Regular expression which contains (non-shy) groups:
2141 Match links where the whole link, including \"::\", and
2142 anything after that, matches the regexp.
2143 In a custom command string, %1, %2, etc. are replaced with
2144 the parts of the link that were matched by the groups.
2145 For backwards compatibility, if a command string is given
2146 that does not use any of the group matches, this case is
2147 handled identically to the second one (i.e. match against
2148 file name only).
2149 In a custom lisp form, you can access the group matches with
2150 (match-string n link).
2152 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2153 to open [[file:document.pdf::5]] with evince at page 5.
2155 `directory' Matches a directory
2156 `remote' Matches a remote file, accessible through tramp or efs.
2157 Remote files most likely should be visited through Emacs
2158 because external applications cannot handle such paths.
2159 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2160 so all files Emacs knows how to handle. Using this with
2161 command `emacs' will open most files in Emacs. Beware that this
2162 will also open html files inside Emacs, unless you add
2163 (\"html\" . default) to the list as well.
2164 t Default for files not matched by any of the other options.
2165 `system' The system command to open files, like `open' on Windows
2166 and Mac OS X, and mailcap under GNU/Linux. This is the command
2167 that will be selected if you call `C-c C-o' with a double
2168 \\[universal-argument] \\[universal-argument] prefix.
2170 Possible values for the command are:
2171 `emacs' The file will be visited by the current Emacs process.
2172 `default' Use the default application for this file type, which is the
2173 association for t in the list, most likely in the system-specific
2174 part.
2175 This can be used to overrule an unwanted setting in the
2176 system-specific variable.
2177 `system' Use the system command for opening files, like \"open\".
2178 This command is specified by the entry whose car is `system'.
2179 Most likely, the system-specific version of this variable
2180 does define this command, but you can overrule/replace it
2181 here.
2182 string A command to be executed by a shell; %s will be replaced
2183 by the path to the file.
2184 sexp A Lisp form which will be evaluated. The file path will
2185 be available in the Lisp variable `file'.
2186 For more examples, see the system specific constants
2187 `org-file-apps-defaults-macosx'
2188 `org-file-apps-defaults-windowsnt'
2189 `org-file-apps-defaults-gnu'."
2190 :group 'org-link-follow
2191 :type '(repeat
2192 (cons (choice :value ""
2193 (string :tag "Extension")
2194 (const :tag "System command to open files" system)
2195 (const :tag "Default for unrecognized files" t)
2196 (const :tag "Remote file" remote)
2197 (const :tag "Links to a directory" directory)
2198 (const :tag "Any files that have Emacs modes"
2199 auto-mode))
2200 (choice :value ""
2201 (const :tag "Visit with Emacs" emacs)
2202 (const :tag "Use default" default)
2203 (const :tag "Use the system command" system)
2204 (string :tag "Command")
2205 (sexp :tag "Lisp form")))))
2207 (defcustom org-doi-server-url "http://dx.doi.org/"
2208 "The URL of the DOI server."
2209 :type 'string
2210 :version "24.3"
2211 :group 'org-link-follow)
2213 (defgroup org-refile nil
2214 "Options concerning refiling entries in Org-mode."
2215 :tag "Org Refile"
2216 :group 'org)
2218 (defcustom org-directory "~/org"
2219 "Directory with org files.
2220 This is just a default location to look for Org files. There is no need
2221 at all to put your files into this directory. It is only used in the
2222 following situations:
2224 1. When a capture template specifies a target file that is not an
2225 absolute path. The path will then be interpreted relative to
2226 `org-directory'
2227 2. When a capture note is filed away in an interactive way (when exiting the
2228 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2229 with `org-directory' as the default path."
2230 :group 'org-refile
2231 :group 'org-capture
2232 :type 'directory)
2234 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2235 "Default target for storing notes.
2236 Used as a fall back file for org-capture.el, for templates that
2237 do not specify a target file."
2238 :group 'org-refile
2239 :group 'org-capture
2240 :type '(choice
2241 (const :tag "Default from remember-data-file" nil)
2242 file))
2244 (defcustom org-goto-interface 'outline
2245 "The default interface to be used for `org-goto'.
2246 Allowed values are:
2247 outline The interface shows an outline of the relevant file
2248 and the correct heading is found by moving through
2249 the outline or by searching with incremental search.
2250 outline-path-completion Headlines in the current buffer are offered via
2251 completion. This is the interface also used by
2252 the refile command."
2253 :group 'org-refile
2254 :type '(choice
2255 (const :tag "Outline" outline)
2256 (const :tag "Outline-path-completion" outline-path-completion)))
2258 (defcustom org-goto-max-level 5
2259 "Maximum target level when running `org-goto' with refile interface."
2260 :group 'org-refile
2261 :type 'integer)
2263 (defcustom org-reverse-note-order nil
2264 "Non-nil means store new notes at the beginning of a file or entry.
2265 When nil, new notes will be filed to the end of a file or entry.
2266 This can also be a list with cons cells of regular expressions that
2267 are matched against file names, and values."
2268 :group 'org-capture
2269 :group 'org-refile
2270 :type '(choice
2271 (const :tag "Reverse always" t)
2272 (const :tag "Reverse never" nil)
2273 (repeat :tag "By file name regexp"
2274 (cons regexp boolean))))
2276 (defcustom org-log-refile nil
2277 "Information to record when a task is refiled.
2279 Possible values are:
2281 nil Don't add anything
2282 time Add a time stamp to the task
2283 note Prompt for a note and add it with template `org-log-note-headings'
2285 This option can also be set with on a per-file-basis with
2287 #+STARTUP: nologrefile
2288 #+STARTUP: logrefile
2289 #+STARTUP: lognoterefile
2291 You can have local logging settings for a subtree by setting the LOGGING
2292 property to one or more of these keywords.
2294 When bulk-refiling from the agenda, the value `note' is forbidden and
2295 will temporarily be changed to `time'."
2296 :group 'org-refile
2297 :group 'org-progress
2298 :version "24.1"
2299 :type '(choice
2300 (const :tag "No logging" nil)
2301 (const :tag "Record timestamp" time)
2302 (const :tag "Record timestamp with note." note)))
2304 (defcustom org-refile-targets nil
2305 "Targets for refiling entries with \\[org-refile].
2306 This is a list of cons cells. Each cell contains:
2307 - a specification of the files to be considered, either a list of files,
2308 or a symbol whose function or variable value will be used to retrieve
2309 a file name or a list of file names. If you use `org-agenda-files' for
2310 that, all agenda files will be scanned for targets. Nil means consider
2311 headings in the current buffer.
2312 - A specification of how to find candidate refile targets. This may be
2313 any of:
2314 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2315 This tag has to be present in all target headlines, inheritance will
2316 not be considered.
2317 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2318 todo keyword.
2319 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2320 headlines that are refiling targets.
2321 - a cons cell (:level . N). Any headline of level N is considered a target.
2322 Note that, when `org-odd-levels-only' is set, level corresponds to
2323 order in hierarchy, not to the number of stars.
2324 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2325 Note that, when `org-odd-levels-only' is set, level corresponds to
2326 order in hierarchy, not to the number of stars.
2328 Each element of this list generates a set of possible targets.
2329 The union of these sets is presented (with completion) to
2330 the user by `org-refile'.
2332 You can set the variable `org-refile-target-verify-function' to a function
2333 to verify each headline found by the simple criteria above.
2335 When this variable is nil, all top-level headlines in the current buffer
2336 are used, equivalent to the value `((nil . (:level . 1))'."
2337 :group 'org-refile
2338 :type '(repeat
2339 (cons
2340 (choice :value org-agenda-files
2341 (const :tag "All agenda files" org-agenda-files)
2342 (const :tag "Current buffer" nil)
2343 (function) (variable) (file))
2344 (choice :tag "Identify target headline by"
2345 (cons :tag "Specific tag" (const :value :tag) (string))
2346 (cons :tag "TODO keyword" (const :value :todo) (string))
2347 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2348 (cons :tag "Level number" (const :value :level) (integer))
2349 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2351 (defcustom org-refile-target-verify-function nil
2352 "Function to verify if the headline at point should be a refile target.
2353 The function will be called without arguments, with point at the
2354 beginning of the headline. It should return t and leave point
2355 where it is if the headline is a valid target for refiling.
2357 If the target should not be selected, the function must return nil.
2358 In addition to this, it may move point to a place from where the search
2359 should be continued. For example, the function may decide that the entire
2360 subtree of the current entry should be excluded and move point to the end
2361 of the subtree."
2362 :group 'org-refile
2363 :type '(choice
2364 (const nil)
2365 (function)))
2367 (defcustom org-refile-use-cache nil
2368 "Non-nil means cache refile targets to speed up the process.
2369 The cache for a particular file will be updated automatically when
2370 the buffer has been killed, or when any of the marker used for flagging
2371 refile targets no longer points at a live buffer.
2372 If you have added new entries to a buffer that might themselves be targets,
2373 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2374 find that easier, `C-u C-u C-u C-c C-w'."
2375 :group 'org-refile
2376 :version "24.1"
2377 :type 'boolean)
2379 (defcustom org-refile-use-outline-path nil
2380 "Non-nil means provide refile targets as paths.
2381 So a level 3 headline will be available as level1/level2/level3.
2383 When the value is `file', also include the file name (without directory)
2384 into the path. In this case, you can also stop the completion after
2385 the file name, to get entries inserted as top level in the file.
2387 When `full-file-path', include the full file path."
2388 :group 'org-refile
2389 :type '(choice
2390 (const :tag "Not" nil)
2391 (const :tag "Yes" t)
2392 (const :tag "Start with file name" file)
2393 (const :tag "Start with full file path" full-file-path)))
2395 (defcustom org-outline-path-complete-in-steps t
2396 "Non-nil means complete the outline path in hierarchical steps.
2397 When Org-mode uses the refile interface to select an outline path
2398 \(see variable `org-refile-use-outline-path'), the completion of
2399 the path can be done is a single go, or if can be done in steps down
2400 the headline hierarchy. Going in steps is probably the best if you
2401 do not use a special completion package like `ido' or `icicles'.
2402 However, when using these packages, going in one step can be very
2403 fast, while still showing the whole path to the entry."
2404 :group 'org-refile
2405 :type 'boolean)
2407 (defcustom org-refile-allow-creating-parent-nodes nil
2408 "Non-nil means allow to create new nodes as refile targets.
2409 New nodes are then created by adding \"/new node name\" to the completion
2410 of an existing node. When the value of this variable is `confirm',
2411 new node creation must be confirmed by the user (recommended).
2412 When nil, the completion must match an existing entry.
2414 Note that, if the new heading is not seen by the criteria
2415 listed in `org-refile-targets', multiple instances of the same
2416 heading would be created by trying again to file under the new
2417 heading."
2418 :group 'org-refile
2419 :type '(choice
2420 (const :tag "Never" nil)
2421 (const :tag "Always" t)
2422 (const :tag "Prompt for confirmation" confirm)))
2424 (defcustom org-refile-active-region-within-subtree nil
2425 "Non-nil means also refile active region within a subtree.
2427 By default `org-refile' doesn't allow refiling regions if they
2428 don't contain a set of subtrees, but it might be convenient to
2429 do so sometimes: in that case, the first line of the region is
2430 converted to a headline before refiling."
2431 :group 'org-refile
2432 :version "24.1"
2433 :type 'boolean)
2435 (defgroup org-todo nil
2436 "Options concerning TODO items in Org-mode."
2437 :tag "Org TODO"
2438 :group 'org)
2440 (defgroup org-progress nil
2441 "Options concerning Progress logging in Org-mode."
2442 :tag "Org Progress"
2443 :group 'org-time)
2445 (defvar org-todo-interpretation-widgets
2446 '((:tag "Sequence (cycling hits every state)" sequence)
2447 (:tag "Type (cycling directly to DONE)" type))
2448 "The available interpretation symbols for customizing `org-todo-keywords'.
2449 Interested libraries should add to this list.")
2451 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2452 "List of TODO entry keyword sequences and their interpretation.
2453 \\<org-mode-map>This is a list of sequences.
2455 Each sequence starts with a symbol, either `sequence' or `type',
2456 indicating if the keywords should be interpreted as a sequence of
2457 action steps, or as different types of TODO items. The first
2458 keywords are states requiring action - these states will select a headline
2459 for inclusion into the global TODO list Org-mode produces. If one of
2460 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2461 signify that no further action is necessary. If \"|\" is not found,
2462 the last keyword is treated as the only DONE state of the sequence.
2464 The command \\[org-todo] cycles an entry through these states, and one
2465 additional state where no keyword is present. For details about this
2466 cycling, see the manual.
2468 TODO keywords and interpretation can also be set on a per-file basis with
2469 the special #+SEQ_TODO and #+TYP_TODO lines.
2471 Each keyword can optionally specify a character for fast state selection
2472 \(in combination with the variable `org-use-fast-todo-selection')
2473 and specifiers for state change logging, using the same syntax that
2474 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2475 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2476 indicates to record a time stamp each time this state is selected.
2478 Each keyword may also specify if a timestamp or a note should be
2479 recorded when entering or leaving the state, by adding additional
2480 characters in the parenthesis after the keyword. This looks like this:
2481 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2482 record only the time of the state change. With X and Y being either
2483 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2484 Y when leaving the state if and only if the *target* state does not
2485 define X. You may omit any of the fast-selection key or X or /Y,
2486 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2488 For backward compatibility, this variable may also be just a list
2489 of keywords. In this case the interpretation (sequence or type) will be
2490 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2491 :group 'org-todo
2492 :group 'org-keywords
2493 :type '(choice
2494 (repeat :tag "Old syntax, just keywords"
2495 (string :tag "Keyword"))
2496 (repeat :tag "New syntax"
2497 (cons
2498 (choice
2499 :tag "Interpretation"
2500 ;;Quick and dirty way to see
2501 ;;`org-todo-interpretations'. This takes the
2502 ;;place of item arguments
2503 :convert-widget
2504 (lambda (widget)
2505 (widget-put widget
2506 :args (mapcar
2507 (lambda (x)
2508 (widget-convert
2509 (cons 'const x)))
2510 org-todo-interpretation-widgets))
2511 widget))
2512 (repeat
2513 (string :tag "Keyword"))))))
2515 (defvar org-todo-keywords-1 nil
2516 "All TODO and DONE keywords active in a buffer.")
2517 (make-variable-buffer-local 'org-todo-keywords-1)
2518 (defvar org-todo-keywords-for-agenda nil)
2519 (defvar org-done-keywords-for-agenda nil)
2520 (defvar org-todo-keyword-alist-for-agenda nil)
2521 (defvar org-tag-alist-for-agenda nil
2522 "Alist of all tags from all agenda files.")
2523 (defvar org-tag-groups-alist-for-agenda nil
2524 "Alist of all groups tags from all current agenda files.")
2525 (defvar org-tag-groups-alist nil)
2526 (make-variable-buffer-local 'org-tag-groups-alist)
2527 (defvar org-agenda-contributing-files nil)
2528 (defvar org-not-done-keywords nil)
2529 (make-variable-buffer-local 'org-not-done-keywords)
2530 (defvar org-done-keywords nil)
2531 (make-variable-buffer-local 'org-done-keywords)
2532 (defvar org-todo-heads nil)
2533 (make-variable-buffer-local 'org-todo-heads)
2534 (defvar org-todo-sets nil)
2535 (make-variable-buffer-local 'org-todo-sets)
2536 (defvar org-todo-log-states nil)
2537 (make-variable-buffer-local 'org-todo-log-states)
2538 (defvar org-todo-kwd-alist nil)
2539 (make-variable-buffer-local 'org-todo-kwd-alist)
2540 (defvar org-todo-key-alist nil)
2541 (make-variable-buffer-local 'org-todo-key-alist)
2542 (defvar org-todo-key-trigger nil)
2543 (make-variable-buffer-local 'org-todo-key-trigger)
2545 (defcustom org-todo-interpretation 'sequence
2546 "Controls how TODO keywords are interpreted.
2547 This variable is in principle obsolete and is only used for
2548 backward compatibility, if the interpretation of todo keywords is
2549 not given already in `org-todo-keywords'. See that variable for
2550 more information."
2551 :group 'org-todo
2552 :group 'org-keywords
2553 :type '(choice (const sequence)
2554 (const type)))
2556 (defcustom org-use-fast-todo-selection t
2557 "Non-nil means use the fast todo selection scheme with C-c C-t.
2558 This variable describes if and under what circumstances the cycling
2559 mechanism for TODO keywords will be replaced by a single-key, direct
2560 selection scheme.
2562 When nil, fast selection is never used.
2564 When the symbol `prefix', it will be used when `org-todo' is called
2565 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2566 `C-u t' in an agenda buffer.
2568 When t, fast selection is used by default. In this case, the prefix
2569 argument forces cycling instead.
2571 In all cases, the special interface is only used if access keys have
2572 actually been assigned by the user, i.e. if keywords in the configuration
2573 are followed by a letter in parenthesis, like TODO(t)."
2574 :group 'org-todo
2575 :type '(choice
2576 (const :tag "Never" nil)
2577 (const :tag "By default" t)
2578 (const :tag "Only with C-u C-c C-t" prefix)))
2580 (defcustom org-provide-todo-statistics t
2581 "Non-nil means update todo statistics after insert and toggle.
2582 ALL-HEADLINES means update todo statistics by including headlines
2583 with no TODO keyword as well, counting them as not done.
2584 A list of TODO keywords means the same, but skip keywords that are
2585 not in this list.
2586 When set to a list of two lists, the first list contains keywords
2587 to consider as TODO keywords, the second list contains keywords
2588 to consider as DONE keywords.
2590 When this is set, todo statistics is updated in the parent of the
2591 current entry each time a todo state is changed."
2592 :group 'org-todo
2593 :type '(choice
2594 (const :tag "Yes, only for TODO entries" t)
2595 (const :tag "Yes, including all entries" all-headlines)
2596 (repeat :tag "Yes, for TODOs in this list"
2597 (string :tag "TODO keyword"))
2598 (list :tag "Yes, for TODOs and DONEs in these lists"
2599 (repeat (string :tag "TODO keyword"))
2600 (repeat (string :tag "DONE keyword")))
2601 (other :tag "No TODO statistics" nil)))
2603 (defcustom org-hierarchical-todo-statistics t
2604 "Non-nil means TODO statistics covers just direct children.
2605 When nil, all entries in the subtree are considered.
2606 This has only an effect if `org-provide-todo-statistics' is set.
2607 To set this to nil for only a single subtree, use a COOKIE_DATA
2608 property and include the word \"recursive\" into the value."
2609 :group 'org-todo
2610 :type 'boolean)
2612 (defcustom org-after-todo-state-change-hook nil
2613 "Hook which is run after the state of a TODO item was changed.
2614 The new state (a string with a TODO keyword, or nil) is available in the
2615 Lisp variable `org-state'."
2616 :group 'org-todo
2617 :type 'hook)
2619 (defvar org-blocker-hook nil
2620 "Hook for functions that are allowed to block a state change.
2622 Functions in this hook should not modify the buffer.
2623 Each function gets as its single argument a property list,
2624 see `org-trigger-hook' for more information about this list.
2626 If any of the functions in this hook returns nil, the state change
2627 is blocked.")
2629 (defvar org-trigger-hook nil
2630 "Hook for functions that are triggered by a state change.
2632 Each function gets as its single argument a property list with at
2633 least the following elements:
2635 (:type type-of-change :position pos-at-entry-start
2636 :from old-state :to new-state)
2638 Depending on the type, more properties may be present.
2640 This mechanism is currently implemented for:
2642 TODO state changes
2643 ------------------
2644 :type todo-state-change
2645 :from previous state (keyword as a string), or nil, or a symbol
2646 'todo' or 'done', to indicate the general type of state.
2647 :to new state, like in :from")
2649 (defcustom org-enforce-todo-dependencies nil
2650 "Non-nil means undone TODO entries will block switching the parent to DONE.
2651 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2652 be blocked if any prior sibling is not yet done.
2653 Finally, if the parent is blocked because of ordered siblings of its own,
2654 the child will also be blocked."
2655 :set (lambda (var val)
2656 (set var val)
2657 (if val
2658 (add-hook 'org-blocker-hook
2659 'org-block-todo-from-children-or-siblings-or-parent)
2660 (remove-hook 'org-blocker-hook
2661 'org-block-todo-from-children-or-siblings-or-parent)))
2662 :group 'org-todo
2663 :type 'boolean)
2665 (defcustom org-enforce-todo-checkbox-dependencies nil
2666 "Non-nil means unchecked boxes will block switching the parent to DONE.
2667 When this is nil, checkboxes have no influence on switching TODO states.
2668 When non-nil, you first need to check off all check boxes before the TODO
2669 entry can be switched to DONE.
2670 This variable needs to be set before org.el is loaded, and you need to
2671 restart Emacs after a change to make the change effective. The only way
2672 to change is while Emacs is running is through the customize interface."
2673 :set (lambda (var val)
2674 (set var val)
2675 (if val
2676 (add-hook 'org-blocker-hook
2677 'org-block-todo-from-checkboxes)
2678 (remove-hook 'org-blocker-hook
2679 'org-block-todo-from-checkboxes)))
2680 :group 'org-todo
2681 :type 'boolean)
2683 (defcustom org-treat-insert-todo-heading-as-state-change nil
2684 "Non-nil means inserting a TODO heading is treated as state change.
2685 So when the command \\[org-insert-todo-heading] is used, state change
2686 logging will apply if appropriate. When nil, the new TODO item will
2687 be inserted directly, and no logging will take place."
2688 :group 'org-todo
2689 :type 'boolean)
2691 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2692 "Non-nil means switching TODO states with S-cursor counts as state change.
2693 This is the default behavior. However, setting this to nil allows a
2694 convenient way to select a TODO state and bypass any logging associated
2695 with that."
2696 :group 'org-todo
2697 :type 'boolean)
2699 (defcustom org-todo-state-tags-triggers nil
2700 "Tag changes that should be triggered by TODO state changes.
2701 This is a list. Each entry is
2703 (state-change (tag . flag) .......)
2705 State-change can be a string with a state, and empty string to indicate the
2706 state that has no TODO keyword, or it can be one of the symbols `todo'
2707 or `done', meaning any not-done or done state, respectively."
2708 :group 'org-todo
2709 :group 'org-tags
2710 :type '(repeat
2711 (cons (choice :tag "When changing to"
2712 (const :tag "Not-done state" todo)
2713 (const :tag "Done state" done)
2714 (string :tag "State"))
2715 (repeat
2716 (cons :tag "Tag action"
2717 (string :tag "Tag")
2718 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2720 (defcustom org-log-done nil
2721 "Information to record when a task moves to the DONE state.
2723 Possible values are:
2725 nil Don't add anything, just change the keyword
2726 time Add a time stamp to the task
2727 note Prompt for a note and add it with template `org-log-note-headings'
2729 This option can also be set with on a per-file-basis with
2731 #+STARTUP: nologdone
2732 #+STARTUP: logdone
2733 #+STARTUP: lognotedone
2735 You can have local logging settings for a subtree by setting the LOGGING
2736 property to one or more of these keywords."
2737 :group 'org-todo
2738 :group 'org-progress
2739 :type '(choice
2740 (const :tag "No logging" nil)
2741 (const :tag "Record CLOSED timestamp" time)
2742 (const :tag "Record CLOSED timestamp with note." note)))
2744 ;; Normalize old uses of org-log-done.
2745 (cond
2746 ((eq org-log-done t) (setq org-log-done 'time))
2747 ((and (listp org-log-done) (memq 'done org-log-done))
2748 (setq org-log-done 'note)))
2750 (defcustom org-log-reschedule nil
2751 "Information to record when the scheduling date of a tasks is modified.
2753 Possible values are:
2755 nil Don't add anything, just change the date
2756 time Add a time stamp to the task
2757 note Prompt for a note and add it with template `org-log-note-headings'
2759 This option can also be set with on a per-file-basis with
2761 #+STARTUP: nologreschedule
2762 #+STARTUP: logreschedule
2763 #+STARTUP: lognotereschedule"
2764 :group 'org-todo
2765 :group 'org-progress
2766 :type '(choice
2767 (const :tag "No logging" nil)
2768 (const :tag "Record timestamp" time)
2769 (const :tag "Record timestamp with note." note)))
2771 (defcustom org-log-redeadline nil
2772 "Information to record when the deadline date of a tasks is modified.
2774 Possible values are:
2776 nil Don't add anything, just change the date
2777 time Add a time stamp to the task
2778 note Prompt for a note and add it with template `org-log-note-headings'
2780 This option can also be set with on a per-file-basis with
2782 #+STARTUP: nologredeadline
2783 #+STARTUP: logredeadline
2784 #+STARTUP: lognoteredeadline
2786 You can have local logging settings for a subtree by setting the LOGGING
2787 property to one or more of these keywords."
2788 :group 'org-todo
2789 :group 'org-progress
2790 :type '(choice
2791 (const :tag "No logging" nil)
2792 (const :tag "Record timestamp" time)
2793 (const :tag "Record timestamp with note." note)))
2795 (defcustom org-log-note-clock-out nil
2796 "Non-nil means record a note when clocking out of an item.
2797 This can also be configured on a per-file basis by adding one of
2798 the following lines anywhere in the buffer:
2800 #+STARTUP: lognoteclock-out
2801 #+STARTUP: nolognoteclock-out"
2802 :group 'org-todo
2803 :group 'org-progress
2804 :type 'boolean)
2806 (defcustom org-log-done-with-time t
2807 "Non-nil means the CLOSED time stamp will contain date and time.
2808 When nil, only the date will be recorded."
2809 :group 'org-progress
2810 :type 'boolean)
2812 (defcustom org-log-note-headings
2813 '((done . "CLOSING NOTE %t")
2814 (state . "State %-12s from %-12S %t")
2815 (note . "Note taken on %t")
2816 (reschedule . "Rescheduled from %S on %t")
2817 (delschedule . "Not scheduled, was %S on %t")
2818 (redeadline . "New deadline from %S on %t")
2819 (deldeadline . "Removed deadline, was %S on %t")
2820 (refile . "Refiled on %t")
2821 (clock-out . ""))
2822 "Headings for notes added to entries.
2823 The value is an alist, with the car being a symbol indicating the note
2824 context, and the cdr is the heading to be used. The heading may also be the
2825 empty string.
2826 %t in the heading will be replaced by a time stamp.
2827 %T will be an active time stamp instead the default inactive one
2828 %d will be replaced by a short-format time stamp.
2829 %D will be replaced by an active short-format time stamp.
2830 %s will be replaced by the new TODO state, in double quotes.
2831 %S will be replaced by the old TODO state, in double quotes.
2832 %u will be replaced by the user name.
2833 %U will be replaced by the full user name.
2835 In fact, it is not a good idea to change the `state' entry, because
2836 agenda log mode depends on the format of these entries."
2837 :group 'org-todo
2838 :group 'org-progress
2839 :type '(list :greedy t
2840 (cons (const :tag "Heading when closing an item" done) string)
2841 (cons (const :tag
2842 "Heading when changing todo state (todo sequence only)"
2843 state) string)
2844 (cons (const :tag "Heading when just taking a note" note) string)
2845 (cons (const :tag "Heading when rescheduling" reschedule) string)
2846 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2847 (cons (const :tag "Heading when changing deadline" redeadline) string)
2848 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2849 (cons (const :tag "Heading when refiling" refile) string)
2850 (cons (const :tag "Heading when clocking out" clock-out) string)))
2852 (unless (assq 'note org-log-note-headings)
2853 (push '(note . "%t") org-log-note-headings))
2855 (defcustom org-log-into-drawer nil
2856 "Non-nil means insert state change notes and time stamps into a drawer.
2857 When nil, state changes notes will be inserted after the headline and
2858 any scheduling and clock lines, but not inside a drawer.
2860 The value of this variable should be the name of the drawer to use.
2861 LOGBOOK is proposed as the default drawer for this purpose, you can
2862 also set this to a string to define the drawer of your choice.
2864 A value of t is also allowed, representing \"LOGBOOK\".
2866 A value of t or nil can also be set with on a per-file-basis with
2868 #+STARTUP: logdrawer
2869 #+STARTUP: nologdrawer
2871 If this variable is set, `org-log-state-notes-insert-after-drawers'
2872 will be ignored.
2874 You can set the property LOG_INTO_DRAWER to overrule this setting for
2875 a subtree."
2876 :group 'org-todo
2877 :group 'org-progress
2878 :type '(choice
2879 (const :tag "Not into a drawer" nil)
2880 (const :tag "LOGBOOK" t)
2881 (string :tag "Other")))
2883 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2885 (defun org-log-into-drawer ()
2886 "Return the value of `org-log-into-drawer', but let properties overrule.
2887 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2888 used instead of the default value."
2889 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2890 (cond
2891 ((not p) org-log-into-drawer)
2892 ((equal p "nil") nil)
2893 ((equal p "t") "LOGBOOK")
2894 (t p))))
2896 (defcustom org-log-state-notes-insert-after-drawers nil
2897 "Non-nil means insert state change notes after any drawers in entry.
2898 Only the drawers that *immediately* follow the headline and the
2899 deadline/scheduled line are skipped.
2900 When nil, insert notes right after the heading and perhaps the line
2901 with deadline/scheduling if present.
2903 This variable will have no effect if `org-log-into-drawer' is
2904 set."
2905 :group 'org-todo
2906 :group 'org-progress
2907 :type 'boolean)
2909 (defcustom org-log-states-order-reversed t
2910 "Non-nil means the latest state note will be directly after heading.
2911 When nil, the state change notes will be ordered according to time.
2913 This option can also be set with on a per-file-basis with
2915 #+STARTUP: logstatesreversed
2916 #+STARTUP: nologstatesreversed"
2917 :group 'org-todo
2918 :group 'org-progress
2919 :type 'boolean)
2921 (defcustom org-todo-repeat-to-state nil
2922 "The TODO state to which a repeater should return the repeating task.
2923 By default this is the first task in a TODO sequence, or the previous state
2924 in a TODO_TYP set. But you can specify another task here.
2925 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2926 :group 'org-todo
2927 :version "24.1"
2928 :type '(choice (const :tag "Head of sequence" nil)
2929 (string :tag "Specific state")))
2931 (defcustom org-log-repeat 'time
2932 "Non-nil means record moving through the DONE state when triggering repeat.
2933 An auto-repeating task is immediately switched back to TODO when
2934 marked DONE. If you are not logging state changes (by adding \"@\"
2935 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2936 record a closing note, there will be no record of the task moving
2937 through DONE. This variable forces taking a note anyway.
2939 nil Don't force a record
2940 time Record a time stamp
2941 note Prompt for a note and add it with template `org-log-note-headings'
2943 This option can also be set with on a per-file-basis with
2945 #+STARTUP: nologrepeat
2946 #+STARTUP: logrepeat
2947 #+STARTUP: lognoterepeat
2949 You can have local logging settings for a subtree by setting the LOGGING
2950 property to one or more of these keywords."
2951 :group 'org-todo
2952 :group 'org-progress
2953 :type '(choice
2954 (const :tag "Don't force a record" nil)
2955 (const :tag "Force recording the DONE state" time)
2956 (const :tag "Force recording a note with the DONE state" note)))
2959 (defgroup org-priorities nil
2960 "Priorities in Org-mode."
2961 :tag "Org Priorities"
2962 :group 'org-todo)
2964 (defcustom org-enable-priority-commands t
2965 "Non-nil means priority commands are active.
2966 When nil, these commands will be disabled, so that you never accidentally
2967 set a priority."
2968 :group 'org-priorities
2969 :type 'boolean)
2971 (defcustom org-highest-priority ?A
2972 "The highest priority of TODO items. A character like ?A, ?B etc.
2973 Must have a smaller ASCII number than `org-lowest-priority'."
2974 :group 'org-priorities
2975 :type 'character)
2977 (defcustom org-lowest-priority ?C
2978 "The lowest priority of TODO items. A character like ?A, ?B etc.
2979 Must have a larger ASCII number than `org-highest-priority'."
2980 :group 'org-priorities
2981 :type 'character)
2983 (defcustom org-default-priority ?B
2984 "The default priority of TODO items.
2985 This is the priority an item gets if no explicit priority is given.
2986 When starting to cycle on an empty priority the first step in the cycle
2987 depends on `org-priority-start-cycle-with-default'. The resulting first
2988 step priority must not exceed the range from `org-highest-priority' to
2989 `org-lowest-priority' which means that `org-default-priority' has to be
2990 in this range exclusive or inclusive the range boundaries. Else the
2991 first step refuses to set the default and the second will fall back
2992 to (depending on the command used) the highest or lowest priority."
2993 :group 'org-priorities
2994 :type 'character)
2996 (defcustom org-priority-start-cycle-with-default t
2997 "Non-nil means start with default priority when starting to cycle.
2998 When this is nil, the first step in the cycle will be (depending on the
2999 command used) one higher or lower than the default priority.
3000 See also `org-default-priority'."
3001 :group 'org-priorities
3002 :type 'boolean)
3004 (defcustom org-get-priority-function nil
3005 "Function to extract the priority from a string.
3006 The string is normally the headline. If this is nil Org computes the
3007 priority from the priority cookie like [#A] in the headline. It returns
3008 an integer, increasing by 1000 for each priority level.
3009 The user can set a different function here, which should take a string
3010 as an argument and return the numeric priority."
3011 :group 'org-priorities
3012 :version "24.1"
3013 :type '(choice
3014 (const nil)
3015 (function)))
3017 (defgroup org-time nil
3018 "Options concerning time stamps and deadlines in Org-mode."
3019 :tag "Org Time"
3020 :group 'org)
3022 (defcustom org-insert-labeled-timestamps-at-point nil
3023 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3024 When nil, these labeled time stamps are forces into the second line of an
3025 entry, just after the headline. When scheduling from the global TODO list,
3026 the time stamp will always be forced into the second line."
3027 :group 'org-time
3028 :type 'boolean)
3030 (defcustom org-time-stamp-rounding-minutes '(0 5)
3031 "Number of minutes to round time stamps to.
3032 These are two values, the first applies when first creating a time stamp.
3033 The second applies when changing it with the commands `S-up' and `S-down'.
3034 When changing the time stamp, this means that it will change in steps
3035 of N minutes, as given by the second value.
3037 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3038 numbers should be factors of 60, so for example 5, 10, 15.
3040 When this is larger than 1, you can still force an exact time stamp by using
3041 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3042 and by using a prefix arg to `S-up/down' to specify the exact number
3043 of minutes to shift."
3044 :group 'org-time
3045 :get (lambda (var) ; Make sure both elements are there
3046 (if (integerp (default-value var))
3047 (list (default-value var) 5)
3048 (default-value var)))
3049 :type '(list
3050 (integer :tag "when inserting times")
3051 (integer :tag "when modifying times")))
3053 ;; Normalize old customizations of this variable.
3054 (when (integerp org-time-stamp-rounding-minutes)
3055 (setq org-time-stamp-rounding-minutes
3056 (list org-time-stamp-rounding-minutes
3057 org-time-stamp-rounding-minutes)))
3059 (defcustom org-display-custom-times nil
3060 "Non-nil means overlay custom formats over all time stamps.
3061 The formats are defined through the variable `org-time-stamp-custom-formats'.
3062 To turn this on on a per-file basis, insert anywhere in the file:
3063 #+STARTUP: customtime"
3064 :group 'org-time
3065 :set 'set-default
3066 :type 'sexp)
3067 (make-variable-buffer-local 'org-display-custom-times)
3069 (defcustom org-time-stamp-custom-formats
3070 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3071 "Custom formats for time stamps. See `format-time-string' for the syntax.
3072 These are overlaid over the default ISO format if the variable
3073 `org-display-custom-times' is set. Time like %H:%M should be at the
3074 end of the second format. The custom formats are also honored by export
3075 commands, if custom time display is turned on at the time of export."
3076 :group 'org-time
3077 :type 'sexp)
3079 (defun org-time-stamp-format (&optional long inactive)
3080 "Get the right format for a time string."
3081 (let ((f (if long (cdr org-time-stamp-formats)
3082 (car org-time-stamp-formats))))
3083 (if inactive
3084 (concat "[" (substring f 1 -1) "]")
3085 f)))
3087 (defcustom org-time-clocksum-format
3088 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3089 "The format string used when creating CLOCKSUM lines.
3090 This is also used when Org mode generates a time duration.
3092 The value can be a single format string containing two
3093 %-sequences, which will be filled with the number of hours and
3094 minutes in that order.
3096 Alternatively, the value can be a plist associating any of the
3097 keys :years, :months, :weeks, :days, :hours or :minutes with
3098 format strings. The time duration is formatted using only the
3099 time components that are needed and concatenating the results.
3100 If a time unit in absent, it falls back to the next smallest
3101 unit.
3103 The keys :require-years, :require-months, :require-days,
3104 :require-weeks, :require-hours, :require-minutes are also
3105 meaningful. A non-nil value for these keys indicates that the
3106 corresponding time component should always be included, even if
3107 its value is 0.
3110 For example,
3112 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3113 :require-minutes t)
3115 means durations longer than a day will be expressed in days,
3116 hours and minutes, and durations less than a day will always be
3117 expressed in hours and minutes (even for durations less than an
3118 hour).
3120 The value
3122 \(:days \"%dd\" :minutes \"%dm\")
3124 means durations longer than a day will be expressed in days and
3125 minutes, and durations less than a day will be expressed entirely
3126 in minutes (even for durations longer than an hour)."
3127 :group 'org-time
3128 :group 'org-clock
3129 :version "24.4"
3130 :package-version '(Org . "8.0")
3131 :type '(choice (string :tag "Format string")
3132 (set :tag "Plist"
3133 (group :inline t (const :tag "Years" :years)
3134 (string :tag "Format string"))
3135 (group :inline t
3136 (const :tag "Always show years" :require-years)
3137 (const t))
3138 (group :inline t (const :tag "Months" :months)
3139 (string :tag "Format string"))
3140 (group :inline t
3141 (const :tag "Always show months" :require-months)
3142 (const t))
3143 (group :inline t (const :tag "Weeks" :weeks)
3144 (string :tag "Format string"))
3145 (group :inline t
3146 (const :tag "Always show weeks" :require-weeks)
3147 (const t))
3148 (group :inline t (const :tag "Days" :days)
3149 (string :tag "Format string"))
3150 (group :inline t
3151 (const :tag "Always show days" :require-days)
3152 (const t))
3153 (group :inline t (const :tag "Hours" :hours)
3154 (string :tag "Format string"))
3155 (group :inline t
3156 (const :tag "Always show hours" :require-hours)
3157 (const t))
3158 (group :inline t (const :tag "Minutes" :minutes)
3159 (string :tag "Format string"))
3160 (group :inline t
3161 (const :tag "Always show minutes" :require-minutes)
3162 (const t)))))
3164 (defcustom org-time-clocksum-use-fractional nil
3165 "When non-nil, \\[org-clock-display] uses fractional times.
3166 See `org-time-clocksum-format' for more on time clock formats."
3167 :group 'org-time
3168 :group 'org-clock
3169 :version "24.3"
3170 :type 'boolean)
3172 (defcustom org-time-clocksum-use-effort-durations nil
3173 "When non-nil, \\[org-clock-display] uses effort durations.
3174 E.g. by default, one day is considered to be a 8 hours effort,
3175 so a task that has been clocked for 16 hours will be displayed
3176 as during 2 days in the clock display or in the clocktable.
3178 See `org-effort-durations' on how to set effort durations
3179 and `org-time-clocksum-format' for more on time clock formats."
3180 :group 'org-time
3181 :group 'org-clock
3182 :version "24.4"
3183 :package-version '(Org . "8.0")
3184 :type 'boolean)
3186 (defcustom org-time-clocksum-fractional-format "%.2f"
3187 "The format string used when creating CLOCKSUM lines,
3188 or when Org mode generates a time duration, if
3189 `org-time-clocksum-use-fractional' is enabled.
3191 The value can be a single format string containing one
3192 %-sequence, which will be filled with the number of hours as
3193 a float.
3195 Alternatively, the value can be a plist associating any of the
3196 keys :years, :months, :weeks, :days, :hours or :minutes with
3197 a format string. The time duration is formatted using the
3198 largest time unit which gives a non-zero integer part. If all
3199 specified formats have zero integer part, the smallest time unit
3200 is used."
3201 :group 'org-time
3202 :type '(choice (string :tag "Format string")
3203 (set (group :inline t (const :tag "Years" :years)
3204 (string :tag "Format string"))
3205 (group :inline t (const :tag "Months" :months)
3206 (string :tag "Format string"))
3207 (group :inline t (const :tag "Weeks" :weeks)
3208 (string :tag "Format string"))
3209 (group :inline t (const :tag "Days" :days)
3210 (string :tag "Format string"))
3211 (group :inline t (const :tag "Hours" :hours)
3212 (string :tag "Format string"))
3213 (group :inline t (const :tag "Minutes" :minutes)
3214 (string :tag "Format string")))))
3216 (defcustom org-deadline-warning-days 14
3217 "Number of days before expiration during which a deadline becomes active.
3218 This variable governs the display in sparse trees and in the agenda.
3219 When 0 or negative, it means use this number (the absolute value of it)
3220 even if a deadline has a different individual lead time specified.
3222 Custom commands can set this variable in the options section."
3223 :group 'org-time
3224 :group 'org-agenda-daily/weekly
3225 :type 'integer)
3227 (defcustom org-scheduled-delay-days 0
3228 "Number of days before a scheduled item becomes active.
3229 This variable governs the display in sparse trees and in the agenda.
3230 The default value (i.e. 0) means: don't delay scheduled item.
3231 When negative, it means use this number (the absolute value of it)
3232 even if a scheduled item has a different individual delay time
3233 specified.
3235 Custom commands can set this variable in the options section."
3236 :group 'org-time
3237 :group 'org-agenda-daily/weekly
3238 :version "24.4"
3239 :package-version '(Org . "8.0")
3240 :type 'integer)
3242 (defcustom org-read-date-prefer-future t
3243 "Non-nil means assume future for incomplete date input from user.
3244 This affects the following situations:
3245 1. The user gives a month but not a year.
3246 For example, if it is April and you enter \"feb 2\", this will be read
3247 as Feb 2, *next* year. \"May 5\", however, will be this year.
3248 2. The user gives a day, but no month.
3249 For example, if today is the 15th, and you enter \"3\", Org-mode will
3250 read this as the third of *next* month. However, if you enter \"17\",
3251 it will be considered as *this* month.
3253 If you set this variable to the symbol `time', then also the following
3254 will work:
3256 3. If the user gives a time.
3257 If the time is before now, it will be interpreted as tomorrow.
3259 Currently none of this works for ISO week specifications.
3261 When this option is nil, the current day, month and year will always be
3262 used as defaults.
3264 See also `org-agenda-jump-prefer-future'."
3265 :group 'org-time
3266 :type '(choice
3267 (const :tag "Never" nil)
3268 (const :tag "Check month and day" t)
3269 (const :tag "Check month, day, and time" time)))
3271 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3272 "Should the agenda jump command prefer the future for incomplete dates?
3273 The default is to do the same as configured in `org-read-date-prefer-future'.
3274 But you can also set a deviating value here.
3275 This may t or nil, or the symbol `org-read-date-prefer-future'."
3276 :group 'org-agenda
3277 :group 'org-time
3278 :version "24.1"
3279 :type '(choice
3280 (const :tag "Use org-read-date-prefer-future"
3281 org-read-date-prefer-future)
3282 (const :tag "Never" nil)
3283 (const :tag "Always" t)))
3285 (defcustom org-read-date-force-compatible-dates t
3286 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3288 Depending on the system Emacs is running on, certain dates cannot
3289 be represented with the type used internally to represent time.
3290 Dates between 1970-1-1 and 2038-1-1 can always be represented
3291 correctly. Some systems allow for earlier dates, some for later,
3292 some for both. One way to find out it to insert any date into an
3293 Org buffer, putting the cursor on the year and hitting S-up and
3294 S-down to test the range.
3296 When this variable is set to t, the date/time prompt will not let
3297 you specify dates outside the 1970-2037 range, so it is certain that
3298 these dates will work in whatever version of Emacs you are
3299 running, and also that you can move a file from one Emacs implementation
3300 to another. WHenever Org is forcing the year for you, it will display
3301 a message and beep.
3303 When this variable is nil, Org will check if the date is
3304 representable in the specific Emacs implementation you are using.
3305 If not, it will force a year, usually the current year, and beep
3306 to remind you. Currently this setting is not recommended because
3307 the likelihood that you will open your Org files in an Emacs that
3308 has limited date range is not negligible.
3310 A workaround for this problem is to use diary sexp dates for time
3311 stamps outside of this range."
3312 :group 'org-time
3313 :version "24.1"
3314 :type 'boolean)
3316 (defcustom org-read-date-display-live t
3317 "Non-nil means display current interpretation of date prompt live.
3318 This display will be in an overlay, in the minibuffer."
3319 :group 'org-time
3320 :type 'boolean)
3322 (defcustom org-read-date-popup-calendar t
3323 "Non-nil means pop up a calendar when prompting for a date.
3324 In the calendar, the date can be selected with mouse-1. However, the
3325 minibuffer will also be active, and you can simply enter the date as well.
3326 When nil, only the minibuffer will be available."
3327 :group 'org-time
3328 :type 'boolean)
3329 (org-defvaralias 'org-popup-calendar-for-date-prompt
3330 'org-read-date-popup-calendar)
3332 (make-obsolete-variable
3333 'org-read-date-minibuffer-setup-hook
3334 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3335 (defcustom org-read-date-minibuffer-setup-hook nil
3336 "Hook to be used to set up keys for the date/time interface.
3337 Add key definitions to `minibuffer-local-map', which will be a
3338 temporary copy.
3340 WARNING: This option is obsolete, you should use
3341 `org-read-date-minibuffer-local-map' to set up keys."
3342 :group 'org-time
3343 :type 'hook)
3345 (defcustom org-extend-today-until 0
3346 "The hour when your day really ends. Must be an integer.
3347 This has influence for the following applications:
3348 - When switching the agenda to \"today\". It it is still earlier than
3349 the time given here, the day recognized as TODAY is actually yesterday.
3350 - When a date is read from the user and it is still before the time given
3351 here, the current date and time will be assumed to be yesterday, 23:59.
3352 Also, timestamps inserted in capture templates follow this rule.
3354 IMPORTANT: This is a feature whose implementation is and likely will
3355 remain incomplete. Really, it is only here because past midnight seems to
3356 be the favorite working time of John Wiegley :-)"
3357 :group 'org-time
3358 :type 'integer)
3360 (defcustom org-use-effective-time nil
3361 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3362 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3363 \"effective time\" of any timestamps between midnight and 8am will be
3364 23:59 of the previous day."
3365 :group 'org-time
3366 :version "24.1"
3367 :type 'boolean)
3369 (defcustom org-use-last-clock-out-time-as-effective-time nil
3370 "When non-nil, use the last clock out time for `org-todo'.
3371 Note that this option has precedence over the combined use of
3372 `org-use-effective-time' and `org-extend-today-until'."
3373 :group 'org-time
3374 :version "24.4"
3375 :package-version '(Org . "8.0")
3376 :type 'boolean)
3378 (defcustom org-edit-timestamp-down-means-later nil
3379 "Non-nil means S-down will increase the time in a time stamp.
3380 When nil, S-up will increase."
3381 :group 'org-time
3382 :type 'boolean)
3384 (defcustom org-calendar-follow-timestamp-change t
3385 "Non-nil means make the calendar window follow timestamp changes.
3386 When a timestamp is modified and the calendar window is visible, it will be
3387 moved to the new date."
3388 :group 'org-time
3389 :type 'boolean)
3391 (defgroup org-tags nil
3392 "Options concerning tags in Org-mode."
3393 :tag "Org Tags"
3394 :group 'org)
3396 (defcustom org-tag-alist nil
3397 "List of tags allowed in Org-mode files.
3398 When this list is nil, Org-mode will base TAG input on what is already in the
3399 buffer.
3400 The value of this variable is an alist, the car of each entry must be a
3401 keyword as a string, the cdr may be a character that is used to select
3402 that tag through the fast-tag-selection interface.
3403 See the manual for details."
3404 :group 'org-tags
3405 :type '(repeat
3406 (choice
3407 (cons (string :tag "Tag name")
3408 (character :tag "Access char"))
3409 (list :tag "Start radio group"
3410 (const :startgroup)
3411 (option (string :tag "Group description")))
3412 (list :tag "Group tags delimiter"
3413 (const :grouptags))
3414 (list :tag "End radio group"
3415 (const :endgroup)
3416 (option (string :tag "Group description")))
3417 (const :tag "New line" (:newline)))))
3419 (defcustom org-tag-persistent-alist nil
3420 "List of tags that will always appear in all Org-mode files.
3421 This is in addition to any in buffer settings or customizations
3422 of `org-tag-alist'.
3423 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3424 The value of this variable is an alist, the car of each entry must be a
3425 keyword as a string, the cdr may be a character that is used to select
3426 that tag through the fast-tag-selection interface.
3427 See the manual for details.
3428 To disable these tags on a per-file basis, insert anywhere in the file:
3429 #+STARTUP: noptag"
3430 :group 'org-tags
3431 :type '(repeat
3432 (choice
3433 (cons (string :tag "Tag name")
3434 (character :tag "Access char"))
3435 (const :tag "Start radio group" (:startgroup))
3436 (const :tag "Group tags delimiter" (:grouptags))
3437 (const :tag "End radio group" (:endgroup))
3438 (const :tag "New line" (:newline)))))
3440 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3441 "If non-nil, always offer completion for all tags of all agenda files.
3442 Instead of customizing this variable directly, you might want to
3443 set it locally for capture buffers, because there no list of
3444 tags in that file can be created dynamically (there are none).
3446 (add-hook 'org-capture-mode-hook
3447 (lambda ()
3448 (set (make-local-variable
3449 'org-complete-tags-always-offer-all-agenda-tags)
3450 t)))"
3451 :group 'org-tags
3452 :version "24.1"
3453 :type 'boolean)
3455 (defvar org-file-tags nil
3456 "List of tags that can be inherited by all entries in the file.
3457 The tags will be inherited if the variable `org-use-tag-inheritance'
3458 says they should be.
3459 This variable is populated from #+FILETAGS lines.")
3461 (defcustom org-use-fast-tag-selection 'auto
3462 "Non-nil means use fast tag selection scheme.
3463 This is a special interface to select and deselect tags with single keys.
3464 When nil, fast selection is never used.
3465 When the symbol `auto', fast selection is used if and only if selection
3466 characters for tags have been configured, either through the variable
3467 `org-tag-alist' or through a #+TAGS line in the buffer.
3468 When t, fast selection is always used and selection keys are assigned
3469 automatically if necessary."
3470 :group 'org-tags
3471 :type '(choice
3472 (const :tag "Always" t)
3473 (const :tag "Never" nil)
3474 (const :tag "When selection characters are configured" auto)))
3476 (defcustom org-fast-tag-selection-single-key nil
3477 "Non-nil means fast tag selection exits after first change.
3478 When nil, you have to press RET to exit it.
3479 During fast tag selection, you can toggle this flag with `C-c'.
3480 This variable can also have the value `expert'. In this case, the window
3481 displaying the tags menu is not even shown, until you press C-c again."
3482 :group 'org-tags
3483 :type '(choice
3484 (const :tag "No" nil)
3485 (const :tag "Yes" t)
3486 (const :tag "Expert" expert)))
3488 (defvar org-fast-tag-selection-include-todo nil
3489 "Non-nil means fast tags selection interface will also offer TODO states.
3490 This is an undocumented feature, you should not rely on it.")
3492 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3493 "The column to which tags should be indented in a headline.
3494 If this number is positive, it specifies the column. If it is negative,
3495 it means that the tags should be flushright to that column. For example,
3496 -80 works well for a normal 80 character screen.
3497 When 0, place tags directly after headline text, with only one space in
3498 between."
3499 :group 'org-tags
3500 :type 'integer)
3502 (defcustom org-auto-align-tags t
3503 "Non-nil keeps tags aligned when modifying headlines.
3504 Some operations (i.e. demoting) change the length of a headline and
3505 therefore shift the tags around. With this option turned on, after
3506 each such operation the tags are again aligned to `org-tags-column'."
3507 :group 'org-tags
3508 :type 'boolean)
3510 (defcustom org-use-tag-inheritance t
3511 "Non-nil means tags in levels apply also for sublevels.
3512 When nil, only the tags directly given in a specific line apply there.
3513 This may also be a list of tags that should be inherited, or a regexp that
3514 matches tags that should be inherited. Additional control is possible
3515 with the variable `org-tags-exclude-from-inheritance' which gives an
3516 explicit list of tags to be excluded from inheritance, even if the value of
3517 `org-use-tag-inheritance' would select it for inheritance.
3519 If this option is t, a match early-on in a tree can lead to a large
3520 number of matches in the subtree when constructing the agenda or creating
3521 a sparse tree. If you only want to see the first match in a tree during
3522 a search, check out the variable `org-tags-match-list-sublevels'."
3523 :group 'org-tags
3524 :type '(choice
3525 (const :tag "Not" nil)
3526 (const :tag "Always" t)
3527 (repeat :tag "Specific tags" (string :tag "Tag"))
3528 (regexp :tag "Tags matched by regexp")))
3530 (defcustom org-tags-exclude-from-inheritance nil
3531 "List of tags that should never be inherited.
3532 This is a way to exclude a few tags from inheritance. For way to do
3533 the opposite, to actively allow inheritance for selected tags,
3534 see the variable `org-use-tag-inheritance'."
3535 :group 'org-tags
3536 :type '(repeat (string :tag "Tag")))
3538 (defun org-tag-inherit-p (tag)
3539 "Check if TAG is one that should be inherited."
3540 (cond
3541 ((member tag org-tags-exclude-from-inheritance) nil)
3542 ((eq org-use-tag-inheritance t) t)
3543 ((not org-use-tag-inheritance) nil)
3544 ((stringp org-use-tag-inheritance)
3545 (string-match org-use-tag-inheritance tag))
3546 ((listp org-use-tag-inheritance)
3547 (member tag org-use-tag-inheritance))
3548 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3550 (defcustom org-tags-match-list-sublevels t
3551 "Non-nil means list also sublevels of headlines matching a search.
3552 This variable applies to tags/property searches, and also to stuck
3553 projects because this search is based on a tags match as well.
3555 When set to the symbol `indented', sublevels are indented with
3556 leading dots.
3558 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3559 the sublevels of a headline matching a tag search often also match
3560 the same search. Listing all of them can create very long lists.
3561 Setting this variable to nil causes subtrees of a match to be skipped.
3563 This variable is semi-obsolete and probably should always be true. It
3564 is better to limit inheritance to certain tags using the variables
3565 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3566 :group 'org-tags
3567 :type '(choice
3568 (const :tag "No, don't list them" nil)
3569 (const :tag "Yes, do list them" t)
3570 (const :tag "List them, indented with leading dots" indented)))
3572 (defcustom org-tags-sort-function nil
3573 "When set, tags are sorted using this function as a comparator."
3574 :group 'org-tags
3575 :type '(choice
3576 (const :tag "No sorting" nil)
3577 (const :tag "Alphabetical" string<)
3578 (const :tag "Reverse alphabetical" string>)
3579 (function :tag "Custom function" nil)))
3581 (defvar org-tags-history nil
3582 "History of minibuffer reads for tags.")
3583 (defvar org-last-tags-completion-table nil
3584 "The last used completion table for tags.")
3585 (defvar org-after-tags-change-hook nil
3586 "Hook that is run after the tags in a line have changed.")
3588 (defgroup org-properties nil
3589 "Options concerning properties in Org-mode."
3590 :tag "Org Properties"
3591 :group 'org)
3593 (defcustom org-property-format "%-10s %s"
3594 "How property key/value pairs should be formatted by `indent-line'.
3595 When `indent-line' hits a property definition, it will format the line
3596 according to this format, mainly to make sure that the values are
3597 lined-up with respect to each other."
3598 :group 'org-properties
3599 :type 'string)
3601 (defcustom org-properties-postprocess-alist nil
3602 "Alist of properties and functions to adjust inserted values.
3603 Elements of this alist must be of the form
3605 ([string] [function])
3607 where [string] must be a property name and [function] must be a
3608 lambda expression: this lambda expression must take one argument,
3609 the value to adjust, and return the new value as a string.
3611 For example, this element will allow the property \"Remaining\"
3612 to be updated wrt the relation between the \"Effort\" property
3613 and the clock summary:
3615 ((\"Remaining\" (lambda(value)
3616 (let ((clocksum (org-clock-sum-current-item))
3617 (effort (org-duration-string-to-minutes
3618 (org-entry-get (point) \"Effort\"))))
3619 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3620 :group 'org-properties
3621 :version "24.1"
3622 :type '(alist :key-type (string :tag "Property")
3623 :value-type (function :tag "Function")))
3625 (defcustom org-use-property-inheritance nil
3626 "Non-nil means properties apply also for sublevels.
3628 This setting is chiefly used during property searches. Turning it on can
3629 cause significant overhead when doing a search, which is why it is not
3630 on by default.
3632 When nil, only the properties directly given in the current entry count.
3633 When t, every property is inherited. The value may also be a list of
3634 properties that should have inheritance, or a regular expression matching
3635 properties that should be inherited.
3637 However, note that some special properties use inheritance under special
3638 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3639 and the properties ending in \"_ALL\" when they are used as descriptor
3640 for valid values of a property.
3642 Note for programmers:
3643 When querying an entry with `org-entry-get', you can control if inheritance
3644 should be used. By default, `org-entry-get' looks only at the local
3645 properties. You can request inheritance by setting the inherit argument
3646 to t (to force inheritance) or to `selective' (to respect the setting
3647 in this variable)."
3648 :group 'org-properties
3649 :type '(choice
3650 (const :tag "Not" nil)
3651 (const :tag "Always" t)
3652 (repeat :tag "Specific properties" (string :tag "Property"))
3653 (regexp :tag "Properties matched by regexp")))
3655 (defun org-property-inherit-p (property)
3656 "Check if PROPERTY is one that should be inherited."
3657 (cond
3658 ((eq org-use-property-inheritance t) t)
3659 ((not org-use-property-inheritance) nil)
3660 ((stringp org-use-property-inheritance)
3661 (string-match org-use-property-inheritance property))
3662 ((listp org-use-property-inheritance)
3663 (member property org-use-property-inheritance))
3664 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3666 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3667 "The default column format, if no other format has been defined.
3668 This variable can be set on the per-file basis by inserting a line
3670 #+COLUMNS: %25ITEM ....."
3671 :group 'org-properties
3672 :type 'string)
3674 (defcustom org-columns-ellipses ".."
3675 "The ellipses to be used when a field in column view is truncated.
3676 When this is the empty string, as many characters as possible are shown,
3677 but then there will be no visual indication that the field has been truncated.
3678 When this is a string of length N, the last N characters of a truncated
3679 field are replaced by this string. If the column is narrower than the
3680 ellipses string, only part of the ellipses string will be shown."
3681 :group 'org-properties
3682 :type 'string)
3684 (defcustom org-columns-modify-value-for-display-function nil
3685 "Function that modifies values for display in column view.
3686 For example, it can be used to cut out a certain part from a time stamp.
3687 The function must take 2 arguments:
3689 column-title The title of the column (*not* the property name)
3690 value The value that should be modified.
3692 The function should return the value that should be displayed,
3693 or nil if the normal value should be used."
3694 :group 'org-properties
3695 :type '(choice (const nil) (function)))
3697 (defconst org-global-properties-fixed
3698 '(("VISIBILITY_ALL" . "folded children content all")
3699 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3700 "List of property/value pairs that can be inherited by any entry.
3702 These are fixed values, for the preset properties. The user variable
3703 that can be used to add to this list is `org-global-properties'.
3705 The entries in this list are cons cells where the car is a property
3706 name and cdr is a string with the value. If the value represents
3707 multiple items like an \"_ALL\" property, separate the items by
3708 spaces.")
3710 (defcustom org-global-properties nil
3711 "List of property/value pairs that can be inherited by any entry.
3713 This list will be combined with the constant `org-global-properties-fixed'.
3715 The entries in this list are cons cells where the car is a property
3716 name and cdr is a string with the value.
3718 You can set buffer-local values for the same purpose in the variable
3719 `org-file-properties' this by adding lines like
3721 #+PROPERTY: NAME VALUE"
3722 :group 'org-properties
3723 :type '(repeat
3724 (cons (string :tag "Property")
3725 (string :tag "Value"))))
3727 (defvar org-file-properties nil
3728 "List of property/value pairs that can be inherited by any entry.
3729 Valid for the current buffer.
3730 This variable is populated from #+PROPERTY lines.")
3731 (make-variable-buffer-local 'org-file-properties)
3733 (defgroup org-agenda nil
3734 "Options concerning agenda views in Org-mode."
3735 :tag "Org Agenda"
3736 :group 'org)
3738 (defvar org-category nil
3739 "Variable used by org files to set a category for agenda display.
3740 Such files should use a file variable to set it, for example
3742 # -*- mode: org; org-category: \"ELisp\"
3744 or contain a special line
3746 #+CATEGORY: ELisp
3748 If the file does not specify a category, then file's base name
3749 is used instead.")
3750 (make-variable-buffer-local 'org-category)
3751 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3753 (defcustom org-agenda-files nil
3754 "The files to be used for agenda display.
3755 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3756 \\[org-remove-file]. You can also use customize to edit the list.
3758 If an entry is a directory, all files in that directory that are matched by
3759 `org-agenda-file-regexp' will be part of the file list.
3761 If the value of the variable is not a list but a single file name, then
3762 the list of agenda files is actually stored and maintained in that file, one
3763 agenda file per line. In this file paths can be given relative to
3764 `org-directory'. Tilde expansion and environment variable substitution
3765 are also made."
3766 :group 'org-agenda
3767 :type '(choice
3768 (repeat :tag "List of files and directories" file)
3769 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3771 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3772 "Regular expression to match files for `org-agenda-files'.
3773 If any element in the list in that variable contains a directory instead
3774 of a normal file, all files in that directory that are matched by this
3775 regular expression will be included."
3776 :group 'org-agenda
3777 :type 'regexp)
3779 (defcustom org-agenda-text-search-extra-files nil
3780 "List of extra files to be searched by text search commands.
3781 These files will be searched in addition to the agenda files by the
3782 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3783 Note that these files will only be searched for text search commands,
3784 not for the other agenda views like todo lists, tag searches or the weekly
3785 agenda. This variable is intended to list notes and possibly archive files
3786 that should also be searched by these two commands.
3787 In fact, if the first element in the list is the symbol `agenda-archives',
3788 then all archive files of all agenda files will be added to the search
3789 scope."
3790 :group 'org-agenda
3791 :type '(set :greedy t
3792 (const :tag "Agenda Archives" agenda-archives)
3793 (repeat :inline t (file))))
3795 (org-defvaralias 'org-agenda-multi-occur-extra-files
3796 'org-agenda-text-search-extra-files)
3798 (defcustom org-agenda-skip-unavailable-files nil
3799 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3800 A nil value means to remove them, after a query, from the list."
3801 :group 'org-agenda
3802 :type 'boolean)
3804 (defcustom org-calendar-to-agenda-key [?c]
3805 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3806 The command `org-calendar-goto-agenda' will be bound to this key. The
3807 default is the character `c' because then `c' can be used to switch back and
3808 forth between agenda and calendar."
3809 :group 'org-agenda
3810 :type 'sexp)
3812 (defcustom org-calendar-insert-diary-entry-key [?i]
3813 "The key to be installed in `calendar-mode-map' for adding diary entries.
3814 This option is irrelevant until `org-agenda-diary-file' has been configured
3815 to point to an Org-mode file. When that is the case, the command
3816 `org-agenda-diary-entry' will be bound to the key given here, by default
3817 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3818 if you want to continue doing this, you need to change this to a different
3819 key."
3820 :group 'org-agenda
3821 :type 'sexp)
3823 (defcustom org-agenda-diary-file 'diary-file
3824 "File to which to add new entries with the `i' key in agenda and calendar.
3825 When this is the symbol `diary-file', the functionality in the Emacs
3826 calendar will be used to add entries to the `diary-file'. But when this
3827 points to a file, `org-agenda-diary-entry' will be used instead."
3828 :group 'org-agenda
3829 :type '(choice
3830 (const :tag "The standard Emacs diary file" diary-file)
3831 (file :tag "Special Org file diary entries")))
3833 (eval-after-load "calendar"
3834 '(progn
3835 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3836 'org-calendar-goto-agenda)
3837 (add-hook 'calendar-mode-hook
3838 (lambda ()
3839 (unless (eq org-agenda-diary-file 'diary-file)
3840 (define-key calendar-mode-map
3841 org-calendar-insert-diary-entry-key
3842 'org-agenda-diary-entry))))))
3844 (defgroup org-latex nil
3845 "Options for embedding LaTeX code into Org-mode."
3846 :tag "Org LaTeX"
3847 :group 'org)
3849 (defcustom org-format-latex-options
3850 '(:foreground default :background default :scale 1.0
3851 :html-foreground "Black" :html-background "Transparent"
3852 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3853 "Options for creating images from LaTeX fragments.
3854 This is a property list with the following properties:
3855 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3856 `default' means use the foreground of the default face.
3857 `auto' means use the foreground from the text face.
3858 :background the background color, or \"Transparent\".
3859 `default' means use the background of the default face.
3860 `auto' means use the background from the text face.
3861 :scale a scaling factor for the size of the images, to get more pixels
3862 :html-foreground, :html-background, :html-scale
3863 the same numbers for HTML export.
3864 :matchers a list indicating which matchers should be used to
3865 find LaTeX fragments. Valid members of this list are:
3866 \"begin\" find environments
3867 \"$1\" find single characters surrounded by $.$
3868 \"$\" find math expressions surrounded by $...$
3869 \"$$\" find math expressions surrounded by $$....$$
3870 \"\\(\" find math expressions surrounded by \\(...\\)
3871 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3872 :group 'org-latex
3873 :type 'plist)
3875 (defcustom org-format-latex-signal-error t
3876 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3877 When nil, just push out a message."
3878 :group 'org-latex
3879 :version "24.1"
3880 :type 'boolean)
3882 (defcustom org-latex-to-mathml-jar-file nil
3883 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3884 Use this to specify additional executable file say a jar file.
3886 When using MathToWeb as the converter, specify the full-path to
3887 your mathtoweb.jar file."
3888 :group 'org-latex
3889 :version "24.1"
3890 :type '(choice
3891 (const :tag "None" nil)
3892 (file :tag "JAR file" :must-match t)))
3894 (defcustom org-latex-to-mathml-convert-command nil
3895 "Command to convert LaTeX fragments to MathML.
3896 Replace format-specifiers in the command as noted below and use
3897 `shell-command' to convert LaTeX to MathML.
3898 %j: Executable file in fully expanded form as specified by
3899 `org-latex-to-mathml-jar-file'.
3900 %I: Input LaTeX file in fully expanded form
3901 %o: Output MathML file
3902 This command is used by `org-create-math-formula'.
3904 When using MathToWeb as the converter, set this to
3905 \"java -jar %j -unicode -force -df %o %I\"."
3906 :group 'org-latex
3907 :version "24.1"
3908 :type '(choice
3909 (const :tag "None" nil)
3910 (string :tag "\nShell command")))
3912 (defcustom org-latex-create-formula-image-program 'dvipng
3913 "Program to convert LaTeX fragments with.
3915 dvipng Process the LaTeX fragments to dvi file, then convert
3916 dvi files to png files using dvipng.
3917 This will also include processing of non-math environments.
3918 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3919 to convert pdf files to png files"
3920 :group 'org-latex
3921 :version "24.1"
3922 :type '(choice
3923 (const :tag "dvipng" dvipng)
3924 (const :tag "imagemagick" imagemagick)))
3926 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3927 "Path to store latex preview images.
3928 A relative path here creates many directories relative to the
3929 processed org files paths. An absolute path puts all preview
3930 images at the same place."
3931 :group 'org-latex
3932 :version "24.3"
3933 :type 'string)
3935 (defun org-format-latex-mathml-available-p ()
3936 "Return t if `org-latex-to-mathml-convert-command' is usable."
3937 (save-match-data
3938 (when (and (boundp 'org-latex-to-mathml-convert-command)
3939 org-latex-to-mathml-convert-command)
3940 (let ((executable (car (split-string
3941 org-latex-to-mathml-convert-command))))
3942 (when (executable-find executable)
3943 (if (string-match
3944 "%j" org-latex-to-mathml-convert-command)
3945 (file-readable-p org-latex-to-mathml-jar-file)
3946 t))))))
3948 (defcustom org-format-latex-header "\\documentclass{article}
3949 \\usepackage[usenames]{color}
3950 \[PACKAGES]
3951 \[DEFAULT-PACKAGES]
3952 \\pagestyle{empty} % do not remove
3953 % The settings below are copied from fullpage.sty
3954 \\setlength{\\textwidth}{\\paperwidth}
3955 \\addtolength{\\textwidth}{-3cm}
3956 \\setlength{\\oddsidemargin}{1.5cm}
3957 \\addtolength{\\oddsidemargin}{-2.54cm}
3958 \\setlength{\\evensidemargin}{\\oddsidemargin}
3959 \\setlength{\\textheight}{\\paperheight}
3960 \\addtolength{\\textheight}{-\\headheight}
3961 \\addtolength{\\textheight}{-\\headsep}
3962 \\addtolength{\\textheight}{-\\footskip}
3963 \\addtolength{\\textheight}{-3cm}
3964 \\setlength{\\topmargin}{1.5cm}
3965 \\addtolength{\\topmargin}{-2.54cm}"
3966 "The document header used for processing LaTeX fragments.
3967 It is imperative that this header make sure that no page number
3968 appears on the page. The package defined in the variables
3969 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3970 will either replace the placeholder \"[PACKAGES]\" in this
3971 header, or they will be appended."
3972 :group 'org-latex
3973 :type 'string)
3975 (defun org-set-packages-alist (var val)
3976 "Set the packages alist and make sure it has 3 elements per entry."
3977 (set var (mapcar (lambda (x)
3978 (if (and (consp x) (= (length x) 2))
3979 (list (car x) (nth 1 x) t)
3981 val)))
3983 (defun org-get-packages-alist (var)
3984 "Get the packages alist and make sure it has 3 elements per entry."
3985 (mapcar (lambda (x)
3986 (if (and (consp x) (= (length x) 2))
3987 (list (car x) (nth 1 x) t)
3989 (default-value var)))
3991 (defcustom org-latex-default-packages-alist
3992 '(("AUTO" "inputenc" t)
3993 ("T1" "fontenc" t)
3994 ("" "fixltx2e" nil)
3995 ("" "graphicx" t)
3996 ("" "longtable" nil)
3997 ("" "float" nil)
3998 ("" "wrapfig" nil)
3999 ("" "rotating" nil)
4000 ("normalem" "ulem" t)
4001 ("" "amsmath" t)
4002 ("" "textcomp" t)
4003 ("" "marvosym" t)
4004 ("" "wasysym" t)
4005 ("" "amssymb" t)
4006 ("" "capt-of" nil)
4007 ("" "hyperref" nil)
4008 "\\tolerance=1000")
4009 "Alist of default packages to be inserted in the header.
4011 Change this only if one of the packages here causes an
4012 incompatibility with another package you are using.
4014 The packages in this list are needed by one part or another of
4015 Org mode to function properly:
4017 - inputenc, fontenc: for basic font and character selection
4018 - fixltx2e: Important patches of LaTeX itself
4019 - graphicx: for including images
4020 - longtable: For multipage tables
4021 - float, wrapfig: for figure placement
4022 - rotating: for sideways figures and tables
4023 - ulem: for underline and strike-through
4024 - amsmath: for subscript and superscript and math environments
4025 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4026 for interpreting the entities in `org-entities'. You can skip
4027 some of these packages if you don't use any of their symbols.
4028 - capt-of: for captions outside of floats
4029 - hyperref: for cross references
4031 Therefore you should not modify this variable unless you know
4032 what you are doing. The one reason to change it anyway is that
4033 you might be loading some other package that conflicts with one
4034 of the default packages. Each element is either a cell or
4035 a string.
4037 A cell is of the format:
4039 \( \"options\" \"package\" SNIPPET-FLAG).
4041 If SNIPPET-FLAG is non-nil, the package also needs to be included
4042 when compiling LaTeX snippets into images for inclusion into
4043 non-LaTeX output.
4045 A string will be inserted as-is in the header of the document."
4046 :group 'org-latex
4047 :group 'org-export-latex
4048 :set 'org-set-packages-alist
4049 :get 'org-get-packages-alist
4050 :version "24.1"
4051 :type '(repeat
4052 (choice
4053 (list :tag "options/package pair"
4054 (string :tag "options")
4055 (string :tag "package")
4056 (boolean :tag "Snippet"))
4057 (string :tag "A line of LaTeX"))))
4059 (defcustom org-latex-packages-alist nil
4060 "Alist of packages to be inserted in every LaTeX header.
4062 These will be inserted after `org-latex-default-packages-alist'.
4063 Each element is either a cell or a string.
4065 A cell is of the format:
4067 \(\"options\" \"package\" SNIPPET-FLAG)
4069 SNIPPET-FLAG, when non-nil, indicates that this package is also
4070 needed when turning LaTeX snippets into images for inclusion into
4071 non-LaTeX output.
4073 A string will be inserted as-is in the header of the document.
4075 Make sure that you only list packages here which:
4077 - you want in every file;
4078 - do not conflict with the setup in `org-format-latex-header';
4079 - do not conflict with the default packages in
4080 `org-latex-default-packages-alist'."
4081 :group 'org-latex
4082 :group 'org-export-latex
4083 :set 'org-set-packages-alist
4084 :get 'org-get-packages-alist
4085 :type '(repeat
4086 (choice
4087 (list :tag "options/package pair"
4088 (string :tag "options")
4089 (string :tag "package")
4090 (boolean :tag "Snippet"))
4091 (string :tag "A line of LaTeX"))))
4093 (defgroup org-appearance nil
4094 "Settings for Org-mode appearance."
4095 :tag "Org Appearance"
4096 :group 'org)
4098 (defcustom org-level-color-stars-only nil
4099 "Non-nil means fontify only the stars in each headline.
4100 When nil, the entire headline is fontified.
4101 Changing it requires restart of `font-lock-mode' to become effective
4102 also in regions already fontified."
4103 :group 'org-appearance
4104 :type 'boolean)
4106 (defcustom org-hide-leading-stars nil
4107 "Non-nil means hide the first N-1 stars in a headline.
4108 This works by using the face `org-hide' for these stars. This
4109 face is white for a light background, and black for a dark
4110 background. You may have to customize the face `org-hide' to
4111 make this work.
4112 Changing it requires restart of `font-lock-mode' to become effective
4113 also in regions already fontified.
4114 You may also set this on a per-file basis by adding one of the following
4115 lines to the buffer:
4117 #+STARTUP: hidestars
4118 #+STARTUP: showstars"
4119 :group 'org-appearance
4120 :type 'boolean)
4122 (defcustom org-hidden-keywords nil
4123 "List of symbols corresponding to keywords to be hidden the org buffer.
4124 For example, a value '(title) for this list will make the document's title
4125 appear in the buffer without the initial #+TITLE: keyword."
4126 :group 'org-appearance
4127 :version "24.1"
4128 :type '(set (const :tag "#+AUTHOR" author)
4129 (const :tag "#+DATE" date)
4130 (const :tag "#+EMAIL" email)
4131 (const :tag "#+TITLE" title)))
4133 (defcustom org-custom-properties nil
4134 "List of properties (as strings) with a special meaning.
4135 The default use of these custom properties is to let the user
4136 hide them with `org-toggle-custom-properties-visibility'."
4137 :group 'org-properties
4138 :group 'org-appearance
4139 :version "24.3"
4140 :type '(repeat (string :tag "Property Name")))
4142 (defcustom org-fontify-done-headline nil
4143 "Non-nil means change the face of a headline if it is marked DONE.
4144 Normally, only the TODO/DONE keyword indicates the state of a headline.
4145 When this is non-nil, the headline after the keyword is set to the
4146 `org-headline-done' as an additional indication."
4147 :group 'org-appearance
4148 :type 'boolean)
4150 (defcustom org-fontify-emphasized-text t
4151 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4152 Changing this variable requires a restart of Emacs to take effect."
4153 :group 'org-appearance
4154 :type 'boolean)
4156 (defcustom org-fontify-whole-heading-line nil
4157 "Non-nil means fontify the whole line for headings.
4158 This is useful when setting a background color for the
4159 org-level-* faces."
4160 :group 'org-appearance
4161 :type 'boolean)
4163 (defcustom org-highlight-latex-and-related nil
4164 "Non-nil means highlight LaTeX related syntax in the buffer.
4165 When non nil, the value should be a list containing any of the
4166 following symbols:
4167 `latex' Highlight LaTeX snippets and environments.
4168 `script' Highlight subscript and superscript.
4169 `entities' Highlight entities."
4170 :group 'org-appearance
4171 :version "24.4"
4172 :package-version '(Org . "8.0")
4173 :type '(choice
4174 (const :tag "No highlighting" nil)
4175 (set :greedy t :tag "Highlight"
4176 (const :tag "LaTeX snippets and environments" latex)
4177 (const :tag "Subscript and superscript" script)
4178 (const :tag "Entities" entities))))
4180 (defcustom org-hide-emphasis-markers nil
4181 "Non-nil mean font-lock should hide the emphasis marker characters."
4182 :group 'org-appearance
4183 :type 'boolean)
4185 (defcustom org-hide-macro-markers nil
4186 "Non-nil mean font-lock should hide the brackets marking macro calls."
4187 :group 'org-appearance
4188 :type 'boolean)
4190 (defcustom org-pretty-entities nil
4191 "Non-nil means show entities as UTF8 characters.
4192 When nil, the \\name form remains in the buffer."
4193 :group 'org-appearance
4194 :version "24.1"
4195 :type 'boolean)
4197 (defcustom org-pretty-entities-include-sub-superscripts t
4198 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4199 :group 'org-appearance
4200 :version "24.1"
4201 :type 'boolean)
4203 (defvar org-emph-re nil
4204 "Regular expression for matching emphasis.
4205 After a match, the match groups contain these elements:
4206 0 The match of the full regular expression, including the characters
4207 before and after the proper match
4208 1 The character before the proper match, or empty at beginning of line
4209 2 The proper match, including the leading and trailing markers
4210 3 The leading marker like * or /, indicating the type of highlighting
4211 4 The text between the emphasis markers, not including the markers
4212 5 The character after the match, empty at the end of a line")
4213 (defvar org-verbatim-re nil
4214 "Regular expression for matching verbatim text.")
4215 (defvar org-emphasis-regexp-components) ; defined just below
4216 (defvar org-emphasis-alist) ; defined just below
4217 (defun org-set-emph-re (var val)
4218 "Set variable and compute the emphasis regular expression."
4219 (set var val)
4220 (when (and (boundp 'org-emphasis-alist)
4221 (boundp 'org-emphasis-regexp-components)
4222 org-emphasis-alist org-emphasis-regexp-components)
4223 (let* ((e org-emphasis-regexp-components)
4224 (pre (car e))
4225 (post (nth 1 e))
4226 (border (nth 2 e))
4227 (body (nth 3 e))
4228 (nl (nth 4 e))
4229 (body1 (concat body "*?"))
4230 (markers (mapconcat 'car org-emphasis-alist ""))
4231 (vmarkers (mapconcat
4232 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4233 org-emphasis-alist "")))
4234 ;; make sure special characters appear at the right position in the class
4235 (if (string-match "\\^" markers)
4236 (setq markers (concat (replace-match "" t t markers) "^")))
4237 (if (string-match "-" markers)
4238 (setq markers (concat (replace-match "" t t markers) "-")))
4239 (if (string-match "\\^" vmarkers)
4240 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4241 (if (string-match "-" vmarkers)
4242 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4243 (if (> nl 0)
4244 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4245 (int-to-string nl) "\\}")))
4246 ;; Make the regexp
4247 (setq org-emph-re
4248 (concat "\\([" pre "]\\|^\\)"
4249 "\\("
4250 "\\([" markers "]\\)"
4251 "\\("
4252 "[^" border "]\\|"
4253 "[^" border "]"
4254 body1
4255 "[^" border "]"
4256 "\\)"
4257 "\\3\\)"
4258 "\\([" post "]\\|$\\)"))
4259 (setq org-verbatim-re
4260 (concat "\\([" pre "]\\|^\\)"
4261 "\\("
4262 "\\([" vmarkers "]\\)"
4263 "\\("
4264 "[^" border "]\\|"
4265 "[^" border "]"
4266 body1
4267 "[^" border "]"
4268 "\\)"
4269 "\\3\\)"
4270 "\\([" post "]\\|$\\)")))))
4272 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4273 ;; set this option proved cumbersome. See this message/thread:
4274 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4275 (defvar org-emphasis-regexp-components
4276 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4277 "Components used to build the regular expression for emphasis.
4278 This is a list with five entries. Terminology: In an emphasis string
4279 like \" *strong word* \", we call the initial space PREMATCH, the final
4280 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4281 and \"trong wor\" is the body. The different components in this variable
4282 specify what is allowed/forbidden in each part:
4284 pre Chars allowed as prematch. Beginning of line will be allowed too.
4285 post Chars allowed as postmatch. End of line will be allowed too.
4286 border The chars *forbidden* as border characters.
4287 body-regexp A regexp like \".\" to match a body character. Don't use
4288 non-shy groups here, and don't allow newline here.
4289 newline The maximum number of newlines allowed in an emphasis exp.
4291 You need to reload Org or to restart Emacs after customizing this.")
4293 (defcustom org-emphasis-alist
4294 `(("*" bold)
4295 ("/" italic)
4296 ("_" underline)
4297 ("=" org-verbatim verbatim)
4298 ("~" org-code verbatim)
4299 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4300 "Alist of characters and faces to emphasize text.
4301 Text starting and ending with a special character will be emphasized,
4302 for example *bold*, _underlined_ and /italic/. This variable sets the
4303 marker characters and the face to be used by font-lock for highlighting
4304 in Org-mode Emacs buffers.
4306 You need to reload Org or to restart Emacs after customizing this."
4307 :group 'org-appearance
4308 :set 'org-set-emph-re
4309 :version "24.4"
4310 :package-version '(Org . "8.0")
4311 :type '(repeat
4312 (list
4313 (string :tag "Marker character")
4314 (choice
4315 (face :tag "Font-lock-face")
4316 (plist :tag "Face property list"))
4317 (option (const verbatim)))))
4319 (defvar org-protecting-blocks
4320 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4321 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4322 This is needed for font-lock setup.")
4324 ;;; Miscellaneous options
4326 (defgroup org-completion nil
4327 "Completion in Org-mode."
4328 :tag "Org Completion"
4329 :group 'org)
4331 (defcustom org-completion-use-ido nil
4332 "Non-nil means use ido completion wherever possible.
4333 Note that `ido-mode' must be active for this variable to be relevant.
4334 If you decide to turn this variable on, you might well want to turn off
4335 `org-outline-path-complete-in-steps'.
4336 See also `org-completion-use-iswitchb'."
4337 :group 'org-completion
4338 :type 'boolean)
4340 (defcustom org-completion-use-iswitchb nil
4341 "Non-nil means use iswitchb completion wherever possible.
4342 Note that `iswitchb-mode' must be active for this variable to be relevant.
4343 If you decide to turn this variable on, you might well want to turn off
4344 `org-outline-path-complete-in-steps'.
4345 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4346 :group 'org-completion
4347 :type 'boolean)
4349 (defcustom org-completion-fallback-command 'hippie-expand
4350 "The expansion command called by \\[pcomplete] in normal context.
4351 Normal means, no org-mode-specific context."
4352 :group 'org-completion
4353 :type 'function)
4355 ;;; Functions and variables from their packages
4356 ;; Declared here to avoid compiler warnings
4358 ;; XEmacs only
4359 (defvar outline-mode-menu-heading)
4360 (defvar outline-mode-menu-show)
4361 (defvar outline-mode-menu-hide)
4362 (defvar zmacs-regions) ; XEmacs regions
4364 ;; Emacs only
4365 (defvar mark-active)
4367 ;; Various packages
4368 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4369 (declare-function calendar-forward-day "cal-move" (arg))
4370 (declare-function calendar-goto-date "cal-move" (date))
4371 (declare-function calendar-goto-today "cal-move" ())
4372 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4373 (defvar calc-embedded-close-formula)
4374 (defvar calc-embedded-open-formula)
4375 (declare-function cdlatex-tab "ext:cdlatex" ())
4376 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4377 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4378 (defvar font-lock-unfontify-region-function)
4379 (declare-function iswitchb-read-buffer "iswitchb"
4380 (prompt &optional default require-match start matches-set))
4381 (defvar iswitchb-temp-buflist)
4382 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4383 (defvar org-agenda-tags-todo-honor-ignore-options)
4384 (declare-function org-agenda-skip "org-agenda" ())
4385 (declare-function
4386 org-agenda-format-item "org-agenda"
4387 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4388 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4389 (declare-function org-agenda-change-all-lines "org-agenda"
4390 (newhead hdmarker &optional fixface just-this))
4391 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4392 (declare-function org-agenda-maybe-redo "org-agenda" ())
4393 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4394 (beg end))
4395 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4396 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4397 "org-agenda" (&optional end))
4398 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4399 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4400 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4401 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4402 (declare-function org-indent-mode "org-indent" (&optional arg))
4403 (declare-function parse-time-string "parse-time" (string))
4404 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4405 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4406 (defvar remember-data-file)
4407 (defvar texmathp-why)
4408 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4409 (declare-function table--at-cell-p "table" (position &optional object at-column))
4410 (declare-function calc-eval "calc" (str &optional separator &rest args))
4412 ;;;###autoload
4413 (defun turn-on-orgtbl ()
4414 "Unconditionally turn on `orgtbl-mode'."
4415 (require 'org-table)
4416 (orgtbl-mode 1))
4418 (defun org-at-table-p (&optional table-type)
4419 "Return t if the cursor is inside an org-type table.
4420 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4421 (if org-enable-table-editor
4422 (save-excursion
4423 (beginning-of-line 1)
4424 (looking-at (if table-type org-table-any-line-regexp
4425 org-table-line-regexp)))
4426 nil))
4427 (defsubst org-table-p () (org-at-table-p))
4429 (defun org-at-table.el-p ()
4430 "Return t if and only if we are at a table.el table."
4431 (and (org-at-table-p 'any)
4432 (save-excursion
4433 (goto-char (org-table-begin 'any))
4434 (looking-at org-table1-hline-regexp))))
4436 (defun org-table-recognize-table.el ()
4437 "If there is a table.el table nearby, recognize it and move into it."
4438 (if org-table-tab-recognizes-table.el
4439 (if (org-at-table.el-p)
4440 (progn
4441 (beginning-of-line 1)
4442 (if (looking-at org-table-dataline-regexp)
4444 (if (looking-at org-table1-hline-regexp)
4445 (progn
4446 (beginning-of-line 2)
4447 (if (looking-at org-table-any-border-regexp)
4448 (beginning-of-line -1)))))
4449 (if (re-search-forward "|" (org-table-end t) t)
4450 (progn
4451 (require 'table)
4452 (if (table--at-cell-p (point))
4454 (message "recognizing table.el table...")
4455 (table-recognize-table)
4456 (message "recognizing table.el table...done")))
4457 (error "This should not happen"))
4459 nil)
4460 nil))
4462 (defun org-at-table-hline-p ()
4463 "Return t if the cursor is inside a hline in a table."
4464 (if org-enable-table-editor
4465 (save-excursion
4466 (beginning-of-line 1)
4467 (looking-at org-table-hline-regexp))
4468 nil))
4470 (defun org-table-map-tables (function &optional quietly)
4471 "Apply FUNCTION to the start of all tables in the buffer."
4472 (save-excursion
4473 (save-restriction
4474 (widen)
4475 (goto-char (point-min))
4476 (while (re-search-forward org-table-any-line-regexp nil t)
4477 (unless quietly
4478 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4479 (beginning-of-line 1)
4480 (when (and (looking-at org-table-line-regexp)
4481 ;; Exclude tables in src/example/verbatim/clocktable blocks
4482 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4483 (save-excursion (funcall function))
4484 (or (looking-at org-table-line-regexp)
4485 (forward-char 1)))
4486 (re-search-forward org-table-any-border-regexp nil 1))))
4487 (unless quietly (message "Mapping tables: done")))
4489 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4490 (declare-function org-clock-update-mode-line "org-clock" ())
4491 (declare-function org-resolve-clocks "org-clock"
4492 (&optional also-non-dangling-p prompt last-valid))
4494 (defun org-at-TBLFM-p (&optional pos)
4495 "Return t when point (or POS) is in #+TBLFM line."
4496 (save-excursion
4497 (let ((pos pos)))
4498 (goto-char (or pos (point)))
4499 (beginning-of-line 1)
4500 (looking-at org-TBLFM-regexp)))
4502 (defvar org-clock-start-time)
4503 (defvar org-clock-marker (make-marker)
4504 "Marker recording the last clock-in.")
4505 (defvar org-clock-hd-marker (make-marker)
4506 "Marker recording the last clock-in, but the headline position.")
4507 (defvar org-clock-heading ""
4508 "The heading of the current clock entry.")
4509 (defun org-clock-is-active ()
4510 "Return the buffer where the clock is currently running.
4511 Return nil if no clock is running."
4512 (marker-buffer org-clock-marker))
4514 (defun org-check-running-clock ()
4515 "Check if the current buffer contains the running clock.
4516 If yes, offer to stop it and to save the buffer with the changes."
4517 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4518 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4519 (buffer-name))))
4520 (org-clock-out)
4521 (when (y-or-n-p "Save changed buffer?")
4522 (save-buffer))))
4524 (defun org-clocktable-try-shift (dir n)
4525 "Check if this line starts a clock table, if yes, shift the time block."
4526 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4527 (org-clocktable-shift dir n)))
4529 ;;;###autoload
4530 (defun org-clock-persistence-insinuate ()
4531 "Set up hooks for clock persistence."
4532 (require 'org-clock)
4533 (add-hook 'org-mode-hook 'org-clock-load)
4534 (add-hook 'kill-emacs-hook 'org-clock-save))
4536 (defgroup org-archive nil
4537 "Options concerning archiving in Org-mode."
4538 :tag "Org Archive"
4539 :group 'org-structure)
4541 (defcustom org-archive-location "%s_archive::"
4542 "The location where subtrees should be archived.
4544 The value of this variable is a string, consisting of two parts,
4545 separated by a double-colon. The first part is a filename and
4546 the second part is a headline.
4548 When the filename is omitted, archiving happens in the same file.
4549 %s in the filename will be replaced by the current file
4550 name (without the directory part). Archiving to a different file
4551 is useful to keep archived entries from contributing to the
4552 Org-mode Agenda.
4554 The archived entries will be filed as subtrees of the specified
4555 headline. When the headline is omitted, the subtrees are simply
4556 filed away at the end of the file, as top-level entries. Also in
4557 the heading you can use %s to represent the file name, this can be
4558 useful when using the same archive for a number of different files.
4560 Here are a few examples:
4561 \"%s_archive::\"
4562 If the current file is Projects.org, archive in file
4563 Projects.org_archive, as top-level trees. This is the default.
4565 \"::* Archived Tasks\"
4566 Archive in the current file, under the top-level headline
4567 \"* Archived Tasks\".
4569 \"~/org/archive.org::\"
4570 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4572 \"~/org/archive.org::* From %s\"
4573 Archive in file ~/org/archive.org (absolute path), under headlines
4574 \"From FILENAME\" where file name is the current file name.
4576 \"~/org/datetree.org::datetree/* Finished Tasks\"
4577 The \"datetree/\" string is special, signifying to archive
4578 items to the datetree. Items are placed in either the CLOSED
4579 date of the item, or the current date if there is no CLOSED date.
4580 The heading will be a subentry to the current date. There doesn't
4581 need to be a heading, but there always needs to be a slash after
4582 datetree. For example, to store archived items directly in the
4583 datetree, use \"~/org/datetree.org::datetree/\".
4585 \"basement::** Finished Tasks\"
4586 Archive in file ./basement (relative path), as level 3 trees
4587 below the level 2 heading \"** Finished Tasks\".
4589 You may set this option on a per-file basis by adding to the buffer a
4590 line like
4592 #+ARCHIVE: basement::** Finished Tasks
4594 You may also define it locally for a subtree by setting an ARCHIVE property
4595 in the entry. If such a property is found in an entry, or anywhere up
4596 the hierarchy, it will be used."
4597 :group 'org-archive
4598 :type 'string)
4600 (defcustom org-agenda-skip-archived-trees t
4601 "Non-nil means the agenda will skip any items located in archived trees.
4602 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4603 variable is no longer recommended, you should leave it at the value t.
4604 Instead, use the key `v' to cycle the archives-mode in the agenda."
4605 :group 'org-archive
4606 :group 'org-agenda-skip
4607 :type 'boolean)
4609 (defcustom org-columns-skip-archived-trees t
4610 "Non-nil means ignore archived trees when creating column view."
4611 :group 'org-archive
4612 :group 'org-properties
4613 :type 'boolean)
4615 (defcustom org-cycle-open-archived-trees nil
4616 "Non-nil means `org-cycle' will open archived trees.
4617 An archived tree is a tree marked with the tag ARCHIVE.
4618 When nil, archived trees will stay folded. You can still open them with
4619 normal outline commands like `show-all', but not with the cycling commands."
4620 :group 'org-archive
4621 :group 'org-cycle
4622 :type 'boolean)
4624 (defcustom org-sparse-tree-open-archived-trees nil
4625 "Non-nil means sparse tree construction shows matches in archived trees.
4626 When nil, matches in these trees are highlighted, but the trees are kept in
4627 collapsed state."
4628 :group 'org-archive
4629 :group 'org-sparse-trees
4630 :type 'boolean)
4632 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4633 "The default date type when building a sparse tree.
4634 When this is nil, a date is a scheduled or a deadline timestamp.
4635 Otherwise, these types are allowed:
4637 all: all timestamps
4638 active: only active timestamps (<...>)
4639 inactive: only inactive timestamps (<...)
4640 scheduled: only scheduled timestamps
4641 deadline: only deadline timestamps"
4642 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4643 (const :tag "All timestamps" all)
4644 (const :tag "Only active timestamps" active)
4645 (const :tag "Only inactive timestamps" inactive)
4646 (const :tag "Only scheduled timestamps" scheduled)
4647 (const :tag "Only deadline timestamps" deadline)
4648 (const :tag "Only closed timestamps" closed))
4649 :version "24.3"
4650 :group 'org-sparse-trees)
4652 (defun org-cycle-hide-archived-subtrees (state)
4653 "Re-hide all archived subtrees after a visibility state change."
4654 (when (and (not org-cycle-open-archived-trees)
4655 (not (memq state '(overview folded))))
4656 (save-excursion
4657 (let* ((globalp (memq state '(contents all)))
4658 (beg (if globalp (point-min) (point)))
4659 (end (if globalp (point-max) (org-end-of-subtree t))))
4660 (org-hide-archived-subtrees beg end)
4661 (goto-char beg)
4662 (if (looking-at (concat ".*:" org-archive-tag ":"))
4663 (message "%s" (substitute-command-keys
4664 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4666 (defun org-force-cycle-archived ()
4667 "Cycle subtree even if it is archived."
4668 (interactive)
4669 (setq this-command 'org-cycle)
4670 (let ((org-cycle-open-archived-trees t))
4671 (call-interactively 'org-cycle)))
4673 (defun org-hide-archived-subtrees (beg end)
4674 "Re-hide all archived subtrees after a visibility state change."
4675 (save-excursion
4676 (let* ((re (concat ":" org-archive-tag ":")))
4677 (goto-char beg)
4678 (while (re-search-forward re end t)
4679 (when (org-at-heading-p)
4680 (org-flag-subtree t)
4681 (org-end-of-subtree t))))))
4683 (declare-function outline-end-of-heading "outline" ())
4684 (declare-function outline-flag-region "outline" (from to flag))
4685 (defun org-flag-subtree (flag)
4686 (save-excursion
4687 (org-back-to-heading t)
4688 (outline-end-of-heading)
4689 (outline-flag-region (point)
4690 (progn (org-end-of-subtree t) (point))
4691 flag)))
4693 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4695 ;; Declare Column View Code
4697 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4698 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4699 (declare-function org-columns-compute "org-colview" (property))
4701 ;; Declare ID code
4703 (declare-function org-id-store-link "org-id")
4704 (declare-function org-id-locations-load "org-id")
4705 (declare-function org-id-locations-save "org-id")
4706 (defvar org-id-track-globally)
4708 ;;; Variables for pre-computed regular expressions, all buffer local
4710 (defvar org-todo-regexp nil
4711 "Matches any of the TODO state keywords.")
4712 (make-variable-buffer-local 'org-todo-regexp)
4713 (defvar org-not-done-regexp nil
4714 "Matches any of the TODO state keywords except the last one.")
4715 (make-variable-buffer-local 'org-not-done-regexp)
4716 (defvar org-not-done-heading-regexp nil
4717 "Matches a TODO headline that is not done.")
4718 (make-variable-buffer-local 'org-not-done-regexp)
4719 (defvar org-todo-line-regexp nil
4720 "Matches a headline and puts TODO state into group 2 if present.")
4721 (make-variable-buffer-local 'org-todo-line-regexp)
4722 (defvar org-complex-heading-regexp nil
4723 "Matches a headline and puts everything into groups:
4724 group 1: the stars
4725 group 2: The todo keyword, maybe
4726 group 3: Priority cookie
4727 group 4: True headline
4728 group 5: Tags")
4729 (make-variable-buffer-local 'org-complex-heading-regexp)
4730 (defvar org-complex-heading-regexp-format nil
4731 "Printf format to make regexp to match an exact headline.
4732 This regexp will match the headline of any node which has the
4733 exact headline text that is put into the format, but may have any
4734 TODO state, priority and tags.")
4735 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4736 (defvar org-todo-line-tags-regexp nil
4737 "Matches a headline and puts TODO state into group 2 if present.
4738 Also put tags into group 4 if tags are present.")
4739 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4740 (defvar org-ds-keyword-length 12
4741 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4742 (make-variable-buffer-local 'org-ds-keyword-length)
4743 (defvar org-deadline-regexp nil
4744 "Matches the DEADLINE keyword.")
4745 (make-variable-buffer-local 'org-deadline-regexp)
4746 (defvar org-deadline-time-regexp nil
4747 "Matches the DEADLINE keyword together with a time stamp.")
4748 (make-variable-buffer-local 'org-deadline-time-regexp)
4749 (defvar org-deadline-time-hour-regexp nil
4750 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4751 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4752 (defvar org-deadline-line-regexp nil
4753 "Matches the DEADLINE keyword and the rest of the line.")
4754 (make-variable-buffer-local 'org-deadline-line-regexp)
4755 (defvar org-scheduled-regexp nil
4756 "Matches the SCHEDULED keyword.")
4757 (make-variable-buffer-local 'org-scheduled-regexp)
4758 (defvar org-scheduled-time-regexp nil
4759 "Matches the SCHEDULED keyword together with a time stamp.")
4760 (make-variable-buffer-local 'org-scheduled-time-regexp)
4761 (defvar org-scheduled-time-hour-regexp nil
4762 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4763 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4764 (defvar org-closed-time-regexp nil
4765 "Matches the CLOSED keyword together with a time stamp.")
4766 (make-variable-buffer-local 'org-closed-time-regexp)
4768 (defvar org-keyword-time-regexp nil
4769 "Matches any of the 4 keywords, together with the time stamp.")
4770 (make-variable-buffer-local 'org-keyword-time-regexp)
4771 (defvar org-keyword-time-not-clock-regexp nil
4772 "Matches any of the 3 keywords, together with the time stamp.")
4773 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4774 (defvar org-maybe-keyword-time-regexp nil
4775 "Matches a timestamp, possibly preceded by a keyword.")
4776 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4777 (defvar org-all-time-keywords nil
4778 "List of time keywords.")
4779 (make-variable-buffer-local 'org-all-time-keywords)
4781 (defconst org-plain-time-of-day-regexp
4782 (concat
4783 "\\(\\<[012]?[0-9]"
4784 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4785 "\\(--?"
4786 "\\(\\<[012]?[0-9]"
4787 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4788 "\\)?")
4789 "Regular expression to match a plain time or time range.
4790 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4791 groups carry important information:
4792 0 the full match
4793 1 the first time, range or not
4794 8 the second time, if it is a range.")
4796 (defconst org-plain-time-extension-regexp
4797 (concat
4798 "\\(\\<[012]?[0-9]"
4799 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4800 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4801 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4802 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4803 groups carry important information:
4804 0 the full match
4805 7 hours of duration
4806 9 minutes of duration")
4808 (defconst org-stamp-time-of-day-regexp
4809 (concat
4810 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4811 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4812 "\\(--?"
4813 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4814 "Regular expression to match a timestamp time or time range.
4815 After a match, the following groups carry important information:
4816 0 the full match
4817 1 date plus weekday, for back referencing to make sure both times are on the same day
4818 2 the first time, range or not
4819 4 the second time, if it is a range.")
4821 (defconst org-startup-options
4822 '(("fold" org-startup-folded t)
4823 ("overview" org-startup-folded t)
4824 ("nofold" org-startup-folded nil)
4825 ("showall" org-startup-folded nil)
4826 ("showeverything" org-startup-folded showeverything)
4827 ("content" org-startup-folded content)
4828 ("indent" org-startup-indented t)
4829 ("noindent" org-startup-indented nil)
4830 ("hidestars" org-hide-leading-stars t)
4831 ("showstars" org-hide-leading-stars nil)
4832 ("odd" org-odd-levels-only t)
4833 ("oddeven" org-odd-levels-only nil)
4834 ("align" org-startup-align-all-tables t)
4835 ("noalign" org-startup-align-all-tables nil)
4836 ("inlineimages" org-startup-with-inline-images t)
4837 ("noinlineimages" org-startup-with-inline-images nil)
4838 ("latexpreview" org-startup-with-latex-preview t)
4839 ("nolatexpreview" org-startup-with-latex-preview nil)
4840 ("customtime" org-display-custom-times t)
4841 ("logdone" org-log-done time)
4842 ("lognotedone" org-log-done note)
4843 ("nologdone" org-log-done nil)
4844 ("lognoteclock-out" org-log-note-clock-out t)
4845 ("nolognoteclock-out" org-log-note-clock-out nil)
4846 ("logrepeat" org-log-repeat state)
4847 ("lognoterepeat" org-log-repeat note)
4848 ("logdrawer" org-log-into-drawer t)
4849 ("nologdrawer" org-log-into-drawer nil)
4850 ("logstatesreversed" org-log-states-order-reversed t)
4851 ("nologstatesreversed" org-log-states-order-reversed nil)
4852 ("nologrepeat" org-log-repeat nil)
4853 ("logreschedule" org-log-reschedule time)
4854 ("lognotereschedule" org-log-reschedule note)
4855 ("nologreschedule" org-log-reschedule nil)
4856 ("logredeadline" org-log-redeadline time)
4857 ("lognoteredeadline" org-log-redeadline note)
4858 ("nologredeadline" org-log-redeadline nil)
4859 ("logrefile" org-log-refile time)
4860 ("lognoterefile" org-log-refile note)
4861 ("nologrefile" org-log-refile nil)
4862 ("fninline" org-footnote-define-inline t)
4863 ("nofninline" org-footnote-define-inline nil)
4864 ("fnlocal" org-footnote-section nil)
4865 ("fnauto" org-footnote-auto-label t)
4866 ("fnprompt" org-footnote-auto-label nil)
4867 ("fnconfirm" org-footnote-auto-label confirm)
4868 ("fnplain" org-footnote-auto-label plain)
4869 ("fnadjust" org-footnote-auto-adjust t)
4870 ("nofnadjust" org-footnote-auto-adjust nil)
4871 ("constcgs" constants-unit-system cgs)
4872 ("constSI" constants-unit-system SI)
4873 ("noptag" org-tag-persistent-alist nil)
4874 ("hideblocks" org-hide-block-startup t)
4875 ("nohideblocks" org-hide-block-startup nil)
4876 ("beamer" org-startup-with-beamer-mode t)
4877 ("entitiespretty" org-pretty-entities t)
4878 ("entitiesplain" org-pretty-entities nil))
4879 "Variable associated with STARTUP options for org-mode.
4880 Each element is a list of three items: the startup options (as written
4881 in the #+STARTUP line), the corresponding variable, and the value to set
4882 this variable to if the option is found. An optional forth element PUSH
4883 means to push this value onto the list in the variable.")
4885 (defun org-update-property-plist (key val props)
4886 "Update PROPS with KEY and VAL."
4887 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4888 (key (if appending (substring key 0 (- (length key) 1)) key))
4889 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4890 (previous (cdr (assoc key props))))
4891 (if appending
4892 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4893 (cons (cons key val) remainder))))
4895 (defcustom org-group-tags t
4896 "When non-nil (the default), use group tags.
4897 This can be turned on/off through `org-toggle-tags-groups'."
4898 :group 'org-tags
4899 :group 'org-startup
4900 :type 'boolean)
4902 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4904 (defun org-toggle-tags-groups ()
4905 "Toggle support for group tags.
4906 Support for group tags is controlled by the option
4907 `org-group-tags', which is non-nil by default."
4908 (interactive)
4909 (setq org-group-tags (not org-group-tags))
4910 (cond ((and (derived-mode-p 'org-agenda-mode)
4911 org-group-tags)
4912 (org-agenda-redo))
4913 ((derived-mode-p 'org-mode)
4914 (let ((org-inhibit-startup t)) (org-mode))))
4915 (message "Groups tags support has been turned %s"
4916 (if org-group-tags "on" "off")))
4918 (defun org-set-regexps-and-options-for-tags ()
4919 "Precompute variables used for tags."
4920 (when (derived-mode-p 'org-mode)
4921 (org-set-local 'org-file-tags nil)
4922 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4923 (splitre "[ \t]+")
4924 (start 0)
4925 tags ftags key value)
4926 (save-excursion
4927 (save-restriction
4928 (widen)
4929 (goto-char (point-min))
4930 (while (re-search-forward re nil t)
4931 (setq key (upcase (org-match-string-no-properties 1))
4932 value (org-match-string-no-properties 2))
4933 (if (stringp value) (setq value (org-trim value)))
4934 (cond
4935 ((equal key "TAGS")
4936 (setq tags (append tags (if tags '("\\n") nil)
4937 (org-split-string value splitre))))
4938 ((equal key "FILETAGS")
4939 (when (string-match "\\S-" value)
4940 (setq ftags
4941 (append
4942 ftags
4943 (apply 'append
4944 (mapcar (lambda (x) (org-split-string x ":"))
4945 (org-split-string value)))))))))))
4946 ;; Process the file tags.
4947 (and ftags (org-set-local 'org-file-tags
4948 (mapcar 'org-add-prop-inherited ftags)))
4949 (org-set-local 'org-tag-groups-alist nil)
4950 ;; Process the tags.
4951 (when (and (not tags) org-tag-alist)
4952 (setq tags
4953 (mapcar
4954 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4955 ((eq (car tg) :endgroup) "}")
4956 ((eq (car tg) :grouptags) ":")
4957 ((eq (car tg) :newline) "\n")
4958 (t (concat (car tg)
4959 (if (characterp (cdr tg))
4960 (format "(%s)" (char-to-string (cdr tg))) "")))))
4961 org-tag-alist)))
4962 (let (e tgs g)
4963 (while (setq e (pop tags))
4964 (cond
4965 ((equal e "{")
4966 (progn (push '(:startgroup) tgs)
4967 (when (equal (nth 1 tags) ":")
4968 (push (list (replace-regexp-in-string
4969 "(.+)$" "" (nth 0 tags)))
4970 org-tag-groups-alist)
4971 (setq g 0))))
4972 ((equal e ":") (push '(:grouptags) tgs))
4973 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4974 ((equal e "\\n") (push '(:newline) tgs))
4975 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4976 (push (cons (match-string 1 e)
4977 (string-to-char (match-string 2 e))) tgs)
4978 (if (and g (> g 0))
4979 (setcar org-tag-groups-alist
4980 (append (car org-tag-groups-alist)
4981 (list (match-string 1 e)))))
4982 (if g (setq g (1+ g))))
4983 (t (push (list e) tgs)
4984 (if (and g (> g 0))
4985 (setcar org-tag-groups-alist
4986 (append (car org-tag-groups-alist) (list e))))
4987 (if g (setq g (1+ g))))))
4988 (org-set-local 'org-tag-alist nil)
4989 (while (setq e (pop tgs))
4990 (or (and (stringp (car e))
4991 (assoc (car e) org-tag-alist))
4992 (push e org-tag-alist)))
4993 ;; Return a list with tag variables
4994 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4996 (defvar org-ota nil)
4997 (defun org-set-regexps-and-options ()
4998 "Precompute regular expressions used in the current buffer."
4999 (when (derived-mode-p 'org-mode)
5000 (org-set-local 'org-todo-kwd-alist nil)
5001 (org-set-local 'org-todo-key-alist nil)
5002 (org-set-local 'org-todo-key-trigger nil)
5003 (org-set-local 'org-todo-keywords-1 nil)
5004 (org-set-local 'org-done-keywords nil)
5005 (org-set-local 'org-todo-heads nil)
5006 (org-set-local 'org-todo-sets nil)
5007 (org-set-local 'org-todo-log-states nil)
5008 (org-set-local 'org-file-properties nil)
5009 (let ((re (org-make-options-regexp
5010 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
5011 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
5012 "SETUPFILE" "OPTIONS")
5013 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
5014 (splitre "[ \t]+")
5015 (scripts org-use-sub-superscripts)
5016 kwds kws0 kwsa key log value cat arch const links hw dws
5017 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
5018 (start 0))
5019 (save-excursion
5020 (save-restriction
5021 (widen)
5022 (goto-char (point-min))
5023 (while
5024 (or (and
5025 ext-setup-or-nil
5026 (not org-ota)
5027 (let (ret)
5028 (with-temp-buffer
5029 (insert ext-setup-or-nil)
5030 (let ((major-mode 'org-mode) org-ota)
5031 (setq ret (save-match-data
5032 (org-set-regexps-and-options-for-tags)))))
5033 ;; Append setupfile tags to existing tags
5034 (setq org-ota t)
5035 (setq org-file-tags
5036 (delq nil (append org-file-tags (nth 0 ret)))
5037 org-tag-alist
5038 (delq nil (append org-tag-alist (nth 1 ret)))
5039 org-tag-groups-alist
5040 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5041 (and ext-setup-or-nil
5042 (string-match re ext-setup-or-nil start)
5043 (setq start (match-end 0)))
5044 (and (setq ext-setup-or-nil nil start 0)
5045 (re-search-forward re nil t)))
5046 (setq key (upcase (match-string 1 ext-setup-or-nil))
5047 value (org-match-string-no-properties 2 ext-setup-or-nil))
5048 (if (stringp value) (setq value (org-trim value)))
5049 (cond
5050 ((equal key "CATEGORY")
5051 (setq cat value))
5052 ((member key '("SEQ_TODO" "TODO"))
5053 (push (cons 'sequence (org-split-string value splitre)) kwds))
5054 ((equal key "TYP_TODO")
5055 (push (cons 'type (org-split-string value splitre)) kwds))
5056 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5057 ;; general TODO-like setup
5058 (push (cons (intern (downcase (match-string 1 key)))
5059 (org-split-string value splitre)) kwds))
5060 ((equal key "COLUMNS")
5061 (org-set-local 'org-columns-default-format value))
5062 ((equal key "LINK")
5063 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5064 (push (cons (match-string 1 value)
5065 (org-trim (match-string 2 value)))
5066 links)))
5067 ((equal key "PRIORITIES")
5068 (setq prio (org-split-string value " +")))
5069 ((equal key "PROPERTY")
5070 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5071 (setq props (org-update-property-plist (match-string 1 value)
5072 (match-string 2 value)
5073 props))))
5074 ((equal key "CONSTANTS")
5075 (org-table-set-constants))
5076 ((equal key "STARTUP")
5077 (let ((opts (org-split-string value splitre))
5078 l var val)
5079 (while (setq l (pop opts))
5080 (when (setq l (assoc l org-startup-options))
5081 (setq var (nth 1 l) val (nth 2 l))
5082 (if (not (nth 3 l))
5083 (set (make-local-variable var) val)
5084 (if (not (listp (symbol-value var)))
5085 (set (make-local-variable var) nil))
5086 (set (make-local-variable var) (symbol-value var))
5087 (add-to-list var val))))))
5088 ((equal key "ARCHIVE")
5089 (setq arch value)
5090 (remove-text-properties 0 (length arch)
5091 '(face t fontified t) arch))
5092 ((equal key "OPTIONS")
5093 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5094 (setq scripts (read (match-string 2 value)))))
5095 ((and (equal key "SETUPFILE")
5096 ;; Prevent checking in Gnus messages
5097 (not buffer-read-only))
5098 (setq setup-contents (org-file-contents
5099 (expand-file-name
5100 (org-remove-double-quotes value))
5101 'noerror))
5102 (if (not ext-setup-or-nil)
5103 (setq ext-setup-or-nil setup-contents start 0)
5104 (setq ext-setup-or-nil
5105 (concat (substring ext-setup-or-nil 0 start)
5106 "\n" setup-contents "\n"
5107 (substring ext-setup-or-nil start)))))))
5108 ;; search for property blocks
5109 (goto-char (point-min))
5110 (while (re-search-forward org-block-regexp nil t)
5111 (when (equal "PROPERTY" (upcase (match-string 1)))
5112 (setq value (replace-regexp-in-string
5113 "[\n\r]" " " (match-string 4)))
5114 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5115 (setq props (org-update-property-plist (match-string 1 value)
5116 (match-string 2 value)
5117 props)))))))
5118 (org-set-local 'org-use-sub-superscripts scripts)
5119 (when cat
5120 (org-set-local 'org-category (intern cat))
5121 (push (cons "CATEGORY" cat) props))
5122 (when prio
5123 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5124 (setq prio (mapcar 'string-to-char prio))
5125 (org-set-local 'org-highest-priority (nth 0 prio))
5126 (org-set-local 'org-lowest-priority (nth 1 prio))
5127 (org-set-local 'org-default-priority (nth 2 prio)))
5128 (and props (org-set-local 'org-file-properties (nreverse props)))
5129 (and arch (org-set-local 'org-archive-location arch))
5130 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5131 ;; Process the TODO keywords
5132 (unless kwds
5133 ;; Use the global values as if they had been given locally.
5134 (setq kwds (default-value 'org-todo-keywords))
5135 (if (stringp (car kwds))
5136 (setq kwds (list (cons org-todo-interpretation
5137 (default-value 'org-todo-keywords)))))
5138 (setq kwds (reverse kwds)))
5139 (setq kwds (nreverse kwds))
5140 (let (inter kws kw)
5141 (while (setq kws (pop kwds))
5142 (let ((kws (or
5143 (run-hook-with-args-until-success
5144 'org-todo-setup-filter-hook kws)
5145 kws)))
5146 (setq inter (pop kws) sep (member "|" kws)
5147 kws0 (delete "|" (copy-sequence kws))
5148 kwsa nil
5149 kws1 (mapcar
5150 (lambda (x)
5151 ;; 1 2
5152 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5153 (progn
5154 (setq kw (match-string 1 x)
5155 key (and (match-end 2) (match-string 2 x))
5156 log (org-extract-log-state-settings x))
5157 (push (cons kw (and key (string-to-char key))) kwsa)
5158 (and log (push log org-todo-log-states))
5160 (error "Invalid TODO keyword %s" x)))
5161 kws0)
5162 kwsa (if kwsa (append '((:startgroup))
5163 (nreverse kwsa)
5164 '((:endgroup))))
5165 hw (car kws1)
5166 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5167 tail (list inter hw (car dws) (org-last dws))))
5168 (add-to-list 'org-todo-heads hw 'append)
5169 (push kws1 org-todo-sets)
5170 (setq org-done-keywords (append org-done-keywords dws nil))
5171 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5172 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5173 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5174 (setq org-todo-sets (nreverse org-todo-sets)
5175 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5176 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5177 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5178 ;; Compute the regular expressions and other local variables.
5179 ;; Using `org-outline-regexp-bol' would complicate them much,
5180 ;; because of the fixed white space at the end of that string.
5181 (if (not org-done-keywords)
5182 (setq org-done-keywords (and org-todo-keywords-1
5183 (list (org-last org-todo-keywords-1)))))
5184 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5185 (length org-scheduled-string)
5186 (length org-clock-string)
5187 (length org-closed-string)))
5188 org-not-done-keywords
5189 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5190 org-todo-regexp
5191 (concat "\\("
5192 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5193 "\\)")
5194 org-not-done-regexp
5195 (concat "\\("
5196 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5197 "\\)")
5198 org-not-done-heading-regexp
5199 (format org-heading-keyword-regexp-format org-not-done-regexp)
5200 org-todo-line-regexp
5201 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5202 org-complex-heading-regexp
5203 (concat "^\\(\\*+\\)"
5204 "\\(?: +" org-todo-regexp "\\)?"
5205 "\\(?: +\\(\\[#.\\]\\)\\)?"
5206 "\\(?: +\\(.*?\\)\\)??"
5207 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5208 "[ \t]*$")
5209 org-complex-heading-regexp-format
5210 (concat "^\\(\\*+\\)"
5211 "\\(?: +" org-todo-regexp "\\)?"
5212 "\\(?: +\\(\\[#.\\]\\)\\)?"
5213 "\\(?: +"
5214 ;; Stats cookies can be stuck to body.
5215 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5216 "\\(%s\\)"
5217 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5218 "\\)"
5219 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5220 "[ \t]*$")
5221 org-todo-line-tags-regexp
5222 (concat "^\\(\\*+\\)"
5223 "\\(?: +" org-todo-regexp "\\)?"
5224 "\\(?: +\\(.*?\\)\\)??"
5225 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5226 "[ \t]*$")
5227 org-deadline-regexp (concat "\\<" org-deadline-string)
5228 org-deadline-time-regexp
5229 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5230 org-deadline-time-hour-regexp
5231 (concat "\\<" org-deadline-string
5232 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5233 org-deadline-line-regexp
5234 (concat "\\<\\(" org-deadline-string "\\).*")
5235 org-scheduled-regexp
5236 (concat "\\<" org-scheduled-string)
5237 org-scheduled-time-regexp
5238 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5239 org-scheduled-time-hour-regexp
5240 (concat "\\<" org-scheduled-string
5241 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5242 org-closed-time-regexp
5243 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5244 org-keyword-time-regexp
5245 (concat "\\<\\(" org-scheduled-string
5246 "\\|" org-deadline-string
5247 "\\|" org-closed-string
5248 "\\|" org-clock-string "\\)"
5249 " *[[<]\\([^]>]+\\)[]>]")
5250 org-keyword-time-not-clock-regexp
5251 (concat "\\<\\(" org-scheduled-string
5252 "\\|" org-deadline-string
5253 "\\|" org-closed-string
5254 "\\)"
5255 " *[[<]\\([^]>]+\\)[]>]")
5256 org-maybe-keyword-time-regexp
5257 (concat "\\(\\<\\(" org-scheduled-string
5258 "\\|" org-deadline-string
5259 "\\|" org-closed-string
5260 "\\|" org-clock-string "\\)\\)?"
5261 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5262 org-all-time-keywords
5263 (mapcar (lambda (w) (substring w 0 -1))
5264 (list org-scheduled-string org-deadline-string
5265 org-clock-string org-closed-string)))
5266 (setq org-ota nil)
5267 (org-compute-latex-and-related-regexp))))
5269 (defun org-file-contents (file &optional noerror)
5270 "Return the contents of FILE, as a string."
5271 (if (and file (file-readable-p file))
5272 (with-temp-buffer
5273 (insert-file-contents file)
5274 (buffer-string))
5275 (funcall (if noerror 'message 'error)
5276 "Cannot read file \"%s\"%s"
5277 file
5278 (let ((from (buffer-file-name (buffer-base-buffer))))
5279 (if from (concat " (referenced in file \"" from "\")") "")))))
5281 (defun org-extract-log-state-settings (x)
5282 "Extract the log state setting from a TODO keyword string.
5283 This will extract info from a string like \"WAIT(w@/!)\"."
5284 (let (kw key log1 log2)
5285 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5286 (setq kw (match-string 1 x)
5287 key (and (match-end 2) (match-string 2 x))
5288 log1 (and (match-end 3) (match-string 3 x))
5289 log2 (and (match-end 4) (match-string 4 x)))
5290 (and (or log1 log2)
5291 (list kw
5292 (and log1 (if (equal log1 "!") 'time 'note))
5293 (and log2 (if (equal log2 "!") 'time 'note)))))))
5295 (defun org-remove-keyword-keys (list)
5296 "Remove a pair of parenthesis at the end of each string in LIST."
5297 (mapcar (lambda (x)
5298 (if (string-match "(.*)$" x)
5299 (substring x 0 (match-beginning 0))
5301 list))
5303 (defun org-assign-fast-keys (alist)
5304 "Assign fast keys to a keyword-key alist.
5305 Respect keys that are already there."
5306 (let (new e (alt ?0))
5307 (while (setq e (pop alist))
5308 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5309 (cdr e)) ;; Key already assigned.
5310 (push e new)
5311 (let ((clist (string-to-list (downcase (car e))))
5312 (used (append new alist)))
5313 (when (= (car clist) ?@)
5314 (pop clist))
5315 (while (and clist (rassoc (car clist) used))
5316 (pop clist))
5317 (unless clist
5318 (while (rassoc alt used)
5319 (incf alt)))
5320 (push (cons (car e) (or (car clist) alt)) new))))
5321 (nreverse new)))
5323 ;;; Some variables used in various places
5325 (defvar org-window-configuration nil
5326 "Used in various places to store a window configuration.")
5327 (defvar org-selected-window nil
5328 "Used in various places to store a window configuration.")
5329 (defvar org-finish-function nil
5330 "Function to be called when `C-c C-c' is used.
5331 This is for getting out of special buffers like capture.")
5334 ;; FIXME: Occasionally check by commenting these, to make sure
5335 ;; no other functions uses these, forgetting to let-bind them.
5336 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5337 (defvar org-last-state)
5338 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5340 ;; Defined somewhere in this file, but used before definition.
5341 (defvar org-entities) ;; defined in org-entities.el
5342 (defvar org-struct-menu)
5343 (defvar org-org-menu)
5344 (defvar org-tbl-menu)
5346 ;;;; Define the Org-mode
5348 ;; We use a before-change function to check if a table might need
5349 ;; an update.
5350 (defvar org-table-may-need-update t
5351 "Indicates that a table might need an update.
5352 This variable is set by `org-before-change-function'.
5353 `org-table-align' sets it back to nil.")
5354 (defun org-before-change-function (beg end)
5355 "Every change indicates that a table might need an update."
5356 (setq org-table-may-need-update t))
5357 (defvar org-mode-map)
5358 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5359 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5360 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5361 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5362 (defvar org-table-buffer-is-an nil)
5364 (defvar bidi-paragraph-direction)
5365 (defvar buffer-face-mode-face)
5367 (require 'outline)
5368 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5369 (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"))
5370 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5372 ;; Other stuff we need.
5373 (require 'time-date)
5374 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5375 (require 'easymenu)
5376 (require 'overlay)
5378 ;; (require 'org-macs) moved higher up in the file before it is first used
5379 (require 'org-entities)
5380 ;; (require 'org-compat) moved higher up in the file before it is first used
5381 (require 'org-faces)
5382 (require 'org-list)
5383 (require 'org-pcomplete)
5384 (require 'org-src)
5385 (require 'org-footnote)
5386 (require 'org-macro)
5388 ;; babel
5389 (require 'ob)
5391 ;;;###autoload
5392 (define-derived-mode org-mode outline-mode "Org"
5393 "Outline-based notes management and organizer, alias
5394 \"Carsten's outline-mode for keeping track of everything.\"
5396 Org-mode develops organizational tasks around a NOTES file which
5397 contains information about projects as plain text. Org-mode is
5398 implemented on top of outline-mode, which is ideal to keep the content
5399 of large files well structured. It supports ToDo items, deadlines and
5400 time stamps, which magically appear in the diary listing of the Emacs
5401 calendar. Tables are easily created with a built-in table editor.
5402 Plain text URL-like links connect to websites, emails (VM), Usenet
5403 messages (Gnus), BBDB entries, and any files related to the project.
5404 For printing and sharing of notes, an Org-mode file (or a part of it)
5405 can be exported as a structured ASCII or HTML file.
5407 The following commands are available:
5409 \\{org-mode-map}"
5411 ;; Get rid of Outline menus, they are not needed
5412 ;; Need to do this here because define-derived-mode sets up
5413 ;; the keymap so late. Still, it is a waste to call this each time
5414 ;; we switch another buffer into org-mode.
5415 (if (featurep 'xemacs)
5416 (when (boundp 'outline-mode-menu-heading)
5417 ;; Assume this is Greg's port, it uses easymenu
5418 (easy-menu-remove outline-mode-menu-heading)
5419 (easy-menu-remove outline-mode-menu-show)
5420 (easy-menu-remove outline-mode-menu-hide))
5421 (define-key org-mode-map [menu-bar headings] 'undefined)
5422 (define-key org-mode-map [menu-bar hide] 'undefined)
5423 (define-key org-mode-map [menu-bar show] 'undefined))
5425 (org-load-modules-maybe)
5426 (easy-menu-add org-org-menu)
5427 (easy-menu-add org-tbl-menu)
5428 (org-install-agenda-files-menu)
5429 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5430 (add-to-invisibility-spec '(org-cwidth))
5431 (add-to-invisibility-spec '(org-hide-block . t))
5432 (when (featurep 'xemacs)
5433 (org-set-local 'line-move-ignore-invisible t))
5434 (org-set-local 'outline-regexp org-outline-regexp)
5435 (org-set-local 'outline-level 'org-outline-level)
5436 (setq bidi-paragraph-direction 'left-to-right)
5437 (when (and org-ellipsis
5438 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5439 (fboundp 'make-glyph-code))
5440 (unless org-display-table
5441 (setq org-display-table (make-display-table)))
5442 (set-display-table-slot
5443 org-display-table 4
5444 (vconcat (mapcar
5445 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5446 org-ellipsis)))
5447 (if (stringp org-ellipsis) org-ellipsis "..."))))
5448 (setq buffer-display-table org-display-table))
5449 (org-set-regexps-and-options-for-tags)
5450 (org-set-regexps-and-options)
5451 (org-set-font-lock-defaults)
5452 (when (and org-tag-faces (not org-tags-special-faces-re))
5453 ;; tag faces set outside customize.... force initialization.
5454 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5455 ;; Calc embedded
5456 (org-set-local 'calc-embedded-open-mode "# ")
5457 ;; Modify a few syntax entries
5458 (modify-syntax-entry ?@ "w")
5459 (modify-syntax-entry ?\" "\"")
5460 (modify-syntax-entry ?\\ "_")
5461 (modify-syntax-entry ?~ "_")
5462 (if org-startup-truncated (setq truncate-lines t))
5463 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5464 (org-set-local 'font-lock-unfontify-region-function
5465 'org-unfontify-region)
5466 ;; Activate before-change-function
5467 (org-set-local 'org-table-may-need-update t)
5468 (org-add-hook 'before-change-functions 'org-before-change-function nil
5469 'local)
5470 ;; Check for running clock before killing a buffer
5471 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5472 ;; Initialize macros templates.
5473 (org-macro-initialize-templates)
5474 ;; Initialize radio targets.
5475 (org-update-radio-target-regexp)
5476 ;; Indentation.
5477 (org-set-local 'indent-line-function 'org-indent-line)
5478 (org-set-local 'indent-region-function 'org-indent-region)
5479 ;; Filling and auto-filling.
5480 (org-setup-filling)
5481 ;; Comments.
5482 (org-setup-comments-handling)
5483 ;; Initialize cache.
5484 (org-element-cache-reset)
5485 ;; Beginning/end of defun
5486 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5487 (org-set-local 'end-of-defun-function
5488 (lambda ()
5489 (if (not (org-at-heading-p))
5490 (org-forward-element)
5491 (org-forward-element)
5492 (forward-char -1))))
5493 ;; Next error for sparse trees
5494 (org-set-local 'next-error-function 'org-occur-next-match)
5495 ;; Make sure dependence stuff works reliably, even for users who set it
5496 ;; too late :-(
5497 (if org-enforce-todo-dependencies
5498 (add-hook 'org-blocker-hook
5499 'org-block-todo-from-children-or-siblings-or-parent)
5500 (remove-hook 'org-blocker-hook
5501 'org-block-todo-from-children-or-siblings-or-parent))
5502 (if org-enforce-todo-checkbox-dependencies
5503 (add-hook 'org-blocker-hook
5504 'org-block-todo-from-checkboxes)
5505 (remove-hook 'org-blocker-hook
5506 'org-block-todo-from-checkboxes))
5508 ;; Align options lines
5509 (org-set-local
5510 'align-mode-rules-list
5511 '((org-in-buffer-settings
5512 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5513 (modes . '(org-mode)))))
5515 ;; Imenu
5516 (org-set-local 'imenu-create-index-function
5517 'org-imenu-get-tree)
5519 ;; Make isearch reveal context
5520 (if (or (featurep 'xemacs)
5521 (not (boundp 'outline-isearch-open-invisible-function)))
5522 ;; Emacs 21 and XEmacs make use of the hook
5523 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5524 ;; Emacs 22 deals with this through a special variable
5525 (org-set-local 'outline-isearch-open-invisible-function
5526 (lambda (&rest ignore) (org-show-context 'isearch))))
5528 ;; Setup the pcomplete hooks
5529 (set (make-local-variable 'pcomplete-command-completion-function)
5530 'org-pcomplete-initial)
5531 (set (make-local-variable 'pcomplete-command-name-function)
5532 'org-command-at-point)
5533 (set (make-local-variable 'pcomplete-default-completion-function)
5534 'ignore)
5535 (set (make-local-variable 'pcomplete-parse-arguments-function)
5536 'org-parse-arguments)
5537 (set (make-local-variable 'pcomplete-termination-string) "")
5538 (when (>= emacs-major-version 23)
5539 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5541 ;; If empty file that did not turn on org-mode automatically, make it to.
5542 (if (and org-insert-mode-line-in-empty-file
5543 (org-called-interactively-p 'any)
5544 (= (point-min) (point-max)))
5545 (insert "# -*- mode: org -*-\n\n"))
5546 (unless org-inhibit-startup
5547 (org-unmodified
5548 (and org-startup-with-beamer-mode (org-beamer-mode))
5549 (when org-startup-align-all-tables
5550 (org-table-map-tables 'org-table-align 'quietly))
5551 (when org-startup-with-inline-images
5552 (org-display-inline-images))
5553 (when org-startup-with-latex-preview
5554 (org-toggle-latex-fragment))
5555 (unless org-inhibit-startup-visibility-stuff
5556 (org-set-startup-visibility))
5557 (org-refresh-effort-properties)))
5558 ;; Try to set org-hide correctly
5559 (let ((foreground (org-find-invisible-foreground)))
5560 (if foreground
5561 (set-face-foreground 'org-hide foreground))))
5563 ;; Update `customize-package-emacs-version-alist'
5564 (add-to-list 'customize-package-emacs-version-alist
5565 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5566 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5567 ("8.2.6" . "24.4")))
5569 (defvar org-mode-transpose-word-syntax-table
5570 (let ((st (make-syntax-table)))
5571 (mapc (lambda(c) (modify-syntax-entry
5572 (string-to-char (car c)) "w p" st))
5573 org-emphasis-alist)
5574 st))
5576 (when (fboundp 'abbrev-table-put)
5577 (abbrev-table-put org-mode-abbrev-table
5578 :parents (list text-mode-abbrev-table)))
5580 (defun org-find-invisible-foreground ()
5581 (let ((candidates (remove
5582 "unspecified-bg"
5583 (nconc
5584 (list (face-background 'default)
5585 (face-background 'org-default))
5586 (mapcar
5587 (lambda (alist)
5588 (when (boundp alist)
5589 (cdr (assoc 'background-color (symbol-value alist)))))
5590 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5591 (list (face-foreground 'org-hide))))))
5592 (car (remove nil candidates))))
5594 (defun org-current-time (&optional rounding-minutes past)
5595 "Current time, possibly rounded to ROUNDING-MINUTES.
5596 When ROUNDING-MINUTES is not an integer, fall back on the car of
5597 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5598 the rounding returns a past time."
5599 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5600 (car org-time-stamp-rounding-minutes)))
5601 (time (decode-time)) res)
5602 (if (< r 1)
5603 (current-time)
5604 (setq res
5605 (apply 'encode-time
5606 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5607 (nthcdr 2 time))))
5608 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5609 (seconds-to-time (- (org-float-time res) (* r 60)))
5610 res))))
5612 (defun org-today ()
5613 "Return today date, considering `org-extend-today-until'."
5614 (time-to-days
5615 (time-subtract (current-time)
5616 (list 0 (* 3600 org-extend-today-until) 0))))
5618 ;;;; Font-Lock stuff, including the activators
5620 (defvar org-mouse-map (make-sparse-keymap))
5621 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5622 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5623 (when org-mouse-1-follows-link
5624 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5625 (when org-tab-follows-link
5626 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5627 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5629 (require 'font-lock)
5631 (defconst org-non-link-chars "]\t\n\r<>")
5632 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5633 "file+sys" "news" "shell" "elisp" "doi" "message"
5634 "help"))
5635 (defvar org-link-types-re nil
5636 "Matches a link that has a url-like prefix like \"http:\"")
5637 (defvar org-link-re-with-space nil
5638 "Matches a link with spaces, optional angular brackets around it.")
5639 (defvar org-link-re-with-space2 nil
5640 "Matches a link with spaces, optional angular brackets around it.")
5641 (defvar org-link-re-with-space3 nil
5642 "Matches a link with spaces, only for internal part in bracket links.")
5643 (defvar org-angle-link-re nil
5644 "Matches link with angular brackets, spaces are allowed.")
5645 (defvar org-plain-link-re nil
5646 "Matches plain link, without spaces.")
5647 (defvar org-bracket-link-regexp nil
5648 "Matches a link in double brackets.")
5649 (defvar org-bracket-link-analytic-regexp nil
5650 "Regular expression used to analyze links.
5651 Here is what the match groups contain after a match:
5652 1: http:
5653 2: http
5654 3: path
5655 4: [desc]
5656 5: desc")
5657 (defvar org-bracket-link-analytic-regexp++ nil
5658 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5659 (defvar org-any-link-re nil
5660 "Regular expression matching any link.")
5662 (defconst org-match-sexp-depth 3
5663 "Number of stacked braces for sub/superscript matching.")
5665 (defun org-create-multibrace-regexp (left right n)
5666 "Create a regular expression which will match a balanced sexp.
5667 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5668 as single character strings.
5669 The regexp returned will match the entire expression including the
5670 delimiters. It will also define a single group which contains the
5671 match except for the outermost delimiters. The maximum depth of
5672 stacked delimiters is N. Escaping delimiters is not possible."
5673 (let* ((nothing (concat "[^" left right "]*?"))
5674 (or "\\|")
5675 (re nothing)
5676 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5677 (while (> n 1)
5678 (setq n (1- n)
5679 re (concat re or next)
5680 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5681 (concat left "\\(" re "\\)" right)))
5683 (defconst org-match-substring-regexp
5684 (concat
5685 "\\(\\S-\\)\\([_^]\\)\\("
5686 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5687 "\\|"
5688 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5689 "\\|"
5690 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5691 "The regular expression matching a sub- or superscript.")
5693 (defconst org-match-substring-with-braces-regexp
5694 (concat
5695 "\\(\\S-\\)\\([_^]\\)"
5696 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5697 "The regular expression matching a sub- or superscript, forcing braces.")
5699 (defun org-make-link-regexps ()
5700 "Update the link regular expressions.
5701 This should be called after the variable `org-link-types' has changed."
5702 (let ((types-re (regexp-opt org-link-types t)))
5703 (setq org-link-types-re
5704 (concat "\\`" types-re ":")
5705 org-link-re-with-space
5706 (concat "<?" types-re ":"
5707 "\\([^" org-non-link-chars " ]"
5708 "[^" org-non-link-chars "]*"
5709 "[^" org-non-link-chars " ]\\)>?")
5710 org-link-re-with-space2
5711 (concat "<?" types-re ":"
5712 "\\([^" org-non-link-chars " ]"
5713 "[^\t\n\r]*"
5714 "[^" org-non-link-chars " ]\\)>?")
5715 org-link-re-with-space3
5716 (concat "<?" types-re ":"
5717 "\\([^" org-non-link-chars " ]"
5718 "[^\t\n\r]*\\)")
5719 org-angle-link-re
5720 (concat "<" types-re ":"
5721 "\\([^" org-non-link-chars " ]"
5722 "[^" org-non-link-chars "]*"
5723 "\\)>")
5724 org-plain-link-re
5725 (concat
5726 "\\<" types-re ":"
5727 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5728 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5729 org-bracket-link-regexp
5730 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5731 org-bracket-link-analytic-regexp
5732 (concat
5733 "\\[\\["
5734 "\\(" types-re ":\\)?"
5735 "\\([^]]+\\)"
5736 "\\]"
5737 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5738 "\\]")
5739 org-bracket-link-analytic-regexp++
5740 (concat
5741 "\\[\\["
5742 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5743 "\\([^]]+\\)"
5744 "\\]"
5745 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5746 "\\]")
5747 org-any-link-re
5748 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5749 org-angle-link-re "\\)\\|\\("
5750 org-plain-link-re "\\)"))))
5752 (org-make-link-regexps)
5754 (defvar org-emph-face nil)
5756 (defun org-do-emphasis-faces (limit)
5757 "Run through the buffer and emphasize strings."
5758 (let (rtn a)
5759 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5760 (let* ((border (char-after (match-beginning 3)))
5761 (bre (regexp-quote (char-to-string border))))
5762 (if (and (not (= border (char-after (match-beginning 4))))
5763 (not (save-match-data
5764 (string-match (concat bre ".*" bre)
5765 (replace-regexp-in-string
5766 "\n" " "
5767 (substring (match-string 2) 1 -1))))))
5768 (progn
5769 (setq rtn t)
5770 (setq a (assoc (match-string 3) org-emphasis-alist))
5771 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5772 'face
5773 (nth 1 a))
5774 (and (nth 2 a)
5775 (org-remove-flyspell-overlays-in
5776 (match-beginning 0) (match-end 0)))
5777 (add-text-properties (match-beginning 2) (match-end 2)
5778 '(font-lock-multiline t org-emphasis t))
5779 (when org-hide-emphasis-markers
5780 (add-text-properties (match-end 4) (match-beginning 5)
5781 '(invisible org-link))
5782 (add-text-properties (match-beginning 3) (match-end 3)
5783 '(invisible org-link))))))
5784 (goto-char (1+ (match-beginning 0))))
5785 rtn))
5787 (defun org-emphasize (&optional char)
5788 "Insert or change an emphasis, i.e. a font like bold or italic.
5789 If there is an active region, change that region to a new emphasis.
5790 If there is no region, just insert the marker characters and position
5791 the cursor between them.
5792 CHAR should be the marker character. If it is a space, it means to
5793 remove the emphasis of the selected region.
5794 If CHAR is not given (for example in an interactive call) it will be
5795 prompted for."
5796 (interactive)
5797 (let ((erc org-emphasis-regexp-components)
5798 (prompt "")
5799 (string "") beg end move c s)
5800 (if (org-region-active-p)
5801 (setq beg (region-beginning) end (region-end)
5802 string (buffer-substring beg end))
5803 (setq move t))
5805 (unless char
5806 (message "Emphasis marker or tag: [%s]"
5807 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5808 (setq char (read-char-exclusive)))
5809 (if (equal char ?\ )
5810 (setq s "" move nil)
5811 (unless (assoc (char-to-string char) org-emphasis-alist)
5812 (user-error "No such emphasis marker: \"%c\"" char))
5813 (setq s (char-to-string char)))
5814 (while (and (> (length string) 1)
5815 (equal (substring string 0 1) (substring string -1))
5816 (assoc (substring string 0 1) org-emphasis-alist))
5817 (setq string (substring string 1 -1)))
5818 (setq string (concat s string s))
5819 (if beg (delete-region beg end))
5820 (unless (or (bolp)
5821 (string-match (concat "[" (nth 0 erc) "\n]")
5822 (char-to-string (char-before (point)))))
5823 (insert " "))
5824 (unless (or (eobp)
5825 (string-match (concat "[" (nth 1 erc) "\n]")
5826 (char-to-string (char-after (point)))))
5827 (insert " ") (backward-char 1))
5828 (insert string)
5829 (and move (backward-char 1))))
5831 (defconst org-nonsticky-props
5832 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5834 (defsubst org-rear-nonsticky-at (pos)
5835 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5837 (defun org-activate-plain-links (limit)
5838 "Add link properties for plain links."
5839 (let (f hl)
5840 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5841 (not (member 'org-tag
5842 (get-text-property (1- (match-beginning 0)) 'face)))
5843 (not (org-in-src-block-p)))
5844 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5845 (setq f (get-text-property (match-beginning 0) 'face))
5846 (setq hl (org-match-string-no-properties 0))
5847 (if (or (eq f 'org-tag)
5848 (and (listp f) (memq 'org-tag f)))
5850 (add-text-properties (match-beginning 0) (match-end 0)
5851 (list 'mouse-face 'highlight
5852 'face 'org-link
5853 'htmlize-link `(:uri ,hl)
5854 'keymap org-mouse-map))
5855 (org-rear-nonsticky-at (match-end 0)))
5856 t)))
5858 (defun org-activate-code (limit)
5859 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5860 (progn
5861 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5862 (remove-text-properties (match-beginning 0) (match-end 0)
5863 '(display t invisible t intangible t))
5864 t)))
5866 (defcustom org-src-fontify-natively t
5867 "When non-nil, fontify code in code blocks."
5868 :type 'boolean
5869 :version "24.4"
5870 :package-version '(Org . "8.3")
5871 :group 'org-appearance
5872 :group 'org-babel)
5874 (defcustom org-allow-promoting-top-level-subtree nil
5875 "When non-nil, allow promoting a top level subtree.
5876 The leading star of the top level headline will be replaced
5877 by a #."
5878 :type 'boolean
5879 :version "24.1"
5880 :group 'org-appearance)
5882 (defun org-fontify-meta-lines-and-blocks (limit)
5883 (condition-case nil
5884 (org-fontify-meta-lines-and-blocks-1 limit)
5885 (error (message "org-mode fontification error"))))
5887 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5888 "Fontify #+ lines and blocks."
5889 (let ((case-fold-search t))
5890 (if (re-search-forward
5891 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5892 limit t)
5893 (let ((beg (match-beginning 0))
5894 (block-start (match-end 0))
5895 (block-end nil)
5896 (lang (match-string 7))
5897 (beg1 (line-beginning-position 2))
5898 (dc1 (downcase (match-string 2)))
5899 (dc3 (downcase (match-string 3)))
5900 end end1 quoting block-type ovl)
5901 (cond
5902 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5903 ;; a single line of backend-specific content
5904 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5905 (remove-text-properties (match-beginning 0) (match-end 0)
5906 '(display t invisible t intangible t))
5907 (add-text-properties (match-beginning 1) (match-end 3)
5908 '(font-lock-fontified t face org-meta-line))
5909 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5910 '(font-lock-fontified t face org-block))
5911 ; for backend-specific code
5913 ((and (match-end 4) (equal dc3 "+begin"))
5914 ;; Truly a block
5915 (setq block-type (downcase (match-string 5))
5916 quoting (member block-type org-protecting-blocks))
5917 (when (re-search-forward
5918 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5919 nil t) ;; on purpose, we look further than LIMIT
5920 (setq end (min (point-max) (match-end 0))
5921 end1 (min (point-max) (1- (match-beginning 0))))
5922 (setq block-end (match-beginning 0))
5923 (when quoting
5924 (org-remove-flyspell-overlays-in beg1 end1)
5925 (remove-text-properties beg end
5926 '(display t invisible t intangible t)))
5927 (add-text-properties
5928 beg end '(font-lock-fontified t font-lock-multiline t))
5929 (add-text-properties beg beg1 '(face org-meta-line))
5930 (org-remove-flyspell-overlays-in beg beg1)
5931 (add-text-properties ; For end_src
5932 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5933 (org-remove-flyspell-overlays-in end1 end)
5934 (cond
5935 ((and lang (not (string= lang "")) org-src-fontify-natively)
5936 (org-src-font-lock-fontify-block lang block-start block-end)
5937 (add-text-properties beg1 block-end '(src-block t)))
5938 (quoting
5939 (add-text-properties beg1 (min (point-max) (1+ end1))
5940 '(face org-block))) ; end of source block
5941 ((not org-fontify-quote-and-verse-blocks))
5942 ((string= block-type "quote")
5943 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5944 ((string= block-type "verse")
5945 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5946 (add-text-properties beg beg1 '(face org-block-begin-line))
5947 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5948 '(face org-block-end-line))
5950 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5951 (org-remove-flyspell-overlays-in
5952 (match-beginning 0)
5953 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5954 (add-text-properties
5955 beg (match-end 3)
5956 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5957 '(font-lock-fontified t invisible t)
5958 '(font-lock-fontified t face org-document-info-keyword)))
5959 (add-text-properties
5960 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5961 (if (string-equal dc1 "+title:")
5962 '(font-lock-fontified t face org-document-title)
5963 '(font-lock-fontified t face org-document-info))))
5964 ((or (equal dc1 "+results")
5965 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5966 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5967 "+call:" "+header:" "+headers:" "+name:"))
5968 (and (match-end 4) (equal dc3 "+attr")))
5969 (org-remove-flyspell-overlays-in
5970 (match-beginning 0)
5971 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5972 (add-text-properties
5973 beg (match-end 0)
5974 '(font-lock-fontified t face org-meta-line))
5976 ((member dc3 '(" " ""))
5977 (org-remove-flyspell-overlays-in beg (match-end 0))
5978 (add-text-properties
5979 beg (match-end 0)
5980 '(font-lock-fontified t face font-lock-comment-face)))
5981 (t ;; just any other in-buffer setting, but not indented
5982 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5983 (add-text-properties
5984 beg (match-end 0)
5985 '(font-lock-fontified t face org-meta-line))
5986 t))))))
5988 (defun org-fontify-drawers (limit)
5989 "Fontify drawers."
5990 (when (re-search-forward org-drawer-regexp limit t)
5991 (add-text-properties
5992 (match-beginning 0) (match-end 0)
5993 '(font-lock-fontified t face org-special-keyword))
5994 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5997 (defun org-fontify-macros (limit)
5998 "Fontify macros."
5999 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6000 (add-text-properties
6001 (match-beginning 0) (match-end 0)
6002 '(font-lock-fontified t face org-macro))
6003 (when org-hide-macro-markers
6004 (add-text-properties (match-end 2) (match-beginning 2)
6005 '(invisible t))
6006 (add-text-properties (match-beginning 1) (match-end 1)
6007 '(invisible t)))
6008 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6011 (defun org-activate-angle-links (limit)
6012 "Add text properties for angle links."
6013 (if (and (re-search-forward org-angle-link-re limit t)
6014 (not (org-in-src-block-p)))
6015 (progn
6016 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6017 (add-text-properties (match-beginning 0) (match-end 0)
6018 (list 'mouse-face 'highlight
6019 'keymap org-mouse-map))
6020 (org-rear-nonsticky-at (match-end 0))
6021 t)))
6023 (defun org-activate-footnote-links (limit)
6024 "Add text properties for footnotes."
6025 (let ((fn (org-footnote-next-reference-or-definition limit)))
6026 (when fn
6027 (let* ((beg (nth 1 fn))
6028 (end (nth 2 fn))
6029 (label (car fn))
6030 (referencep (/= (line-beginning-position) beg)))
6031 (when (and referencep (nth 3 fn))
6032 (save-excursion
6033 (goto-char beg)
6034 (search-forward (or label "fn:"))
6035 (org-remove-flyspell-overlays-in beg (match-end 0))))
6036 (add-text-properties beg end
6037 (list 'mouse-face 'highlight
6038 'keymap org-mouse-map
6039 'help-echo
6040 (if referencep "Footnote reference"
6041 "Footnote definition")
6042 'font-lock-fontified t
6043 'font-lock-multiline t
6044 'face 'org-footnote))))))
6046 (defun org-activate-bracket-links (limit)
6047 "Add text properties for bracketed links."
6048 (if (and (re-search-forward org-bracket-link-regexp limit t)
6049 (not (org-in-src-block-p)))
6050 (let* ((hl (org-match-string-no-properties 1))
6051 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6052 (ip (org-maybe-intangible
6053 (list 'invisible 'org-link
6054 'keymap org-mouse-map 'mouse-face 'highlight
6055 'font-lock-multiline t 'help-echo help
6056 'htmlize-link `(:uri ,hl))))
6057 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6058 'font-lock-multiline t 'help-echo help
6059 'htmlize-link `(:uri ,hl))))
6060 ;; We need to remove the invisible property here. Table narrowing
6061 ;; may have made some of this invisible.
6062 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6063 (remove-text-properties (match-beginning 0) (match-end 0)
6064 '(invisible nil))
6065 (if (match-end 3)
6066 (progn
6067 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6068 (org-rear-nonsticky-at (match-beginning 3))
6069 (add-text-properties (match-beginning 3) (match-end 3) vp)
6070 (org-rear-nonsticky-at (match-end 3))
6071 (add-text-properties (match-end 3) (match-end 0) ip)
6072 (org-rear-nonsticky-at (match-end 0)))
6073 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6074 (org-rear-nonsticky-at (match-beginning 1))
6075 (add-text-properties (match-beginning 1) (match-end 1) vp)
6076 (org-rear-nonsticky-at (match-end 1))
6077 (add-text-properties (match-end 1) (match-end 0) ip)
6078 (org-rear-nonsticky-at (match-end 0)))
6079 t)))
6081 (defun org-activate-dates (limit)
6082 "Add text properties for dates."
6083 (if (and (re-search-forward org-tsr-regexp-both limit t)
6084 (not (equal (char-before (match-beginning 0)) 91)))
6085 (progn
6086 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6087 (add-text-properties (match-beginning 0) (match-end 0)
6088 (list 'mouse-face 'highlight
6089 'keymap org-mouse-map))
6090 (org-rear-nonsticky-at (match-end 0))
6091 (when org-display-custom-times
6092 (if (match-end 3)
6093 (org-display-custom-time (match-beginning 3) (match-end 3)))
6094 (org-display-custom-time (match-beginning 1) (match-end 1)))
6095 t)))
6097 (defvar org-target-link-regexp nil
6098 "Regular expression matching radio targets in plain text.")
6099 (make-variable-buffer-local 'org-target-link-regexp)
6101 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6102 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6103 border border border))
6104 "Regular expression matching a link target.")
6106 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6107 "Regular expression matching a radio target.")
6109 (defconst org-any-target-regexp
6110 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6111 "Regular expression matching any target.")
6113 (defun org-activate-target-links (limit)
6114 "Add text properties for target matches."
6115 (when org-target-link-regexp
6116 (let ((case-fold-search t))
6117 (if (re-search-forward org-target-link-regexp limit t)
6118 (progn
6119 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6120 (add-text-properties (match-beginning 1) (match-end 1)
6121 (list 'mouse-face 'highlight
6122 'keymap org-mouse-map
6123 'help-echo "Radio target link"
6124 'org-linked-text t))
6125 (org-rear-nonsticky-at (match-end 1))
6126 t)))))
6128 (defun org-update-radio-target-regexp ()
6129 "Find all radio targets in this file and update the regular expression.
6130 Also refresh fontification if needed."
6131 (interactive)
6132 (let ((old-regexp org-target-link-regexp)
6133 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6134 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6135 (targets
6136 (org-with-wide-buffer
6137 (goto-char (point-min))
6138 (let (rtn)
6139 (while (re-search-forward org-radio-target-regexp nil t)
6140 ;; Make sure point is really within the object.
6141 (backward-char)
6142 (let ((obj (org-element-context)))
6143 (when (eq (org-element-type obj) 'radio-target)
6144 (add-to-list 'rtn (org-element-property :value obj)))))
6145 rtn))))
6146 (setq org-target-link-regexp
6147 (and targets
6148 (concat before-re
6149 (mapconcat
6150 (lambda (x)
6151 (replace-regexp-in-string
6152 " +" "\\s-+" (regexp-quote x) t t))
6153 targets
6154 "\\|")
6155 after-re)))
6156 (unless (equal old-regexp org-target-link-regexp)
6157 ;; Clean-up cache.
6158 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6159 ((not org-target-link-regexp) old-regexp)
6161 (concat before-re
6162 (mapconcat
6163 (lambda (re)
6164 (substring re (length before-re)
6165 (- (length after-re))))
6166 (list old-regexp org-target-link-regexp)
6167 "\\|")
6168 after-re)))))
6169 (org-with-wide-buffer
6170 (goto-char (point-min))
6171 (while (re-search-forward regexp nil t)
6172 (org-element-cache-refresh (match-beginning 1)))))
6173 ;; Re fontify buffer.
6174 (when (memq 'radio org-highlight-links)
6175 (org-restart-font-lock)))))
6177 (defun org-hide-wide-columns (limit)
6178 (let (s e)
6179 (setq s (text-property-any (point) (or limit (point-max))
6180 'org-cwidth t))
6181 (when s
6182 (setq e (next-single-property-change s 'org-cwidth))
6183 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6184 (goto-char e)
6185 t)))
6187 (defvar org-latex-and-related-regexp nil
6188 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6190 (defun org-compute-latex-and-related-regexp ()
6191 "Compute regular expression for LaTeX, entities and sub/superscript.
6192 Result depends on variable `org-highlight-latex-and-related'."
6193 (org-set-local
6194 'org-latex-and-related-regexp
6195 (let* ((re-sub
6196 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6197 ((eq org-use-sub-superscripts '{})
6198 (list org-match-substring-with-braces-regexp))
6199 (org-use-sub-superscripts (list org-match-substring-regexp))))
6200 (re-latex
6201 (when (memq 'latex org-highlight-latex-and-related)
6202 (let ((matchers (plist-get org-format-latex-options :matchers)))
6203 (delq nil
6204 (mapcar (lambda (x)
6205 (and (member (car x) matchers) (nth 1 x)))
6206 org-latex-regexps)))))
6207 (re-entities
6208 (when (memq 'entities org-highlight-latex-and-related)
6209 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6210 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6212 (defun org-do-latex-and-related (limit)
6213 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6214 LIMIT bounds the search for syntax to highlight. Stop at first
6215 highlighted object, if any. Return t if some highlighting was
6216 done, nil otherwise."
6217 (when (org-string-nw-p org-latex-and-related-regexp)
6218 (catch 'found
6219 (while (re-search-forward org-latex-and-related-regexp limit t)
6220 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6221 'face))
6222 '(org-code org-verbatim underline))
6223 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6224 '(?_ ?^))
6226 0)))
6227 (font-lock-prepend-text-property
6228 (+ offset (match-beginning 0)) (match-end 0)
6229 'face 'org-latex-and-related)
6230 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6231 '(font-lock-multiline t)))
6232 (throw 'found t)))
6233 nil)))
6235 (defun org-restart-font-lock ()
6236 "Restart `font-lock-mode', to force refontification."
6237 (when (and (boundp 'font-lock-mode) font-lock-mode)
6238 (font-lock-mode -1)
6239 (font-lock-mode 1)))
6241 (defun org-activate-tags (limit)
6242 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6243 (progn
6244 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6245 (add-text-properties (match-beginning 1) (match-end 1)
6246 (list 'mouse-face 'highlight
6247 'keymap org-mouse-map))
6248 (org-rear-nonsticky-at (match-end 1))
6249 t)))
6251 (defun org-outline-level ()
6252 "Compute the outline level of the heading at point.
6253 If this is called at a normal headline, the level is the number of stars.
6254 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6255 (save-excursion
6256 (if (not (ignore-errors (org-back-to-heading t)))
6258 (looking-at org-outline-regexp)
6259 (1- (- (match-end 0) (match-beginning 0))))))
6261 (defvar org-font-lock-keywords nil)
6263 (defsubst org-re-property (property &optional literal allow-null)
6264 "Return a regexp matching a PROPERTY line.
6266 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6267 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6268 non-nil, match properties even without a value.
6270 Match group 3 is set to the value when it exists. If there is no
6271 value and ALLOW-NULL is non-nil, it is set to the empty string."
6272 (concat
6273 "^\\(?4:[ \t]*\\)"
6274 (format "\\(?1::\\(?2:%s\\):\\)"
6275 (if literal property (regexp-quote property)))
6276 (if allow-null
6277 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$"
6278 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$")))
6280 (defconst org-property-re
6281 (org-re-property ".*?" 'literal t)
6282 "Regular expression matching a property line.
6283 There are four matching groups:
6284 1: :PROPKEY: including the leading and trailing colon,
6285 2: PROPKEY without the leading and trailing colon,
6286 3: PROPVAL without leading or trailing spaces,
6287 4: the indentation of the current line,
6288 5: trailing whitespace.")
6290 (defvar org-font-lock-hook nil
6291 "Functions to be called for special font lock stuff.")
6293 (defvar org-font-lock-set-keywords-hook nil
6294 "Functions that can manipulate `org-font-lock-extra-keywords'.
6295 This is called after `org-font-lock-extra-keywords' is defined, but before
6296 it is installed to be used by font lock. This can be useful if something
6297 needs to be inserted at a specific position in the font-lock sequence.")
6299 (defun org-font-lock-hook (limit)
6300 "Run `org-font-lock-hook' within LIMIT."
6301 (run-hook-with-args 'org-font-lock-hook limit))
6303 (defun org-set-font-lock-defaults ()
6304 "Set font lock defaults for the current buffer."
6305 (let* ((em org-fontify-emphasized-text)
6306 (lk org-highlight-links)
6307 (org-font-lock-extra-keywords
6308 (list
6309 ;; Call the hook
6310 '(org-font-lock-hook)
6311 ;; Headlines
6312 `(,(if org-fontify-whole-heading-line
6313 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6314 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6315 (1 (org-get-level-face 1))
6316 (2 (org-get-level-face 2))
6317 (3 (org-get-level-face 3)))
6318 ;; Table lines
6319 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6320 (1 'org-table t))
6321 ;; Table internals
6322 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6323 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6324 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6325 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6326 ;; Drawers
6327 '(org-fontify-drawers)
6328 ;; Properties
6329 (list org-property-re
6330 '(1 'org-special-keyword t)
6331 '(3 'org-property-value t))
6332 ;; Links
6333 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6334 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6335 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6336 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6337 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6338 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6339 (if (memq 'footnote lk) '(org-activate-footnote-links))
6340 ;; Targets.
6341 (list org-any-target-regexp '(0 'org-target t))
6342 ;; Diary sexps.
6343 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6344 ;; Macro
6345 '(org-fontify-macros)
6346 '(org-hide-wide-columns (0 nil append))
6347 ;; TODO keyword
6348 (list (format org-heading-keyword-regexp-format
6349 org-todo-regexp)
6350 '(2 (org-get-todo-face 2) t))
6351 ;; DONE
6352 (if org-fontify-done-headline
6353 (list (format org-heading-keyword-regexp-format
6354 (concat
6355 "\\(?:"
6356 (mapconcat 'regexp-quote org-done-keywords "\\|")
6357 "\\)"))
6358 '(2 'org-headline-done t))
6359 nil)
6360 ;; Priorities
6361 '(org-font-lock-add-priority-faces)
6362 ;; Tags
6363 '(org-font-lock-add-tag-faces)
6364 ;; Tags groups
6365 (if (and org-group-tags org-tag-groups-alist)
6366 (list (concat org-outline-regexp-bol ".+\\(:"
6367 (regexp-opt (mapcar 'car org-tag-groups-alist))
6368 ":\\).*$")
6369 '(1 'org-tag-group prepend)))
6370 ;; Special keywords
6371 (list (concat "\\<" org-comment-string) '(0 'org-special-keyword t))
6372 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6373 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6374 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6375 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6376 ;; Emphasis
6377 (if em
6378 (if (featurep 'xemacs)
6379 '(org-do-emphasis-faces (0 nil append))
6380 '(org-do-emphasis-faces)))
6381 ;; Checkboxes
6382 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6383 1 'org-checkbox prepend)
6384 (if (cdr (assq 'checkbox org-list-automatic-rules))
6385 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6386 (0 (org-get-checkbox-statistics-face) t)))
6387 ;; Description list items
6388 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6389 1 'org-list-dt prepend)
6390 ;; ARCHIVEd headings
6391 (list (concat
6392 org-outline-regexp-bol
6393 "\\(.*:" org-archive-tag ":.*\\)")
6394 '(1 'org-archived prepend))
6395 ;; Specials
6396 '(org-do-latex-and-related)
6397 '(org-fontify-entities)
6398 '(org-raise-scripts)
6399 ;; Code
6400 '(org-activate-code (1 'org-code t))
6401 ;; COMMENT
6402 (list (format
6403 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6404 org-todo-regexp
6405 org-comment-string)
6406 '(9 'org-special-keyword t))
6407 ;; Blocks and meta lines
6408 '(org-fontify-meta-lines-and-blocks))))
6409 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6410 (run-hooks 'org-font-lock-set-keywords-hook)
6411 ;; Now set the full font-lock-keywords
6412 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6413 (org-set-local 'font-lock-defaults
6414 '(org-font-lock-keywords t nil nil backward-paragraph))
6415 (kill-local-variable 'font-lock-keywords) nil))
6417 (defun org-toggle-pretty-entities ()
6418 "Toggle the composition display of entities as UTF8 characters."
6419 (interactive)
6420 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6421 (org-restart-font-lock)
6422 (if org-pretty-entities
6423 (message "Entities are now displayed as UTF8 characters")
6424 (save-restriction
6425 (widen)
6426 (org-decompose-region (point-min) (point-max))
6427 (message "Entities are now displayed as plain text"))))
6429 (defvar org-custom-properties-overlays nil
6430 "List of overlays used for custom properties.")
6431 (make-variable-buffer-local 'org-custom-properties-overlays)
6433 (defun org-toggle-custom-properties-visibility ()
6434 "Display or hide properties in `org-custom-properties'."
6435 (interactive)
6436 (if org-custom-properties-overlays
6437 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6438 (setq org-custom-properties-overlays nil))
6439 (unless (not org-custom-properties)
6440 (save-excursion
6441 (save-restriction
6442 (widen)
6443 (goto-char (point-min))
6444 (while (re-search-forward org-property-re nil t)
6445 (mapc (lambda(p)
6446 (when (equal p (substring (match-string 1) 1 -1))
6447 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6448 (overlay-put o 'invisible t)
6449 (overlay-put o 'org-custom-property t)
6450 (push o org-custom-properties-overlays))))
6451 org-custom-properties)))))))
6453 (defun org-fontify-entities (limit)
6454 "Find an entity to fontify."
6455 (let (ee)
6456 (when org-pretty-entities
6457 (catch 'match
6458 (while (re-search-forward
6459 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6460 limit t)
6461 (if (and (not (org-at-comment-p))
6462 (setq ee (org-entity-get (match-string 1)))
6463 (= (length (nth 6 ee)) 1))
6464 (let*
6465 ((end (if (equal (match-string 2) "{}")
6466 (match-end 2)
6467 (match-end 1))))
6468 (add-text-properties
6469 (match-beginning 0) end
6470 (list 'font-lock-fontified t))
6471 (compose-region (match-beginning 0) end
6472 (nth 6 ee) nil)
6473 (backward-char 1)
6474 (throw 'match t))))
6475 nil))))
6477 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6478 "Fontify string S like in Org-mode."
6479 (with-temp-buffer
6480 (insert s)
6481 (let ((org-odd-levels-only odd-levels))
6482 (org-mode)
6483 (font-lock-ensure)
6484 (buffer-string))))
6486 (defvar org-m nil)
6487 (defvar org-l nil)
6488 (defvar org-f nil)
6489 (defun org-get-level-face (n)
6490 "Get the right face for match N in font-lock matching of headlines."
6491 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6492 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6493 (if org-cycle-level-faces
6494 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6495 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6496 (cond
6497 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6498 ((eq n 2) org-f)
6499 (t (if org-level-color-stars-only nil org-f))))
6502 (defun org-get-todo-face (kwd)
6503 "Get the right face for a TODO keyword KWD.
6504 If KWD is a number, get the corresponding match group."
6505 (if (numberp kwd) (setq kwd (match-string kwd)))
6506 (or (org-face-from-face-or-color
6507 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6508 (and (member kwd org-done-keywords) 'org-done)
6509 'org-todo))
6511 (defun org-face-from-face-or-color (context inherit face-or-color)
6512 "Create a face list that inherits INHERIT, but sets the foreground color.
6513 When FACE-OR-COLOR is not a string, just return it."
6514 (if (stringp face-or-color)
6515 (list :inherit inherit
6516 (cdr (assoc context org-faces-easy-properties))
6517 face-or-color)
6518 face-or-color))
6520 (defun org-font-lock-add-tag-faces (limit)
6521 "Add the special tag faces."
6522 (when (and org-tag-faces org-tags-special-faces-re)
6523 (while (re-search-forward org-tags-special-faces-re limit t)
6524 (add-text-properties (match-beginning 1) (match-end 1)
6525 (list 'face (org-get-tag-face 1)
6526 'font-lock-fontified t))
6527 (backward-char 1))))
6529 (defun org-font-lock-add-priority-faces (limit)
6530 "Add the special priority faces."
6531 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6532 (when (save-match-data (org-at-heading-p))
6533 (add-text-properties
6534 (match-beginning 0) (match-end 0)
6535 (list 'face (or (org-face-from-face-or-color
6536 'priority 'org-priority
6537 (cdr (assoc (char-after (match-beginning 1))
6538 org-priority-faces)))
6539 'org-priority)
6540 'font-lock-fontified t)))))
6542 (defun org-get-tag-face (kwd)
6543 "Get the right face for a TODO keyword KWD.
6544 If KWD is a number, get the corresponding match group."
6545 (if (numberp kwd) (setq kwd (match-string kwd)))
6546 (or (org-face-from-face-or-color
6547 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6548 'org-tag))
6550 (defun org-unfontify-region (beg end &optional maybe_loudly)
6551 "Remove fontification and activation overlays from links."
6552 (font-lock-default-unfontify-region beg end)
6553 (let* ((buffer-undo-list t)
6554 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6555 (inhibit-modification-hooks t)
6556 deactivate-mark buffer-file-name buffer-file-truename)
6557 (org-decompose-region beg end)
6558 (remove-text-properties beg end
6559 '(mouse-face t keymap t org-linked-text t
6560 invisible t intangible t
6561 org-emphasis t))
6562 (org-remove-font-lock-display-properties beg end)))
6564 (defconst org-script-display '(((raise -0.3) (height 0.7))
6565 ((raise 0.3) (height 0.7))
6566 ((raise -0.5))
6567 ((raise 0.5)))
6568 "Display properties for showing superscripts and subscripts.")
6570 (defun org-remove-font-lock-display-properties (beg end)
6571 "Remove specific display properties that have been added by font lock.
6572 The will remove the raise properties that are used to show superscripts
6573 and subscripts."
6574 (let (next prop)
6575 (while (< beg end)
6576 (setq next (next-single-property-change beg 'display nil end)
6577 prop (get-text-property beg 'display))
6578 (if (member prop org-script-display)
6579 (put-text-property beg next 'display nil))
6580 (setq beg next))))
6582 (defun org-raise-scripts (limit)
6583 "Add raise properties to sub/superscripts."
6584 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6585 (if (re-search-forward
6586 (if (eq org-use-sub-superscripts t)
6587 org-match-substring-regexp
6588 org-match-substring-with-braces-regexp)
6589 limit t)
6590 (let* ((pos (point)) table-p comment-p
6591 (mpos (match-beginning 3))
6592 (emph-p (get-text-property mpos 'org-emphasis))
6593 (link-p (get-text-property mpos 'mouse-face))
6594 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6595 (goto-char (point-at-bol))
6596 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6597 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6598 (goto-char pos)
6599 ;; Handle a_b^c
6600 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6601 (if (or comment-p emph-p link-p keyw-p)
6603 (put-text-property (match-beginning 3) (match-end 0)
6604 'display
6605 (if (equal (char-after (match-beginning 2)) ?^)
6606 (nth (if table-p 3 1) org-script-display)
6607 (nth (if table-p 2 0) org-script-display)))
6608 (add-text-properties (match-beginning 2) (match-end 2)
6609 (list 'invisible t
6610 'org-dwidth t 'org-dwidth-n 1))
6611 (if (and (eq (char-after (match-beginning 3)) ?{)
6612 (eq (char-before (match-end 3)) ?}))
6613 (progn
6614 (add-text-properties
6615 (match-beginning 3) (1+ (match-beginning 3))
6616 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6617 (add-text-properties
6618 (1- (match-end 3)) (match-end 3)
6619 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6620 t)))))
6622 ;;;; Visibility cycling, including org-goto and indirect buffer
6624 ;;; Cycling
6626 (defvar org-cycle-global-status nil)
6627 (make-variable-buffer-local 'org-cycle-global-status)
6628 (put 'org-cycle-global-status 'org-state t)
6629 (defvar org-cycle-subtree-status nil)
6630 (make-variable-buffer-local 'org-cycle-subtree-status)
6631 (put 'org-cycle-subtree-status 'org-state t)
6633 (defvar org-inlinetask-min-level)
6635 (defun org-unlogged-message (&rest args)
6636 "Display a message, but avoid logging it in the *Messages* buffer."
6637 (let ((message-log-max nil))
6638 (apply 'message args)))
6640 ;;;###autoload
6641 (defun org-cycle (&optional arg)
6642 "TAB-action and visibility cycling for Org-mode.
6644 This is the command invoked in Org-mode by the TAB key. Its main purpose
6645 is outline visibility cycling, but it also invokes other actions
6646 in special contexts.
6648 - When this function is called with a prefix argument, rotate the entire
6649 buffer through 3 states (global cycling)
6650 1. OVERVIEW: Show only top-level headlines.
6651 2. CONTENTS: Show all headlines of all levels, but no body text.
6652 3. SHOW ALL: Show everything.
6653 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6654 determined by the variable `org-startup-folded', and by any VISIBILITY
6655 properties in the buffer.
6656 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6657 including any drawers.
6659 - When inside a table, re-align the table and move to the next field.
6661 - When point is at the beginning of a headline, rotate the subtree started
6662 by this line through 3 different states (local cycling)
6663 1. FOLDED: Only the main headline is shown.
6664 2. CHILDREN: The main headline and the direct children are shown.
6665 From this state, you can move to one of the children
6666 and zoom in further.
6667 3. SUBTREE: Show the entire subtree, including body text.
6668 If there is no subtree, switch directly from CHILDREN to FOLDED.
6670 - When point is at the beginning of an empty headline and the variable
6671 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6672 of the headline by demoting and promoting it to likely levels. This
6673 speeds up creation document structure by pressing TAB once or several
6674 times right after creating a new headline.
6676 - When there is a numeric prefix, go up to a heading with level ARG, do
6677 a `show-subtree' and return to the previous cursor position. If ARG
6678 is negative, go up that many levels.
6680 - When point is not at the beginning of a headline, execute the global
6681 binding for TAB, which is re-indenting the line. See the option
6682 `org-cycle-emulate-tab' for details.
6684 - Special case: if point is at the beginning of the buffer and there is
6685 no headline in line 1, this function will act as if called with prefix arg
6686 (C-u TAB, same as S-TAB) also when called without prefix arg.
6687 But only if also the variable `org-cycle-global-at-bob' is t."
6688 (interactive "P")
6689 (org-load-modules-maybe)
6690 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6691 (and org-cycle-level-after-item/entry-creation
6692 (or (org-cycle-level)
6693 (org-cycle-item-indentation))))
6694 (let* ((limit-level
6695 (or org-cycle-max-level
6696 (and (boundp 'org-inlinetask-min-level)
6697 org-inlinetask-min-level
6698 (1- org-inlinetask-min-level))))
6699 (nstars (and limit-level
6700 (if org-odd-levels-only
6701 (and limit-level (1- (* limit-level 2)))
6702 limit-level)))
6703 (org-outline-regexp
6704 (if (not (derived-mode-p 'org-mode))
6705 outline-regexp
6706 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6707 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6708 (not (looking-at org-outline-regexp))))
6709 (org-cycle-hook
6710 (if bob-special
6711 (delq 'org-optimize-window-after-visibility-change
6712 (copy-sequence org-cycle-hook))
6713 org-cycle-hook))
6714 (pos (point)))
6716 (if (or bob-special (equal arg '(4)))
6717 ;; special case: use global cycling
6718 (setq arg t))
6720 (cond
6722 ((equal arg '(16))
6723 (setq last-command 'dummy)
6724 (org-set-startup-visibility)
6725 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6727 ((equal arg '(64))
6728 (show-all)
6729 (org-unlogged-message "Entire buffer visible, including drawers"))
6731 ;; Try cdlatex TAB completion
6732 ((org-try-cdlatex-tab))
6734 ;; Table: enter it or move to the next field.
6735 ((org-at-table-p 'any)
6736 (if (org-at-table.el-p)
6737 (message "Use C-c ' to edit table.el tables")
6738 (if arg (org-table-edit-field t)
6739 (org-table-justify-field-maybe)
6740 (call-interactively 'org-table-next-field))))
6742 ((run-hook-with-args-until-success
6743 'org-tab-after-check-for-table-hook))
6745 ;; Global cycling: delegate to `org-cycle-internal-global'.
6746 ((eq arg t) (org-cycle-internal-global))
6748 ;; Drawers: delegate to `org-flag-drawer'.
6749 ((save-excursion
6750 (beginning-of-line 1)
6751 (looking-at org-drawer-regexp))
6752 (org-flag-drawer ; toggle block visibility
6753 (not (get-char-property (match-end 0) 'invisible))))
6755 ;; Show-subtree, ARG levels up from here.
6756 ((integerp arg)
6757 (save-excursion
6758 (org-back-to-heading)
6759 (outline-up-heading (if (< arg 0) (- arg)
6760 (- (funcall outline-level) arg)))
6761 (org-show-subtree)))
6763 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6764 ((and (featurep 'org-inlinetask)
6765 (org-inlinetask-at-task-p)
6766 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6767 (org-inlinetask-toggle-visibility))
6769 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6770 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6771 (save-excursion (beginning-of-line 1)
6772 (looking-at org-outline-regexp)))
6773 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6774 (org-cycle-internal-local))
6776 ;; From there: TAB emulation and template completion.
6777 (buffer-read-only (org-back-to-heading))
6779 ((run-hook-with-args-until-success
6780 'org-tab-after-check-for-cycling-hook))
6782 ((org-try-structure-completion))
6784 ((run-hook-with-args-until-success
6785 'org-tab-before-tab-emulation-hook))
6787 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6788 (or (not (bolp))
6789 (not (looking-at org-outline-regexp))))
6790 (call-interactively (global-key-binding "\t")))
6792 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6793 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6794 (or (and (eq org-cycle-emulate-tab 'white)
6795 (= (match-end 0) (point-at-eol)))
6796 (and (eq org-cycle-emulate-tab 'whitestart)
6797 (>= (match-end 0) pos))))
6799 (eq org-cycle-emulate-tab t))
6800 (call-interactively (global-key-binding "\t")))
6802 (t (save-excursion
6803 (org-back-to-heading)
6804 (org-cycle)))))))
6806 (defun org-cycle-internal-global ()
6807 "Do the global cycling action."
6808 ;; Hack to avoid display of messages for .org attachments in Gnus
6809 (let ((ga (string-match "\\*fontification" (buffer-name))))
6810 (cond
6811 ((and (eq last-command this-command)
6812 (eq org-cycle-global-status 'overview))
6813 ;; We just created the overview - now do table of contents
6814 ;; This can be slow in very large buffers, so indicate action
6815 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6816 (unless ga (org-unlogged-message "CONTENTS..."))
6817 (org-content)
6818 (unless ga (org-unlogged-message "CONTENTS...done"))
6819 (setq org-cycle-global-status 'contents)
6820 (run-hook-with-args 'org-cycle-hook 'contents))
6822 ((and (eq last-command this-command)
6823 (eq org-cycle-global-status 'contents))
6824 ;; We just showed the table of contents - now show everything
6825 (run-hook-with-args 'org-pre-cycle-hook 'all)
6826 (show-all)
6827 (unless ga (org-unlogged-message "SHOW ALL"))
6828 (setq org-cycle-global-status 'all)
6829 (run-hook-with-args 'org-cycle-hook 'all))
6832 ;; Default action: go to overview
6833 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6834 (org-overview)
6835 (unless ga (org-unlogged-message "OVERVIEW"))
6836 (setq org-cycle-global-status 'overview)
6837 (run-hook-with-args 'org-cycle-hook 'overview)))))
6839 (defvar org-called-with-limited-levels nil
6840 "Non-nil when `org-with-limited-levels' is currently active.")
6842 (defun org-cycle-internal-local ()
6843 "Do the local cycling action."
6844 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6845 ;; First, determine end of headline (EOH), end of subtree or item
6846 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6847 (save-excursion
6848 (if (org-at-item-p)
6849 (progn
6850 (beginning-of-line)
6851 (setq struct (org-list-struct))
6852 (setq eoh (point-at-eol))
6853 (setq eos (org-list-get-item-end-before-blank (point) struct))
6854 (setq has-children (org-list-has-child-p (point) struct)))
6855 (org-back-to-heading)
6856 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6857 (setq eos (save-excursion (org-end-of-subtree t t)
6858 (when (bolp) (backward-char)) (point)))
6859 (setq has-children
6860 (or (save-excursion
6861 (let ((level (funcall outline-level)))
6862 (outline-next-heading)
6863 (and (org-at-heading-p t)
6864 (> (funcall outline-level) level))))
6865 (save-excursion
6866 (org-list-search-forward (org-item-beginning-re) eos t)))))
6867 ;; Determine end invisible part of buffer (EOL)
6868 (beginning-of-line 2)
6869 ;; XEmacs doesn't have `next-single-char-property-change'
6870 (if (featurep 'xemacs)
6871 (while (and (not (eobp)) ;; this is like `next-line'
6872 (get-char-property (1- (point)) 'invisible))
6873 (beginning-of-line 2))
6874 (while (and (not (eobp)) ;; this is like `next-line'
6875 (get-char-property (1- (point)) 'invisible))
6876 (goto-char (next-single-char-property-change (point) 'invisible))
6877 (and (eolp) (beginning-of-line 2))))
6878 (setq eol (point)))
6879 ;; Find out what to do next and set `this-command'
6880 (cond
6881 ((= eos eoh)
6882 ;; Nothing is hidden behind this heading
6883 (unless (org-before-first-heading-p)
6884 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6885 (org-unlogged-message "EMPTY ENTRY")
6886 (setq org-cycle-subtree-status nil)
6887 (save-excursion
6888 (goto-char eos)
6889 (outline-next-heading)
6890 (if (outline-invisible-p) (org-flag-heading nil))))
6891 ((and (or (>= eol eos)
6892 (not (string-match "\\S-" (buffer-substring eol eos))))
6893 (or has-children
6894 (not (setq children-skipped
6895 org-cycle-skip-children-state-if-no-children))))
6896 ;; Entire subtree is hidden in one line: children view
6897 (unless (org-before-first-heading-p)
6898 (run-hook-with-args 'org-pre-cycle-hook 'children))
6899 (if (org-at-item-p)
6900 (org-list-set-item-visibility (point-at-bol) struct 'children)
6901 (org-show-entry)
6902 (org-with-limited-levels (show-children))
6903 ;; FIXME: This slows down the func way too much.
6904 ;; How keep drawers hidden in subtree anyway?
6905 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6906 ;; (org-cycle-hide-drawers 'subtree))
6908 ;; Fold every list in subtree to top-level items.
6909 (when (eq org-cycle-include-plain-lists 'integrate)
6910 (save-excursion
6911 (org-back-to-heading)
6912 (while (org-list-search-forward (org-item-beginning-re) eos t)
6913 (beginning-of-line 1)
6914 (let* ((struct (org-list-struct))
6915 (prevs (org-list-prevs-alist struct))
6916 (end (org-list-get-bottom-point struct)))
6917 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6918 (org-list-get-all-items (point) struct prevs))
6919 (goto-char (if (< end eos) end eos)))))))
6920 (org-unlogged-message "CHILDREN")
6921 (save-excursion
6922 (goto-char eos)
6923 (outline-next-heading)
6924 (if (outline-invisible-p) (org-flag-heading nil)))
6925 (setq org-cycle-subtree-status 'children)
6926 (unless (org-before-first-heading-p)
6927 (run-hook-with-args 'org-cycle-hook 'children)))
6928 ((or children-skipped
6929 (and (eq last-command this-command)
6930 (eq org-cycle-subtree-status 'children)))
6931 ;; We just showed the children, or no children are there,
6932 ;; now show everything.
6933 (unless (org-before-first-heading-p)
6934 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6935 (outline-flag-region eoh eos nil)
6936 (org-unlogged-message
6937 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6938 (setq org-cycle-subtree-status 'subtree)
6939 (unless (org-before-first-heading-p)
6940 (run-hook-with-args 'org-cycle-hook 'subtree)))
6942 ;; Default action: hide the subtree.
6943 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6944 (outline-flag-region eoh eos t)
6945 (org-unlogged-message "FOLDED")
6946 (setq org-cycle-subtree-status 'folded)
6947 (unless (org-before-first-heading-p)
6948 (run-hook-with-args 'org-cycle-hook 'folded))))))
6950 ;;;###autoload
6951 (defun org-global-cycle (&optional arg)
6952 "Cycle the global visibility. For details see `org-cycle'.
6953 With \\[universal-argument] prefix arg, switch to startup visibility.
6954 With a numeric prefix, show all headlines up to that level."
6955 (interactive "P")
6956 (let ((org-cycle-include-plain-lists
6957 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6958 (cond
6959 ((integerp arg)
6960 (show-all)
6961 (hide-sublevels arg)
6962 (setq org-cycle-global-status 'contents))
6963 ((equal arg '(4))
6964 (org-set-startup-visibility)
6965 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6967 (org-cycle '(4))))))
6969 (defun org-set-startup-visibility ()
6970 "Set the visibility required by startup options and properties."
6971 (cond
6972 ((eq org-startup-folded t)
6973 (org-overview))
6974 ((eq org-startup-folded 'content)
6975 (org-content))
6976 ((or (eq org-startup-folded 'showeverything)
6977 (eq org-startup-folded nil))
6978 (show-all)))
6979 (unless (eq org-startup-folded 'showeverything)
6980 (if org-hide-block-startup (org-hide-block-all))
6981 (org-set-visibility-according-to-property 'no-cleanup)
6982 (org-cycle-hide-archived-subtrees 'all)
6983 (org-cycle-hide-drawers 'all)
6984 (org-cycle-show-empty-lines t)))
6986 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6987 "Switch subtree visibilities according to :VISIBILITY: property."
6988 (interactive)
6989 (let (org-show-entry-below state)
6990 (save-excursion
6991 (goto-char (point-min))
6992 (while (re-search-forward
6993 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6994 nil t)
6995 (setq state (match-string 1))
6996 (save-excursion
6997 (org-back-to-heading t)
6998 (hide-subtree)
6999 (org-reveal)
7000 (cond
7001 ((equal state '("fold" "folded"))
7002 (hide-subtree))
7003 ((equal state "children")
7004 (org-show-hidden-entry)
7005 (show-children))
7006 ((equal state "content")
7007 (save-excursion
7008 (save-restriction
7009 (org-narrow-to-subtree)
7010 (org-content))))
7011 ((member state '("all" "showall"))
7012 (show-subtree)))))
7013 (unless no-cleanup
7014 (org-cycle-hide-archived-subtrees 'all)
7015 (org-cycle-hide-drawers 'all)
7016 (org-cycle-show-empty-lines 'all)))))
7018 ;; This function uses outline-regexp instead of the more fundamental
7019 ;; org-outline-regexp so that org-cycle-global works outside of Org
7020 ;; buffers, where outline-regexp is needed.
7021 (defun org-overview ()
7022 "Switch to overview mode, showing only top-level headlines.
7023 This shows all headlines with a level equal or greater than the level
7024 of the first headline in the buffer. This is important, because if the
7025 first headline is not level one, then (hide-sublevels 1) gives confusing
7026 results."
7027 (interactive)
7028 (save-excursion
7029 (let ((level
7030 (save-excursion
7031 (goto-char (point-min))
7032 (if (re-search-forward (concat "^" outline-regexp) nil t)
7033 (progn
7034 (goto-char (match-beginning 0))
7035 (funcall outline-level))))))
7036 (and level (hide-sublevels level)))))
7038 (defun org-content (&optional arg)
7039 "Show all headlines in the buffer, like a table of contents.
7040 With numerical argument N, show content up to level N."
7041 (interactive "P")
7042 (org-overview)
7043 (save-excursion
7044 ;; Visit all headings and show their offspring
7045 (and (integerp arg) (org-overview))
7046 (goto-char (point-max))
7047 (catch 'exit
7048 (while (and (progn (condition-case nil
7049 (outline-previous-visible-heading 1)
7050 (error (goto-char (point-min))))
7052 (looking-at org-outline-regexp))
7053 (if (integerp arg)
7054 (show-children (1- arg))
7055 (show-branches))
7056 (if (bobp) (throw 'exit nil))))))
7058 (defun org-optimize-window-after-visibility-change (state)
7059 "Adjust the window after a change in outline visibility.
7060 This function is the default value of the hook `org-cycle-hook'."
7061 (when (get-buffer-window (current-buffer))
7062 (cond
7063 ((eq state 'content) nil)
7064 ((eq state 'all) nil)
7065 ((eq state 'folded) nil)
7066 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7067 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7069 (defun org-remove-empty-overlays-at (pos)
7070 "Remove outline overlays that do not contain non-white stuff."
7071 (mapc
7072 (lambda (o)
7073 (and (eq 'outline (overlay-get o 'invisible))
7074 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7075 (overlay-end o))))
7076 (delete-overlay o)))
7077 (overlays-at pos)))
7079 (defun org-clean-visibility-after-subtree-move ()
7080 "Fix visibility issues after moving a subtree."
7081 ;; First, find a reasonable region to look at:
7082 ;; Start two siblings above, end three below
7083 (let* ((beg (save-excursion
7084 (and (org-get-last-sibling)
7085 (org-get-last-sibling))
7086 (point)))
7087 (end (save-excursion
7088 (and (org-get-next-sibling)
7089 (org-get-next-sibling)
7090 (org-get-next-sibling))
7091 (if (org-at-heading-p)
7092 (point-at-eol)
7093 (point))))
7094 (level (looking-at "\\*+"))
7095 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7096 (save-excursion
7097 (save-restriction
7098 (narrow-to-region beg end)
7099 (when re
7100 ;; Properly fold already folded siblings
7101 (goto-char (point-min))
7102 (while (re-search-forward re nil t)
7103 (if (and (not (outline-invisible-p))
7104 (save-excursion
7105 (goto-char (point-at-eol)) (outline-invisible-p)))
7106 (hide-entry))))
7107 (org-cycle-show-empty-lines 'overview)
7108 (org-cycle-hide-drawers 'overview)))))
7110 (defun org-cycle-show-empty-lines (state)
7111 "Show empty lines above all visible headlines.
7112 The region to be covered depends on STATE when called through
7113 `org-cycle-hook'. Lisp program can use t for STATE to get the
7114 entire buffer covered. Note that an empty line is only shown if there
7115 are at least `org-cycle-separator-lines' empty lines before the headline."
7116 (when (not (= org-cycle-separator-lines 0))
7117 (save-excursion
7118 (let* ((n (abs org-cycle-separator-lines))
7119 (re (cond
7120 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7121 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7122 (t (let ((ns (number-to-string (- n 2))))
7123 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7124 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7125 beg end b e)
7126 (cond
7127 ((memq state '(overview contents t))
7128 (setq beg (point-min) end (point-max)))
7129 ((memq state '(children folded))
7130 (setq beg (point) end (progn (org-end-of-subtree t t)
7131 (beginning-of-line 2)
7132 (point)))))
7133 (when beg
7134 (goto-char beg)
7135 (while (re-search-forward re end t)
7136 (unless (get-char-property (match-end 1) 'invisible)
7137 (setq e (match-end 1))
7138 (if (< org-cycle-separator-lines 0)
7139 (setq b (save-excursion
7140 (goto-char (match-beginning 0))
7141 (org-back-over-empty-lines)
7142 (if (save-excursion
7143 (goto-char (max (point-min) (1- (point))))
7144 (org-at-heading-p))
7145 (1- (point))
7146 (point))))
7147 (setq b (match-beginning 1)))
7148 (outline-flag-region b e nil)))))))
7149 ;; Never hide empty lines at the end of the file.
7150 (save-excursion
7151 (goto-char (point-max))
7152 (outline-previous-heading)
7153 (outline-end-of-heading)
7154 (if (and (looking-at "[ \t\n]+")
7155 (= (match-end 0) (point-max)))
7156 (outline-flag-region (point) (match-end 0) nil))))
7158 (defun org-show-empty-lines-in-parent ()
7159 "Move to the parent and re-show empty lines before visible headlines."
7160 (save-excursion
7161 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7162 (org-cycle-show-empty-lines context))))
7164 (defun org-files-list ()
7165 "Return `org-agenda-files' list, plus all open org-mode files.
7166 This is useful for operations that need to scan all of a user's
7167 open and agenda-wise Org files."
7168 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7169 (dolist (buf (buffer-list))
7170 (with-current-buffer buf
7171 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7172 (let ((file (expand-file-name (buffer-file-name))))
7173 (unless (member file files)
7174 (push file files))))))
7175 files))
7177 (defsubst org-entry-beginning-position ()
7178 "Return the beginning position of the current entry."
7179 (save-excursion (outline-back-to-heading t) (point)))
7181 (defsubst org-entry-end-position ()
7182 "Return the end position of the current entry."
7183 (save-excursion (outline-next-heading) (point)))
7185 (defun org-cycle-hide-drawers (state &optional exceptions)
7186 "Re-hide all drawers after a visibility state change.
7187 When non-nil, optional argument EXCEPTIONS is a list of strings
7188 specifying which drawers should not be hidden."
7189 (when (and (derived-mode-p 'org-mode)
7190 (not (memq state '(overview folded contents))))
7191 (save-excursion
7192 (let* ((globalp (memq state '(contents all)))
7193 (beg (if globalp (point-min) (point)))
7194 (end (if globalp (point-max)
7195 (if (eq state 'children)
7196 (save-excursion (outline-next-heading) (point))
7197 (org-end-of-subtree t)))))
7198 (goto-char beg)
7199 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7200 (unless (member-ignore-case (match-string 1) exceptions)
7201 (let ((drawer (org-element-at-point)))
7202 (when (memq (org-element-type drawer) '(drawer property-drawer))
7203 (org-flag-drawer t drawer)
7204 ;; Make sure to skip drawer entirely or we might flag
7205 ;; it another time when matching its ending line with
7206 ;; `org-drawer-regexp'.
7207 (goto-char (org-element-property :end drawer))))))))))
7209 (defun org-cycle-hide-inline-tasks (state)
7210 "Re-hide inline tasks when switching to 'contents or 'children
7211 visibility state."
7212 (case state
7213 (contents
7214 (when (org-bound-and-true-p org-inlinetask-min-level)
7215 (hide-sublevels (1- org-inlinetask-min-level))))
7216 (children
7217 (when (featurep 'org-inlinetask)
7218 (save-excursion
7219 (while (and (outline-next-heading)
7220 (org-inlinetask-at-task-p))
7221 (org-inlinetask-toggle-visibility)
7222 (org-inlinetask-goto-end)))))))
7224 (defun org-flag-drawer (flag &optional element)
7225 "When FLAG is non-nil, hide the drawer we are at.
7226 Otherwise make it visible. When optional argument ELEMENT is
7227 a parsed drawer, as returned by `org-element-at-point', hide or
7228 show that drawer instead."
7229 (when (save-excursion
7230 (beginning-of-line)
7231 (org-looking-at-p org-drawer-regexp))
7232 (let ((drawer (or element (org-element-at-point))))
7233 (when (memq (org-element-type drawer) '(drawer property-drawer))
7234 (let ((post (org-element-property :post-affiliated drawer)))
7235 (save-excursion
7236 (outline-flag-region
7237 (progn (goto-char post) (line-end-position))
7238 (progn (goto-char (org-element-property :end drawer))
7239 (skip-chars-backward " \r\t\n")
7240 (line-end-position))
7241 flag))
7242 ;; When the drawer is hidden away, make sure point lies in
7243 ;; a visible part of the buffer.
7244 (when (and flag (> (line-beginning-position) post))
7245 (goto-char post)))))))
7247 (defun org-subtree-end-visible-p ()
7248 "Is the end of the current subtree visible?"
7249 (pos-visible-in-window-p
7250 (save-excursion (org-end-of-subtree t) (point))))
7252 (defun org-first-headline-recenter ()
7253 "Move cursor to the first headline and recenter the headline."
7254 (goto-char (point-min))
7255 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7256 (set-window-start (selected-window) (point-at-bol))))
7258 ;;; Saving and restoring visibility
7260 (defun org-outline-overlay-data (&optional use-markers)
7261 "Return a list of the locations of all outline overlays.
7262 These are overlays with the `invisible' property value `outline'.
7263 The return value is a list of cons cells, with start and stop
7264 positions for each overlay.
7265 If USE-MARKERS is set, return the positions as markers."
7266 (let (beg end)
7267 (save-excursion
7268 (save-restriction
7269 (widen)
7270 (delq nil
7271 (mapcar (lambda (o)
7272 (when (eq (overlay-get o 'invisible) 'outline)
7273 (setq beg (overlay-start o)
7274 end (overlay-end o))
7275 (and beg end (> end beg)
7276 (if use-markers
7277 (cons (copy-marker beg)
7278 (copy-marker end t))
7279 (cons beg end)))))
7280 (overlays-in (point-min) (point-max))))))))
7282 (defun org-set-outline-overlay-data (data)
7283 "Create visibility overlays for all positions in DATA.
7284 DATA should have been made by `org-outline-overlay-data'."
7285 (let (o)
7286 (save-excursion
7287 (save-restriction
7288 (widen)
7289 (show-all)
7290 (mapc (lambda (c)
7291 (outline-flag-region (car c) (cdr c) t))
7292 data)))))
7294 ;;; Folding of blocks
7296 (defvar org-hide-block-overlays nil
7297 "Overlays hiding blocks.")
7298 (make-variable-buffer-local 'org-hide-block-overlays)
7300 (defun org-block-map (function &optional start end)
7301 "Call FUNCTION at the head of all source blocks in the current buffer.
7302 Optional arguments START and END can be used to limit the range."
7303 (let ((start (or start (point-min)))
7304 (end (or end (point-max))))
7305 (save-excursion
7306 (goto-char start)
7307 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7308 (save-excursion
7309 (save-match-data
7310 (goto-char (match-beginning 0))
7311 (funcall function)))))))
7313 (defun org-hide-block-toggle-all ()
7314 "Toggle the visibility of all blocks in the current buffer."
7315 (org-block-map 'org-hide-block-toggle))
7317 (defun org-hide-block-all ()
7318 "Fold all blocks in the current buffer."
7319 (interactive)
7320 (org-show-block-all)
7321 (org-block-map 'org-hide-block-toggle-maybe))
7323 (defun org-show-block-all ()
7324 "Unfold all blocks in the current buffer."
7325 (interactive)
7326 (mapc 'delete-overlay org-hide-block-overlays)
7327 (setq org-hide-block-overlays nil))
7329 (defun org-hide-block-toggle-maybe ()
7330 "Toggle visibility of block at point.
7331 Unlike to `org-hide-block-toggle', this function does not throw
7332 an error. Return a non-nil value when toggling is successful."
7333 (interactive)
7334 (ignore-errors (org-hide-block-toggle)))
7336 (defun org-hide-block-toggle (&optional force)
7337 "Toggle the visibility of the current block.
7338 When optional argument FORCE is `off', make block visible. If it
7339 is non-nil, hide it unconditionally. Throw an error when not at
7340 a block. Return a non-nil value when toggling is successful."
7341 (interactive)
7342 (let ((element (org-element-at-point)))
7343 (unless (memq (org-element-type element)
7344 '(center-block comment-block dynamic-block example-block
7345 export-block quote-block special-block
7346 src-block verse-block))
7347 (user-error "Not at a block"))
7348 (let* ((start (save-excursion
7349 (goto-char (org-element-property :post-affiliated element))
7350 (line-end-position)))
7351 (end (save-excursion
7352 (goto-char (org-element-property :end element))
7353 (skip-chars-backward " \r\t\n")
7354 (line-end-position)))
7355 (overlays (overlays-at start)))
7356 (cond
7357 ;; Do nothing when not before or at the block opening line or
7358 ;; at the block closing line.
7359 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7360 ((and (not (eq force 'off))
7361 (not (memq t (mapcar
7362 (lambda (o)
7363 (eq (overlay-get o 'invisible) 'org-hide-block))
7364 overlays))))
7365 (let ((ov (make-overlay start end)))
7366 (overlay-put ov 'invisible 'org-hide-block)
7367 ;; Make the block accessible to `isearch'.
7368 (overlay-put
7369 ov 'isearch-open-invisible
7370 (lambda (ov)
7371 (when (memq ov org-hide-block-overlays)
7372 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7373 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7374 (delete-overlay ov))))
7375 (push ov org-hide-block-overlays)
7376 ;; When the block is hidden away, make sure point is left in
7377 ;; a visible part of the buffer.
7378 (when (> (line-beginning-position) start)
7379 (goto-char start)
7380 (beginning-of-line))
7381 ;; Signal successful toggling.
7383 ((or (not force) (eq force 'off))
7384 (dolist (ov overlays t)
7385 (when (memq ov org-hide-block-overlays)
7386 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7387 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7388 (delete-overlay ov))))))))
7390 ;; org-tab-after-check-for-cycling-hook
7391 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7392 ;; Remove overlays when changing major mode
7393 (add-hook 'org-mode-hook
7394 (lambda () (org-add-hook 'change-major-mode-hook
7395 'org-show-block-all 'append 'local)))
7397 ;;; Org-goto
7399 (defvar org-goto-window-configuration nil)
7400 (defvar org-goto-marker nil)
7401 (defvar org-goto-map)
7402 (defun org-goto-map ()
7403 "Set the keymap `org-goto'."
7404 (setq org-goto-map
7405 (let ((map (make-sparse-keymap)))
7406 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7407 mouse-drag-region universal-argument org-occur))
7408 cmd)
7409 (while (setq cmd (pop cmds))
7410 (substitute-key-definition cmd cmd map global-map)))
7411 (suppress-keymap map)
7412 (org-defkey map "\C-m" 'org-goto-ret)
7413 (org-defkey map [(return)] 'org-goto-ret)
7414 (org-defkey map [(left)] 'org-goto-left)
7415 (org-defkey map [(right)] 'org-goto-right)
7416 (org-defkey map [(control ?g)] 'org-goto-quit)
7417 (org-defkey map "\C-i" 'org-cycle)
7418 (org-defkey map [(tab)] 'org-cycle)
7419 (org-defkey map [(down)] 'outline-next-visible-heading)
7420 (org-defkey map [(up)] 'outline-previous-visible-heading)
7421 (if org-goto-auto-isearch
7422 (if (fboundp 'define-key-after)
7423 (define-key-after map [t] 'org-goto-local-auto-isearch)
7424 nil)
7425 (org-defkey map "q" 'org-goto-quit)
7426 (org-defkey map "n" 'outline-next-visible-heading)
7427 (org-defkey map "p" 'outline-previous-visible-heading)
7428 (org-defkey map "f" 'outline-forward-same-level)
7429 (org-defkey map "b" 'outline-backward-same-level)
7430 (org-defkey map "u" 'outline-up-heading))
7431 (org-defkey map "/" 'org-occur)
7432 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7433 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7434 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7435 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7436 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7437 map)))
7439 (defconst org-goto-help
7440 "Browse buffer copy, to find location or copy text.%s
7441 RET=jump to location C-g=quit and return to previous location
7442 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7444 (defvar org-goto-start-pos) ; dynamically scoped parameter
7446 (defun org-goto (&optional alternative-interface)
7447 "Look up a different location in the current file, keeping current visibility.
7449 When you want look-up or go to a different location in a
7450 document, the fastest way is often to fold the entire buffer and
7451 then dive into the tree. This method has the disadvantage, that
7452 the previous location will be folded, which may not be what you
7453 want.
7455 This command works around this by showing a copy of the current
7456 buffer in an indirect buffer, in overview mode. You can dive
7457 into the tree in that copy, use org-occur and incremental search
7458 to find a location. When pressing RET or `Q', the command
7459 returns to the original buffer in which the visibility is still
7460 unchanged. After RET it will also jump to the location selected
7461 in the indirect buffer and expose the headline hierarchy above.
7463 With a prefix argument, use the alternative interface: e.g. if
7464 `org-goto-interface' is 'outline use 'outline-path-completion."
7465 (interactive "P")
7466 (org-goto-map)
7467 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7468 (org-refile-use-outline-path t)
7469 (org-refile-target-verify-function nil)
7470 (interface
7471 (if (not alternative-interface)
7472 org-goto-interface
7473 (if (eq org-goto-interface 'outline)
7474 'outline-path-completion
7475 'outline)))
7476 (org-goto-start-pos (point))
7477 (selected-point
7478 (if (eq interface 'outline)
7479 (car (org-get-location (current-buffer) org-goto-help))
7480 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7481 (org-refile-check-position pa)
7482 (nth 3 pa)))))
7483 (if selected-point
7484 (progn
7485 (org-mark-ring-push org-goto-start-pos)
7486 (goto-char selected-point)
7487 (if (or (outline-invisible-p) (org-invisible-p2))
7488 (org-show-context 'org-goto)))
7489 (message "Quit"))))
7491 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7492 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7493 (defvar org-goto-local-auto-isearch-map) ; defined below
7495 (defun org-get-location (buf help)
7496 "Let the user select a location in the Org-mode buffer BUF.
7497 This function uses a recursive edit. It returns the selected position
7498 or nil."
7499 (org-no-popups
7500 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7501 (isearch-hide-immediately nil)
7502 (isearch-search-fun-function
7503 (lambda () 'org-goto-local-search-headings))
7504 (org-goto-selected-point org-goto-exit-command))
7505 (save-excursion
7506 (save-window-excursion
7507 (delete-other-windows)
7508 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7509 (org-pop-to-buffer-same-window
7510 (condition-case nil
7511 (make-indirect-buffer (current-buffer) "*org-goto*")
7512 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7513 (with-output-to-temp-buffer "*Org Help*"
7514 (princ (format help (if org-goto-auto-isearch
7515 " Just type for auto-isearch."
7516 " n/p/f/b/u to navigate, q to quit."))))
7517 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7518 (setq buffer-read-only nil)
7519 (let ((org-startup-truncated t)
7520 (org-startup-folded nil)
7521 (org-startup-align-all-tables nil))
7522 (org-mode)
7523 (org-overview))
7524 (setq buffer-read-only t)
7525 (if (and (boundp 'org-goto-start-pos)
7526 (integer-or-marker-p org-goto-start-pos))
7527 (let ((org-show-hierarchy-above t)
7528 (org-show-siblings t)
7529 (org-show-following-heading t))
7530 (goto-char org-goto-start-pos)
7531 (and (outline-invisible-p) (org-show-context)))
7532 (goto-char (point-min)))
7533 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7534 (message "Select location and press RET")
7535 (use-local-map org-goto-map)
7536 (recursive-edit)))
7537 (kill-buffer "*org-goto*")
7538 (cons org-goto-selected-point org-goto-exit-command))))
7540 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7541 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7542 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7543 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7545 (defun org-goto-local-search-headings (string bound noerror)
7546 "Search and make sure that any matches are in headlines."
7547 (catch 'return
7548 (while (if isearch-forward
7549 (search-forward string bound noerror)
7550 (search-backward string bound noerror))
7551 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7552 (and (member :headline context)
7553 (not (member :tags context))))
7554 (throw 'return (point))))))
7556 (defun org-goto-local-auto-isearch ()
7557 "Start isearch."
7558 (interactive)
7559 (goto-char (point-min))
7560 (let ((keys (this-command-keys)))
7561 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7562 (isearch-mode t)
7563 (isearch-process-search-char (string-to-char keys)))))
7565 (defun org-goto-ret (&optional arg)
7566 "Finish `org-goto' by going to the new location."
7567 (interactive "P")
7568 (setq org-goto-selected-point (point)
7569 org-goto-exit-command 'return)
7570 (throw 'exit nil))
7572 (defun org-goto-left ()
7573 "Finish `org-goto' by going to the new location."
7574 (interactive)
7575 (if (org-at-heading-p)
7576 (progn
7577 (beginning-of-line 1)
7578 (setq org-goto-selected-point (point)
7579 org-goto-exit-command 'left)
7580 (throw 'exit nil))
7581 (user-error "Not on a heading")))
7583 (defun org-goto-right ()
7584 "Finish `org-goto' by going to the new location."
7585 (interactive)
7586 (if (org-at-heading-p)
7587 (progn
7588 (setq org-goto-selected-point (point)
7589 org-goto-exit-command 'right)
7590 (throw 'exit nil))
7591 (user-error "Not on a heading")))
7593 (defun org-goto-quit ()
7594 "Finish `org-goto' without cursor motion."
7595 (interactive)
7596 (setq org-goto-selected-point nil)
7597 (setq org-goto-exit-command 'quit)
7598 (throw 'exit nil))
7600 ;;; Indirect buffer display of subtrees
7602 (defvar org-indirect-dedicated-frame nil
7603 "This is the frame being used for indirect tree display.")
7604 (defvar org-last-indirect-buffer nil)
7606 (defun org-tree-to-indirect-buffer (&optional arg)
7607 "Create indirect buffer and narrow it to current subtree.
7608 With a numerical prefix ARG, go up to this level and then take that tree.
7609 If ARG is negative, go up that many levels.
7611 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7612 indirect buffer previously made with this command, to avoid proliferation of
7613 indirect buffers. However, when you call the command with a \
7614 \\[universal-argument] prefix, or
7615 when `org-indirect-buffer-display' is `new-frame', the last buffer
7616 is kept so that you can work with several indirect buffers at the same time.
7617 If `org-indirect-buffer-display' is `dedicated-frame', the \
7618 \\[universal-argument] prefix also
7619 requests that a new frame be made for the new buffer, so that the dedicated
7620 frame is not changed."
7621 (interactive "P")
7622 (let ((cbuf (current-buffer))
7623 (cwin (selected-window))
7624 (pos (point))
7625 beg end level heading ibuf)
7626 (save-excursion
7627 (org-back-to-heading t)
7628 (when (numberp arg)
7629 (setq level (org-outline-level))
7630 (if (< arg 0) (setq arg (+ level arg)))
7631 (while (> (setq level (org-outline-level)) arg)
7632 (org-up-heading-safe)))
7633 (setq beg (point)
7634 heading (org-get-heading))
7635 (org-end-of-subtree t t)
7636 (if (org-at-heading-p) (backward-char 1))
7637 (setq end (point)))
7638 (if (and (buffer-live-p org-last-indirect-buffer)
7639 (not (eq org-indirect-buffer-display 'new-frame))
7640 (not arg))
7641 (kill-buffer org-last-indirect-buffer))
7642 (setq ibuf (org-get-indirect-buffer cbuf heading)
7643 org-last-indirect-buffer ibuf)
7644 (cond
7645 ((or (eq org-indirect-buffer-display 'new-frame)
7646 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7647 (select-frame (make-frame))
7648 (delete-other-windows)
7649 (org-pop-to-buffer-same-window ibuf)
7650 (org-set-frame-title heading))
7651 ((eq org-indirect-buffer-display 'dedicated-frame)
7652 (raise-frame
7653 (select-frame (or (and org-indirect-dedicated-frame
7654 (frame-live-p org-indirect-dedicated-frame)
7655 org-indirect-dedicated-frame)
7656 (setq org-indirect-dedicated-frame (make-frame)))))
7657 (delete-other-windows)
7658 (org-pop-to-buffer-same-window ibuf)
7659 (org-set-frame-title (concat "Indirect: " heading)))
7660 ((eq org-indirect-buffer-display 'current-window)
7661 (org-pop-to-buffer-same-window ibuf))
7662 ((eq org-indirect-buffer-display 'other-window)
7663 (pop-to-buffer ibuf))
7664 (t (error "Invalid value")))
7665 (if (featurep 'xemacs)
7666 (save-excursion (org-mode) (turn-on-font-lock)))
7667 (narrow-to-region beg end)
7668 (show-all)
7669 (goto-char pos)
7670 (run-hook-with-args 'org-cycle-hook 'all)
7671 (and (window-live-p cwin) (select-window cwin))))
7673 (defun org-get-indirect-buffer (&optional buffer heading)
7674 (setq buffer (or buffer (current-buffer)))
7675 (let ((n 1) (base (buffer-name buffer)) bname)
7676 (while (buffer-live-p
7677 (get-buffer
7678 (setq bname
7679 (concat base "-"
7680 (if heading (concat heading "-" (number-to-string n))
7681 (number-to-string n))))))
7682 (setq n (1+ n)))
7683 (condition-case nil
7684 (make-indirect-buffer buffer bname 'clone)
7685 (error (make-indirect-buffer buffer bname)))))
7687 (defun org-set-frame-title (title)
7688 "Set the title of the current frame to the string TITLE."
7689 ;; FIXME: how to name a single frame in XEmacs???
7690 (unless (featurep 'xemacs)
7691 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7693 ;;;; Structure editing
7695 ;;; Inserting headlines
7697 (defun org-previous-line-empty-p (&optional next)
7698 "Is the previous line a blank line?
7699 When NEXT is non-nil, check the next line instead."
7700 (save-excursion
7701 (and (not (bobp))
7702 (or (beginning-of-line (if next 2 0)) t)
7703 (save-match-data
7704 (looking-at "[ \t]*$")))))
7706 (defun org-insert-heading (&optional arg invisible-ok)
7707 "Insert a new heading or an item with the same depth at point.
7709 If point is at the beginning of a heading or a list item, insert
7710 a new heading or a new item above the current one. If point is
7711 at the beginning of a normal line, turn the line into a heading.
7713 If point is in the middle of a headline or a list item, split the
7714 headline or the item and create a new headline/item with the text
7715 in the current line after point \(see `org-M-RET-may-split-line'
7716 on how to modify this behavior).
7718 With one universal prefix argument, set the user option
7719 `org-insert-heading-respect-content' to t for the duration of
7720 the command. This modifies the behavior described above in this
7721 ways: on list items and at the beginning of normal lines, force
7722 the insertion of a heading after the current subtree.
7724 With two universal prefix arguments, insert the heading at the
7725 end of the grandparent subtree. For example, if point is within
7726 a 2nd-level heading, then it will insert a 2nd-level heading at
7727 the end of the 1st-level parent heading.
7729 If point is at the beginning of a headline, insert a sibling
7730 before the current headline. If point is not at the beginning,
7731 split the line and create a new headline with the text in the
7732 current line after point \(see `org-M-RET-may-split-line' on how
7733 to modify this behavior).
7735 If point is at the beginning of a normal line, turn this line
7736 into a heading.
7738 When INVISIBLE-OK is set, stop at invisible headlines when going
7739 back. This is important for non-interactive uses of the
7740 command."
7741 (interactive "P")
7742 (if (org-called-interactively-p 'any) (org-reveal))
7743 (let ((itemp (org-in-item-p))
7744 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7745 (respect-content (or org-insert-heading-respect-content
7746 (equal arg '(4))))
7747 (initial-content "")
7748 (adjust-empty-lines t))
7750 (cond
7752 ((or (= (buffer-size) 0)
7753 (and (not (save-excursion
7754 (and (ignore-errors (org-back-to-heading invisible-ok))
7755 (org-at-heading-p))))
7756 (or arg (not itemp))))
7757 ;; At beginning of buffer or so high up that only a heading
7758 ;; makes sense.
7759 (cond ((and (bolp) (not respect-content)) (insert "* "))
7760 ((not respect-content)
7761 (unless may-split (end-of-line))
7762 (insert "\n* "))
7763 ((re-search-forward org-outline-regexp-bol nil t)
7764 (beginning-of-line)
7765 (insert "* \n")
7766 (backward-char))
7767 (t (goto-char (point-max))
7768 (insert "\n* ")))
7769 (run-hooks 'org-insert-heading-hook))
7771 ((and itemp (not (member arg '((4) (16)))))
7772 ;; Insert an item
7773 (org-insert-item))
7776 ;; Maybe move at the end of the subtree
7777 (when (equal arg '(16))
7778 (org-up-heading-safe)
7779 (org-end-of-subtree t))
7780 ;; Insert a heading
7781 (save-restriction
7782 (widen)
7783 (let* ((level nil)
7784 (on-heading (org-at-heading-p))
7785 (empty-line-p (if on-heading
7786 (org-previous-line-empty-p)
7787 ;; We will decide later
7788 nil))
7789 ;; Get a level string to fall back on
7790 (fix-level
7791 (if (org-before-first-heading-p) "*"
7792 (save-excursion
7793 (org-back-to-heading t)
7794 (if (org-previous-line-empty-p) (setq empty-line-p t))
7795 (looking-at org-outline-regexp)
7796 (make-string (1- (length (match-string 0))) ?*))))
7797 (stars
7798 (save-excursion
7799 (condition-case nil
7800 (progn
7801 (org-back-to-heading invisible-ok)
7802 (when (and (not on-heading)
7803 (featurep 'org-inlinetask)
7804 (integerp org-inlinetask-min-level)
7805 (>= (length (match-string 0))
7806 org-inlinetask-min-level))
7807 ;; Find a heading level before the inline task
7808 (while (and (setq level (org-up-heading-safe))
7809 (>= level org-inlinetask-min-level)))
7810 (if (org-at-heading-p)
7811 (org-back-to-heading invisible-ok)
7812 (error "This should not happen")))
7813 (unless (and (save-excursion
7814 (save-match-data
7815 (org-backward-heading-same-level
7816 1 invisible-ok))
7817 (= (point) (match-beginning 0)))
7818 (not (org-previous-line-empty-p t)))
7819 (setq empty-line-p (or empty-line-p
7820 (org-previous-line-empty-p))))
7821 (match-string 0))
7822 (error (or fix-level "* ")))))
7823 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7824 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7825 pos hide-previous previous-pos)
7827 ;; If we insert after content, move there and clean up whitespace
7828 (when (and respect-content
7829 (not (org-looking-at-p org-outline-regexp-bol)))
7830 (if (not (org-before-first-heading-p))
7831 (org-end-of-subtree nil t)
7832 (re-search-forward org-outline-regexp-bol)
7833 (beginning-of-line 0))
7834 (skip-chars-backward " \r\n")
7835 (and (not (looking-back "^\\*+"))
7836 (looking-at "[ \t]+") (replace-match ""))
7837 (unless (eobp) (forward-char 1))
7838 (when (looking-at "^\\*")
7839 (unless (bobp) (backward-char 1))
7840 (insert "\n")))
7842 ;; If we are splitting, grab the text that should be moved to the new headline
7843 (when may-split
7844 (if (org-on-heading-p)
7845 ;; This is a heading, we split intelligently (keeping tags)
7846 (let ((pos (point)))
7847 (goto-char (point-at-bol))
7848 (unless (looking-at org-complex-heading-regexp)
7849 (error "This should not happen"))
7850 (when (and (match-beginning 4)
7851 (> pos (match-beginning 4))
7852 (< pos (match-end 4)))
7853 (setq initial-content (buffer-substring pos (match-end 4)))
7854 (goto-char pos)
7855 (delete-region (point) (match-end 4))
7856 (if (looking-at "[ \t]*$")
7857 (replace-match "")
7858 (insert (make-string (length initial-content) ?\ )))
7859 (setq initial-content (org-trim initial-content)))
7860 (goto-char pos))
7861 ;; a normal line
7862 (setq initial-content
7863 (org-trim (buffer-substring (point) (point-at-eol))))
7864 (delete-region (point) (point-at-eol))))
7866 ;; If we are at the beginning of the line, insert before it. Else after
7867 (cond
7868 ((and (bolp) (looking-at "[ \t]*$")))
7869 ((and (bolp) (not (looking-at "[ \t]*$")))
7870 (open-line 1))
7872 (goto-char (point-at-eol))
7873 (insert "\n")))
7875 ;; Insert the new heading
7876 (insert stars)
7877 (just-one-space)
7878 (insert initial-content)
7879 (when adjust-empty-lines
7880 (if (or (not blank)
7881 (and blank (not (org-previous-line-empty-p))))
7882 (org-N-empty-lines-before-current (if blank 1 0))))
7883 (run-hooks 'org-insert-heading-hook)))))))
7885 (defun org-N-empty-lines-before-current (N)
7886 "Make the number of empty lines before current exactly N.
7887 So this will delete or add empty lines."
7888 (save-excursion
7889 (beginning-of-line)
7890 (let ((p (point)))
7891 (skip-chars-backward " \r\t\n")
7892 (unless (bolp) (forward-line))
7893 (delete-region (point) p))
7894 (when (> N 0) (insert (make-string N ?\n)))))
7896 (defun org-get-heading (&optional no-tags no-todo)
7897 "Return the heading of the current entry, without the stars.
7898 When NO-TAGS is non-nil, don't include tags.
7899 When NO-TODO is non-nil, don't include TODO keywords."
7900 (save-excursion
7901 (org-back-to-heading t)
7902 (cond
7903 ((and no-tags no-todo)
7904 (looking-at org-complex-heading-regexp)
7905 (match-string 4))
7906 (no-tags
7907 (looking-at (concat org-outline-regexp
7908 "\\(.*?\\)"
7909 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7910 (match-string 1))
7911 (no-todo
7912 (looking-at org-todo-line-regexp)
7913 (match-string 3))
7914 (t (looking-at org-heading-regexp)
7915 (match-string 2)))))
7917 (defvar orgstruct-mode) ; defined below
7919 (defun org-heading-components ()
7920 "Return the components of the current heading.
7921 This is a list with the following elements:
7922 - the level as an integer
7923 - the reduced level, different if `org-odd-levels-only' is set.
7924 - the TODO keyword, or nil
7925 - the priority character, like ?A, or nil if no priority is given
7926 - the headline text itself, or the tags string if no headline text
7927 - the tags string, or nil."
7928 (save-excursion
7929 (org-back-to-heading t)
7930 (if (let (case-fold-search)
7931 (looking-at
7932 (if orgstruct-mode
7933 org-heading-regexp
7934 org-complex-heading-regexp)))
7935 (if orgstruct-mode
7936 (list (length (match-string 1))
7937 (org-reduced-level (length (match-string 1)))
7940 (match-string 2)
7941 nil)
7942 (list (length (match-string 1))
7943 (org-reduced-level (length (match-string 1)))
7944 (org-match-string-no-properties 2)
7945 (and (match-end 3) (aref (match-string 3) 2))
7946 (org-match-string-no-properties 4)
7947 (org-match-string-no-properties 5))))))
7949 (defun org-get-entry ()
7950 "Get the entry text, after heading, entire subtree."
7951 (save-excursion
7952 (org-back-to-heading t)
7953 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7955 (defun org-insert-heading-after-current ()
7956 "Insert a new heading with same level as current, after current subtree."
7957 (interactive)
7958 (org-back-to-heading)
7959 (org-insert-heading)
7960 (org-move-subtree-down)
7961 (end-of-line 1))
7963 (defun org-insert-heading-respect-content (&optional invisible-ok)
7964 "Insert heading with `org-insert-heading-respect-content' set to t."
7965 (interactive)
7966 (org-insert-heading '(4) invisible-ok))
7968 (defun org-insert-todo-heading-respect-content (&optional force-state)
7969 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7970 (interactive)
7971 (org-insert-todo-heading force-state '(4)))
7973 (defun org-insert-todo-heading (arg &optional force-heading)
7974 "Insert a new heading with the same level and TODO state as current heading.
7975 If the heading has no TODO state, or if the state is DONE, use the first
7976 state (TODO by default). Also with one prefix arg, force first state. With
7977 two prefix args, force inserting at the end of the parent subtree."
7978 (interactive "P")
7979 (when (or force-heading (not (org-insert-item 'checkbox)))
7980 (org-insert-heading (or (and (equal arg '(16)) '(16))
7981 force-heading))
7982 (save-excursion
7983 (org-back-to-heading)
7984 (outline-previous-heading)
7985 (looking-at org-todo-line-regexp))
7986 (let*
7987 ((new-mark-x
7988 (if (or (equal arg '(4))
7989 (not (match-beginning 2))
7990 (member (match-string 2) org-done-keywords))
7991 (car org-todo-keywords-1)
7992 (match-string 2)))
7993 (new-mark
7995 (run-hook-with-args-until-success
7996 'org-todo-get-default-hook new-mark-x nil)
7997 new-mark-x)))
7998 (beginning-of-line 1)
7999 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8000 (if org-treat-insert-todo-heading-as-state-change
8001 (org-todo new-mark)
8002 (insert new-mark " "))))
8003 (when org-provide-todo-statistics
8004 (org-update-parent-todo-statistics))))
8006 (defun org-insert-subheading (arg)
8007 "Insert a new subheading and demote it.
8008 Works for outline headings and for plain lists alike."
8009 (interactive "P")
8010 (org-insert-heading arg)
8011 (cond
8012 ((org-at-heading-p) (org-do-demote))
8013 ((org-at-item-p) (org-indent-item))))
8015 (defun org-insert-todo-subheading (arg)
8016 "Insert a new subheading with TODO keyword or checkbox and demote it.
8017 Works for outline headings and for plain lists alike."
8018 (interactive "P")
8019 (org-insert-todo-heading arg)
8020 (cond
8021 ((org-at-heading-p) (org-do-demote))
8022 ((org-at-item-p) (org-indent-item))))
8024 ;;; Promotion and Demotion
8026 (defvar org-after-demote-entry-hook nil
8027 "Hook run after an entry has been demoted.
8028 The cursor will be at the beginning of the entry.
8029 When a subtree is being demoted, the hook will be called for each node.")
8031 (defvar org-after-promote-entry-hook nil
8032 "Hook run after an entry has been promoted.
8033 The cursor will be at the beginning of the entry.
8034 When a subtree is being promoted, the hook will be called for each node.")
8036 (defun org-promote-subtree ()
8037 "Promote the entire subtree.
8038 See also `org-promote'."
8039 (interactive)
8040 (save-excursion
8041 (org-with-limited-levels (org-map-tree 'org-promote)))
8042 (org-fix-position-after-promote))
8044 (defun org-demote-subtree ()
8045 "Demote the entire subtree. See `org-demote'.
8046 See also `org-promote'."
8047 (interactive)
8048 (save-excursion
8049 (org-with-limited-levels (org-map-tree 'org-demote)))
8050 (org-fix-position-after-promote))
8053 (defun org-do-promote ()
8054 "Promote the current heading higher up the tree.
8055 If the region is active in `transient-mark-mode', promote all headings
8056 in the region."
8057 (interactive)
8058 (save-excursion
8059 (if (org-region-active-p)
8060 (org-map-region 'org-promote (region-beginning) (region-end))
8061 (org-promote)))
8062 (org-fix-position-after-promote))
8064 (defun org-do-demote ()
8065 "Demote the current heading lower down the tree.
8066 If the region is active in `transient-mark-mode', demote all headings
8067 in the region."
8068 (interactive)
8069 (save-excursion
8070 (if (org-region-active-p)
8071 (org-map-region 'org-demote (region-beginning) (region-end))
8072 (org-demote)))
8073 (org-fix-position-after-promote))
8075 (defun org-fix-position-after-promote ()
8076 "Make sure that after pro/demotion cursor position is right."
8077 (let ((pos (point)))
8078 (when (save-excursion
8079 (beginning-of-line 1)
8080 (looking-at org-todo-line-regexp)
8081 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8082 (cond ((eobp) (insert " "))
8083 ((eolp) (insert " "))
8084 ((equal (char-after) ?\ ) (forward-char 1))))))
8086 (defun org-current-level ()
8087 "Return the level of the current entry, or nil if before the first headline.
8088 The level is the number of stars at the beginning of the headline."
8089 (save-excursion
8090 (org-with-limited-levels
8091 (if (ignore-errors (org-back-to-heading t))
8092 (funcall outline-level)))))
8094 (defun org-get-previous-line-level ()
8095 "Return the outline depth of the last headline before the current line.
8096 Returns 0 for the first headline in the buffer, and nil if before the
8097 first headline."
8098 (and (org-current-level)
8099 (or (and (/= (line-beginning-position) (point-min))
8100 (save-excursion (beginning-of-line 0) (org-current-level)))
8101 0)))
8103 (defun org-reduced-level (l)
8104 "Compute the effective level of a heading.
8105 This takes into account the setting of `org-odd-levels-only'."
8106 (cond
8107 ((zerop l) 0)
8108 (org-odd-levels-only (1+ (floor (/ l 2))))
8109 (t l)))
8111 (defun org-level-increment ()
8112 "Return the number of stars that will be added or removed at a
8113 time to headlines when structure editing, based on the value of
8114 `org-odd-levels-only'."
8115 (if org-odd-levels-only 2 1))
8117 (defun org-get-valid-level (level &optional change)
8118 "Rectify a level change under the influence of `org-odd-levels-only'
8119 LEVEL is a current level, CHANGE is by how much the level should be
8120 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8121 even level numbers will become the next higher odd number."
8122 (if org-odd-levels-only
8123 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8124 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8125 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8126 (max 1 (+ level (or change 0)))))
8128 (if (boundp 'define-obsolete-function-alias)
8129 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8130 (define-obsolete-function-alias 'org-get-legal-level
8131 'org-get-valid-level)
8132 (define-obsolete-function-alias 'org-get-legal-level
8133 'org-get-valid-level "23.1")))
8135 (defun org-promote ()
8136 "Promote the current heading higher up the tree.
8137 If the region is active in `transient-mark-mode', promote all headings
8138 in the region."
8139 (org-back-to-heading t)
8140 (let* ((level (save-match-data (funcall outline-level)))
8141 (after-change-functions (remove 'flyspell-after-change-function
8142 after-change-functions))
8143 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8144 (diff (abs (- level (length up-head) -1))))
8145 (cond ((and (= level 1) org-called-with-limited-levels
8146 org-allow-promoting-top-level-subtree)
8147 (replace-match "# " nil t))
8148 ((= level 1)
8149 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8150 (t (replace-match up-head nil t)))
8151 ;; Fixup tag positioning
8152 (unless (= level 1)
8153 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8154 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8155 (run-hooks 'org-after-promote-entry-hook)))
8157 (defun org-demote ()
8158 "Demote the current heading lower down the tree.
8159 If the region is active in `transient-mark-mode', demote all headings
8160 in the region."
8161 (org-back-to-heading t)
8162 (let* ((level (save-match-data (funcall outline-level)))
8163 (after-change-functions (remove 'flyspell-after-change-function
8164 after-change-functions))
8165 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8166 (diff (abs (- level (length down-head) -1))))
8167 (replace-match down-head nil t)
8168 ;; Fixup tag positioning
8169 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8170 (if org-adapt-indentation (org-fixup-indentation diff))
8171 (run-hooks 'org-after-demote-entry-hook)))
8173 (defun org-cycle-level ()
8174 "Cycle the level of an empty headline through possible states.
8175 This goes first to child, then to parent, level, then up the hierarchy.
8176 After top level, it switches back to sibling level."
8177 (interactive)
8178 (let ((org-adapt-indentation nil))
8179 (when (org-point-at-end-of-empty-headline)
8180 (setq this-command 'org-cycle-level) ; Only needed for caching
8181 (let ((cur-level (org-current-level))
8182 (prev-level (org-get-previous-line-level)))
8183 (cond
8184 ;; If first headline in file, promote to top-level.
8185 ((= prev-level 0)
8186 (loop repeat (/ (- cur-level 1) (org-level-increment))
8187 do (org-do-promote)))
8188 ;; If same level as prev, demote one.
8189 ((= prev-level cur-level)
8190 (org-do-demote))
8191 ;; If parent is top-level, promote to top level if not already.
8192 ((= prev-level 1)
8193 (loop repeat (/ (- cur-level 1) (org-level-increment))
8194 do (org-do-promote)))
8195 ;; If top-level, return to prev-level.
8196 ((= cur-level 1)
8197 (loop repeat (/ (- prev-level 1) (org-level-increment))
8198 do (org-do-demote)))
8199 ;; If less than prev-level, promote one.
8200 ((< cur-level prev-level)
8201 (org-do-promote))
8202 ;; If deeper than prev-level, promote until higher than
8203 ;; prev-level.
8204 ((> cur-level prev-level)
8205 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8206 do (org-do-promote))))
8207 t))))
8209 (defun org-map-tree (fun)
8210 "Call FUN for every heading underneath the current one."
8211 (org-back-to-heading)
8212 (let ((level (funcall outline-level)))
8213 (save-excursion
8214 (funcall fun)
8215 (while (and (progn
8216 (outline-next-heading)
8217 (> (funcall outline-level) level))
8218 (not (eobp)))
8219 (funcall fun)))))
8221 (defun org-map-region (fun beg end)
8222 "Call FUN for every heading between BEG and END."
8223 (let ((org-ignore-region t))
8224 (save-excursion
8225 (setq end (copy-marker end))
8226 (goto-char beg)
8227 (if (and (re-search-forward org-outline-regexp-bol nil t)
8228 (< (point) end))
8229 (funcall fun))
8230 (while (and (progn
8231 (outline-next-heading)
8232 (< (point) end))
8233 (not (eobp)))
8234 (funcall fun)))))
8236 (defvar org-property-end-re) ; silence byte-compiler
8237 (defun org-fixup-indentation (diff)
8238 "Change the indentation in the current entry by DIFF.
8239 However, if any line in the current entry has no indentation, or if it
8240 would end up with no indentation after the change, nothing at all is done."
8241 (save-excursion
8242 (let ((end (save-excursion (outline-next-heading)
8243 (point-marker)))
8244 (prohibit (if (> diff 0)
8245 "^\\S-"
8246 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8247 col)
8248 (unless (save-excursion (end-of-line 1)
8249 (re-search-forward prohibit end t))
8250 (while (and (< (point) end)
8251 (re-search-forward "^[ \t]+" end t))
8252 (goto-char (match-end 0))
8253 (setq col (current-column))
8254 (if (< diff 0) (replace-match ""))
8255 (org-indent-to-column (+ diff col))))
8256 (move-marker end nil))))
8258 (defun org-convert-to-odd-levels ()
8259 "Convert an org-mode file with all levels allowed to one with odd levels.
8260 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8261 level 5 etc."
8262 (interactive)
8263 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8264 (let ((outline-level 'org-outline-level)
8265 (org-odd-levels-only nil) n)
8266 (save-excursion
8267 (goto-char (point-min))
8268 (while (re-search-forward "^\\*\\*+ " nil t)
8269 (setq n (- (length (match-string 0)) 2))
8270 (while (>= (setq n (1- n)) 0)
8271 (org-demote))
8272 (end-of-line 1))))))
8274 (defun org-convert-to-oddeven-levels ()
8275 "Convert an org-mode file with only odd levels to one with odd/even levels.
8276 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8277 file contains a section with an even level, conversion would
8278 destroy the structure of the file. An error is signaled in this
8279 case."
8280 (interactive)
8281 (goto-char (point-min))
8282 ;; First check if there are no even levels
8283 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8284 (org-show-context t)
8285 (error "Not all levels are odd in this file. Conversion not possible"))
8286 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8287 (let ((outline-regexp org-outline-regexp)
8288 (outline-level 'org-outline-level)
8289 (org-odd-levels-only nil) n)
8290 (save-excursion
8291 (goto-char (point-min))
8292 (while (re-search-forward "^\\*\\*+ " nil t)
8293 (setq n (/ (1- (length (match-string 0))) 2))
8294 (while (>= (setq n (1- n)) 0)
8295 (org-promote))
8296 (end-of-line 1))))))
8298 (defun org-tr-level (n)
8299 "Make N odd if required."
8300 (if org-odd-levels-only (1+ (/ n 2)) n))
8302 ;;; Vertical tree motion, cutting and pasting of subtrees
8304 (defun org-move-subtree-up (&optional arg)
8305 "Move the current subtree up past ARG headlines of the same level."
8306 (interactive "p")
8307 (org-move-subtree-down (- (prefix-numeric-value arg))))
8309 (defun org-move-subtree-down (&optional arg)
8310 "Move the current subtree down past ARG headlines of the same level."
8311 (interactive "p")
8312 (setq arg (prefix-numeric-value arg))
8313 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8314 'org-get-last-sibling))
8315 (ins-point (make-marker))
8316 (cnt (abs arg))
8317 (col (current-column))
8318 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8319 ;; Select the tree
8320 (org-back-to-heading)
8321 (setq beg0 (point))
8322 (save-excursion
8323 (setq ne-beg (org-back-over-empty-lines))
8324 (setq beg (point)))
8325 (save-match-data
8326 (save-excursion (outline-end-of-heading)
8327 (setq folded (outline-invisible-p)))
8328 (progn (org-end-of-subtree nil t)
8329 (unless (eobp) (backward-char))))
8330 (outline-next-heading)
8331 (setq ne-end (org-back-over-empty-lines))
8332 (setq end (point))
8333 (goto-char beg0)
8334 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8335 ;; include less whitespace
8336 (save-excursion
8337 (goto-char beg)
8338 (forward-line (- ne-beg ne-end))
8339 (setq beg (point))))
8340 ;; Find insertion point, with error handling
8341 (while (> cnt 0)
8342 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8343 (progn (goto-char beg0)
8344 (user-error "Cannot move past superior level or buffer limit")))
8345 (setq cnt (1- cnt)))
8346 (if (> arg 0)
8347 ;; Moving forward - still need to move over subtree
8348 (progn (org-end-of-subtree t t)
8349 (save-excursion
8350 (org-back-over-empty-lines)
8351 (or (bolp) (newline)))))
8352 (setq ne-ins (org-back-over-empty-lines))
8353 (move-marker ins-point (point))
8354 (setq txt (buffer-substring beg end))
8355 (org-save-markers-in-region beg end)
8356 (delete-region beg end)
8357 (org-remove-empty-overlays-at beg)
8358 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8359 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8360 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8361 (let ((bbb (point)))
8362 (insert-before-markers txt)
8363 (org-reinstall-markers-in-region bbb)
8364 (move-marker ins-point bbb))
8365 (or (bolp) (insert "\n"))
8366 (setq ins-end (point))
8367 (goto-char ins-point)
8368 (org-skip-whitespace)
8369 (when (and (< arg 0)
8370 (org-first-sibling-p)
8371 (> ne-ins ne-beg))
8372 ;; Move whitespace back to beginning
8373 (save-excursion
8374 (goto-char ins-end)
8375 (let ((kill-whole-line t))
8376 (kill-line (- ne-ins ne-beg)) (point)))
8377 (insert (make-string (- ne-ins ne-beg) ?\n)))
8378 (move-marker ins-point nil)
8379 (if folded
8380 (hide-subtree)
8381 (org-show-entry)
8382 (show-children)
8383 (org-cycle-hide-drawers 'children))
8384 (org-clean-visibility-after-subtree-move)
8385 ;; move back to the initial column we were at
8386 (move-to-column col)))
8388 (defvar org-subtree-clip ""
8389 "Clipboard for cut and paste of subtrees.
8390 This is actually only a copy of the kill, because we use the normal kill
8391 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8393 (defvar org-subtree-clip-folded nil
8394 "Was the last copied subtree folded?
8395 This is used to fold the tree back after pasting.")
8397 (defun org-cut-subtree (&optional n)
8398 "Cut the current subtree into the clipboard.
8399 With prefix arg N, cut this many sequential subtrees.
8400 This is a short-hand for marking the subtree and then cutting it."
8401 (interactive "p")
8402 (org-copy-subtree n 'cut))
8404 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8405 "Copy the current subtree it in the clipboard.
8406 With prefix arg N, copy this many sequential subtrees.
8407 This is a short-hand for marking the subtree and then copying it.
8408 If CUT is non-nil, actually cut the subtree.
8409 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8410 of some markers in the region, even if CUT is non-nil. This is
8411 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8412 (interactive "p")
8413 (let (beg end folded (beg0 (point)))
8414 (if (org-called-interactively-p 'any)
8415 (org-back-to-heading nil) ; take what looks like a subtree
8416 (org-back-to-heading t)) ; take what is really there
8417 (setq beg (point))
8418 (skip-chars-forward " \t\r\n")
8419 (save-match-data
8420 (if nosubtrees
8421 (outline-next-heading)
8422 (save-excursion (outline-end-of-heading)
8423 (setq folded (outline-invisible-p)))
8424 (ignore-errors (org-forward-heading-same-level (1- n) t))
8425 (org-end-of-subtree t t)))
8426 (setq end (point))
8427 (goto-char beg0)
8428 (when (> end beg)
8429 (setq org-subtree-clip-folded folded)
8430 (when (or cut force-store-markers)
8431 (org-save-markers-in-region beg end))
8432 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8433 (setq org-subtree-clip (current-kill 0))
8434 (message "%s: Subtree(s) with %d characters"
8435 (if cut "Cut" "Copied")
8436 (length org-subtree-clip)))))
8438 (defun org-paste-subtree (&optional level tree for-yank remove)
8439 "Paste the clipboard as a subtree, with modification of headline level.
8440 The entire subtree is promoted or demoted in order to match a new headline
8441 level.
8443 If the cursor is at the beginning of a headline, the same level as
8444 that headline is used to paste the tree.
8446 If not, the new level is derived from the *visible* headings
8447 before and after the insertion point, and taken to be the inferior headline
8448 level of the two. So if the previous visible heading is level 3 and the
8449 next is level 4 (or vice versa), level 4 will be used for insertion.
8450 This makes sure that the subtree remains an independent subtree and does
8451 not swallow low level entries.
8453 You can also force a different level, either by using a numeric prefix
8454 argument, or by inserting the heading marker by hand. For example, if the
8455 cursor is after \"*****\", then the tree will be shifted to level 5.
8457 If optional TREE is given, use this text instead of the kill ring.
8459 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8460 move back over whitespace before inserting, and move point to the end of
8461 the inserted text when done.
8463 When REMOVE is non-nil, remove the subtree from the clipboard."
8464 (interactive "P")
8465 (setq tree (or tree (and kill-ring (current-kill 0))))
8466 (unless (org-kill-is-subtree-p tree)
8467 (user-error "%s"
8468 (substitute-command-keys
8469 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8470 (org-with-limited-levels
8471 (let* ((visp (not (outline-invisible-p)))
8472 (txt tree)
8473 (^re_ "\\(\\*+\\)[ \t]*")
8474 (old-level (if (string-match org-outline-regexp-bol txt)
8475 (- (match-end 0) (match-beginning 0) 1)
8476 -1))
8477 (force-level (cond (level (prefix-numeric-value level))
8478 ((and (looking-at "[ \t]*$")
8479 (string-match
8480 "^\\*+$" (buffer-substring
8481 (point-at-bol) (point))))
8482 (- (match-end 0) (match-beginning 0)))
8483 ((and (bolp)
8484 (looking-at org-outline-regexp))
8485 (- (match-end 0) (point) 1))))
8486 (previous-level (save-excursion
8487 (condition-case nil
8488 (progn
8489 (outline-previous-visible-heading 1)
8490 (if (looking-at ^re_)
8491 (- (match-end 0) (match-beginning 0) 1)
8493 (error 1))))
8494 (next-level (save-excursion
8495 (condition-case nil
8496 (progn
8497 (or (looking-at org-outline-regexp)
8498 (outline-next-visible-heading 1))
8499 (if (looking-at ^re_)
8500 (- (match-end 0) (match-beginning 0) 1)
8502 (error 1))))
8503 (new-level (or force-level (max previous-level next-level)))
8504 (shift (if (or (= old-level -1)
8505 (= new-level -1)
8506 (= old-level new-level))
8508 (- new-level old-level)))
8509 (delta (if (> shift 0) -1 1))
8510 (func (if (> shift 0) 'org-demote 'org-promote))
8511 (org-odd-levels-only nil)
8512 beg end newend)
8513 ;; Remove the forced level indicator
8514 (if force-level
8515 (delete-region (point-at-bol) (point)))
8516 ;; Paste
8517 (beginning-of-line (if (bolp) 1 2))
8518 (setq beg (point))
8519 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8520 (insert-before-markers txt)
8521 (unless (string-match "\n\\'" txt) (insert "\n"))
8522 (setq newend (point))
8523 (org-reinstall-markers-in-region beg)
8524 (setq end (point))
8525 (goto-char beg)
8526 (skip-chars-forward " \t\n\r")
8527 (setq beg (point))
8528 (if (and (outline-invisible-p) visp)
8529 (save-excursion (outline-show-heading)))
8530 ;; Shift if necessary
8531 (unless (= shift 0)
8532 (save-restriction
8533 (narrow-to-region beg end)
8534 (while (not (= shift 0))
8535 (org-map-region func (point-min) (point-max))
8536 (setq shift (+ delta shift)))
8537 (goto-char (point-min))
8538 (setq newend (point-max))))
8539 (when (or (org-called-interactively-p 'interactive) for-yank)
8540 (message "Clipboard pasted as level %d subtree" new-level))
8541 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8542 kill-ring
8543 (eq org-subtree-clip (current-kill 0))
8544 org-subtree-clip-folded)
8545 ;; The tree was folded before it was killed/copied
8546 (hide-subtree))
8547 (and for-yank (goto-char newend))
8548 (and remove (setq kill-ring (cdr kill-ring))))))
8550 (defun org-kill-is-subtree-p (&optional txt)
8551 "Check if the current kill is an outline subtree, or a set of trees.
8552 Returns nil if kill does not start with a headline, or if the first
8553 headline level is not the largest headline level in the tree.
8554 So this will actually accept several entries of equal levels as well,
8555 which is OK for `org-paste-subtree'.
8556 If optional TXT is given, check this string instead of the current kill."
8557 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8558 (re (org-get-limited-outline-regexp))
8559 (^re (concat "^" re))
8560 (start-level (and kill
8561 (string-match
8562 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8563 kill)
8564 (- (match-end 2) (match-beginning 2) 1)))
8565 (start (1+ (or (match-beginning 2) -1))))
8566 (if (not start-level)
8567 (progn
8568 nil) ;; does not even start with a heading
8569 (catch 'exit
8570 (while (setq start (string-match ^re kill (1+ start)))
8571 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8572 (throw 'exit nil)))
8573 t))))
8575 (defvar org-markers-to-move nil
8576 "Markers that should be moved with a cut-and-paste operation.
8577 Those markers are stored together with their positions relative to
8578 the start of the region.")
8580 (defun org-save-markers-in-region (beg end)
8581 "Check markers in region.
8582 If these markers are between BEG and END, record their position relative
8583 to BEG, so that after moving the block of text, we can put the markers back
8584 into place.
8585 This function gets called just before an entry or tree gets cut from the
8586 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8587 called immediately, to move the markers with the entries."
8588 (setq org-markers-to-move nil)
8589 (when (featurep 'org-clock)
8590 (org-clock-save-markers-for-cut-and-paste beg end))
8591 (when (featurep 'org-agenda)
8592 (org-agenda-save-markers-for-cut-and-paste beg end)))
8594 (defun org-check-and-save-marker (marker beg end)
8595 "Check if MARKER is between BEG and END.
8596 If yes, remember the marker and the distance to BEG."
8597 (when (and (marker-buffer marker)
8598 (equal (marker-buffer marker) (current-buffer)))
8599 (if (and (>= marker beg) (< marker end))
8600 (push (cons marker (- marker beg)) org-markers-to-move))))
8602 (defun org-reinstall-markers-in-region (beg)
8603 "Move all remembered markers to their position relative to BEG."
8604 (mapc (lambda (x)
8605 (move-marker (car x) (+ beg (cdr x))))
8606 org-markers-to-move)
8607 (setq org-markers-to-move nil))
8609 (defun org-narrow-to-subtree ()
8610 "Narrow buffer to the current subtree."
8611 (interactive)
8612 (save-excursion
8613 (save-match-data
8614 (org-with-limited-levels
8615 (narrow-to-region
8616 (progn (org-back-to-heading t) (point))
8617 (progn (org-end-of-subtree t t)
8618 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8619 (point)))))))
8621 (defun org-narrow-to-block ()
8622 "Narrow buffer to the current block."
8623 (interactive)
8624 (let* ((case-fold-search t)
8625 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8626 "^[ \t]*#\\+end_.*")))
8627 (if blockp
8628 (narrow-to-region (car blockp) (cdr blockp))
8629 (user-error "Not in a block"))))
8631 (eval-when-compile
8632 (defvar org-property-drawer-re))
8634 (defvar org-property-start-re) ;; defined below
8635 (defun org-clone-subtree-with-time-shift (n &optional shift)
8636 "Clone the task (subtree) at point N times.
8637 The clones will be inserted as siblings.
8639 In interactive use, the user will be prompted for the number of
8640 clones to be produced. If the entry has a timestamp, the user
8641 will also be prompted for a time shift, which may be a repeater
8642 as used in time stamps, for example `+3d'. To disable this,
8643 you can call the function with a universal prefix argument.
8645 When a valid repeater is given and the entry contains any time
8646 stamps, the clones will become a sequence in time, with time
8647 stamps in the subtree shifted for each clone produced. If SHIFT
8648 is nil or the empty string, time stamps will be left alone. The
8649 ID property of the original subtree is removed.
8651 If the original subtree did contain time stamps with a repeater,
8652 the following will happen:
8653 - the repeater will be removed in each clone
8654 - an additional clone will be produced, with the current, unshifted
8655 date(s) in the entry.
8656 - the original entry will be placed *after* all the clones, with
8657 repeater intact.
8658 - the start days in the repeater in the original entry will be shifted
8659 to past the last clone.
8660 In this way you can spell out a number of instances of a repeating task,
8661 and still retain the repeater to cover future instances of the task."
8662 (interactive "nNumber of clones to produce: ")
8663 (let ((shift
8664 (or shift
8665 (if (and (not (equal current-prefix-arg '(4)))
8666 (save-excursion
8667 (re-search-forward org-ts-regexp-both
8668 (save-excursion
8669 (org-end-of-subtree t)
8670 (point)) t)))
8671 (read-from-minibuffer
8672 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8673 ""))) ;; No time shift
8674 (n-no-remove -1)
8675 (drawer-re org-drawer-regexp)
8676 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8677 beg end template task idprop
8678 shift-n shift-what doshift nmin nmax)
8679 (if (not (and (integerp n) (> n 0)))
8680 (user-error "Invalid number of replications %s" n))
8681 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8682 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8683 shift)))
8684 (user-error "Invalid shift specification %s" shift))
8685 (when doshift
8686 (setq shift-n (string-to-number (match-string 1 shift))
8687 shift-what (cdr (assoc (match-string 2 shift)
8688 '(("d" . day) ("w" . week)
8689 ("m" . month) ("y" . year))))))
8690 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8691 (setq nmin 1 nmax n)
8692 (org-back-to-heading t)
8693 (setq beg (point))
8694 (setq idprop (org-entry-get nil "ID"))
8695 (org-end-of-subtree t t)
8696 (or (bolp) (insert "\n"))
8697 (setq end (point))
8698 (setq template (buffer-substring beg end))
8699 (when (and doshift
8700 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8701 (delete-region beg end)
8702 (setq end beg)
8703 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8704 (goto-char end)
8705 (loop for n from nmin to nmax do
8706 ;; prepare clone
8707 (with-temp-buffer
8708 (insert template)
8709 (org-mode)
8710 (goto-char (point-min))
8711 (org-show-subtree)
8712 (and idprop (if org-clone-delete-id
8713 (org-entry-delete nil "ID")
8714 (org-id-get-create t)))
8715 (unless (= n 0)
8716 (while (re-search-forward org-clock-re nil t)
8717 (kill-whole-line))
8718 (goto-char (point-min))
8719 (while (re-search-forward drawer-re nil t)
8720 (org-remove-empty-drawer-at (point))))
8721 (goto-char (point-min))
8722 (when doshift
8723 (while (re-search-forward org-ts-regexp-both nil t)
8724 (org-timestamp-change (* n shift-n) shift-what))
8725 (unless (= n n-no-remove)
8726 (goto-char (point-min))
8727 (while (re-search-forward org-ts-regexp nil t)
8728 (save-excursion
8729 (goto-char (match-beginning 0))
8730 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8731 (delete-region (match-beginning 1) (match-end 1)))))))
8732 (setq task (buffer-string)))
8733 (insert task))
8734 (goto-char beg)))
8736 ;;; Outline Sorting
8738 (defun org-sort (with-case)
8739 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8740 Optional argument WITH-CASE means sort case-sensitively."
8741 (interactive "P")
8742 (cond
8743 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8744 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8746 (org-call-with-arg 'org-sort-entries with-case))))
8748 (defun org-sort-remove-invisible (s)
8749 "Remove invisible links from string S."
8750 (remove-text-properties 0 (length s) org-rm-props s)
8751 (while (string-match org-bracket-link-regexp s)
8752 (setq s (replace-match (if (match-end 2)
8753 (match-string 3 s)
8754 (match-string 1 s)) t t s)))
8755 (let ((st (format " %s " s)))
8756 (while (string-match org-emph-re st)
8757 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8758 (setq s (substring st 1 -1)))
8761 (defvar org-priority-regexp) ; defined later in the file
8763 (defvar org-after-sorting-entries-or-items-hook nil
8764 "Hook that is run after a bunch of entries or items have been sorted.
8765 When children are sorted, the cursor is in the parent line when this
8766 hook gets called. When a region or a plain list is sorted, the cursor
8767 will be in the first entry of the sorted region/list.")
8769 (defun org-sort-entries
8770 (&optional with-case sorting-type getkey-func compare-func property)
8771 "Sort entries on a certain level of an outline tree.
8772 If there is an active region, the entries in the region are sorted.
8773 Else, if the cursor is before the first entry, sort the top-level items.
8774 Else, the children of the entry at point are sorted.
8776 Sorting can be alphabetically, numerically, by date/time as given by
8777 a time stamp, by a property, by priority order, or by a custom function.
8779 The command prompts for the sorting type unless it has been given to the
8780 function through the SORTING-TYPE argument, which needs to be a character,
8781 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8782 the precise meaning of each character:
8784 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8785 c By creation time, which is assumed to be the first inactive time stamp
8786 at the beginning of a line.
8787 d By deadline date/time.
8788 k By clocking time.
8789 n Numerically, by converting the beginning of the entry/item to a number.
8790 o By order of TODO keywords.
8791 p By priority according to the cookie.
8792 r By the value of a property.
8793 s By scheduled date/time.
8794 t By date/time, either the first active time stamp in the entry, or, if
8795 none exist, by the first inactive one.
8797 Capital letters will reverse the sort order.
8799 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8800 called with point at the beginning of the record. It must return either
8801 a string or a number that should serve as the sorting key for that record.
8803 Comparing entries ignores case by default. However, with an optional argument
8804 WITH-CASE, the sorting considers case as well.
8806 Sorting is done against the visible part of the headlines, it ignores hidden
8807 links.
8809 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8810 (interactive "P")
8811 (let ((case-func (if with-case 'identity 'downcase))
8812 (cmstr
8813 ;; The clock marker is lost when using `sort-subr', let's
8814 ;; store the clocking string.
8815 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8816 (save-excursion
8817 (goto-char org-clock-marker)
8818 (looking-back "^.*") (match-string-no-properties 0))))
8819 start beg end stars re re2
8820 txt what tmp)
8821 ;; Find beginning and end of region to sort
8822 (cond
8823 ((org-region-active-p)
8824 ;; we will sort the region
8825 (setq end (region-end)
8826 what "region")
8827 (goto-char (region-beginning))
8828 (if (not (org-at-heading-p)) (outline-next-heading))
8829 (setq start (point)))
8830 ((or (org-at-heading-p)
8831 (ignore-errors (progn (org-back-to-heading) t)))
8832 ;; we will sort the children of the current headline
8833 (org-back-to-heading)
8834 (setq start (point)
8835 end (progn (org-end-of-subtree t t)
8836 (or (bolp) (insert "\n"))
8837 (when (>= (org-back-over-empty-lines) 1)
8838 (forward-line 1))
8839 (point))
8840 what "children")
8841 (goto-char start)
8842 (show-subtree)
8843 (outline-next-heading))
8845 ;; we will sort the top-level entries in this file
8846 (goto-char (point-min))
8847 (or (org-at-heading-p) (outline-next-heading))
8848 (setq start (point))
8849 (goto-char (point-max))
8850 (beginning-of-line 1)
8851 (when (looking-at ".*?\\S-")
8852 ;; File ends in a non-white line
8853 (end-of-line 1)
8854 (insert "\n"))
8855 (setq end (point-max))
8856 (setq what "top-level")
8857 (goto-char start)
8858 (show-all)))
8860 (setq beg (point))
8861 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8863 (looking-at "\\(\\*+\\)")
8864 (setq stars (match-string 1)
8865 re (concat "^" (regexp-quote stars) " +")
8866 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8867 txt (buffer-substring beg end))
8868 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8869 (if (and (not (equal stars "*")) (string-match re2 txt))
8870 (user-error "Region to sort contains a level above the first entry"))
8872 (unless sorting-type
8873 (message
8874 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8875 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8876 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8877 what)
8878 (setq sorting-type (read-char-exclusive))
8880 (unless getkey-func
8881 (and (= (downcase sorting-type) ?f)
8882 (setq getkey-func
8883 (org-icompleting-read "Sort using function: "
8884 obarray 'fboundp t nil nil))
8885 (setq getkey-func (intern getkey-func))))
8887 (and (= (downcase sorting-type) ?r)
8888 (not property)
8889 (setq property
8890 (org-icompleting-read "Property: "
8891 (mapcar 'list (org-buffer-property-keys t))
8892 nil t))))
8894 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8895 (message "Sorting entries...")
8897 (save-restriction
8898 (narrow-to-region start end)
8899 (let ((dcst (downcase sorting-type))
8900 (case-fold-search nil)
8901 (now (current-time)))
8902 (sort-subr
8903 (/= dcst sorting-type)
8904 ;; This function moves to the beginning character of the "record" to
8905 ;; be sorted.
8906 (lambda nil
8907 (if (re-search-forward re nil t)
8908 (goto-char (match-beginning 0))
8909 (goto-char (point-max))))
8910 ;; This function moves to the last character of the "record" being
8911 ;; sorted.
8912 (lambda nil
8913 (save-match-data
8914 (condition-case nil
8915 (outline-forward-same-level 1)
8916 (error
8917 (goto-char (point-max))))))
8918 ;; This function returns the value that gets sorted against.
8919 (lambda nil
8920 (cond
8921 ((= dcst ?n)
8922 (if (looking-at org-complex-heading-regexp)
8923 (string-to-number (org-sort-remove-invisible (match-string 4)))
8924 nil))
8925 ((= dcst ?a)
8926 (if (looking-at org-complex-heading-regexp)
8927 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8928 nil))
8929 ((= dcst ?k)
8930 (or (get-text-property (point) :org-clock-minutes) 0))
8931 ((= dcst ?t)
8932 (let ((end (save-excursion (outline-next-heading) (point))))
8933 (if (or (re-search-forward org-ts-regexp end t)
8934 (re-search-forward org-ts-regexp-both end t))
8935 (org-time-string-to-seconds (match-string 0))
8936 (org-float-time now))))
8937 ((= dcst ?c)
8938 (let ((end (save-excursion (outline-next-heading) (point))))
8939 (if (re-search-forward
8940 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8941 end t)
8942 (org-time-string-to-seconds (match-string 0))
8943 (org-float-time now))))
8944 ((= dcst ?s)
8945 (let ((end (save-excursion (outline-next-heading) (point))))
8946 (if (re-search-forward org-scheduled-time-regexp end t)
8947 (org-time-string-to-seconds (match-string 1))
8948 (org-float-time now))))
8949 ((= dcst ?d)
8950 (let ((end (save-excursion (outline-next-heading) (point))))
8951 (if (re-search-forward org-deadline-time-regexp end t)
8952 (org-time-string-to-seconds (match-string 1))
8953 (org-float-time now))))
8954 ((= dcst ?p)
8955 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8956 (string-to-char (match-string 2))
8957 org-default-priority))
8958 ((= dcst ?r)
8959 (or (org-entry-get nil property) ""))
8960 ((= dcst ?o)
8961 (if (looking-at org-complex-heading-regexp)
8962 (let* ((m (match-string 2))
8963 (s (if (member m org-done-keywords) '- '+)))
8964 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8965 ((= dcst ?f)
8966 (if getkey-func
8967 (progn
8968 (setq tmp (funcall getkey-func))
8969 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8970 tmp)
8971 (error "Invalid key function `%s'" getkey-func)))
8972 (t (error "Invalid sorting type `%c'" sorting-type))))
8974 (cond
8975 ((= dcst ?a) 'string<)
8976 ((= dcst ?f) compare-func)
8977 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8978 (run-hooks 'org-after-sorting-entries-or-items-hook)
8979 ;; Reset the clock marker if needed
8980 (when cmstr
8981 (save-excursion
8982 (goto-char start)
8983 (search-forward cmstr nil t)
8984 (move-marker org-clock-marker (point))))
8985 (message "Sorting entries...done")))
8987 (defun org-do-sort (table what &optional with-case sorting-type)
8988 "Sort TABLE of WHAT according to SORTING-TYPE.
8989 The user will be prompted for the SORTING-TYPE if the call to this
8990 function does not specify it.
8991 WHAT is only for the prompt, to indicate what is being sorted.
8992 The sorting key will be extracted from the car of the elements of
8993 the table.
8994 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8995 (unless sorting-type
8996 (message
8997 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8998 what)
8999 (setq sorting-type (read-char-exclusive)))
9000 (let ((dcst (downcase sorting-type))
9001 extractfun comparefun)
9002 ;; Define the appropriate functions
9003 (cond
9004 ((= dcst ?n)
9005 (setq extractfun 'string-to-number
9006 comparefun (if (= dcst sorting-type) '< '>)))
9007 ((= dcst ?a)
9008 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
9009 (lambda(x) (downcase (org-sort-remove-invisible x))))
9010 comparefun (if (= dcst sorting-type)
9011 'string<
9012 (lambda (a b) (and (not (string< a b))
9013 (not (string= a b)))))))
9014 ((= dcst ?t)
9015 (setq extractfun
9016 (lambda (x)
9017 (cond ((or (string-match org-ts-regexp x)
9018 (string-match org-ts-regexp-both x))
9019 (org-float-time
9020 (org-time-string-to-time (match-string 0 x))))
9021 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
9022 (org-hh:mm-string-to-minutes x))
9023 (t 0)))
9024 comparefun (if (= dcst sorting-type) '< '>)))
9025 (t (error "Invalid sorting type `%c'" sorting-type)))
9027 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
9028 table)
9029 (lambda (a b) (funcall comparefun (car a) (car b))))))
9032 ;;; The orgstruct minor mode
9034 ;; Define a minor mode which can be used in other modes in order to
9035 ;; integrate the org-mode structure editing commands.
9037 ;; This is really a hack, because the org-mode structure commands use
9038 ;; keys which normally belong to the major mode. Here is how it
9039 ;; works: The minor mode defines all the keys necessary to operate the
9040 ;; structure commands, but wraps the commands into a function which
9041 ;; tests if the cursor is currently at a headline or a plain list
9042 ;; item. If that is the case, the structure command is used,
9043 ;; temporarily setting many Org-mode variables like regular
9044 ;; expressions for filling etc. However, when any of those keys is
9045 ;; used at a different location, function uses `key-binding' to look
9046 ;; up if the key has an associated command in another currently active
9047 ;; keymap (minor modes, major mode, global), and executes that
9048 ;; command. There might be problems if any of the keys is otherwise
9049 ;; used as a prefix key.
9051 (defcustom orgstruct-heading-prefix-regexp ""
9052 "Regexp that matches the custom prefix of Org headlines in
9053 orgstruct(++)-mode."
9054 :group 'org
9055 :version "24.4"
9056 :package-version '(Org . "8.3")
9057 :type 'regexp)
9058 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9060 (defcustom orgstruct-setup-hook nil
9061 "Hook run after orgstruct-mode-map is filled."
9062 :group 'org
9063 :version "24.4"
9064 :package-version '(Org . "8.0")
9065 :type 'hook)
9067 (defvar orgstruct-initialized nil)
9069 (defvar org-local-vars nil
9070 "List of local variables, for use by `orgstruct-mode'.")
9072 ;;;###autoload
9073 (define-minor-mode orgstruct-mode
9074 "Toggle the minor mode `orgstruct-mode'.
9075 This mode is for using Org-mode structure commands in other
9076 modes. The following keys behave as if Org-mode were active, if
9077 the cursor is on a headline, or on a plain list item (both as
9078 defined by Org-mode)."
9079 nil " OrgStruct" (make-sparse-keymap)
9080 (funcall (if orgstruct-mode
9081 'add-to-invisibility-spec
9082 'remove-from-invisibility-spec)
9083 '(outline . t))
9084 (when orgstruct-mode
9085 (org-load-modules-maybe)
9086 (unless orgstruct-initialized
9087 (orgstruct-setup)
9088 (setq orgstruct-initialized t))))
9090 ;;;###autoload
9091 (defun turn-on-orgstruct ()
9092 "Unconditionally turn on `orgstruct-mode'."
9093 (orgstruct-mode 1))
9095 (defvar org-fb-vars nil)
9096 (make-variable-buffer-local 'org-fb-vars)
9097 (defun orgstruct++-mode (&optional arg)
9098 "Toggle `orgstruct-mode', the enhanced version of it.
9099 In addition to setting orgstruct-mode, this also exports all
9100 indentation and autofilling variables from org-mode into the
9101 buffer. It will also recognize item context in multiline items."
9102 (interactive "P")
9103 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9104 (if (< arg 1)
9105 (progn (orgstruct-mode -1)
9106 (mapc (lambda(v)
9107 (org-set-local (car v)
9108 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9109 org-fb-vars))
9110 (orgstruct-mode 1)
9111 (setq org-fb-vars nil)
9112 (unless org-local-vars
9113 (setq org-local-vars (org-get-local-variables)))
9114 (let (var val)
9115 (mapc
9116 (lambda (x)
9117 (when (string-match
9118 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9119 (symbol-name (car x)))
9120 (setq var (car x) val (nth 1 x))
9121 (push (list var `(quote ,(eval var))) org-fb-vars)
9122 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9123 org-local-vars)
9124 (org-set-local 'orgstruct-is-++ t))))
9126 (defvar orgstruct-is-++ nil
9127 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9128 (make-variable-buffer-local 'orgstruct-is-++)
9130 ;;;###autoload
9131 (defun turn-on-orgstruct++ ()
9132 "Unconditionally turn on `orgstruct++-mode'."
9133 (orgstruct++-mode 1))
9135 (defun orgstruct-error ()
9136 "Error when there is no default binding for a structure key."
9137 (interactive)
9138 (funcall (if (fboundp 'user-error)
9139 'user-error
9140 'error)
9141 "This key has no function outside structure elements"))
9143 (defun orgstruct-setup ()
9144 "Setup orgstruct keymap."
9145 (dolist (cell '((org-demote . t)
9146 (org-metaleft . t)
9147 (org-metaright . t)
9148 (org-promote . t)
9149 (org-shiftmetaleft . t)
9150 (org-shiftmetaright . t)
9151 org-backward-element
9152 org-backward-heading-same-level
9153 org-ctrl-c-ret
9154 org-ctrl-c-minus
9155 org-ctrl-c-star
9156 org-cycle
9157 org-forward-heading-same-level
9158 org-insert-heading
9159 org-insert-heading-respect-content
9160 org-kill-note-or-show-branches
9161 org-mark-subtree
9162 org-meta-return
9163 org-metadown
9164 org-metaup
9165 org-narrow-to-subtree
9166 org-promote-subtree
9167 org-reveal
9168 org-shiftdown
9169 org-shiftleft
9170 org-shiftmetadown
9171 org-shiftmetaup
9172 org-shiftright
9173 org-shifttab
9174 org-shifttab
9175 org-shiftup
9176 org-show-subtree
9177 org-sort
9178 org-up-element
9179 outline-demote
9180 outline-next-visible-heading
9181 outline-previous-visible-heading
9182 outline-promote
9183 outline-up-heading
9184 show-children))
9185 (let ((f (or (car-safe cell) cell))
9186 (disable-when-heading-prefix (cdr-safe cell)))
9187 (when (fboundp f)
9188 (let ((new-bindings))
9189 (dolist (binding (nconc (where-is-internal f org-mode-map)
9190 (where-is-internal f outline-mode-map)))
9191 (push binding new-bindings)
9192 ;; TODO use local-function-key-map
9193 (dolist (rep '(("<tab>" . "TAB")
9194 ("<return>" . "RET")
9195 ("<escape>" . "ESC")
9196 ("<delete>" . "DEL")))
9197 (setq binding (read-kbd-macro
9198 (let ((case-fold-search))
9199 (replace-regexp-in-string
9200 (regexp-quote (cdr rep))
9201 (car rep)
9202 (key-description binding)))))
9203 (pushnew binding new-bindings :test 'equal)))
9204 (dolist (binding new-bindings)
9205 (let ((key (lookup-key orgstruct-mode-map binding)))
9206 (when (or (not key) (numberp key))
9207 (ignore-errors
9208 (org-defkey orgstruct-mode-map
9209 binding
9210 (orgstruct-make-binding
9211 f binding disable-when-heading-prefix))))))))))
9212 (run-hooks 'orgstruct-setup-hook))
9214 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9215 "Create a function for binding in the structure minor mode.
9216 FUN is the command to call inside a table. KEY is the key that
9217 should be checked in for a command to execute outside of tables.
9218 Non-nil `disable-when-heading-prefix' means to disable the command
9219 if `orgstruct-heading-prefix-regexp' is not empty."
9220 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9221 (let ((nname name)
9222 (i 0))
9223 (while (fboundp (intern nname))
9224 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9225 (setq name (intern nname)))
9226 (eval
9227 (let ((bindings '((org-heading-regexp
9228 (concat "^"
9229 orgstruct-heading-prefix-regexp
9230 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9231 (org-outline-regexp
9232 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9233 (org-outline-regexp-bol
9234 (concat "^" org-outline-regexp))
9235 (outline-regexp org-outline-regexp)
9236 (outline-heading-end-regexp "\n")
9237 (outline-level 'org-outline-level)
9238 (outline-heading-alist))))
9239 `(defun ,name (arg)
9240 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9241 "Outside of structure, run the binding of `"
9242 (key-description key) "'."
9243 (when disable-when-heading-prefix
9244 (concat
9245 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9246 "back to the default binding due to limitations of Org's implementation of\n"
9247 "`" (symbol-name fun) "'.")))
9248 (interactive "p")
9249 (let* ((disable
9250 ,(and disable-when-heading-prefix
9251 '(not (string= orgstruct-heading-prefix-regexp ""))))
9252 (fallback
9253 (or disable
9254 (not
9255 (let* ,bindings
9256 (org-context-p 'headline 'item
9257 ,(when (memq fun
9258 '(org-insert-heading
9259 org-insert-heading-respect-content
9260 org-meta-return))
9261 '(when orgstruct-is-++
9262 'item-body))))))))
9263 (if fallback
9264 (let* ((orgstruct-mode)
9265 (binding
9266 (let ((key ,key))
9267 (catch 'exit
9268 (dolist
9269 (rep
9270 '(nil
9271 ("<\\([^>]*\\)tab>" . "\\1TAB")
9272 ("<\\([^>]*\\)return>" . "\\1RET")
9273 ("<\\([^>]*\\)escape>" . "\\1ESC")
9274 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9275 nil)
9276 (when rep
9277 (setq key (read-kbd-macro
9278 (let ((case-fold-search))
9279 (replace-regexp-in-string
9280 (car rep)
9281 (cdr rep)
9282 (key-description key))))))
9283 (when (key-binding key)
9284 (throw 'exit (key-binding key))))))))
9285 (if (keymapp binding)
9286 (org-set-transient-map binding)
9287 (let ((func (or binding
9288 (unless disable
9289 'orgstruct-error))))
9290 (when func
9291 (call-interactively func)))))
9292 (org-run-like-in-org-mode
9293 (lambda ()
9294 (interactive)
9295 (let* ,bindings
9296 (call-interactively ',fun)))))))))
9297 name))
9299 (defun org-contextualize-keys (alist contexts)
9300 "Return valid elements in ALIST depending on CONTEXTS.
9302 `org-agenda-custom-commands' or `org-capture-templates' are the
9303 values used for ALIST, and `org-agenda-custom-commands-contexts'
9304 or `org-capture-templates-contexts' are the associated contexts
9305 definitions."
9306 (let ((contexts
9307 ;; normalize contexts
9308 (mapcar
9309 (lambda(c) (cond ((listp (cadr c))
9310 (list (car c) (car c) (cadr c)))
9311 ((string= "" (cadr c))
9312 (list (car c) (car c) (caddr c)))
9313 (t c))) contexts))
9314 (a alist) c r s)
9315 ;; loop over all commands or templates
9316 (while (setq c (pop a))
9317 (let (vrules repl)
9318 (cond
9319 ((not (assoc (car c) contexts))
9320 (push c r))
9321 ((and (assoc (car c) contexts)
9322 (setq vrules (org-contextualize-validate-key
9323 (car c) contexts)))
9324 (mapc (lambda (vr)
9325 (when (not (equal (car vr) (cadr vr)))
9326 (setq repl vr))) vrules)
9327 (if (not repl) (push c r)
9328 (push (cadr repl) s)
9329 (push
9330 (cons (car c)
9331 (cdr (or (assoc (cadr repl) alist)
9332 (error "Undefined key `%s' as contextual replacement for `%s'"
9333 (cadr repl) (car c)))))
9334 r))))))
9335 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9336 (delq
9338 (delete-dups
9339 (mapcar (lambda (x)
9340 (let ((tpl (car x)))
9341 (when (not (delq
9343 (mapcar (lambda(y)
9344 (equal y tpl)) s))) x)))
9345 (reverse r))))))
9347 (defun org-contextualize-validate-key (key contexts)
9348 "Check CONTEXTS for agenda or capture KEY."
9349 (let (r rr res)
9350 (while (setq r (pop contexts))
9351 (mapc
9352 (lambda (rr)
9353 (when
9354 (and (equal key (car r))
9355 (if (functionp rr) (funcall rr)
9356 (or (and (eq (car rr) 'in-file)
9357 (buffer-file-name)
9358 (string-match (cdr rr) (buffer-file-name)))
9359 (and (eq (car rr) 'in-mode)
9360 (string-match (cdr rr) (symbol-name major-mode)))
9361 (and (eq (car rr) 'in-buffer)
9362 (string-match (cdr rr) (buffer-name)))
9363 (when (and (eq (car rr) 'not-in-file)
9364 (buffer-file-name))
9365 (not (string-match (cdr rr) (buffer-file-name))))
9366 (when (eq (car rr) 'not-in-mode)
9367 (not (string-match (cdr rr) (symbol-name major-mode))))
9368 (when (eq (car rr) 'not-in-buffer)
9369 (not (string-match (cdr rr) (buffer-name)))))))
9370 (push r res)))
9371 (car (last r))))
9372 (delete-dups (delq nil res))))
9374 (defun org-context-p (&rest contexts)
9375 "Check if local context is any of CONTEXTS.
9376 Possible values in the list of contexts are `table', `headline', and `item'."
9377 (let ((pos (point)))
9378 (goto-char (point-at-bol))
9379 (prog1 (or (and (memq 'table contexts)
9380 (looking-at "[ \t]*|"))
9381 (and (memq 'headline contexts)
9382 (looking-at org-outline-regexp))
9383 (and (memq 'item contexts)
9384 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9385 (and (memq 'item-body contexts)
9386 (org-in-item-p)))
9387 (goto-char pos))))
9389 (defun org-get-local-variables ()
9390 "Return a list of all local variables in an Org mode buffer."
9391 (let (varlist)
9392 (with-current-buffer (get-buffer-create "*Org tmp*")
9393 (erase-buffer)
9394 (org-mode)
9395 (setq varlist (buffer-local-variables)))
9396 (kill-buffer "*Org tmp*")
9397 (delq nil
9398 (mapcar
9399 (lambda (x)
9400 (setq x
9401 (if (symbolp x)
9402 (list x)
9403 (list (car x) (cdr x))))
9404 (if (and (not (get (car x) 'org-state))
9405 (string-match
9406 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9407 (symbol-name (car x))))
9408 x nil))
9409 varlist))))
9411 (defun org-clone-local-variables (from-buffer &optional regexp)
9412 "Clone local variables from FROM-BUFFER.
9413 Optional argument REGEXP selects variables to clone."
9414 (mapc
9415 (lambda (pair)
9416 (and (symbolp (car pair))
9417 (or (null regexp)
9418 (string-match regexp (symbol-name (car pair))))
9419 (set (make-local-variable (car pair))
9420 (cdr pair))))
9421 (buffer-local-variables from-buffer)))
9423 ;;;###autoload
9424 (defun org-run-like-in-org-mode (cmd)
9425 "Run a command, pretending that the current buffer is in Org-mode.
9426 This will temporarily bind local variables that are typically bound in
9427 Org-mode to the values they have in Org-mode, and then interactively
9428 call CMD."
9429 (org-load-modules-maybe)
9430 (unless org-local-vars
9431 (setq org-local-vars (org-get-local-variables)))
9432 (let (binds)
9433 (dolist (var org-local-vars)
9434 (when (or (not (boundp (car var)))
9435 (eq (symbol-value (car var))
9436 (default-value (car var))))
9437 (push (list (car var) `(quote ,(cadr var))) binds)))
9438 (eval `(let ,binds
9439 (call-interactively (quote ,cmd))))))
9441 (defun org-get-category (&optional pos force-refresh)
9442 "Get the category applying to position POS."
9443 (save-match-data
9444 (if force-refresh (org-refresh-category-properties))
9445 (let ((pos (or pos (point))))
9446 (or (get-text-property pos 'org-category)
9447 (progn (org-refresh-category-properties)
9448 (get-text-property pos 'org-category))))))
9450 ;;; Refresh properties
9452 (defun org-refresh-properties (dprop tprop)
9453 "Refresh buffer text properties.
9454 DPROP is the drawer property and TPROP is either the
9455 corresponding text property to set, or an alist with each element
9456 being a text property (as a symbol) and a function to apply to
9457 the value of the drawer property."
9458 (let ((case-fold-search t)
9459 (inhibit-read-only t))
9460 (org-with-silent-modifications
9461 (save-excursion
9462 (save-restriction
9463 (widen)
9464 (goto-char (point-min))
9465 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9466 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9468 (defun org-refresh-property (tprop p)
9469 "Refresh the buffer text property TPROP from the drawer property P.
9470 The refresh happens only for the current tree (not subtree)."
9471 (save-excursion
9472 (org-back-to-heading t)
9473 ;; tprop is a text property symbol
9474 (if (symbolp tprop)
9475 (put-text-property
9476 (point) (or (outline-next-heading) (point-max)) tprop p)
9477 ;; tprop is an alist with (properties . function) elements
9478 (mapc (lambda(al)
9479 (save-excursion
9480 (put-text-property
9481 (point-at-bol) (or (outline-next-heading) (point-max))
9482 (car al)
9483 (funcall (cdr al) p))))
9484 tprop))))
9486 (defun org-refresh-category-properties ()
9487 "Refresh category text properties in the buffer."
9488 (let ((case-fold-search t)
9489 (inhibit-read-only t)
9490 (def-cat (cond
9491 ((null org-category)
9492 (if buffer-file-name
9493 (file-name-sans-extension
9494 (file-name-nondirectory buffer-file-name))
9495 "???"))
9496 ((symbolp org-category) (symbol-name org-category))
9497 (t org-category)))
9498 beg end cat pos optionp)
9499 (org-with-silent-modifications
9500 (save-excursion
9501 (save-restriction
9502 (widen)
9503 (goto-char (point-min))
9504 (put-text-property (point) (point-max) 'org-category def-cat)
9505 (while (re-search-forward
9506 "^[ \t]*\\(\\(?:#\\+\\|:\\)CATEGORY:\\)\\(.*\\)" nil t)
9507 (setq pos (match-end 0)
9508 optionp (equal (char-after (match-beginning 0)) ?#)
9509 cat (org-trim (match-string 2)))
9510 (if optionp
9511 (setq beg (point-at-bol) end (point-max))
9512 (org-back-to-heading t)
9513 (setq beg (point) end (org-end-of-subtree t t)))
9514 (put-text-property beg end 'org-category cat)
9515 (goto-char pos)))))))
9517 (defun org-refresh-stats-properties ()
9518 "Refresh stats text properties in the buffer."
9519 (let (stats)
9520 (org-with-silent-modifications
9521 (save-excursion
9522 (save-restriction
9523 (widen)
9524 (goto-char (point-min))
9525 (while (re-search-forward
9526 (concat org-outline-regexp-bol ".*"
9527 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9528 nil t)
9529 (setq stats (cond ((equal (match-string 3) "0") 0)
9530 ((match-string 2)
9531 (/ (* (string-to-number (match-string 2)) 100)
9532 (string-to-number (match-string 3))))
9533 (t (string-to-number (match-string 1)))))
9534 (org-back-to-heading t)
9535 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9536 'org-stats stats)))))))
9538 (defun org-refresh-effort-properties ()
9539 "Refresh effort properties"
9540 (org-refresh-properties
9541 org-effort-property
9542 '((effort . identity)
9543 (effort-minutes . org-duration-string-to-minutes))))
9545 ;;;; Link Stuff
9547 ;;; Link abbreviations
9549 (defun org-link-expand-abbrev (link)
9550 "Apply replacements as defined in `org-link-abbrev-alist'."
9551 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9552 (let* ((key (match-string 1 link))
9553 (as (or (assoc key org-link-abbrev-alist-local)
9554 (assoc key org-link-abbrev-alist)))
9555 (tag (and (match-end 2) (match-string 3 link)))
9556 rpl)
9557 (if (not as)
9558 link
9559 (setq rpl (cdr as))
9560 (cond
9561 ((symbolp rpl) (funcall rpl tag))
9562 ((string-match "%(\\([^)]+\\))" rpl)
9563 (replace-match
9564 (save-match-data
9565 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9566 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9567 ((string-match "%h" rpl)
9568 (replace-match (url-hexify-string (or tag "")) t t rpl))
9569 (t (concat rpl tag)))))
9570 link))
9572 ;;; Storing and inserting links
9574 (defvar org-insert-link-history nil
9575 "Minibuffer history for links inserted with `org-insert-link'.")
9577 (defvar org-stored-links nil
9578 "Contains the links stored with `org-store-link'.")
9580 (defvar org-store-link-plist nil
9581 "Plist with info about the most recently link created with `org-store-link'.")
9583 (defvar org-link-protocols nil
9584 "Link protocols added to Org-mode using `org-add-link-type'.")
9586 (defvar org-store-link-functions nil
9587 "List of functions that are called to create and store a link.
9588 Each function will be called in turn until one returns a non-nil
9589 value. Each function should check if it is responsible for creating
9590 this link (for example by looking at the major mode).
9591 If not, it must exit and return nil.
9592 If yes, it should return a non-nil value after a calling
9593 `org-store-link-props' with a list of properties and values.
9594 Special properties are:
9596 :type The link prefix, like \"http\". This must be given.
9597 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9598 This is obligatory as well.
9599 :description Optional default description for the second pair
9600 of brackets in an Org-mode link. The user can still change
9601 this when inserting this link into an Org-mode buffer.
9603 In addition to these, any additional properties can be specified
9604 and then used in capture templates.")
9606 (defun org-add-link-type (type &optional follow export)
9607 "Add TYPE to the list of `org-link-types'.
9608 Re-compute all regular expressions depending on `org-link-types'
9610 FOLLOW and EXPORT are two functions.
9612 FOLLOW should take the link path as the single argument and do whatever
9613 is necessary to follow the link, for example find a file or display
9614 a mail message.
9616 EXPORT should format the link path for export to one of the export formats.
9617 It should be a function accepting three arguments:
9619 path the path of the link, the text after the prefix (like \"http:\")
9620 desc the description of the link, if any, or a description added by
9621 org-export-normalize-links if there is none
9622 format the export format, a symbol like `html' or `latex' or `ascii'..
9624 The function may use the FORMAT information to return different values
9625 depending on the format. The return value will be put literally into
9626 the exported file. If the return value is nil, this means Org should
9627 do what it normally does with links which do not have EXPORT defined.
9629 Org-mode has a built-in default for exporting links. If you are happy with
9630 this default, there is no need to define an export function for the link
9631 type. For a simple example of an export function, see `org-bbdb.el'."
9632 (add-to-list 'org-link-types type t)
9633 (org-make-link-regexps)
9634 (if (assoc type org-link-protocols)
9635 (setcdr (assoc type org-link-protocols) (list follow export))
9636 (push (list type follow export) org-link-protocols)))
9638 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9639 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9641 ;;;###autoload
9642 (defun org-store-link (arg)
9643 "\\<org-mode-map>Store an org-link to the current location.
9644 This link is added to `org-stored-links' and can later be inserted
9645 into an org-buffer with \\[org-insert-link].
9647 For some link types, a prefix arg is interpreted.
9648 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9649 For file links, arg negates `org-context-in-file-links'.
9651 A double prefix arg force skipping storing functions that are not
9652 part of Org's core.
9654 A triple prefix arg force storing a link for each line in the
9655 active region."
9656 (interactive "P")
9657 (org-load-modules-maybe)
9658 (if (and (equal arg '(64)) (org-region-active-p))
9659 (save-excursion
9660 (let ((end (region-end)))
9661 (goto-char (region-beginning))
9662 (set-mark (point))
9663 (while (< (point-at-eol) end)
9664 (move-end-of-line 1) (activate-mark)
9665 (let (current-prefix-arg)
9666 (call-interactively 'org-store-link))
9667 (move-beginning-of-line 2)
9668 (set-mark (point)))))
9669 (org-with-limited-levels
9670 (setq org-store-link-plist nil)
9671 (let (link cpltxt desc description search
9672 txt custom-id agenda-link sfuns sfunsn)
9673 (cond
9675 ;; Store a link using an external link type
9676 ((and (not (equal arg '(16)))
9677 (setq sfuns
9678 (delq
9679 nil (mapcar (lambda (f)
9680 (let (fs) (if (funcall f) (push f fs))))
9681 org-store-link-functions))
9682 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9683 (or (and (cdr sfuns)
9684 (funcall (intern
9685 (completing-read
9686 "Which function for creating the link? "
9687 sfunsn nil t (car sfunsn)))))
9688 (funcall (caar sfuns)))
9689 (setq link (plist-get org-store-link-plist :link)
9690 desc (or (plist-get org-store-link-plist
9691 :description) link))))
9693 ;; Store a link from a source code buffer
9694 ((org-src-edit-buffer-p)
9695 (let (label gc)
9696 (while (or (not label)
9697 (save-excursion
9698 (save-restriction
9699 (widen)
9700 (goto-char (point-min))
9701 (re-search-forward
9702 (regexp-quote (format org-coderef-label-format label))
9703 nil t))))
9704 (when label (message "Label exists already") (sit-for 2))
9705 (setq label (read-string "Code line label: " label)))
9706 (end-of-line 1)
9707 (setq link (format org-coderef-label-format label))
9708 (setq gc (- 79 (length link)))
9709 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9710 (insert link)
9711 (setq link (concat "(" label ")") desc nil)))
9713 ;; We are in the agenda, link to referenced location
9714 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9715 (let ((m (or (get-text-property (point) 'org-hd-marker)
9716 (get-text-property (point) 'org-marker))))
9717 (when m
9718 (org-with-point-at m
9719 (setq agenda-link
9720 (if (org-called-interactively-p 'any)
9721 (call-interactively 'org-store-link)
9722 (org-store-link nil)))))))
9724 ((eq major-mode 'calendar-mode)
9725 (let ((cd (calendar-cursor-to-date)))
9726 (setq link
9727 (format-time-string
9728 (car org-time-stamp-formats)
9729 (apply 'encode-time
9730 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9731 nil nil nil))))
9732 (org-store-link-props :type "calendar" :date cd)))
9734 ((eq major-mode 'help-mode)
9735 (setq link (concat "help:" (save-excursion
9736 (goto-char (point-min))
9737 (looking-at "^[^ ]+")
9738 (match-string 0))))
9739 (org-store-link-props :type "help"))
9741 ((eq major-mode 'w3-mode)
9742 (setq cpltxt (if (and (buffer-name)
9743 (not (string-match "Untitled" (buffer-name))))
9744 (buffer-name)
9745 (url-view-url t))
9746 link (url-view-url t))
9747 (org-store-link-props :type "w3" :url (url-view-url t)))
9749 ((eq major-mode 'image-mode)
9750 (setq cpltxt (concat "file:"
9751 (abbreviate-file-name buffer-file-name))
9752 link cpltxt)
9753 (org-store-link-props :type "image" :file buffer-file-name))
9755 ;; In dired, store a link to the file of the current line
9756 ((derived-mode-p 'dired-mode)
9757 (let ((file (dired-get-filename nil t)))
9758 (setq file (if file
9759 (abbreviate-file-name
9760 (expand-file-name (dired-get-filename nil t)))
9761 ;; otherwise, no file so use current directory.
9762 default-directory))
9763 (setq cpltxt (concat "file:" file)
9764 link cpltxt)))
9766 ((setq search (run-hook-with-args-until-success
9767 'org-create-file-search-functions))
9768 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9769 "::" search))
9770 (setq cpltxt (or description link)))
9772 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9773 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9774 (cond
9775 ;; Store a link using the target at point
9776 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9777 (setq cpltxt
9778 (concat "file:"
9779 (abbreviate-file-name
9780 (buffer-file-name (buffer-base-buffer)))
9781 "::" (match-string 1))
9782 link cpltxt))
9783 ((and (featurep 'org-id)
9784 (or (eq org-id-link-to-org-use-id t)
9785 (and (org-called-interactively-p 'any)
9786 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9787 (and (eq org-id-link-to-org-use-id
9788 'create-if-interactive-and-no-custom-id)
9789 (not custom-id))))
9790 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9791 ;; Store a link using the ID at point
9792 (setq link (condition-case nil
9793 (prog1 (org-id-store-link)
9794 (setq desc (or (plist-get org-store-link-plist
9795 :description)
9796 "")))
9797 (error
9798 ;; Probably before first headline, link only to file
9799 (concat "file:"
9800 (abbreviate-file-name
9801 (buffer-file-name (buffer-base-buffer))))))))
9803 ;; Just link to current headline
9804 (setq cpltxt (concat "file:"
9805 (abbreviate-file-name
9806 (buffer-file-name (buffer-base-buffer)))))
9807 ;; Add a context search string
9808 (when (org-xor org-context-in-file-links arg)
9809 (let* ((ee (org-element-at-point))
9810 (et (org-element-type ee))
9811 (ev (plist-get (cadr ee) :value))
9812 (ek (plist-get (cadr ee) :key))
9813 (eok (and (stringp ek) (string-match "name" ek))))
9814 (setq txt (cond
9815 ((org-at-heading-p) nil)
9816 ((and (eq et 'keyword) eok) ev)
9817 ((org-region-active-p)
9818 (buffer-substring (region-beginning) (region-end)))))
9819 (when (or (null txt) (string-match "\\S-" txt))
9820 (setq cpltxt
9821 (concat cpltxt "::"
9822 (condition-case nil
9823 (org-make-org-heading-search-string txt)
9824 (error "")))
9825 desc (or (and (eq et 'keyword) eok ev)
9826 (nth 4 (ignore-errors (org-heading-components)))
9827 "NONE")))))
9828 (if (string-match "::\\'" cpltxt)
9829 (setq cpltxt (substring cpltxt 0 -2)))
9830 (setq link cpltxt))))
9832 ((buffer-file-name (buffer-base-buffer))
9833 ;; Just link to this file here.
9834 (setq cpltxt (concat "file:"
9835 (abbreviate-file-name
9836 (buffer-file-name (buffer-base-buffer)))))
9837 ;; Add a context string.
9838 (when (org-xor org-context-in-file-links arg)
9839 (setq txt (if (org-region-active-p)
9840 (buffer-substring (region-beginning) (region-end))
9841 (buffer-substring (point-at-bol) (point-at-eol))))
9842 ;; Only use search option if there is some text.
9843 (when (string-match "\\S-" txt)
9844 (setq cpltxt
9845 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9846 desc "NONE")))
9847 (setq link cpltxt))
9849 ((org-called-interactively-p 'interactive)
9850 (user-error "No method for storing a link from this buffer"))
9852 (t (setq link nil)))
9854 ;; We're done setting link and desc, clean up
9855 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9856 (setq link (or link cpltxt)
9857 desc (or desc cpltxt))
9858 (cond ((equal desc "NONE") (setq desc nil))
9859 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9860 (let ((d0 (match-string 3 desc))
9861 (p0 (match-string 5 desc)))
9862 (setq desc
9863 (replace-regexp-in-string
9864 org-bracket-link-regexp
9865 (concat (or p0 d0)
9866 (if (equal (length (match-string 0 desc))
9867 (length desc)) "*" "")) desc)))))
9869 ;; Return the link
9870 (if (not (and (or (org-called-interactively-p 'any)
9871 executing-kbd-macro) link))
9872 (or agenda-link (and link (org-make-link-string link desc)))
9873 (push (list link desc) org-stored-links)
9874 (message "Stored: %s" (or desc link))
9875 (when custom-id
9876 (setq link (concat "file:" (abbreviate-file-name
9877 (buffer-file-name)) "::#" custom-id))
9878 (push (list link desc) org-stored-links))
9879 (car org-stored-links))))))
9881 (defun org-store-link-props (&rest plist)
9882 "Store link properties, extract names and addresses."
9883 (let (x adr)
9884 (when (setq x (plist-get plist :from))
9885 (setq adr (mail-extract-address-components x))
9886 (setq plist (plist-put plist :fromname (car adr)))
9887 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9888 (when (setq x (plist-get plist :to))
9889 (setq adr (mail-extract-address-components x))
9890 (setq plist (plist-put plist :toname (car adr)))
9891 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9892 (let ((from (plist-get plist :from))
9893 (to (plist-get plist :to)))
9894 (when (and from to org-from-is-user-regexp)
9895 (setq plist
9896 (plist-put plist :fromto
9897 (if (string-match org-from-is-user-regexp from)
9898 (concat "to %t")
9899 (concat "from %f"))))))
9900 (setq org-store-link-plist plist))
9902 (defun org-add-link-props (&rest plist)
9903 "Add these properties to the link property list."
9904 (let (key value)
9905 (while plist
9906 (setq key (pop plist) value (pop plist))
9907 (setq org-store-link-plist
9908 (plist-put org-store-link-plist key value)))))
9910 (defun org-email-link-description (&optional fmt)
9911 "Return the description part of an email link.
9912 This takes information from `org-store-link-plist' and formats it
9913 according to FMT (default from `org-email-link-description-format')."
9914 (setq fmt (or fmt org-email-link-description-format))
9915 (let* ((p org-store-link-plist)
9916 (to (plist-get p :toaddress))
9917 (from (plist-get p :fromaddress))
9918 (table
9919 (list
9920 (cons "%c" (plist-get p :fromto))
9921 (cons "%F" (plist-get p :from))
9922 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9923 (cons "%T" (plist-get p :to))
9924 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9925 (cons "%s" (plist-get p :subject))
9926 (cons "%d" (plist-get p :date))
9927 (cons "%m" (plist-get p :message-id)))))
9928 (when (string-match "%c" fmt)
9929 ;; Check if the user wrote this message
9930 (if (and org-from-is-user-regexp from to
9931 (save-match-data (string-match org-from-is-user-regexp from)))
9932 (setq fmt (replace-match "to %t" t t fmt))
9933 (setq fmt (replace-match "from %f" t t fmt))))
9934 (org-replace-escapes fmt table)))
9936 (defun org-make-org-heading-search-string (&optional string)
9937 "Make search string for the current headline or STRING."
9938 (let ((s (or string
9939 (and (derived-mode-p 'org-mode)
9940 (save-excursion
9941 (org-back-to-heading t)
9942 (org-element-property :raw-value (org-element-at-point))))))
9943 (lines org-context-in-file-links))
9944 (or string (setq s (concat "*" s))) ; Add * for headlines
9945 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9946 (when (and string (integerp lines) (> lines 0))
9947 (let ((slines (org-split-string s "\n")))
9948 (when (< lines (length slines))
9949 (setq s (mapconcat
9950 'identity
9951 (reverse (nthcdr (- (length slines) lines)
9952 (reverse slines))) "\n")))))
9953 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9955 (defun org-make-link-string (link &optional description)
9956 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9957 (unless (string-match "\\S-" link)
9958 (error "Empty link"))
9959 (when (and description
9960 (stringp description)
9961 (not (string-match "\\S-" description)))
9962 (setq description nil))
9963 (when (stringp description)
9964 ;; Remove brackets from the description, they are fatal.
9965 (while (string-match "\\[" description)
9966 (setq description (replace-match "{" t t description)))
9967 (while (string-match "\\]" description)
9968 (setq description (replace-match "}" t t description))))
9969 (when (equal link description)
9970 ;; No description needed, it is identical
9971 (setq description nil))
9972 (when (and (not description)
9973 (not (string-match (org-image-file-name-regexp) link))
9974 (not (equal link (org-link-escape link))))
9975 (setq description (org-extract-attributes link)))
9976 (setq link
9977 (cond ((string-match (org-image-file-name-regexp) link) link)
9978 ((string-match org-link-types-re link)
9979 (concat (match-string 1 link)
9980 (org-link-escape (substring link (match-end 1)))))
9981 (t (org-link-escape link))))
9982 (concat "[[" link "]"
9983 (if description (concat "[" description "]") "")
9984 "]"))
9986 (defconst org-link-escape-chars
9987 ;;%20 %5B %5D
9988 '(?\ ?\[ ?\])
9989 "List of characters that should be escaped in a link when stored to Org.
9990 This is the list that is used for internal purposes.")
9992 (defconst org-link-escape-chars-browser
9993 ;;%20 %22
9994 '(?\ ?\")
9995 "List of characters to be escaped before handing over to the browser.
9996 If you consider using this constant then you probably want to use
9997 the function `org-link-escape-browser' instead. See there why
9998 this constant is a candidate to be removed once Org drops support
9999 for Emacs 24.1 and 24.2.")
10001 (defun org-link-escape (text &optional table merge)
10002 "Return percent escaped representation of TEXT.
10003 TEXT is a string with the text to escape.
10004 Optional argument TABLE is a list with characters that should be
10005 escaped. When nil, `org-link-escape-chars' is used.
10006 If optional argument MERGE is set, merge TABLE into
10007 `org-link-escape-chars'."
10008 ;; Don't escape chars in internal links
10009 (if (string-match "^\\*[[:alnum:]]+" text)
10010 text
10011 (cond
10012 ((and table merge)
10013 (mapc (lambda (defchr)
10014 (unless (member defchr table)
10015 (setq table (cons defchr table))))
10016 org-link-escape-chars))
10017 ((null table)
10018 (setq table org-link-escape-chars)))
10019 (mapconcat
10020 (lambda (char)
10021 (if (or (member char table)
10022 (and (or (< char 32) (= char ?\%) (> char 126))
10023 org-url-hexify-p))
10024 (mapconcat (lambda (sequence-element)
10025 (format "%%%.2X" sequence-element))
10026 (or (encode-coding-char char 'utf-8)
10027 (error "Unable to percent escape character: %s"
10028 (char-to-string char))) "")
10029 (char-to-string char))) text "")))
10031 (defun org-link-escape-browser (text)
10032 "Escape some characters before handing over to the browser.
10033 This function is a candidate to be removed together with the
10034 constant `org-link-escape-chars-browser' once Org drops support
10035 for Emacs 24.1 and 24.2. All calls to this function will have to
10036 be replaced with `url-encode-url' which is available since Emacs
10037 24.3.1."
10038 ;; Example with the Org link
10039 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10040 ;; to open the browser with +subject:"Release 8.2" filled into the
10041 ;; query field: In this case the variable TEXT contains the
10042 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10043 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10044 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10045 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10046 (if (fboundp 'url-encode-url)
10047 (url-encode-url text)
10048 (if (org-string-match-p
10049 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10050 text)
10051 (org-link-escape text org-link-escape-chars-browser)
10052 text)))
10054 (defun org-link-unescape (str)
10055 "Unhex hexified Unicode strings as returned from the JavaScript function
10056 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10057 (unless (and (null str) (string= "" str))
10058 (let ((pos 0) (case-fold-search t) unhexed)
10059 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10060 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10061 (setq str (replace-match unhexed t t str))
10062 (setq pos (+ pos (length unhexed))))))
10063 str)
10065 (defun org-link-unescape-compound (hex)
10066 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10067 Note: this function also decodes single byte encodings like
10068 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10069 (save-match-data
10070 (let* ((bytes (cdr (split-string hex "%")))
10071 (ret "")
10072 (eat 0)
10073 (sum 0))
10074 (while bytes
10075 (let* ((val (string-to-number (pop bytes) 16))
10076 (shift-xor
10077 (if (= 0 eat)
10078 (cond
10079 ((>= val 252) (cons 6 252))
10080 ((>= val 248) (cons 5 248))
10081 ((>= val 240) (cons 4 240))
10082 ((>= val 224) (cons 3 224))
10083 ((>= val 192) (cons 2 192))
10084 (t (cons 0 0)))
10085 (cons 6 128))))
10086 (if (>= val 192) (setq eat (car shift-xor)))
10087 (setq val (logxor val (cdr shift-xor)))
10088 (setq sum (+ (lsh sum (car shift-xor)) val))
10089 (if (> eat 0) (setq eat (- eat 1)))
10090 (cond
10091 ((= 0 eat) ;multi byte
10092 (setq ret (concat ret (org-char-to-string sum)))
10093 (setq sum 0))
10094 ((not bytes) ; single byte(s)
10095 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10096 ret)))
10098 (defun org-link-unescape-single-byte-sequence (hex)
10099 "Unhexify hex-encoded single byte character sequences."
10100 (mapconcat (lambda (byte)
10101 (char-to-string (string-to-number byte 16)))
10102 (cdr (split-string hex "%")) ""))
10104 (defun org-xor (a b)
10105 "Exclusive or."
10106 (if a (not b) b))
10108 (defun org-fixup-message-id-for-http (s)
10109 "Replace special characters in a message id, so it can be used in an http query."
10110 (when (string-match "%" s)
10111 (setq s (mapconcat (lambda (c)
10112 (if (eq c ?%)
10113 "%25"
10114 (char-to-string c)))
10115 s "")))
10116 (while (string-match "<" s)
10117 (setq s (replace-match "%3C" t t s)))
10118 (while (string-match ">" s)
10119 (setq s (replace-match "%3E" t t s)))
10120 (while (string-match "@" s)
10121 (setq s (replace-match "%40" t t s)))
10124 (defun org-link-prettify (link)
10125 "Return a human-readable representation of LINK.
10126 The car of LINK must be a raw link.
10127 The cdr of LINK must be either a link description or nil."
10128 (let ((desc (or (cadr link) "<no description>")))
10129 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10130 "<" (car link) ">")))
10132 ;;;###autoload
10133 (defun org-insert-link-global ()
10134 "Insert a link like Org-mode does.
10135 This command can be called in any mode to insert a link in Org-mode syntax."
10136 (interactive)
10137 (org-load-modules-maybe)
10138 (org-run-like-in-org-mode 'org-insert-link))
10140 (defun org-insert-all-links (arg &optional pre post)
10141 "Insert all links in `org-stored-links'.
10142 When a universal prefix, do not delete the links from `org-stored-links'.
10143 When `ARG' is a number, insert the last N link(s).
10144 `PRE' and `POST' are optional arguments to define a string to
10145 prepend or to append."
10146 (interactive "P")
10147 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10148 (links (copy-seq org-stored-links))
10149 (pr (or pre "- "))
10150 (po (or post "\n"))
10151 (cnt 1) l)
10152 (if (null org-stored-links)
10153 (message "No link to insert")
10154 (while (and (or (listp arg) (>= arg cnt))
10155 (setq l (if (listp arg)
10156 (pop links)
10157 (pop org-stored-links))))
10158 (setq cnt (1+ cnt))
10159 (insert pr)
10160 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10161 (insert po)))))
10163 (defun org-insert-last-stored-link (arg)
10164 "Insert the last link stored in `org-stored-links'."
10165 (interactive "p")
10166 (org-insert-all-links arg "" "\n"))
10168 (defun org-link-fontify-links-to-this-file ()
10169 "Fontify links to the current file in `org-stored-links'."
10170 (let ((f (buffer-file-name)) a b)
10171 (setq a (mapcar (lambda(l)
10172 (let ((ll (car l)))
10173 (when (and (string-match "^file:\\(.+\\)::" ll)
10174 (equal f (expand-file-name (match-string 1 ll))))
10175 ll)))
10176 org-stored-links))
10177 (when (featurep 'org-id)
10178 (setq b (mapcar (lambda(l)
10179 (let ((ll (car l)))
10180 (when (and (string-match "^id:\\(.+\\)$" ll)
10181 (equal f (expand-file-name
10182 (or (org-id-find-id-file
10183 (match-string 1 ll)) ""))))
10184 ll)))
10185 org-stored-links)))
10186 (mapcar (lambda(l)
10187 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10188 (delq nil (append a b)))))
10190 (defvar org-link-links-in-this-file nil)
10191 (defun org-insert-link (&optional complete-file link-location default-description)
10192 "Insert a link. At the prompt, enter the link.
10194 Completion can be used to insert any of the link protocol prefixes like
10195 http or ftp in use.
10197 The history can be used to select a link previously stored with
10198 `org-store-link'. When the empty string is entered (i.e. if you just
10199 press RET at the prompt), the link defaults to the most recently
10200 stored link. As SPC triggers completion in the minibuffer, you need to
10201 use M-SPC or C-q SPC to force the insertion of a space character.
10203 You will also be prompted for a description, and if one is given, it will
10204 be displayed in the buffer instead of the link.
10206 If there is already a link at point, this command will allow you to edit link
10207 and description parts.
10209 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10210 be selected using completion. The path to the file will be relative to the
10211 current directory if the file is in the current directory or a subdirectory.
10212 Otherwise, the link will be the absolute path as completed in the minibuffer
10213 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10214 option `org-link-file-path-type'.
10216 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10217 the current directory or below.
10219 With three \\[universal-argument] prefixes, negate the meaning of
10220 `org-keep-stored-link-after-insertion'.
10222 If `org-make-link-description-function' is non-nil, this function will be
10223 called with the link target, and the result will be the default
10224 link description.
10226 If the LINK-LOCATION parameter is non-nil, this value will be
10227 used as the link location instead of reading one interactively.
10229 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10230 be used as the default description."
10231 (interactive "P")
10232 (let* ((wcf (current-window-configuration))
10233 (origbuf (current-buffer))
10234 (region (if (org-region-active-p)
10235 (buffer-substring (region-beginning) (region-end))))
10236 (remove (and region (list (region-beginning) (region-end))))
10237 (desc region)
10238 tmphist ; byte-compile incorrectly complains about this
10239 (link link-location)
10240 (abbrevs org-link-abbrev-alist-local)
10241 entry file all-prefixes auto-desc)
10242 (cond
10243 (link-location) ; specified by arg, just use it.
10244 ((org-in-regexp org-bracket-link-regexp 1)
10245 ;; We do have a link at point, and we are going to edit it.
10246 (setq remove (list (match-beginning 0) (match-end 0)))
10247 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10248 (setq link (read-string "Link: "
10249 (org-link-unescape
10250 (org-match-string-no-properties 1)))))
10251 ((or (org-in-regexp org-angle-link-re)
10252 (org-in-regexp org-plain-link-re))
10253 ;; Convert to bracket link
10254 (setq remove (list (match-beginning 0) (match-end 0))
10255 link (read-string "Link: "
10256 (org-remove-angle-brackets (match-string 0)))))
10257 ((member complete-file '((4) (16)))
10258 ;; Completing read for file names.
10259 (setq link (org-file-complete-link complete-file)))
10261 ;; Read link, with completion for stored links.
10262 (org-link-fontify-links-to-this-file)
10263 (org-switch-to-buffer-other-window "*Org Links*")
10264 (with-current-buffer "*Org Links*"
10265 (erase-buffer)
10266 (insert "Insert a link.
10267 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10268 (when org-stored-links
10269 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10270 (insert (mapconcat 'org-link-prettify
10271 (reverse org-stored-links) "\n")))
10272 (goto-char (point-min)))
10273 (let ((cw (selected-window)))
10274 (select-window (get-buffer-window "*Org Links*" 'visible))
10275 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10276 (unless (pos-visible-in-window-p (point-max))
10277 (org-fit-window-to-buffer))
10278 (and (window-live-p cw) (select-window cw)))
10279 ;; Fake a link history, containing the stored links.
10280 (setq tmphist (append (mapcar 'car org-stored-links)
10281 org-insert-link-history))
10282 (setq all-prefixes (append (mapcar 'car abbrevs)
10283 (mapcar 'car org-link-abbrev-alist)
10284 org-link-types))
10285 (unwind-protect
10286 (progn
10287 (setq link
10288 (org-completing-read
10289 "Link: "
10290 (append
10291 (mapcar (lambda (x) (concat x ":"))
10292 all-prefixes)
10293 (mapcar 'car org-stored-links))
10294 nil nil nil
10295 'tmphist
10296 (caar org-stored-links)))
10297 (if (not (string-match "\\S-" link))
10298 (user-error "No link selected"))
10299 (mapc (lambda(l)
10300 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10301 org-stored-links)
10302 (if (or (member link all-prefixes)
10303 (and (equal ":" (substring link -1))
10304 (member (substring link 0 -1) all-prefixes)
10305 (setq link (substring link 0 -1))))
10306 (setq link (with-current-buffer origbuf
10307 (org-link-try-special-completion link)))))
10308 (set-window-configuration wcf)
10309 (kill-buffer "*Org Links*"))
10310 (setq entry (assoc link org-stored-links))
10311 (or entry (push link org-insert-link-history))
10312 (setq desc (or desc (nth 1 entry)))))
10314 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10315 (not org-keep-stored-link-after-insertion))
10316 (setq org-stored-links (delq (assoc link org-stored-links)
10317 org-stored-links)))
10319 (if (and (string-match org-plain-link-re link)
10320 (not (string-match org-ts-regexp link)))
10321 ;; URL-like link, normalize the use of angular brackets.
10322 (setq link (org-remove-angle-brackets link)))
10324 ;; Check if we are linking to the current file with a search
10325 ;; option If yes, simplify the link by using only the search
10326 ;; option.
10327 (when (and buffer-file-name
10328 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10329 (let* ((path (match-string 1 link))
10330 (case-fold-search nil)
10331 (search (match-string 2 link)))
10332 (save-match-data
10333 (if (equal (file-truename buffer-file-name) (file-truename path))
10334 ;; We are linking to this same file, with a search option
10335 (setq link search)))))
10337 ;; Check if we can/should use a relative path. If yes, simplify the link
10338 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10339 (let* ((type (match-string 1 link))
10340 (path (match-string 2 link))
10341 (origpath path)
10342 (case-fold-search nil))
10343 (cond
10344 ((or (eq org-link-file-path-type 'absolute)
10345 (equal complete-file '(16)))
10346 (setq path (abbreviate-file-name (expand-file-name path))))
10347 ((eq org-link-file-path-type 'noabbrev)
10348 (setq path (expand-file-name path)))
10349 ((eq org-link-file-path-type 'relative)
10350 (setq path (file-relative-name path)))
10352 (save-match-data
10353 (if (string-match (concat "^" (regexp-quote
10354 (expand-file-name
10355 (file-name-as-directory
10356 default-directory))))
10357 (expand-file-name path))
10358 ;; We are linking a file with relative path name.
10359 (setq path (substring (expand-file-name path)
10360 (match-end 0)))
10361 (setq path (abbreviate-file-name (expand-file-name path)))))))
10362 (setq link (concat type path))
10363 (if (equal desc origpath)
10364 (setq desc path))))
10366 (if org-make-link-description-function
10367 (setq desc
10368 (or (condition-case nil
10369 (funcall org-make-link-description-function link desc)
10370 (error (progn (message "Can't get link description from `%s'"
10371 (symbol-name org-make-link-description-function))
10372 (sit-for 2) nil)))
10373 (read-string "Description: " default-description)))
10374 (if default-description (setq desc default-description)
10375 (setq desc (or (and auto-desc desc)
10376 (read-string "Description: " desc)))))
10378 (unless (string-match "\\S-" desc) (setq desc nil))
10379 (if remove (apply 'delete-region remove))
10380 (insert (org-make-link-string link desc))))
10382 (defun org-link-try-special-completion (type)
10383 "If there is completion support for link type TYPE, offer it."
10384 (let ((fun (intern (concat "org-" type "-complete-link"))))
10385 (if (functionp fun)
10386 (funcall fun)
10387 (read-string "Link (no completion support): " (concat type ":")))))
10389 (defun org-file-complete-link (&optional arg)
10390 "Create a file link using completion."
10391 (let (file link)
10392 (setq file (org-iread-file-name "File: "))
10393 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10394 (pwd1 (file-name-as-directory (abbreviate-file-name
10395 (expand-file-name ".")))))
10396 (cond
10397 ((equal arg '(16))
10398 (setq link (concat
10399 "file:"
10400 (abbreviate-file-name (expand-file-name file)))))
10401 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10402 (setq link (concat "file:" (match-string 1 file))))
10403 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10404 (expand-file-name file))
10405 (setq link (concat
10406 "file:" (match-string 1 (expand-file-name file)))))
10407 (t (setq link (concat "file:" file)))))
10408 link))
10410 (defun org-iread-file-name (&rest args)
10411 "Read-file-name using `ido-mode' speedup if available.
10412 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10413 See `read-file-name' for a description of parameters."
10414 (org-without-partial-completion
10415 (if (and org-completion-use-ido
10416 (fboundp 'ido-read-file-name)
10417 (boundp 'ido-mode) ido-mode
10418 (listp (second args)))
10419 (let ((ido-enter-matching-directory nil))
10420 (apply 'ido-read-file-name args))
10421 (apply 'read-file-name args))))
10423 (defun org-completing-read (&rest args)
10424 "Completing-read with SPACE being a normal character."
10425 (let ((enable-recursive-minibuffers t)
10426 (minibuffer-local-completion-map
10427 (copy-keymap minibuffer-local-completion-map)))
10428 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10429 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10430 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10431 (apply 'org-icompleting-read args)))
10433 (defun org-completing-read-no-i (&rest args)
10434 (let (org-completion-use-ido org-completion-use-iswitchb)
10435 (apply 'org-completing-read args)))
10437 (defun org-iswitchb-completing-read (prompt choices &rest args)
10438 "Use iswitch as a completing-read replacement to choose from choices.
10439 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10440 from."
10441 (let* ((iswitchb-use-virtual-buffers nil)
10442 (iswitchb-make-buflist-hook
10443 (lambda ()
10444 (setq iswitchb-temp-buflist choices))))
10445 (iswitchb-read-buffer prompt)))
10447 (defun org-icompleting-read (&rest args)
10448 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10449 (org-without-partial-completion
10450 (if (and org-completion-use-ido
10451 (fboundp 'ido-completing-read)
10452 (boundp 'ido-mode) ido-mode
10453 (listp (second args)))
10454 (let ((ido-enter-matching-directory nil))
10455 (apply 'ido-completing-read (concat (car args))
10456 (if (consp (car (nth 1 args)))
10457 (mapcar 'car (nth 1 args))
10458 (nth 1 args))
10459 (cddr args)))
10460 (if (and org-completion-use-iswitchb
10461 (boundp 'iswitchb-mode) iswitchb-mode
10462 (listp (second args)))
10463 (apply 'org-iswitchb-completing-read (concat (car args))
10464 (if (consp (car (nth 1 args)))
10465 (mapcar 'car (nth 1 args))
10466 (nth 1 args))
10467 (cddr args))
10468 (apply 'completing-read args)))))
10470 (defun org-extract-attributes (s)
10471 "Extract the attributes cookie from a string and set as text property."
10472 (let (a attr (start 0) key value)
10473 (save-match-data
10474 (when (string-match "{{\\([^}]+\\)}}$" s)
10475 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10476 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10477 (setq key (match-string 1 a) value (match-string 2 a)
10478 start (match-end 0)
10479 attr (plist-put attr (intern key) value))))
10480 (org-add-props s nil 'org-attr attr))
10483 ;;; Opening/following a link
10485 (defvar org-link-search-failed nil)
10487 (defvar org-open-link-functions nil
10488 "Hook for functions finding a plain text link.
10489 These functions must take a single argument, the link content.
10490 They will be called for links that look like [[link text][description]]
10491 when LINK TEXT does not have a protocol like \"http:\" and does not look
10492 like a filename (e.g. \"./blue.png\").
10494 These functions will be called *before* Org attempts to resolve the
10495 link by doing text searches in the current buffer - so if you want a
10496 link \"[[target]]\" to still find \"<<target>>\", your function should
10497 handle this as a special case.
10499 When the function does handle the link, it must return a non-nil value.
10500 If it decides that it is not responsible for this link, it must return
10501 nil to indicate that that Org-mode can continue with other options
10502 like exact and fuzzy text search.")
10504 (defun org-next-link (&optional search-backward)
10505 "Move forward to the next link.
10506 If the link is in hidden text, expose it."
10507 (interactive "P")
10508 (when (and org-link-search-failed (eq this-command last-command))
10509 (goto-char (point-min))
10510 (message "Link search wrapped back to beginning of buffer"))
10511 (setq org-link-search-failed nil)
10512 (let* ((pos (point))
10513 (ct (org-context))
10514 (a (assoc :link ct))
10515 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10516 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10517 ((looking-at org-any-link-re)
10518 ;; Don't stay stuck at link without an org-link face
10519 (forward-char (if search-backward -1 1))))
10520 (if (funcall srch-fun org-any-link-re nil t)
10521 (progn
10522 (goto-char (match-beginning 0))
10523 (if (outline-invisible-p) (org-show-context)))
10524 (goto-char pos)
10525 (setq org-link-search-failed t)
10526 (message "No further link found"))))
10528 (defun org-previous-link ()
10529 "Move backward to the previous link.
10530 If the link is in hidden text, expose it."
10531 (interactive)
10532 (funcall 'org-next-link t))
10534 (defun org-translate-link (s)
10535 "Translate a link string if a translation function has been defined."
10536 (if (and org-link-translation-function
10537 (fboundp org-link-translation-function)
10538 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10539 (progn
10540 (setq s (funcall org-link-translation-function
10541 (match-string 1 s) (match-string 2 s)))
10542 (concat (car s) ":" (cdr s)))
10545 (defun org-translate-link-from-planner (type path)
10546 "Translate a link from Emacs Planner syntax so that Org can follow it.
10547 This is still an experimental function, your mileage may vary."
10548 (cond
10549 ((member type '("http" "https" "news" "ftp"))
10550 ;; standard Internet links are the same.
10551 nil)
10552 ((and (equal type "irc") (string-match "^//" path))
10553 ;; Planner has two / at the beginning of an irc link, we have 1.
10554 ;; We should have zero, actually....
10555 (setq path (substring path 1)))
10556 ((and (equal type "lisp") (string-match "^/" path))
10557 ;; Planner has a slash, we do not.
10558 (setq type "elisp" path (substring path 1)))
10559 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10560 ;; A typical message link. Planner has the id after the final slash,
10561 ;; we separate it with a hash mark
10562 (setq path (concat (match-string 1 path) "#"
10563 (org-remove-angle-brackets (match-string 2 path))))))
10564 (cons type path))
10566 (defun org-find-file-at-mouse (ev)
10567 "Open file link or URL at mouse."
10568 (interactive "e")
10569 (mouse-set-point ev)
10570 (org-open-at-point 'in-emacs))
10572 (defun org-open-at-mouse (ev)
10573 "Open file link or URL at mouse.
10574 See the docstring of `org-open-file' for details."
10575 (interactive "e")
10576 (mouse-set-point ev)
10577 (if (eq major-mode 'org-agenda-mode)
10578 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10579 (org-open-at-point))
10581 (defvar org-window-config-before-follow-link nil
10582 "The window configuration before following a link.
10583 This is saved in case the need arises to restore it.")
10585 (defvar org-open-link-marker (make-marker)
10586 "Marker pointing to the location where `org-open-at-point' was called.")
10588 ;;;###autoload
10589 (defun org-open-at-point-global ()
10590 "Follow a link like Org-mode does.
10591 This command can be called in any mode to follow a link that has
10592 Org-mode syntax."
10593 (interactive)
10594 (org-run-like-in-org-mode 'org-open-at-point))
10596 ;;;###autoload
10597 (defun org-open-link-from-string (s &optional arg reference-buffer)
10598 "Open a link in the string S, as if it was in Org-mode."
10599 (interactive "sLink: \nP")
10600 (let ((reference-buffer (or reference-buffer (current-buffer))))
10601 (with-temp-buffer
10602 (let ((org-inhibit-startup (not reference-buffer)))
10603 (org-mode)
10604 (insert s)
10605 (goto-char (point-min))
10606 (when reference-buffer
10607 (setq org-link-abbrev-alist-local
10608 (with-current-buffer reference-buffer
10609 org-link-abbrev-alist-local)))
10610 (org-open-at-point arg reference-buffer)))))
10612 (defvar org-open-at-point-functions nil
10613 "Hook that is run when following a link at point.
10615 Functions in this hook must return t if they identify and follow
10616 a link at point. If they don't find anything interesting at point,
10617 they must return nil.")
10619 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10620 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10621 (defun org-open-at-point (&optional arg reference-buffer)
10622 "Open link, timestamp, footnote or tags at point.
10624 When point is on a link, follow it. Normally, files will be
10625 opened by an appropriate application. If the optional prefix
10626 argument ARG is non-nil, Emacs will visit the file. With
10627 a double prefix argument, try to open outside of Emacs, in the
10628 application the system uses for this file type.
10630 When point is on a timestamp, open the agenda at the day
10631 specified.
10633 When point is a footnote definition, move to the first reference
10634 found. If it is on a reference, move to the associated
10635 definition.
10637 When point is on a headline, display a list of every link in the
10638 entry, so it is possible to pick one, or all, of them. If point
10639 is on a tag, call `org-tags-view' instead.
10641 When optional argument REFERENCE-BUFFER is non-nil, it should
10642 specify a buffer from where the link search should happen. This
10643 is used internally by `org-open-link-from-string'.
10645 On top of syntactically correct links, this function will open
10646 the link at point in comments or comment blocks and the first
10647 link in a property drawer line."
10648 (interactive "P")
10649 ;; On a code block, open block's results.
10650 (unless (call-interactively 'org-babel-open-src-block-result)
10651 (org-load-modules-maybe)
10652 (move-marker org-open-link-marker (point))
10653 (setq org-window-config-before-follow-link (current-window-configuration))
10654 (org-remove-occur-highlights nil nil t)
10655 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10656 (let* ((context (org-element-context)) type value)
10657 ;; On an unsupported type, check if point is contained within
10658 ;; a support one.
10659 (while (and (not (memq (setq type (org-element-type context))
10660 '(comment comment-block
10661 headline inlinetask link
10662 footnote-definition footnote-reference
10663 node-property timestamp)))
10664 (setq context (org-element-property :parent context))))
10665 (setq value (org-element-property :value context))
10666 (cond
10667 ;; Blank lines at the beginning of buffer: bail out.
10668 ((not context) (user-error "No link found"))
10669 ;; Exception n°1: links in property drawers
10670 ((eq type 'node-property)
10671 (org-open-link-from-string
10672 (and (string-match org-any-link-re value)
10673 (match-string-no-properties 0 value))))
10674 ;; Exception n°2: links in comments.
10675 ((memq type '(comment comment-block))
10676 (save-excursion
10677 (skip-chars-forward "\\S-" (point-at-eol))
10678 (let ((string-rear (replace-regexp-in-string
10679 "^[ \t]*# [ \t]*" ""
10680 (buffer-substring (point) (line-beginning-position))))
10681 (string-front (buffer-substring (point) (line-end-position))))
10682 (with-temp-buffer
10683 (let ((org-inhibit-startup t)) (org-mode))
10684 (insert value)
10685 (goto-char (point-min))
10686 (when (and (search-forward string-rear nil t)
10687 (search-forward string-front (line-end-position) t))
10688 (goto-char (match-beginning 0))
10689 (org-open-at-point)
10690 (when (string= string-rear "") (forward-char)))))))
10691 ;; On a headline or an inlinetask, but not on a timestamp,
10692 ;; a link, a footnote reference or on tags.
10693 ((and (memq type '(headline inlinetask))
10694 ;; Not on tags.
10695 (progn (save-excursion (beginning-of-line)
10696 (looking-at org-complex-heading-regexp))
10697 (or (not (match-beginning 5))
10698 (< (point) (match-beginning 5)))))
10699 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10700 (links (car data))
10701 (links-end (cdr data)))
10702 (if links
10703 (dolist (link (if (stringp links) (list links) links))
10704 (search-forward link nil links-end)
10705 (goto-char (match-beginning 0))
10706 (org-open-at-point))
10707 (require 'org-attach)
10708 (org-attach-reveal 'if-exists))))
10709 ;; Do nothing on white spaces after an object, unless point
10710 ;; is right after it.
10711 ((> (point)
10712 (save-excursion
10713 (goto-char (org-element-property :end context))
10714 (skip-chars-backward " \t")
10715 (point)))
10716 (user-error "No link found"))
10717 ((eq type 'timestamp) (org-follow-timestamp-link))
10718 ;; On tags within a headline or an inlinetask.
10719 ((and (memq type '(headline inlinetask))
10720 (progn (save-excursion (beginning-of-line)
10721 (looking-at org-complex-heading-regexp))
10722 (and (match-beginning 5)
10723 (>= (point) (match-beginning 5)))))
10724 (org-tags-view arg (substring (match-string 5) 0 -1)))
10725 ((eq type 'link)
10726 (let ((type (org-element-property :type context))
10727 (path (org-link-unescape (org-element-property :path context))))
10728 ;; Switch back to REFERENCE-BUFFER needed when called in
10729 ;; a temporary buffer through `org-open-link-from-string'.
10730 (with-current-buffer (or reference-buffer (current-buffer))
10731 (cond
10732 ((equal type "file")
10733 (if (string-match "[*?{]" (file-name-nondirectory path))
10734 (dired path)
10735 ;; Look into `org-link-protocols' in order to find
10736 ;; a DEDICATED-FUNCTION to open file. The function
10737 ;; will be applied on raw link instead of parsed
10738 ;; link due to the limitation in `org-add-link-type'
10739 ;; ("open" function called with a single argument).
10740 ;; If no such function is found, fallback to
10741 ;; `org-open-file'.
10743 ;; Note : "file+emacs" and "file+sys" types are
10744 ;; hard-coded in order to escape the previous
10745 ;; limitation.
10746 (let* ((option (org-element-property :search-option context))
10747 (app (org-element-property :application context))
10748 (dedicated-function
10749 (nth 1 (assoc app org-link-protocols))))
10750 (if dedicated-function
10751 (funcall dedicated-function
10752 (concat path
10753 (and option (concat "::" option))))
10754 (apply 'org-open-file
10755 path
10756 (cond (arg)
10757 ((equal app "emacs") 'emacs)
10758 ((equal app "sys") 'system))
10759 (cond ((not option) nil)
10760 ((org-string-match-p "\\`[0-9]+\\'" option)
10761 (list (string-to-number option)))
10762 (t (list nil
10763 (org-link-unescape option)))))))))
10764 ((assoc type org-link-protocols)
10765 (funcall (nth 1 (assoc type org-link-protocols)) path))
10766 ((equal type "help")
10767 (let ((f-or-v (intern path)))
10768 (cond ((fboundp f-or-v) (describe-function f-or-v))
10769 ((boundp f-or-v) (describe-variable f-or-v))
10770 (t (error "Not a known function or variable")))))
10771 ((member type '("http" "https" "ftp" "mailto" "news"))
10772 (browse-url (org-link-escape-browser (concat type ":" path))))
10773 ((equal type "doi")
10774 (browse-url
10775 (org-link-escape-browser (concat org-doi-server-url path))))
10776 ((equal type "message") (browse-url (concat type ":" path)))
10777 ((equal type "shell")
10778 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10779 (cmd path))
10780 (if (or (and (org-string-nw-p
10781 org-confirm-shell-link-not-regexp)
10782 (string-match
10783 org-confirm-shell-link-not-regexp cmd))
10784 (not org-confirm-shell-link-function)
10785 (funcall org-confirm-shell-link-function
10786 (format "Execute \"%s\" in shell? "
10787 (org-add-props cmd nil
10788 'face 'org-warning))))
10789 (progn
10790 (message "Executing %s" cmd)
10791 (shell-command cmd buf)
10792 (when (featurep 'midnight)
10793 (setq clean-buffer-list-kill-buffer-names
10794 (cons buf
10795 clean-buffer-list-kill-buffer-names))))
10796 (user-error "Abort"))))
10797 ((equal type "elisp")
10798 (let ((cmd path))
10799 (if (or (and (org-string-nw-p
10800 org-confirm-elisp-link-not-regexp)
10801 (org-string-match-p
10802 org-confirm-elisp-link-not-regexp cmd))
10803 (not org-confirm-elisp-link-function)
10804 (funcall org-confirm-elisp-link-function
10805 (format "Execute \"%s\" as elisp? "
10806 (org-add-props cmd nil
10807 'face 'org-warning))))
10808 (message "%s => %s" cmd
10809 (if (eq (string-to-char cmd) ?\()
10810 (eval (read cmd))
10811 (call-interactively (read cmd))))
10812 (user-error "Abort"))))
10813 ((equal type "id")
10814 (require 'ord-id)
10815 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10816 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10817 (unless (run-hook-with-args-until-success
10818 'org-open-link-functions path)
10819 (if (not arg) (org-mark-ring-push)
10820 (switch-to-buffer-other-window
10821 (org-get-buffer-for-internal-link (current-buffer))))
10822 (let ((cmd `(org-link-search
10823 ,(if (member type '("custom-id" "coderef"))
10824 (org-element-property :raw-link context)
10825 path)
10826 ,(cond ((equal arg '(4)) 'occur)
10827 ((equal arg '(16)) 'org-occur))
10828 ,(org-element-property :begin context))))
10829 (condition-case nil
10830 (let ((org-link-search-inhibit-query t))
10831 (eval cmd))
10832 (error (progn (widen) (eval cmd)))))))
10833 (t (browse-url-at-point))))))
10834 ;; On a footnote reference or at a footnote definition's label.
10835 ((or (eq type 'footnote-reference)
10836 (and (eq type 'footnote-definition)
10837 (save-excursion
10838 ;; Do not validate action when point is on the
10839 ;; spaces right after the footnote label, in
10840 ;; order to be on par with behaviour on links.
10841 (skip-chars-forward " \t")
10842 (let ((begin
10843 (org-element-property :contents-begin context)))
10844 (if begin (< (point) begin)
10845 (= (org-element-property :post-affiliated context)
10846 (line-beginning-position)))))))
10847 (org-footnote-action))
10848 (t (user-error "No link found")))))
10849 (move-marker org-open-link-marker nil)
10850 (run-hook-with-args 'org-follow-link-hook)))
10852 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10853 "Offer links in the current entry and return the selected link.
10854 If there is only one link, return it.
10855 If NTH is an integer, return the NTH link found.
10856 If ZERO is a string, check also this string for a link, and if
10857 there is one, return it."
10858 (with-current-buffer buffer
10859 (save-excursion
10860 (save-restriction
10861 (widen)
10862 (goto-char marker)
10863 (let ((cnt ?0)
10864 (in-emacs (if (integerp nth) nil nth))
10865 have-zero end links link c)
10866 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10867 (push (match-string 0 zero) links)
10868 (setq cnt (1- cnt) have-zero t))
10869 (save-excursion
10870 (org-back-to-heading t)
10871 (setq end (save-excursion (outline-next-heading) (point)))
10872 (while (re-search-forward org-any-link-re end t)
10873 (push (match-string 0) links))
10874 (setq links (org-uniquify (reverse links))))
10875 (cond
10876 ((null links)
10877 (message "No links"))
10878 ((equal (length links) 1)
10879 (setq link (car links)))
10880 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10881 (setq link (nth (if have-zero nth (1- nth)) links)))
10882 (t ; we have to select a link
10883 (save-excursion
10884 (save-window-excursion
10885 (delete-other-windows)
10886 (with-output-to-temp-buffer "*Select Link*"
10887 (mapc (lambda (l)
10888 (if (not (string-match org-bracket-link-regexp l))
10889 (princ (format "[%c] %s\n" (incf cnt)
10890 (org-remove-angle-brackets l)))
10891 (if (match-end 3)
10892 (princ (format "[%c] %s (%s)\n" (incf cnt)
10893 (match-string 3 l) (match-string 1 l)))
10894 (princ (format "[%c] %s\n" (incf cnt)
10895 (match-string 1 l))))))
10896 links))
10897 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10898 (message "Select link to open, RET to open all:")
10899 (setq c (read-char-exclusive))
10900 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10901 (when (equal c ?q) (user-error "Abort"))
10902 (if (equal c ?\C-m)
10903 (setq link links)
10904 (setq nth (- c ?0))
10905 (if have-zero (setq nth (1+ nth)))
10906 (unless (and (integerp nth) (>= (length links) nth))
10907 (user-error "Invalid link selection"))
10908 (setq link (nth (1- nth) links)))))
10909 (cons link end))))))
10911 ;; TODO: These functions are deprecated since `org-open-at-point'
10912 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10913 (defun org-open-file-with-system (path)
10914 "Open file at PATH using the system way of opening it."
10915 (org-open-file path 'system))
10916 (defun org-open-file-with-emacs (path)
10917 "Open file at PATH in Emacs."
10918 (org-open-file path 'emacs))
10921 ;;; File search
10923 (defvar org-create-file-search-functions nil
10924 "List of functions to construct the right search string for a file link.
10925 These functions are called in turn with point at the location to
10926 which the link should point.
10928 A function in the hook should first test if it would like to
10929 handle this file type, for example by checking the `major-mode'
10930 or the file extension. If it decides not to handle this file, it
10931 should just return nil to give other functions a chance. If it
10932 does handle the file, it must return the search string to be used
10933 when following the link. The search string will be part of the
10934 file link, given after a double colon, and `org-open-at-point'
10935 will automatically search for it. If special measures must be
10936 taken to make the search successful, another function should be
10937 added to the companion hook `org-execute-file-search-functions',
10938 which see.
10940 A function in this hook may also use `setq' to set the variable
10941 `description' to provide a suggestion for the descriptive text to
10942 be used for this link when it gets inserted into an Org-mode
10943 buffer with \\[org-insert-link].")
10945 (defvar org-execute-file-search-functions nil
10946 "List of functions to execute a file search triggered by a link.
10948 Functions added to this hook must accept a single argument, the
10949 search string that was part of the file link, the part after the
10950 double colon. The function must first check if it would like to
10951 handle this search, for example by checking the `major-mode' or
10952 the file extension. If it decides not to handle this search, it
10953 should just return nil to give other functions a chance. If it
10954 does handle the search, it must return a non-nil value to keep
10955 other functions from trying.
10957 Each function can access the current prefix argument through the
10958 variable `current-prefix-arg'. Note that a single prefix is used
10959 to force opening a link in Emacs, so it may be good to only use a
10960 numeric or double prefix to guide the search function.
10962 In case this is needed, a function in this hook can also restore
10963 the window configuration before `org-open-at-point' was called using:
10965 (set-window-configuration org-window-config-before-follow-link)")
10967 (defun org-link-search (s &optional type avoid-pos stealth)
10968 "Search for a link search option.
10969 If S is surrounded by forward slashes, it is interpreted as a
10970 regular expression. In org-mode files, this will create an `org-occur'
10971 sparse tree. In ordinary files, `occur' will be used to list matches.
10972 If the current buffer is in `dired-mode', grep will be used to search
10973 in all files. If AVOID-POS is given, ignore matches near that position.
10975 When optional argument STEALTH is non-nil, do not modify
10976 visibility around point, thus ignoring
10977 `org-show-hierarchy-above', `org-show-following-heading' and
10978 `org-show-siblings' variables."
10979 (let ((case-fold-search t)
10980 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10981 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10982 (append '(("") (" ") ("\t") ("\n"))
10983 org-emphasis-alist)
10984 "\\|") "\\)"))
10985 (pos (point))
10986 (pre nil) (post nil)
10987 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10988 (cond
10989 ;; First check if there are any special search functions
10990 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10991 ;; Now try the builtin stuff
10992 ((and (equal (string-to-char s0) ?#)
10993 (> (length s0) 1)
10994 (save-excursion
10995 (goto-char (point-min))
10996 (and
10997 (re-search-forward
10998 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10999 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
11000 (setq type 'dedicated
11001 pos (match-beginning 0))))
11002 ;; There is an exact target for this
11003 (goto-char pos)
11004 (org-back-to-heading t)))
11005 ((save-excursion
11006 (goto-char (point-min))
11007 (and
11008 (re-search-forward
11009 (concat "<<" (regexp-quote s0) ">>") nil t)
11010 (setq type 'dedicated
11011 pos (match-beginning 0))))
11012 ;; There is an exact target for this
11013 (goto-char pos))
11014 ((save-excursion
11015 (goto-char (point-min))
11016 (and
11017 (re-search-forward
11018 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
11019 (setq type 'dedicated pos (match-beginning 0))))
11020 ;; Found an element with a matching #+name affiliated keyword.
11021 (goto-char pos))
11022 ((and (string-match "^(\\(.*\\))$" s0)
11023 (save-excursion
11024 (goto-char (point-min))
11025 (and
11026 (re-search-forward
11027 (concat "[^[]" (regexp-quote
11028 (format org-coderef-label-format
11029 (match-string 1 s0))))
11030 nil t)
11031 (setq type 'dedicated
11032 pos (1+ (match-beginning 0))))))
11033 ;; There is a coderef target for this
11034 (goto-char pos))
11035 ((string-match "^/\\(.*\\)/$" s)
11036 ;; A regular expression
11037 (cond
11038 ((derived-mode-p 'org-mode)
11039 (org-occur (match-string 1 s)))
11040 (t (org-do-occur (match-string 1 s)))))
11041 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11042 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11043 (goto-char (point-min))
11044 (cond
11045 ((let (case-fold-search)
11046 (re-search-forward (format org-complex-heading-regexp-format
11047 (regexp-quote s))
11048 nil t))
11049 ;; OK, found a match
11050 (setq type 'dedicated)
11051 (goto-char (match-beginning 0)))
11052 ((and (not org-link-search-inhibit-query)
11053 (eq org-link-search-must-match-exact-headline 'query-to-create)
11054 (y-or-n-p "No match - create this as a new heading? "))
11055 (goto-char (point-max))
11056 (or (bolp) (newline))
11057 (insert "* " s "\n")
11058 (beginning-of-line 0))
11060 (goto-char pos)
11061 (error "No match"))))
11063 ;; A normal search string
11064 (when (equal (string-to-char s) ?*)
11065 ;; Anchor on headlines, post may include tags.
11066 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11067 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11068 s (substring s 1)))
11069 (remove-text-properties
11070 0 (length s)
11071 '(face nil mouse-face nil keymap nil fontified nil) s)
11072 ;; Make a series of regular expressions to find a match
11073 (setq words (org-split-string s "[ \n\r\t]+")
11075 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11076 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11077 "\\)" markers)
11078 re2a_ (concat "\\(" (mapconcat 'downcase words
11079 "[ \t\r\n]+") "\\)[ \t\r\n]")
11080 re2a (concat "[ \t\r\n]" re2a_)
11081 re4_ (concat "\\(" (mapconcat 'downcase words
11082 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11083 re4 (concat "[^a-zA-Z_]" re4_)
11085 re1 (concat pre re2 post)
11086 re3 (concat pre (if pre re4_ re4) post)
11087 re5 (concat pre ".*" re4)
11088 re2 (concat pre re2)
11089 re2a (concat pre (if pre re2a_ re2a))
11090 re4 (concat pre (if pre re4_ re4))
11091 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11092 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11093 re5 "\\)"))
11094 (cond
11095 ((eq type 'org-occur) (org-occur reall))
11096 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11097 (t (goto-char (point-min))
11098 (setq type 'fuzzy)
11099 (if (or (and (org-search-not-self 1 re0 nil t)
11100 (setq type 'dedicated))
11101 (org-search-not-self 1 re1 nil t)
11102 (org-search-not-self 1 re2 nil t)
11103 (org-search-not-self 1 re2a nil t)
11104 (org-search-not-self 1 re3 nil t)
11105 (org-search-not-self 1 re4 nil t)
11106 (org-search-not-self 1 re5 nil t))
11107 (goto-char (match-beginning 1))
11108 (goto-char pos)
11109 (error "No match"))))))
11110 (and (derived-mode-p 'org-mode)
11111 (not stealth)
11112 (org-show-context 'link-search))
11113 type))
11115 (defun org-search-not-self (group &rest args)
11116 "Execute `re-search-forward', but only accept matches that do not
11117 enclose the position of `org-open-link-marker'."
11118 (let ((m org-open-link-marker))
11119 (catch 'exit
11120 (while (apply 're-search-forward args)
11121 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11122 (goto-char (match-end group))
11123 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11124 (> (match-beginning 0) (marker-position m))
11125 (< (match-end 0) (marker-position m)))
11126 (save-match-data
11127 (or (not (org-in-regexp
11128 org-bracket-link-analytic-regexp 1))
11129 (not (match-end 4)) ; no description
11130 (and (<= (match-beginning 4) (point))
11131 (>= (match-end 4) (point))))))
11132 (throw 'exit (point))))))))
11134 (defun org-get-buffer-for-internal-link (buffer)
11135 "Return a buffer to be used for displaying the link target of internal links."
11136 (cond
11137 ((not org-display-internal-link-with-indirect-buffer)
11138 buffer)
11139 ((string-match "(Clone)$" (buffer-name buffer))
11140 (message "Buffer is already a clone, not making another one")
11141 ;; we also do not modify visibility in this case
11142 buffer)
11143 (t ; make a new indirect buffer for displaying the link
11144 (let* ((bn (buffer-name buffer))
11145 (ibn (concat bn "(Clone)"))
11146 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11147 (with-current-buffer ib (org-overview))
11148 ib))))
11150 (defun org-do-occur (regexp &optional cleanup)
11151 "Call the Emacs command `occur'.
11152 If CLEANUP is non-nil, remove the printout of the regular expression
11153 in the *Occur* buffer. This is useful if the regex is long and not useful
11154 to read."
11155 (occur regexp)
11156 (when cleanup
11157 (let ((cwin (selected-window)) win beg end)
11158 (when (setq win (get-buffer-window "*Occur*"))
11159 (select-window win))
11160 (goto-char (point-min))
11161 (when (re-search-forward "match[a-z]+" nil t)
11162 (setq beg (match-end 0))
11163 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11164 (setq end (1- (match-beginning 0)))))
11165 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11166 (goto-char (point-min))
11167 (select-window cwin))))
11169 ;;; The mark ring for links jumps
11171 (defvar org-mark-ring nil
11172 "Mark ring for positions before jumps in Org-mode.")
11173 (defvar org-mark-ring-last-goto nil
11174 "Last position in the mark ring used to go back.")
11175 ;; Fill and close the ring
11176 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11177 (loop for i from 1 to org-mark-ring-length do
11178 (push (make-marker) org-mark-ring))
11179 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11180 org-mark-ring)
11182 (defun org-mark-ring-push (&optional pos buffer)
11183 "Put the current position or POS into the mark ring and rotate it."
11184 (interactive)
11185 (setq pos (or pos (point)))
11186 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11187 (move-marker (car org-mark-ring)
11188 (or pos (point))
11189 (or buffer (current-buffer)))
11190 (message "%s"
11191 (substitute-command-keys
11192 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11194 (defun org-mark-ring-goto (&optional n)
11195 "Jump to the previous position in the mark ring.
11196 With prefix arg N, jump back that many stored positions. When
11197 called several times in succession, walk through the entire ring.
11198 Org-mode commands jumping to a different position in the current file,
11199 or to another Org-mode file, automatically push the old position
11200 onto the ring."
11201 (interactive "p")
11202 (let (p m)
11203 (if (eq last-command this-command)
11204 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11205 (setq p org-mark-ring))
11206 (setq org-mark-ring-last-goto p)
11207 (setq m (car p))
11208 (org-pop-to-buffer-same-window (marker-buffer m))
11209 (goto-char m)
11210 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11212 (defun org-remove-angle-brackets (s)
11213 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11214 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11216 (defun org-add-angle-brackets (s)
11217 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11218 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11220 (defun org-remove-double-quotes (s)
11221 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11222 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11225 ;;; Following specific links
11227 (defun org-follow-timestamp-link ()
11228 "Open an agenda view for the time-stamp date/range at point."
11229 (cond
11230 ((org-at-date-range-p t)
11231 (let ((org-agenda-start-on-weekday)
11232 (t1 (match-string 1))
11233 (t2 (match-string 2)) tt1 tt2)
11234 (setq tt1 (time-to-days (org-time-string-to-time t1))
11235 tt2 (time-to-days (org-time-string-to-time t2)))
11236 (let ((org-agenda-buffer-tmp-name
11237 (format "*Org Agenda(a:%s)"
11238 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11239 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11240 ((org-at-timestamp-p t)
11241 (let ((org-agenda-buffer-tmp-name
11242 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11243 (org-agenda-list nil (time-to-days (org-time-string-to-time
11244 (substring (match-string 1) 0 10)))
11245 1)))
11246 (t (error "This should not happen"))))
11249 ;;; Following file links
11250 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11251 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11252 (declare-function mailcap-mime-info
11253 "mailcap" (string &optional request no-decode))
11254 (defvar org-wait nil)
11255 (defun org-open-file (path &optional in-emacs line search)
11256 "Open the file at PATH.
11257 First, this expands any special file name abbreviations. Then the
11258 configuration variable `org-file-apps' is checked if it contains an
11259 entry for this file type, and if yes, the corresponding command is launched.
11261 If no application is found, Emacs simply visits the file.
11263 With optional prefix argument IN-EMACS, Emacs will visit the file.
11264 With a double \\[universal-argument] \\[universal-argument] \
11265 prefix arg, Org tries to avoid opening in Emacs
11266 and to use an external application to visit the file.
11268 Optional LINE specifies a line to go to, optional SEARCH a string
11269 to search for. If LINE or SEARCH is given, the file will be
11270 opened in Emacs, unless an entry from org-file-apps that makes
11271 use of groups in a regexp matches.
11273 If you want to change the way frames are used when following a
11274 link, please customize `org-link-frame-setup'.
11276 If the file does not exist, an error is thrown."
11277 (let* ((file (if (equal path "")
11278 buffer-file-name
11279 (substitute-in-file-name (expand-file-name path))))
11280 (file-apps (append org-file-apps (org-default-apps)))
11281 (apps (org-remove-if
11282 'org-file-apps-entry-match-against-dlink-p file-apps))
11283 (apps-dlink (org-remove-if-not
11284 'org-file-apps-entry-match-against-dlink-p file-apps))
11285 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11286 (dirp (if remp nil (file-directory-p file)))
11287 (file (if (and dirp org-open-directory-means-index-dot-org)
11288 (concat (file-name-as-directory file) "index.org")
11289 file))
11290 (a-m-a-p (assq 'auto-mode apps))
11291 (dfile (downcase file))
11292 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11293 (link (cond ((and (eq line nil)
11294 (eq search nil))
11295 file)
11296 (line
11297 (concat file "::" (number-to-string line)))
11298 (search
11299 (concat file "::" search))))
11300 (dlink (downcase link))
11301 (old-buffer (current-buffer))
11302 (old-pos (point))
11303 (old-mode major-mode)
11304 ext cmd link-match-data)
11305 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11306 (setq ext (match-string 1 dfile))
11307 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11308 (setq ext (match-string 1 dfile))))
11309 (cond
11310 ((member in-emacs '((16) system))
11311 (setq cmd (cdr (assoc 'system apps))))
11312 (in-emacs (setq cmd 'emacs))
11314 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11315 (and dirp (cdr (assoc 'directory apps)))
11316 ; first, try matching against apps-dlink
11317 ; if we get a match here, store the match data for later
11318 (let ((match (assoc-default dlink apps-dlink
11319 'string-match)))
11320 (if match
11321 (progn (setq link-match-data (match-data))
11322 match)
11323 (progn (setq in-emacs (or in-emacs line search))
11324 nil))) ; if we have no match in apps-dlink,
11325 ; always open the file in emacs if line or search
11326 ; is given (for backwards compatibility)
11327 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11328 'string-match)
11329 (cdr (assoc ext apps))
11330 (cdr (assoc t apps))))))
11331 (when (eq cmd 'system)
11332 (setq cmd (cdr (assoc 'system apps))))
11333 (when (eq cmd 'default)
11334 (setq cmd (cdr (assoc t apps))))
11335 (when (eq cmd 'mailcap)
11336 (require 'mailcap)
11337 (mailcap-parse-mailcaps)
11338 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11339 (command (mailcap-mime-info mime-type)))
11340 (if (stringp command)
11341 (setq cmd command)
11342 (setq cmd 'emacs))))
11343 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11344 (not (file-exists-p file))
11345 (not org-open-non-existing-files))
11346 (user-error "No such file: %s" file))
11347 (cond
11348 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11349 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11350 (while (string-match "['\"]%s['\"]" cmd)
11351 (setq cmd (replace-match "%s" t t cmd)))
11352 (while (string-match "%s" cmd)
11353 (setq cmd (replace-match
11354 (save-match-data
11355 (shell-quote-argument
11356 (convert-standard-filename file)))
11357 t t cmd)))
11359 ;; Replace "%1", "%2" etc. in command with group matches from regex
11360 (save-match-data
11361 (let ((match-index 1)
11362 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11363 (set-match-data link-match-data)
11364 (while (<= match-index number-of-groups)
11365 (let ((regex (concat "%" (number-to-string match-index)))
11366 (replace-with (match-string match-index dlink)))
11367 (while (string-match regex cmd)
11368 (setq cmd (replace-match replace-with t t cmd))))
11369 (setq match-index (+ match-index 1)))))
11371 (save-window-excursion
11372 (message "Running %s...done" cmd)
11373 (start-process-shell-command cmd nil cmd)
11374 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11375 ((or (stringp cmd)
11376 (eq cmd 'emacs))
11377 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11378 (widen)
11379 (if line (progn (org-goto-line line)
11380 (if (derived-mode-p 'org-mode)
11381 (org-reveal)))
11382 (if search (org-link-search search))))
11383 ((consp cmd)
11384 (let ((file (convert-standard-filename file)))
11385 (save-match-data
11386 (set-match-data link-match-data)
11387 (eval cmd))))
11388 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11389 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11390 (or (not (equal old-buffer (current-buffer)))
11391 (not (equal old-pos (point))))
11392 (org-mark-ring-push old-pos old-buffer))))
11394 (defun org-file-apps-entry-match-against-dlink-p (entry)
11395 "This function returns non-nil if `entry' uses a regular
11396 expression which should be matched against the whole link by
11397 org-open-file.
11399 It assumes that is the case when the entry uses a regular
11400 expression which has at least one grouping construct and the
11401 action is either a lisp form or a command string containing
11402 '%1', i.e. using at least one subexpression match as a
11403 parameter."
11404 (let ((selector (car entry))
11405 (action (cdr entry)))
11406 (if (stringp selector)
11407 (and (> (regexp-opt-depth selector) 0)
11408 (or (and (stringp action)
11409 (string-match "%[0-9]" action))
11410 (consp action)))
11411 nil)))
11413 (defun org-default-apps ()
11414 "Return the default applications for this operating system."
11415 (cond
11416 ((eq system-type 'darwin)
11417 org-file-apps-defaults-macosx)
11418 ((eq system-type 'windows-nt)
11419 org-file-apps-defaults-windowsnt)
11420 (t org-file-apps-defaults-gnu)))
11422 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11423 "Convert extensions to regular expressions in the cars of LIST.
11424 Also, weed out any non-string entries, because the return value is used
11425 only for regexp matching.
11426 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11427 point to the symbol `emacs', indicating that the file should
11428 be opened in Emacs."
11429 (append
11430 (delq nil
11431 (mapcar (lambda (x)
11432 (if (not (stringp (car x)))
11434 (if (string-match "\\W" (car x))
11436 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11437 list))
11438 (if add-auto-mode
11439 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11441 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11442 (defun org-file-remote-p (file)
11443 "Test whether FILE specifies a location on a remote system.
11444 Return non-nil if the location is indeed remote.
11446 For example, the filename \"/user@host:/foo\" specifies a location
11447 on the system \"/user@host:\"."
11448 (cond ((fboundp 'file-remote-p)
11449 (file-remote-p file))
11450 ((fboundp 'tramp-handle-file-remote-p)
11451 (tramp-handle-file-remote-p file))
11452 ((and (boundp 'ange-ftp-name-format)
11453 (string-match (car ange-ftp-name-format) file))
11454 t)))
11457 ;;;; Refiling
11459 (defun org-get-org-file ()
11460 "Read a filename, with default directory `org-directory'."
11461 (let ((default (or org-default-notes-file remember-data-file)))
11462 (read-file-name (format "File name [%s]: " default)
11463 (file-name-as-directory org-directory)
11464 default)))
11466 (defun org-notes-order-reversed-p ()
11467 "Check if the current file should receive notes in reversed order."
11468 (cond
11469 ((not org-reverse-note-order) nil)
11470 ((eq t org-reverse-note-order) t)
11471 ((not (listp org-reverse-note-order)) nil)
11472 (t (catch 'exit
11473 (let ((all org-reverse-note-order)
11474 entry)
11475 (while (setq entry (pop all))
11476 (if (string-match (car entry) buffer-file-name)
11477 (throw 'exit (cdr entry))))
11478 nil)))))
11480 (defvar org-refile-target-table nil
11481 "The list of refile targets, created by `org-refile'.")
11483 (defvar org-agenda-new-buffers nil
11484 "Buffers created to visit agenda files.")
11486 (defvar org-refile-cache nil
11487 "Cache for refile targets.")
11489 (defvar org-refile-markers nil
11490 "All the markers used for caching refile locations.")
11492 (defun org-refile-marker (pos)
11493 "Get a new refile marker, but only if caching is in use."
11494 (if (not org-refile-use-cache)
11496 (let ((m (make-marker)))
11497 (move-marker m pos)
11498 (push m org-refile-markers)
11499 m)))
11501 (defun org-refile-cache-clear ()
11502 "Clear the refile cache and disable all the markers."
11503 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11504 (setq org-refile-markers nil)
11505 (setq org-refile-cache nil)
11506 (message "Refile cache has been cleared"))
11508 (defun org-refile-cache-check-set (set)
11509 "Check if all the markers in the cache still have live buffers."
11510 (let (marker)
11511 (catch 'exit
11512 (while (and set (setq marker (nth 3 (pop set))))
11513 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11514 (when (and marker (null (marker-buffer marker)))
11515 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11516 (sit-for 3)
11517 (throw 'exit nil)))
11518 t)))
11520 (defun org-refile-cache-put (set &rest identifiers)
11521 "Push the refile targets SET into the cache, under IDENTIFIERS."
11522 (let* ((key (sha1 (prin1-to-string identifiers)))
11523 (entry (assoc key org-refile-cache)))
11524 (if entry
11525 (setcdr entry set)
11526 (push (cons key set) org-refile-cache))))
11528 (defun org-refile-cache-get (&rest identifiers)
11529 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11530 (cond
11531 ((not org-refile-cache) nil)
11532 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11534 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11535 org-refile-cache))))
11536 (and set (org-refile-cache-check-set set) set)))))
11538 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11539 "Produce a table with refile targets."
11540 (let ((case-fold-search nil)
11541 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11542 (entries (or org-refile-targets '((nil . (:level . 1)))))
11543 targets tgs txt re files f desc descre fast-path-p level pos0)
11544 (message "Getting targets...")
11545 (with-current-buffer (or default-buffer (current-buffer))
11546 (while (setq entry (pop entries))
11547 (setq files (car entry) desc (cdr entry))
11548 (setq fast-path-p nil)
11549 (cond
11550 ((null files) (setq files (list (current-buffer))))
11551 ((eq files 'org-agenda-files)
11552 (setq files (org-agenda-files 'unrestricted)))
11553 ((and (symbolp files) (fboundp files))
11554 (setq files (funcall files)))
11555 ((and (symbolp files) (boundp files))
11556 (setq files (symbol-value files))))
11557 (if (stringp files) (setq files (list files)))
11558 (cond
11559 ((eq (car desc) :tag)
11560 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11561 ((eq (car desc) :todo)
11562 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11563 ((eq (car desc) :regexp)
11564 (setq descre (cdr desc)))
11565 ((eq (car desc) :level)
11566 (setq descre (concat "^\\*\\{" (number-to-string
11567 (if org-odd-levels-only
11568 (1- (* 2 (cdr desc)))
11569 (cdr desc)))
11570 "\\}[ \t]")))
11571 ((eq (car desc) :maxlevel)
11572 (setq fast-path-p t)
11573 (setq descre (concat "^\\*\\{1," (number-to-string
11574 (if org-odd-levels-only
11575 (1- (* 2 (cdr desc)))
11576 (cdr desc)))
11577 "\\}[ \t]")))
11578 (t (error "Bad refiling target description %s" desc)))
11579 (while (setq f (pop files))
11580 (with-current-buffer
11581 (if (bufferp f) f (org-get-agenda-file-buffer f))
11583 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11584 (progn
11585 (if (bufferp f) (setq f (buffer-file-name
11586 (buffer-base-buffer f))))
11587 (setq f (and f (expand-file-name f)))
11588 (if (eq org-refile-use-outline-path 'file)
11589 (push (list (file-name-nondirectory f) f nil nil) tgs))
11590 (save-excursion
11591 (save-restriction
11592 (widen)
11593 (goto-char (point-min))
11594 (while (re-search-forward descre nil t)
11595 (goto-char (setq pos0 (point-at-bol)))
11596 (catch 'next
11597 (when org-refile-target-verify-function
11598 (save-match-data
11599 (or (funcall org-refile-target-verify-function)
11600 (throw 'next t))))
11601 (when (and (looking-at org-complex-heading-regexp)
11602 (not (member (match-string 4) excluded-entries))
11603 (match-string 4))
11604 (setq level (org-reduced-level
11605 (- (match-end 1) (match-beginning 1)))
11606 txt (org-link-display-format (match-string 4))
11607 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11608 re (format org-complex-heading-regexp-format
11609 (regexp-quote (match-string 4))))
11610 (when org-refile-use-outline-path
11611 (setq txt (mapconcat
11612 'org-protect-slash
11613 (append
11614 (if (eq org-refile-use-outline-path
11615 'file)
11616 (list (file-name-nondirectory
11617 (buffer-file-name
11618 (buffer-base-buffer))))
11619 (if (eq org-refile-use-outline-path
11620 'full-file-path)
11621 (list (buffer-file-name
11622 (buffer-base-buffer)))))
11623 (org-get-outline-path fast-path-p
11624 level txt)
11625 (list txt))
11626 "/")))
11627 (push (list txt f re (org-refile-marker (point)))
11628 tgs)))
11629 (when (= (point) pos0)
11630 ;; verification function has not moved point
11631 (goto-char (point-at-eol))))))))
11632 (when org-refile-use-cache
11633 (org-refile-cache-put tgs (buffer-file-name) descre))
11634 (setq targets (append tgs targets))))))
11635 (message "Getting targets...done")
11636 (nreverse targets)))
11638 (defun org-protect-slash (s)
11639 (while (string-match "/" s)
11640 (setq s (replace-match "\\" t t s)))
11643 (defvar org-olpa (make-vector 20 nil))
11645 (defun org-get-outline-path (&optional fastp level heading)
11646 "Return the outline path to the current entry, as a list.
11648 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11649 routine which makes outline path derivations for an entire file,
11650 avoiding backtracing. Refile target collection makes use of that."
11651 (if fastp
11652 (progn
11653 (if (> level 19)
11654 (error "Outline path failure, more than 19 levels"))
11655 (loop for i from level upto 19 do
11656 (aset org-olpa i nil))
11657 (prog1
11658 (delq nil (append org-olpa nil))
11659 (aset org-olpa level heading)))
11660 (let (rtn case-fold-search)
11661 (save-excursion
11662 (save-restriction
11663 (widen)
11664 (while (org-up-heading-safe)
11665 (when (looking-at org-complex-heading-regexp)
11666 (push (org-trim
11667 (replace-regexp-in-string
11668 ;; Remove statistical/checkboxes cookies
11669 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11670 (org-match-string-no-properties 4)))
11671 rtn)))
11672 rtn)))))
11674 (defun org-format-outline-path (path &optional width prefix separator)
11675 "Format the outline path PATH for display.
11676 WIDTH is the maximum number of characters that is available.
11677 PREFIX is a prefix to be included in the returned string,
11678 such as the file name.
11679 SEPARATOR is inserted between the different parts of the path,
11680 the default is \"/\"."
11681 (setq width (or width 79))
11682 (if prefix (setq width (- width (length prefix))))
11683 (if (not path)
11684 (or prefix "")
11685 (let* ((nsteps (length path))
11686 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11687 (maxwidth (if (<= total-width width)
11688 10000 ;; everything fits
11689 ;; we need to shorten the level headings
11690 (/ (- width nsteps) nsteps)))
11691 (org-odd-levels-only nil)
11692 (n 0)
11693 (total (1+ (length prefix))))
11694 (setq maxwidth (max maxwidth 10))
11695 (concat prefix
11696 (if prefix (or separator "/"))
11697 (mapconcat
11698 (lambda (h)
11699 (setq n (1+ n))
11700 (if (and (= n nsteps) (< maxwidth 10000))
11701 (setq maxwidth (- total-width total)))
11702 (if (< (length h) maxwidth)
11703 (progn (setq total (+ total (length h) 1)) h)
11704 (setq h (substring h 0 (- maxwidth 2))
11705 total (+ total maxwidth 1))
11706 (if (string-match "[ \t]+\\'" h)
11707 (setq h (substring h 0 (match-beginning 0))))
11708 (setq h (concat h "..")))
11709 (org-add-props h nil 'face
11710 (nth (% (1- n) org-n-level-faces)
11711 org-level-faces))
11713 path (or separator "/"))))))
11715 (defun org-display-outline-path (&optional file current separator just-return-string)
11716 "Display the current outline path in the echo area.
11718 If FILE is non-nil, prepend the output with the file name.
11719 If CURRENT is non-nil, append the current heading to the output.
11720 SEPARATOR is passed through to `org-format-outline-path'. It separates
11721 the different parts of the path and defaults to \"/\".
11722 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11723 (interactive "P")
11724 (let* (case-fold-search
11725 (bfn (buffer-file-name (buffer-base-buffer)))
11726 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11727 res)
11728 (if current (setq path (append path
11729 (save-excursion
11730 (org-back-to-heading t)
11731 (if (looking-at org-complex-heading-regexp)
11732 (list (match-string 4)))))))
11733 (setq res
11734 (org-format-outline-path
11735 path
11736 (1- (frame-width))
11737 (and file bfn (concat (file-name-nondirectory bfn) separator))
11738 separator))
11739 (if just-return-string
11740 (org-no-properties res)
11741 (org-unlogged-message "%s" res))))
11743 (defvar org-refile-history nil
11744 "History for refiling operations.")
11746 (defvar org-after-refile-insert-hook nil
11747 "Hook run after `org-refile' has inserted its stuff at the new location.
11748 Note that this is still *before* the stuff will be removed from
11749 the *old* location.")
11751 (defvar org-capture-last-stored-marker)
11752 (defvar org-refile-keep nil
11753 "Non-nil means `org-refile' will copy instead of refile.")
11755 (defun org-copy ()
11756 "Like `org-refile', but copy."
11757 (interactive)
11758 (let ((org-refile-keep t))
11759 (funcall 'org-refile nil nil nil "Copy")))
11761 (defun org-refile (&optional arg default-buffer rfloc msg)
11762 "Move the entry or entries at point to another heading.
11763 The list of target headings is compiled using the information in
11764 `org-refile-targets', which see.
11766 At the target location, the entry is filed as a subitem of the
11767 target heading. Depending on `org-reverse-note-order', the new
11768 subitem will either be the first or the last subitem.
11770 If there is an active region, all entries in that region will be
11771 refiled. However, the region must fulfill the requirement that
11772 the first heading sets the top-level of the moved text.
11774 With prefix arg ARG, the command will only visit the target
11775 location and not actually move anything.
11777 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11778 refiling operation has put the subtree.
11780 With a numeric prefix argument of `2', refile to the running clock.
11782 With a numeric prefix argument of `3', emulate `org-refile-keep'
11783 being set to `t' and copy to the target location, don't move it.
11784 Beware that keeping refiled entries may result in duplicated ID
11785 properties.
11787 RFLOC can be a refile location obtained in a different way.
11789 MSG is a string to replace \"Refile\" in the default prompt with
11790 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11792 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11794 If you are using target caching (see `org-refile-use-cache'), you
11795 have to clear the target cache in order to find new targets.
11796 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11797 prefix argument (`C-u C-u C-u C-c C-w')."
11798 (interactive "P")
11799 (if (member arg '(0 (64)))
11800 (org-refile-cache-clear)
11801 (let* ((actionmsg (cond (msg msg)
11802 ((equal arg 3) "Refile (and keep)")
11803 (t "Refile")))
11804 (cbuf (current-buffer))
11805 (regionp (org-region-active-p))
11806 (region-start (and regionp (region-beginning)))
11807 (region-end (and regionp (region-end)))
11808 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11809 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11810 pos it nbuf file re level reversed)
11811 (setq last-command nil)
11812 (when regionp
11813 (goto-char region-start)
11814 (or (bolp) (goto-char (point-at-bol)))
11815 (setq region-start (point))
11816 (unless (or (org-kill-is-subtree-p
11817 (buffer-substring region-start region-end))
11818 (prog1 org-refile-active-region-within-subtree
11819 (let ((s (point-at-eol)))
11820 (org-toggle-heading)
11821 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11822 (user-error "The region is not a (sequence of) subtree(s)")))
11823 (if (equal arg '(16))
11824 (org-refile-goto-last-stored)
11825 (when (or
11826 (and (equal arg 2)
11827 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11828 (prog1
11829 (setq it (list (or org-clock-heading "running clock")
11830 (buffer-file-name
11831 (marker-buffer org-clock-hd-marker))
11833 (marker-position org-clock-hd-marker)))
11834 (setq arg nil)))
11835 (setq it (or rfloc
11836 (let (heading-text)
11837 (save-excursion
11838 (unless (and arg (listp arg))
11839 (org-back-to-heading t)
11840 (setq heading-text
11841 (replace-regexp-in-string
11842 org-bracket-link-regexp
11843 "\\3"
11844 (nth 4 (org-heading-components)))))
11845 (org-refile-get-location
11846 (cond ((and arg (listp arg)) "Goto")
11847 (regionp (concat actionmsg " region to"))
11848 (t (concat actionmsg " subtree \""
11849 heading-text "\" to")))
11850 default-buffer
11851 (and (not (equal '(4) arg))
11852 org-refile-allow-creating-parent-nodes)
11853 arg))))))
11854 (setq file (nth 1 it)
11855 re (nth 2 it)
11856 pos (nth 3 it))
11857 (if (and (not arg)
11859 (equal (buffer-file-name) file)
11860 (if regionp
11861 (and (>= pos region-start)
11862 (<= pos region-end))
11863 (and (>= pos (point))
11864 (< pos (save-excursion
11865 (org-end-of-subtree t t))))))
11866 (error "Cannot refile to position inside the tree or region"))
11867 (setq nbuf (or (find-buffer-visiting file)
11868 (find-file-noselect file)))
11869 (if (and arg (not (equal arg 3)))
11870 (progn
11871 (org-pop-to-buffer-same-window nbuf)
11872 (goto-char pos)
11873 (org-show-context 'org-goto))
11874 (if regionp
11875 (progn
11876 (org-kill-new (buffer-substring region-start region-end))
11877 (org-save-markers-in-region region-start region-end))
11878 (org-copy-subtree 1 nil t))
11879 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11880 (find-file-noselect file)))
11881 (setq reversed (org-notes-order-reversed-p))
11882 (save-excursion
11883 (save-restriction
11884 (widen)
11885 (if pos
11886 (progn
11887 (goto-char pos)
11888 (looking-at org-outline-regexp)
11889 (setq level (org-get-valid-level (funcall outline-level) 1))
11890 (goto-char
11891 (if reversed
11892 (or (outline-next-heading) (point-max))
11893 (or (save-excursion (org-get-next-sibling))
11894 (org-end-of-subtree t t)
11895 (point-max)))))
11896 (setq level 1)
11897 (if (not reversed)
11898 (goto-char (point-max))
11899 (goto-char (point-min))
11900 (or (outline-next-heading) (goto-char (point-max)))))
11901 (if (not (bolp)) (newline))
11902 (org-paste-subtree level nil nil t)
11903 (when org-log-refile
11904 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11905 (unless (eq org-log-refile 'note)
11906 (save-excursion (org-add-log-note))))
11907 (and org-auto-align-tags
11908 (let ((org-loop-over-headlines-in-active-region nil))
11909 (org-set-tags nil t)))
11910 (let ((bookmark-name (plist-get org-bookmark-names-plist
11911 :last-refile)))
11912 (when bookmark-name
11913 (with-demoted-errors
11914 (bookmark-set bookmark-name))))
11915 ;; If we are refiling for capture, make sure that the
11916 ;; last-capture pointers point here
11917 (when (org-bound-and-true-p org-refile-for-capture)
11918 (let ((bookmark-name (plist-get org-bookmark-names-plist
11919 :last-capture-marker)))
11920 (when bookmark-name
11921 (with-demoted-errors
11922 (bookmark-set bookmark-name))))
11923 (move-marker org-capture-last-stored-marker (point)))
11924 (if (fboundp 'deactivate-mark) (deactivate-mark))
11925 (run-hooks 'org-after-refile-insert-hook))))
11926 (unless org-refile-keep
11927 (if regionp
11928 (delete-region (point) (+ (point) (- region-end region-start)))
11929 (delete-region
11930 (and (org-back-to-heading t) (point))
11931 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11932 (when (featurep 'org-inlinetask)
11933 (org-inlinetask-remove-END-maybe))
11934 (setq org-markers-to-move nil)
11935 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11937 (defun org-refile-goto-last-stored ()
11938 "Go to the location where the last refile was stored."
11939 (interactive)
11940 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11941 (message "This is the location of the last refile"))
11943 (defun org-refile--get-location (refloc tbl)
11944 "When user refile to REFLOC, find the associated target in TBL.
11945 Also check `org-refile-target-table'."
11946 (car (delq
11948 (mapcar
11949 (lambda (r) (or (assoc r tbl)
11950 (assoc r org-refile-target-table)))
11951 (list (replace-regexp-in-string "/$" "" refloc)
11952 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11954 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11955 no-exclude)
11956 "Prompt the user for a refile location, using PROMPT.
11957 PROMPT should not be suffixed with a colon and a space, because
11958 this function appends the default value from
11959 `org-refile-history' automatically, if that is not empty.
11960 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11961 this is used for the GOTO interface."
11962 (let ((org-refile-targets org-refile-targets)
11963 (org-refile-use-outline-path org-refile-use-outline-path)
11964 excluded-entries)
11965 (when (and (derived-mode-p 'org-mode)
11966 (not org-refile-use-cache)
11967 (not no-exclude))
11968 (org-map-tree
11969 (lambda()
11970 (setq excluded-entries
11971 (append excluded-entries (list (org-get-heading t t)))))))
11972 (setq org-refile-target-table
11973 (org-refile-get-targets default-buffer excluded-entries)))
11974 (unless org-refile-target-table
11975 (user-error "No refile targets"))
11976 (let* ((cbuf (current-buffer))
11977 (partial-completion-mode nil)
11978 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11979 (cfunc (if (and org-refile-use-outline-path
11980 org-outline-path-complete-in-steps)
11981 'org-olpath-completing-read
11982 'org-icompleting-read))
11983 (extra (if org-refile-use-outline-path "/" ""))
11984 (cbnex (concat (buffer-name) extra))
11985 (filename (and cfn (expand-file-name cfn)))
11986 (tbl (mapcar
11987 (lambda (x)
11988 (if (and (not (member org-refile-use-outline-path
11989 '(file full-file-path)))
11990 (not (equal filename (nth 1 x))))
11991 (cons (concat (car x) extra " ("
11992 (file-name-nondirectory (nth 1 x)) ")")
11993 (cdr x))
11994 (cons (concat (car x) extra) (cdr x))))
11995 org-refile-target-table))
11996 (completion-ignore-case t)
11997 cdef
11998 (prompt (concat prompt
11999 (or (and (car org-refile-history)
12000 (concat " (default " (car org-refile-history) ")"))
12001 (and (assoc cbnex tbl) (setq cdef cbnex)
12002 (concat " (default " cbnex ")"))) ": "))
12003 pa answ parent-target child parent old-hist)
12004 (setq old-hist org-refile-history)
12005 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12006 nil 'org-refile-history (or cdef (car org-refile-history))))
12007 (if (setq pa (org-refile--get-location answ tbl))
12008 (progn
12009 (org-refile-check-position pa)
12010 (when (or (not org-refile-history)
12011 (not (eq old-hist org-refile-history))
12012 (not (equal (car pa) (car org-refile-history))))
12013 (setq org-refile-history
12014 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12015 org-refile-history
12016 (cdr org-refile-history))))
12017 (if (equal (car org-refile-history) (nth 1 org-refile-history))
12018 (pop org-refile-history)))
12020 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12021 (progn
12022 (setq parent (match-string 1 answ)
12023 child (match-string 2 answ))
12024 (setq parent-target (org-refile--get-location parent tbl))
12025 (when (and parent-target
12026 (or (eq new-nodes t)
12027 (and (eq new-nodes 'confirm)
12028 (y-or-n-p (format "Create new node \"%s\"? "
12029 child)))))
12030 (org-refile-new-child parent-target child)))
12031 (user-error "Invalid target location")))))
12033 (declare-function org-string-nw-p "org-macs" (s))
12034 (defun org-refile-check-position (refile-pointer)
12035 "Check if the refile pointer matches the headline to which it points."
12036 (let* ((file (nth 1 refile-pointer))
12037 (re (nth 2 refile-pointer))
12038 (pos (nth 3 refile-pointer))
12039 buffer)
12040 (if (and (not (markerp pos)) (not file))
12041 (user-error "Please indicate a target file in the refile path")
12042 (when (org-string-nw-p re)
12043 (setq buffer (if (markerp pos)
12044 (marker-buffer pos)
12045 (or (find-buffer-visiting file)
12046 (find-file-noselect file))))
12047 (with-current-buffer buffer
12048 (save-excursion
12049 (save-restriction
12050 (widen)
12051 (goto-char pos)
12052 (beginning-of-line 1)
12053 (unless (org-looking-at-p re)
12054 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12056 (defun org-refile-new-child (parent-target child)
12057 "Use refile target PARENT-TARGET to add new CHILD below it."
12058 (unless parent-target
12059 (error "Cannot find parent for new node"))
12060 (let ((file (nth 1 parent-target))
12061 (pos (nth 3 parent-target))
12062 level)
12063 (with-current-buffer (or (find-buffer-visiting file)
12064 (find-file-noselect file))
12065 (save-excursion
12066 (save-restriction
12067 (widen)
12068 (if pos
12069 (goto-char pos)
12070 (goto-char (point-max))
12071 (if (not (bolp)) (newline)))
12072 (when (looking-at org-outline-regexp)
12073 (setq level (funcall outline-level))
12074 (org-end-of-subtree t t))
12075 (org-back-over-empty-lines)
12076 (insert "\n" (make-string
12077 (if pos (org-get-valid-level level 1) 1) ?*)
12078 " " child "\n")
12079 (beginning-of-line 0)
12080 (list (concat (car parent-target) "/" child) file "" (point)))))))
12082 (defun org-olpath-completing-read (prompt collection &rest args)
12083 "Read an outline path like a file name."
12084 (let ((thetable collection)
12085 (org-completion-use-ido nil) ; does not work with ido.
12086 (org-completion-use-iswitchb nil)) ; or iswitchb
12087 (apply
12088 'org-icompleting-read prompt
12089 (lambda (string predicate &optional flag)
12090 (let (rtn r f (l (length string)))
12091 (cond
12092 ((eq flag nil)
12093 ;; try completion
12094 (try-completion string thetable))
12095 ((eq flag t)
12096 ;; all-completions
12097 (setq rtn (all-completions string thetable predicate))
12098 (mapcar
12099 (lambda (x)
12100 (setq r (substring x l))
12101 (if (string-match " ([^)]*)$" x)
12102 (setq f (match-string 0 x))
12103 (setq f ""))
12104 (if (string-match "/" r)
12105 (concat string (substring r 0 (match-end 0)) f)
12107 rtn))
12108 ((eq flag 'lambda)
12109 ;; exact match?
12110 (assoc string thetable)))))
12111 args)))
12113 ;;;; Dynamic blocks
12115 (defun org-find-dblock (name)
12116 "Find the first dynamic block with name NAME in the buffer.
12117 If not found, stay at current position and return nil."
12118 (let ((case-fold-search t) pos)
12119 (save-excursion
12120 (goto-char (point-min))
12121 (setq pos (and (re-search-forward
12122 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12123 (match-beginning 0))))
12124 (if pos (goto-char pos))
12125 pos))
12127 (defun org-create-dblock (plist)
12128 "Create a dynamic block section, with parameters taken from PLIST.
12129 PLIST must contain a :name entry which is used as the name of the block."
12130 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12131 (end-of-line 1)
12132 (newline))
12133 (let ((col (current-column))
12134 (name (plist-get plist :name)))
12135 (insert "#+BEGIN: " name)
12136 (while plist
12137 (if (eq (car plist) :name)
12138 (setq plist (cddr plist))
12139 (insert " " (prin1-to-string (pop plist)))))
12140 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12141 (beginning-of-line -2)))
12143 (defun org-prepare-dblock ()
12144 "Prepare dynamic block for refresh.
12145 This empties the block, puts the cursor at the insert position and returns
12146 the property list including an extra property :name with the block name."
12147 (unless (looking-at org-dblock-start-re)
12148 (user-error "Not at a dynamic block"))
12149 (let* ((begdel (1+ (match-end 0)))
12150 (name (org-no-properties (match-string 1)))
12151 (params (append (list :name name)
12152 (read (concat "(" (match-string 3) ")")))))
12153 (save-excursion
12154 (beginning-of-line 1)
12155 (skip-chars-forward " \t")
12156 (setq params (plist-put params :indentation-column (current-column))))
12157 (unless (re-search-forward org-dblock-end-re nil t)
12158 (error "Dynamic block not terminated"))
12159 (setq params
12160 (append params
12161 (list :content (buffer-substring
12162 begdel (match-beginning 0)))))
12163 (delete-region begdel (match-beginning 0))
12164 (goto-char begdel)
12165 (open-line 1)
12166 params))
12168 (defun org-map-dblocks (&optional command)
12169 "Apply COMMAND to all dynamic blocks in the current buffer.
12170 If COMMAND is not given, use `org-update-dblock'."
12171 (let ((cmd (or command 'org-update-dblock)))
12172 (save-excursion
12173 (goto-char (point-min))
12174 (while (re-search-forward org-dblock-start-re nil t)
12175 (goto-char (match-beginning 0))
12176 (save-excursion
12177 (condition-case nil
12178 (funcall cmd)
12179 (error (message "Error during update of dynamic block"))))
12180 (unless (re-search-forward org-dblock-end-re nil t)
12181 (error "Dynamic block not terminated"))))))
12183 (defun org-dblock-update (&optional arg)
12184 "User command for updating dynamic blocks.
12185 Update the dynamic block at point. With prefix ARG, update all dynamic
12186 blocks in the buffer."
12187 (interactive "P")
12188 (if arg
12189 (org-update-all-dblocks)
12190 (or (looking-at org-dblock-start-re)
12191 (org-beginning-of-dblock))
12192 (org-update-dblock)))
12194 (defun org-update-dblock ()
12195 "Update the dynamic block at point.
12196 This means to empty the block, parse for parameters and then call
12197 the correct writing function."
12198 (interactive)
12199 (save-excursion
12200 (let* ((win (selected-window))
12201 (pos (point))
12202 (line (org-current-line))
12203 (params (org-prepare-dblock))
12204 (name (plist-get params :name))
12205 (indent (plist-get params :indentation-column))
12206 (cmd (intern (concat "org-dblock-write:" name))))
12207 (message "Updating dynamic block `%s' at line %d..." name line)
12208 (funcall cmd params)
12209 (message "Updating dynamic block `%s' at line %d...done" name line)
12210 (goto-char pos)
12211 (when (and indent (> indent 0))
12212 (setq indent (make-string indent ?\ ))
12213 (save-excursion
12214 (select-window win)
12215 (org-beginning-of-dblock)
12216 (forward-line 1)
12217 (while (not (looking-at org-dblock-end-re))
12218 (insert indent)
12219 (beginning-of-line 2))
12220 (when (looking-at org-dblock-end-re)
12221 (and (looking-at "[ \t]+")
12222 (replace-match ""))
12223 (insert indent)))))))
12225 (defun org-beginning-of-dblock ()
12226 "Find the beginning of the dynamic block at point.
12227 Error if there is no such block at point."
12228 (let ((pos (point))
12229 beg)
12230 (end-of-line 1)
12231 (if (and (re-search-backward org-dblock-start-re nil t)
12232 (setq beg (match-beginning 0))
12233 (re-search-forward org-dblock-end-re nil t)
12234 (> (match-end 0) pos))
12235 (goto-char beg)
12236 (goto-char pos)
12237 (error "Not in a dynamic block"))))
12239 (defun org-update-all-dblocks ()
12240 "Update all dynamic blocks in the buffer.
12241 This function can be used in a hook."
12242 (interactive)
12243 (when (derived-mode-p 'org-mode)
12244 (org-map-dblocks 'org-update-dblock)))
12247 ;;;; Completion
12249 (declare-function org-export-backend-name "org-export" (cl-x))
12250 (declare-function org-export-backend-options "org-export" (cl-x))
12251 (defun org-get-export-keywords ()
12252 "Return a list of all currently understood export keywords.
12253 Export keywords include options, block names, attributes and
12254 keywords relative to each registered export back-end."
12255 (let (keywords)
12256 (dolist (backend
12257 (org-bound-and-true-p org-export--registered-backends)
12258 (delq nil keywords))
12259 ;; Back-end name (for keywords, like #+LATEX:)
12260 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12261 (dolist (option-entry (org-export-backend-options backend))
12262 ;; Back-end options.
12263 (push (nth 1 option-entry) keywords)))))
12265 (defconst org-options-keywords
12266 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12267 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12268 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12269 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12270 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12272 (defcustom org-structure-template-alist
12273 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12274 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12275 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12276 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12277 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12278 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12279 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12280 ("L" "#+LaTeX: ")
12281 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12282 ("H" "#+HTML: ")
12283 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12284 ("A" "#+ASCII: ")
12285 ("i" "#+INDEX: ?")
12286 ("I" "#+INCLUDE: %file ?"))
12287 "Structure completion elements.
12288 This is a list of abbreviation keys and values. The value gets inserted
12289 if you type `<' followed by the key and then press the completion key,
12290 usually `TAB'. %file will be replaced by a file name after prompting
12291 for the file using completion. The cursor will be placed at the position
12292 of the `?` in the template.
12293 There are two templates for each key, the first uses the original Org syntax,
12294 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12295 the default when the /org-mtags.el/ module has been loaded. See also the
12296 variable `org-mtags-prefer-muse-templates'."
12297 :group 'org-completion
12298 :type '(repeat
12299 (list
12300 (string :tag "Key")
12301 (string :tag "Template")))
12302 :version 24.4
12303 :package-version '(Org . "8.3"))
12305 (defun org-try-structure-completion ()
12306 "Try to complete a structure template before point.
12307 This looks for strings like \"<e\" on an otherwise empty line and
12308 expands them."
12309 (let ((l (buffer-substring (point-at-bol) (point)))
12311 (when (and (looking-at "[ \t]*$")
12312 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12313 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12314 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12315 (match-beginning 1)) a)
12316 t)))
12318 (defun org-complete-expand-structure-template (start cell)
12319 "Expand a structure template."
12320 (let ((rpl (nth 1 cell))
12321 (ind ""))
12322 (delete-region start (point))
12323 (when (string-match "\\`[ \t]*#\\+" rpl)
12324 (cond
12325 ((bolp))
12326 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12327 (setq ind (buffer-substring (point-at-bol) (point))))
12328 (t (newline))))
12329 (setq start (point))
12330 (if (string-match "%file" rpl)
12331 (setq rpl (replace-match
12332 (concat
12333 "\""
12334 (save-match-data
12335 (abbreviate-file-name (read-file-name "Include file: ")))
12336 "\"")
12337 t t rpl)))
12338 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12339 (concat "\n" ind)))
12340 (insert rpl)
12341 (if (re-search-backward "\\?" start t) (delete-char 1))))
12343 ;;;; TODO, DEADLINE, Comments
12345 (defun org-toggle-comment ()
12346 "Change the COMMENT state of an entry."
12347 (interactive)
12348 (save-excursion
12349 (org-back-to-heading)
12350 (looking-at org-complex-heading-regexp)
12351 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12352 (skip-chars-forward " \t")
12353 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12354 (if (org-in-commented-heading-p t)
12355 (delete-region (point)
12356 (progn (search-forward " " (line-end-position) 'move)
12357 (skip-chars-forward " \t")
12358 (point)))
12359 (insert org-comment-string)
12360 (unless (eolp) (insert " ")))))
12362 (defvar org-last-todo-state-is-todo nil
12363 "This is non-nil when the last TODO state change led to a TODO state.
12364 If the last change removed the TODO tag or switched to DONE, then
12365 this is nil.")
12367 (defvar org-setting-tags nil) ; dynamically skipped
12369 (defvar org-todo-setup-filter-hook nil
12370 "Hook for functions that pre-filter todo specs.
12371 Each function takes a todo spec and returns either nil or the spec
12372 transformed into canonical form." )
12374 (defvar org-todo-get-default-hook nil
12375 "Hook for functions that get a default item for todo.
12376 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12377 nil or a string to be used for the todo mark." )
12379 (defvar org-agenda-headline-snapshot-before-repeat)
12381 (defun org-current-effective-time ()
12382 "Return current time adjusted for `org-extend-today-until' variable."
12383 (let* ((ct (org-current-time))
12384 (dct (decode-time ct))
12385 (ct1
12386 (cond
12387 (org-use-last-clock-out-time-as-effective-time
12388 (or (org-clock-get-last-clock-out-time) ct))
12389 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12390 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12391 (t ct))))
12392 ct1))
12394 (defun org-todo-yesterday (&optional arg)
12395 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12396 (interactive "P")
12397 (if (eq major-mode 'org-agenda-mode)
12398 (apply 'org-agenda-todo-yesterday arg)
12399 (let* ((hour (third (decode-time
12400 (org-current-time))))
12401 (org-extend-today-until (1+ hour)))
12402 (org-todo arg))))
12404 (defvar org-block-entry-blocking ""
12405 "First entry preventing the TODO state change.")
12407 (defun org-cancel-repeater ()
12408 "Cancel a repeater by setting its numeric value to zero."
12409 (interactive)
12410 (save-excursion
12411 (org-back-to-heading t)
12412 (let ((bound1 (point))
12413 (bound0 (save-excursion (outline-next-heading) (point))))
12414 (when (re-search-forward
12415 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12416 org-deadline-time-regexp "\\)\\|\\("
12417 org-ts-regexp "\\)")
12418 bound0 t)
12419 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12420 (replace-match "0" t nil nil 1))))))
12422 (defun org-todo (&optional arg)
12423 "Change the TODO state of an item.
12424 The state of an item is given by a keyword at the start of the heading,
12425 like
12426 *** TODO Write paper
12427 *** DONE Call mom
12429 The different keywords are specified in the variable `org-todo-keywords'.
12430 By default the available states are \"TODO\" and \"DONE\".
12431 So for this example: when the item starts with TODO, it is changed to DONE.
12432 When it starts with DONE, the DONE is removed. And when neither TODO nor
12433 DONE are present, add TODO at the beginning of the heading.
12435 With \\[universal-argument] prefix arg, use completion to determine the new \
12436 state.
12437 With numeric prefix arg, switch to that state.
12438 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12439 keywords (nextset).
12440 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12441 With a numeric prefix arg of 0, inhibit note taking for the change.
12442 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12444 When called through ELisp, arg is also interpreted in the following way:
12445 'none -> empty state
12446 \"\"(empty string) -> switch to empty state
12447 'done -> switch to DONE
12448 'nextset -> switch to the next set of keywords
12449 'previousset -> switch to the previous set of keywords
12450 \"WAITING\" -> switch to the specified keyword, but only if it
12451 really is a member of `org-todo-keywords'."
12452 (interactive "P")
12453 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12454 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12455 'region-start-level 'region))
12456 org-loop-over-headlines-in-active-region)
12457 (org-map-entries
12458 `(org-todo ,arg)
12459 org-loop-over-headlines-in-active-region
12460 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12461 (if (equal arg '(16)) (setq arg 'nextset))
12462 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12463 (let ((org-blocker-hook org-blocker-hook)
12464 commentp
12465 case-fold-search)
12466 (when (equal arg '(64))
12467 (setq arg nil org-blocker-hook nil))
12468 (when (and org-blocker-hook
12469 (or org-inhibit-blocking
12470 (org-entry-get nil "NOBLOCKING")))
12471 (setq org-blocker-hook nil))
12472 (save-excursion
12473 (catch 'exit
12474 (org-back-to-heading t)
12475 (when (org-in-commented-heading-p t)
12476 (org-toggle-comment)
12477 (setq commentp t))
12478 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12479 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12480 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12481 (let* ((match-data (match-data))
12482 (startpos (point-at-bol))
12483 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12484 (org-log-done org-log-done)
12485 (org-log-repeat org-log-repeat)
12486 (org-todo-log-states org-todo-log-states)
12487 (org-inhibit-logging
12488 (if (equal arg 0)
12489 (progn (setq arg nil) 'note) org-inhibit-logging))
12490 (this (match-string 1))
12491 (hl-pos (match-beginning 0))
12492 (head (org-get-todo-sequence-head this))
12493 (ass (assoc head org-todo-kwd-alist))
12494 (interpret (nth 1 ass))
12495 (done-word (nth 3 ass))
12496 (final-done-word (nth 4 ass))
12497 (org-last-state (or this ""))
12498 (completion-ignore-case t)
12499 (member (member this org-todo-keywords-1))
12500 (tail (cdr member))
12501 (org-state (cond
12502 ((and org-todo-key-trigger
12503 (or (and (equal arg '(4))
12504 (eq org-use-fast-todo-selection 'prefix))
12505 (and (not arg) org-use-fast-todo-selection
12506 (not (eq org-use-fast-todo-selection
12507 'prefix)))))
12508 ;; Use fast selection
12509 (org-fast-todo-selection))
12510 ((and (equal arg '(4))
12511 (or (not org-use-fast-todo-selection)
12512 (not org-todo-key-trigger)))
12513 ;; Read a state with completion
12514 (org-icompleting-read
12515 "State: " (mapcar 'list org-todo-keywords-1)
12516 nil t))
12517 ((eq arg 'right)
12518 (if this
12519 (if tail (car tail) nil)
12520 (car org-todo-keywords-1)))
12521 ((eq arg 'left)
12522 (if (equal member org-todo-keywords-1)
12524 (if this
12525 (nth (- (length org-todo-keywords-1)
12526 (length tail) 2)
12527 org-todo-keywords-1)
12528 (org-last org-todo-keywords-1))))
12529 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12530 (setq arg nil))) ; hack to fall back to cycling
12531 (arg
12532 ;; user or caller requests a specific state
12533 (cond
12534 ((equal arg "") nil)
12535 ((eq arg 'none) nil)
12536 ((eq arg 'done) (or done-word (car org-done-keywords)))
12537 ((eq arg 'nextset)
12538 (or (car (cdr (member head org-todo-heads)))
12539 (car org-todo-heads)))
12540 ((eq arg 'previousset)
12541 (let ((org-todo-heads (reverse org-todo-heads)))
12542 (or (car (cdr (member head org-todo-heads)))
12543 (car org-todo-heads))))
12544 ((car (member arg org-todo-keywords-1)))
12545 ((stringp arg)
12546 (user-error "State `%s' not valid in this file" arg))
12547 ((nth (1- (prefix-numeric-value arg))
12548 org-todo-keywords-1))))
12549 ((null member) (or head (car org-todo-keywords-1)))
12550 ((equal this final-done-word) nil) ;; -> make empty
12551 ((null tail) nil) ;; -> first entry
12552 ((memq interpret '(type priority))
12553 (if (eq this-command last-command)
12554 (car tail)
12555 (if (> (length tail) 0)
12556 (or done-word (car org-done-keywords))
12557 nil)))
12559 (car tail))))
12560 (org-state (or
12561 (run-hook-with-args-until-success
12562 'org-todo-get-default-hook org-state org-last-state)
12563 org-state))
12564 (next (if org-state (concat " " org-state " ") " "))
12565 (change-plist (list :type 'todo-state-change :from this :to org-state
12566 :position startpos))
12567 dolog now-done-p)
12568 (when org-blocker-hook
12569 (setq org-last-todo-state-is-todo
12570 (not (member this org-done-keywords)))
12571 (unless (save-excursion
12572 (save-match-data
12573 (org-with-wide-buffer
12574 (run-hook-with-args-until-failure
12575 'org-blocker-hook change-plist))))
12576 (if (org-called-interactively-p 'interactive)
12577 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12578 this org-state org-block-entry-blocking)
12579 ;; fail silently
12580 (message "TODO state change from %s to %s blocked (by \"%s\")"
12581 this org-state org-block-entry-blocking)
12582 (throw 'exit nil))))
12583 (store-match-data match-data)
12584 (replace-match next t t)
12585 (cond ((equal this org-state)
12586 (message "TODO state was already %s" (org-trim next)))
12587 ((pos-visible-in-window-p hl-pos)
12588 (message "TODO state changed to %s" (org-trim next))))
12589 (unless head
12590 (setq head (org-get-todo-sequence-head org-state)
12591 ass (assoc head org-todo-kwd-alist)
12592 interpret (nth 1 ass)
12593 done-word (nth 3 ass)
12594 final-done-word (nth 4 ass)))
12595 (when (memq arg '(nextset previousset))
12596 (message "Keyword-Set %d/%d: %s"
12597 (- (length org-todo-sets) -1
12598 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12599 (length org-todo-sets)
12600 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12601 (setq org-last-todo-state-is-todo
12602 (not (member org-state org-done-keywords)))
12603 (setq now-done-p (and (member org-state org-done-keywords)
12604 (not (member this org-done-keywords))))
12605 (and logging (org-local-logging logging))
12606 (when (and (or org-todo-log-states org-log-done)
12607 (not (eq org-inhibit-logging t))
12608 (not (memq arg '(nextset previousset))))
12609 ;; we need to look at recording a time and note
12610 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12611 (nth 2 (assoc this org-todo-log-states))))
12612 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12613 (setq dolog 'time))
12614 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12615 (and org-state
12616 (member org-state org-not-done-keywords)
12617 (not (member this org-not-done-keywords))))
12618 ;; This is now a todo state and was not one before
12619 ;; If there was a CLOSED time stamp, get rid of it.
12620 (org-add-planning-info nil nil 'closed))
12621 (when (and now-done-p org-log-done)
12622 ;; It is now done, and it was not done before
12623 (org-add-planning-info 'closed (org-current-effective-time))
12624 (if (and (not dolog) (eq 'note org-log-done))
12625 (org-add-log-setup 'done org-state this 'findpos 'note)))
12626 (when (and org-state dolog)
12627 ;; This is a non-nil state, and we need to log it
12628 (org-add-log-setup 'state org-state this 'findpos dolog)))
12629 ;; Fixup tag positioning
12630 (org-todo-trigger-tag-changes org-state)
12631 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12632 (when org-provide-todo-statistics
12633 (org-update-parent-todo-statistics))
12634 (run-hooks 'org-after-todo-state-change-hook)
12635 (if (and arg (not (member org-state org-done-keywords)))
12636 (setq head (org-get-todo-sequence-head org-state)))
12637 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12638 ;; Do we need to trigger a repeat?
12639 (when now-done-p
12640 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12641 ;; This is for the agenda, take a snapshot of the headline.
12642 (save-match-data
12643 (setq org-agenda-headline-snapshot-before-repeat
12644 (org-get-heading))))
12645 (org-auto-repeat-maybe org-state))
12646 ;; Fixup cursor location if close to the keyword
12647 (if (and (outline-on-heading-p)
12648 (not (bolp))
12649 (save-excursion (beginning-of-line 1)
12650 (looking-at org-todo-line-regexp))
12651 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12652 (progn
12653 (goto-char (or (match-end 2) (match-end 1)))
12654 (and (looking-at " ") (just-one-space))))
12655 (when org-trigger-hook
12656 (save-excursion
12657 (run-hook-with-args 'org-trigger-hook change-plist)))
12658 (when commentp (org-toggle-comment))))))))
12660 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12661 "Block turning an entry into a TODO, using the hierarchy.
12662 This checks whether the current task should be blocked from state
12663 changes. Such blocking occurs when:
12665 1. The task has children which are not all in a completed state.
12667 2. A task has a parent with the property :ORDERED:, and there
12668 are siblings prior to the current task with incomplete
12669 status.
12671 3. The parent of the task is blocked because it has siblings that should
12672 be done first, or is child of a block grandparent TODO entry."
12674 (if (not org-enforce-todo-dependencies)
12675 t ; if locally turned off don't block
12676 (catch 'dont-block
12677 ;; If this is not a todo state change, or if this entry is already DONE,
12678 ;; do not block
12679 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12680 (member (plist-get change-plist :from)
12681 (cons 'done org-done-keywords))
12682 (member (plist-get change-plist :to)
12683 (cons 'todo org-not-done-keywords))
12684 (not (plist-get change-plist :to)))
12685 (throw 'dont-block t))
12686 ;; If this task has children, and any are undone, it's blocked
12687 (save-excursion
12688 (org-back-to-heading t)
12689 (let ((this-level (funcall outline-level)))
12690 (outline-next-heading)
12691 (let ((child-level (funcall outline-level)))
12692 (while (and (not (eobp))
12693 (> child-level this-level))
12694 ;; this todo has children, check whether they are all
12695 ;; completed
12696 (if (and (not (org-entry-is-done-p))
12697 (org-entry-is-todo-p))
12698 (progn (setq org-block-entry-blocking (org-get-heading))
12699 (throw 'dont-block nil)))
12700 (outline-next-heading)
12701 (setq child-level (funcall outline-level))))))
12702 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12703 ;; any previous siblings are undone, it's blocked
12704 (save-excursion
12705 (org-back-to-heading t)
12706 (let* ((pos (point))
12707 (parent-pos (and (org-up-heading-safe) (point))))
12708 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12709 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12710 (forward-line 1)
12711 (re-search-forward org-not-done-heading-regexp pos t))
12712 (setq org-block-entry-blocking (match-string 0))
12713 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12714 ;; Search further up the hierarchy, to see if an ancestor is blocked
12715 (while t
12716 (goto-char parent-pos)
12717 (if (not (looking-at org-not-done-heading-regexp))
12718 (throw 'dont-block t)) ; do not block, parent is not a TODO
12719 (setq pos (point))
12720 (setq parent-pos (and (org-up-heading-safe) (point)))
12721 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12722 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12723 (forward-line 1)
12724 (re-search-forward org-not-done-heading-regexp pos t)
12725 (setq org-block-entry-blocking (org-get-heading)))
12726 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12728 (defcustom org-track-ordered-property-with-tag nil
12729 "Should the ORDERED property also be shown as a tag?
12730 The ORDERED property decides if an entry should require subtasks to be
12731 completed in sequence. Since a property is not very visible, setting
12732 this option means that toggling the ORDERED property with the command
12733 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12734 not relevant for the behavior, but it makes things more visible.
12736 Note that toggling the tag with tags commands will not change the property
12737 and therefore not influence behavior!
12739 This can be t, meaning the tag ORDERED should be used, It can also be a
12740 string to select a different tag for this task."
12741 :group 'org-todo
12742 :type '(choice
12743 (const :tag "No tracking" nil)
12744 (const :tag "Track with ORDERED tag" t)
12745 (string :tag "Use other tag")))
12747 (defun org-toggle-ordered-property ()
12748 "Toggle the ORDERED property of the current entry.
12749 For better visibility, you can track the value of this property with a tag.
12750 See variable `org-track-ordered-property-with-tag'."
12751 (interactive)
12752 (let* ((t1 org-track-ordered-property-with-tag)
12753 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12754 (save-excursion
12755 (org-back-to-heading)
12756 (if (org-entry-get nil "ORDERED")
12757 (progn
12758 (org-delete-property "ORDERED")
12759 (and tag (org-toggle-tag tag 'off))
12760 (message "Subtasks can be completed in arbitrary order"))
12761 (org-entry-put nil "ORDERED" "t")
12762 (and tag (org-toggle-tag tag 'on))
12763 (message "Subtasks must be completed in sequence")))))
12765 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12766 (defun org-block-todo-from-checkboxes (change-plist)
12767 "Block turning an entry into a TODO, using checkboxes.
12768 This checks whether the current task should be blocked from state
12769 changes because there are unchecked boxes in this entry."
12770 (if (not org-enforce-todo-checkbox-dependencies)
12771 t ; if locally turned off don't block
12772 (catch 'dont-block
12773 ;; If this is not a todo state change, or if this entry is already DONE,
12774 ;; do not block
12775 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12776 (member (plist-get change-plist :from)
12777 (cons 'done org-done-keywords))
12778 (member (plist-get change-plist :to)
12779 (cons 'todo org-not-done-keywords))
12780 (not (plist-get change-plist :to)))
12781 (throw 'dont-block t))
12782 ;; If this task has checkboxes that are not checked, it's blocked
12783 (save-excursion
12784 (org-back-to-heading t)
12785 (let ((beg (point)) end)
12786 (outline-next-heading)
12787 (setq end (point))
12788 (goto-char beg)
12789 (if (org-list-search-forward
12790 (concat (org-item-beginning-re)
12791 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12792 "\\[[- ]\\]")
12793 end t)
12794 (progn
12795 (if (boundp 'org-blocked-by-checkboxes)
12796 (setq org-blocked-by-checkboxes t))
12797 (throw 'dont-block nil)))))
12798 t))) ; do not block
12800 (defun org-entry-blocked-p ()
12801 "Is the current entry blocked?"
12802 (org-with-silent-modifications
12803 (if (org-entry-get nil "NOBLOCKING")
12804 nil ;; Never block this entry
12805 (not (run-hook-with-args-until-failure
12806 'org-blocker-hook
12807 (list :type 'todo-state-change
12808 :position (point)
12809 :from 'todo
12810 :to 'done))))))
12812 (defun org-update-statistics-cookies (all)
12813 "Update the statistics cookie, either from TODO or from checkboxes.
12814 This should be called with the cursor in a line with a statistics cookie."
12815 (interactive "P")
12816 (if all
12817 (progn
12818 (org-update-checkbox-count 'all)
12819 (org-map-entries 'org-update-parent-todo-statistics))
12820 (if (not (org-at-heading-p))
12821 (org-update-checkbox-count)
12822 (let ((pos (point-marker))
12823 end l1 l2)
12824 (ignore-errors (org-back-to-heading t))
12825 (if (not (org-at-heading-p))
12826 (org-update-checkbox-count)
12827 (setq l1 (org-outline-level))
12828 (setq end (save-excursion
12829 (outline-next-heading)
12830 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12831 (point)))
12832 (if (and (save-excursion
12833 (re-search-forward
12834 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12835 (not (save-excursion (re-search-forward
12836 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12837 (org-update-checkbox-count)
12838 (if (and l2 (> l2 l1))
12839 (progn
12840 (goto-char end)
12841 (org-update-parent-todo-statistics))
12842 (goto-char pos)
12843 (beginning-of-line 1)
12844 (while (re-search-forward
12845 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12846 (point-at-eol) t)
12847 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12848 (goto-char pos)
12849 (move-marker pos nil)))))
12851 (defvar org-entry-property-inherited-from) ;; defined below
12852 (defun org-update-parent-todo-statistics ()
12853 "Update any statistics cookie in the parent of the current headline.
12854 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12855 the entire subtree and this will travel up the hierarchy and update
12856 statistics everywhere."
12857 (let* ((prop (save-excursion (org-up-heading-safe)
12858 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12859 (recursive (or (not org-hierarchical-todo-statistics)
12860 (and prop (string-match "\\<recursive\\>" prop))))
12861 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12863 (first t)
12864 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12865 level ltoggle l1 new ndel
12866 (cnt-all 0) (cnt-done 0) is-percent kwd
12867 checkbox-beg ov ovs ove cookie-present)
12868 (catch 'exit
12869 (save-excursion
12870 (beginning-of-line 1)
12871 (setq ltoggle (funcall outline-level))
12872 ;; Three situations are to consider:
12874 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12875 ;; to the top-level ancestor on the headline;
12877 ;; 2. If parent has "recursive" property, repeat up to the
12878 ;; headline setting that property, taking inheritance into
12879 ;; account;
12881 ;; 3. Else, move up to direct parent and proceed only once.
12882 (while (and (setq level (org-up-heading-safe))
12883 (or recursive first)
12884 (>= (point) lim))
12885 (setq first nil cookie-present nil)
12886 (unless (and level
12887 (not (string-match
12888 "\\<checkbox\\>"
12889 (downcase (or (org-entry-get nil "COOKIE_DATA")
12890 "")))))
12891 (throw 'exit nil))
12892 (while (re-search-forward box-re (point-at-eol) t)
12893 (setq cnt-all 0 cnt-done 0 cookie-present t)
12894 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12895 (save-match-data
12896 (unless (outline-next-heading) (throw 'exit nil))
12897 (while (and (looking-at org-complex-heading-regexp)
12898 (> (setq l1 (length (match-string 1))) level))
12899 (setq kwd (and (or recursive (= l1 ltoggle))
12900 (match-string 2)))
12901 (if (or (eq org-provide-todo-statistics 'all-headlines)
12902 (and (eq org-provide-todo-statistics t)
12903 (or (member kwd org-done-keywords)))
12904 (and (listp org-provide-todo-statistics)
12905 (stringp (car org-provide-todo-statistics))
12906 (or (member kwd org-provide-todo-statistics)
12907 (member kwd org-done-keywords)))
12908 (and (listp org-provide-todo-statistics)
12909 (listp (car org-provide-todo-statistics))
12910 (or (member kwd (car org-provide-todo-statistics))
12911 (and (member kwd org-done-keywords)
12912 (member kwd (cadr org-provide-todo-statistics))))))
12913 (setq cnt-all (1+ cnt-all))
12914 (if (eq org-provide-todo-statistics t)
12915 (and kwd (setq cnt-all (1+ cnt-all)))))
12916 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12917 (member kwd org-done-keywords))
12918 (and (listp org-provide-todo-statistics)
12919 (listp (car org-provide-todo-statistics))
12920 (member kwd org-done-keywords)
12921 (member kwd (cadr org-provide-todo-statistics)))
12922 (and (listp org-provide-todo-statistics)
12923 (stringp (car org-provide-todo-statistics))
12924 (member kwd org-done-keywords)))
12925 (setq cnt-done (1+ cnt-done)))
12926 (outline-next-heading)))
12927 (setq new
12928 (if is-percent
12929 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12930 (format "[%d/%d]" cnt-done cnt-all))
12931 ndel (- (match-end 0) checkbox-beg))
12932 ;; handle overlays when updating cookie from column view
12933 (when (setq ov (car (overlays-at checkbox-beg)))
12934 (setq ovs (overlay-start ov) ove (overlay-end ov))
12935 (delete-overlay ov))
12936 (goto-char checkbox-beg)
12937 (insert new)
12938 (delete-region (point) (+ (point) ndel))
12939 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12940 (when ov (move-overlay ov ovs ove)))
12941 (when cookie-present
12942 (run-hook-with-args 'org-after-todo-statistics-hook
12943 cnt-done (- cnt-all cnt-done))))))
12944 (run-hooks 'org-todo-statistics-hook)))
12946 (defvar org-after-todo-statistics-hook nil
12947 "Hook that is called after a TODO statistics cookie has been updated.
12948 Each function is called with two arguments: the number of not-done entries
12949 and the number of done entries.
12951 For example, the following function, when added to this hook, will switch
12952 an entry to DONE when all children are done, and back to TODO when new
12953 entries are set to a TODO status. Note that this hook is only called
12954 when there is a statistics cookie in the headline!
12956 (defun org-summary-todo (n-done n-not-done)
12957 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12958 (let (org-log-done org-log-states) ; turn off logging
12959 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12962 (defvar org-todo-statistics-hook nil
12963 "Hook that is run whenever Org thinks TODO statistics should be updated.
12964 This hook runs even if there is no statistics cookie present, in which case
12965 `org-after-todo-statistics-hook' would not run.")
12967 (defun org-todo-trigger-tag-changes (state)
12968 "Apply the changes defined in `org-todo-state-tags-triggers'."
12969 (let ((l org-todo-state-tags-triggers)
12970 changes)
12971 (when (or (not state) (equal state ""))
12972 (setq changes (append changes (cdr (assoc "" l)))))
12973 (when (and (stringp state) (> (length state) 0))
12974 (setq changes (append changes (cdr (assoc state l)))))
12975 (when (member state org-not-done-keywords)
12976 (setq changes (append changes (cdr (assoc 'todo l)))))
12977 (when (member state org-done-keywords)
12978 (setq changes (append changes (cdr (assoc 'done l)))))
12979 (dolist (c changes)
12980 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12982 (defun org-local-logging (value)
12983 "Get logging settings from a property VALUE."
12984 (let* (words w a)
12985 ;; directly set the variables, they are already local.
12986 (setq org-log-done nil
12987 org-log-repeat nil
12988 org-todo-log-states nil)
12989 (setq words (org-split-string value))
12990 (while (setq w (pop words))
12991 (cond
12992 ((setq a (assoc w org-startup-options))
12993 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12994 (set (nth 1 a) (nth 2 a))))
12995 ((setq a (org-extract-log-state-settings w))
12996 (and (member (car a) org-todo-keywords-1)
12997 (push a org-todo-log-states)))))))
12999 (defun org-get-todo-sequence-head (kwd)
13000 "Return the head of the TODO sequence to which KWD belongs.
13001 If KWD is not set, check if there is a text property remembering the
13002 right sequence."
13003 (let (p)
13004 (cond
13005 ((not kwd)
13006 (or (get-text-property (point-at-bol) 'org-todo-head)
13007 (progn
13008 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13009 nil (point-at-eol)))
13010 (get-text-property p 'org-todo-head))))
13011 ((not (member kwd org-todo-keywords-1))
13012 (car org-todo-keywords-1))
13013 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13015 (defun org-fast-todo-selection ()
13016 "Fast TODO keyword selection with single keys.
13017 Returns the new TODO keyword, or nil if no state change should occur."
13018 (let* ((fulltable org-todo-key-alist)
13019 (done-keywords org-done-keywords) ;; needed for the faces.
13020 (maxlen (apply 'max (mapcar
13021 (lambda (x)
13022 (if (stringp (car x)) (string-width (car x)) 0))
13023 fulltable)))
13024 (expert nil)
13025 (fwidth (+ maxlen 3 1 3))
13026 (ncol (/ (- (window-width) 4) fwidth))
13027 tg cnt e c tbl
13028 groups ingroup)
13029 (save-excursion
13030 (save-window-excursion
13031 (if expert
13032 (set-buffer (get-buffer-create " *Org todo*"))
13033 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13034 (erase-buffer)
13035 (org-set-local 'org-done-keywords done-keywords)
13036 (setq tbl fulltable cnt 0)
13037 (while (setq e (pop tbl))
13038 (cond
13039 ((equal e '(:startgroup))
13040 (push '() groups) (setq ingroup t)
13041 (when (not (= cnt 0))
13042 (setq cnt 0)
13043 (insert "\n"))
13044 (insert "{ "))
13045 ((equal e '(:endgroup))
13046 (setq ingroup nil cnt 0)
13047 (insert "}\n"))
13048 ((equal e '(:newline))
13049 (when (not (= cnt 0))
13050 (setq cnt 0)
13051 (insert "\n")
13052 (setq e (car tbl))
13053 (while (equal (car tbl) '(:newline))
13054 (insert "\n")
13055 (setq tbl (cdr tbl)))))
13057 (setq tg (car e) c (cdr e))
13058 (if ingroup (push tg (car groups)))
13059 (setq tg (org-add-props tg nil 'face
13060 (org-get-todo-face tg)))
13061 (if (and (= cnt 0) (not ingroup)) (insert " "))
13062 (insert "[" c "] " tg (make-string
13063 (- fwidth 4 (length tg)) ?\ ))
13064 (when (= (setq cnt (1+ cnt)) ncol)
13065 (insert "\n")
13066 (if ingroup (insert " "))
13067 (setq cnt 0)))))
13068 (insert "\n")
13069 (goto-char (point-min))
13070 (if (not expert) (org-fit-window-to-buffer))
13071 (message "[a-z..]:Set [SPC]:clear")
13072 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13073 (cond
13074 ((or (= c ?\C-g)
13075 (and (= c ?q) (not (rassoc c fulltable))))
13076 (setq quit-flag t))
13077 ((= c ?\ ) nil)
13078 ((setq e (rassoc c fulltable) tg (car e))
13080 (t (setq quit-flag t)))))))
13082 (defun org-entry-is-todo-p ()
13083 (member (org-get-todo-state) org-not-done-keywords))
13085 (defun org-entry-is-done-p ()
13086 (member (org-get-todo-state) org-done-keywords))
13088 (defun org-get-todo-state ()
13089 "Return the TODO keyword of the current subtree."
13090 (save-excursion
13091 (org-back-to-heading t)
13092 (and (looking-at org-todo-line-regexp)
13093 (match-end 2)
13094 (match-string 2))))
13096 (defun org-at-date-range-p (&optional inactive-ok)
13097 "Is the cursor inside a date range?"
13098 (interactive)
13099 (save-excursion
13100 (catch 'exit
13101 (let ((pos (point)))
13102 (skip-chars-backward "^[<\r\n")
13103 (skip-chars-backward "<[")
13104 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13105 (>= (match-end 0) pos)
13106 (throw 'exit t))
13107 (skip-chars-backward "^<[\r\n")
13108 (skip-chars-backward "<[")
13109 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13110 (>= (match-end 0) pos)
13111 (throw 'exit t)))
13112 nil)))
13114 (defun org-get-repeat (&optional tagline)
13115 "Check if there is a deadline/schedule with repeater in this entry."
13116 (save-match-data
13117 (save-excursion
13118 (org-back-to-heading t)
13119 (and (re-search-forward (if tagline
13120 (concat tagline "\\s-*" org-repeat-re)
13121 org-repeat-re)
13122 (org-entry-end-position) t)
13123 (match-string-no-properties 1)))))
13125 (defvar org-last-changed-timestamp)
13126 (defvar org-last-inserted-timestamp)
13127 (defvar org-log-post-message)
13128 (defvar org-log-note-purpose)
13129 (defvar org-log-note-how nil)
13130 (defvar org-log-note-extra)
13131 (defun org-auto-repeat-maybe (done-word)
13132 "Check if the current headline contains a repeated deadline/schedule.
13133 If yes, set TODO state back to what it was and change the base date
13134 of repeating deadline/scheduled time stamps to new date.
13135 This function is run automatically after each state change to a DONE state."
13136 ;; last-state is dynamically scoped into this function
13137 (let* ((repeat (org-get-repeat))
13138 (aa (assoc org-last-state org-todo-kwd-alist))
13139 (interpret (nth 1 aa))
13140 (head (nth 2 aa))
13141 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13142 (msg "Entry repeats: ")
13143 (org-log-done nil)
13144 (org-todo-log-states nil)
13145 re type n what ts time to-state)
13146 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13147 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13148 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13149 org-todo-repeat-to-state))
13150 (unless (and to-state (member to-state org-todo-keywords-1))
13151 (setq to-state (if (eq interpret 'type) org-last-state head)))
13152 (org-todo to-state)
13153 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13154 (org-entry-put nil "LAST_REPEAT" (format-time-string
13155 (org-time-stamp-format t t))))
13156 (when org-log-repeat
13157 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13158 (memq 'org-add-log-note post-command-hook))
13159 ;; OK, we are already setup for some record
13160 (if (eq org-log-repeat 'note)
13161 ;; make sure we take a note, not only a time stamp
13162 (setq org-log-note-how 'note))
13163 ;; Set up for taking a record
13164 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13165 org-last-state
13166 'findpos org-log-repeat)))
13167 (org-back-to-heading t)
13168 (org-add-planning-info nil nil 'closed)
13169 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13170 org-deadline-time-regexp "\\)\\|\\("
13171 org-ts-regexp "\\)"))
13172 (while (re-search-forward
13173 re (save-excursion (outline-next-heading) (point)) t)
13174 (setq type (if (match-end 1) org-scheduled-string
13175 (if (match-end 3) org-deadline-string "Plain:"))
13176 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13177 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13178 (setq n (string-to-number (match-string 2 ts))
13179 what (match-string 3 ts))
13180 (if (equal what "w") (setq n (* n 7) what "d"))
13181 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13182 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13183 ;; Preparation, see if we need to modify the start date for the change
13184 (when (match-end 1)
13185 (setq time (save-match-data (org-time-string-to-time ts)))
13186 (cond
13187 ((equal (match-string 1 ts) ".")
13188 ;; Shift starting date to today
13189 (org-timestamp-change
13190 (- (org-today) (time-to-days time))
13191 'day))
13192 ((equal (match-string 1 ts) "+")
13193 (let ((nshiftmax 10) (nshift 0))
13194 (while (or (= nshift 0)
13195 (<= (time-to-days time)
13196 (time-to-days (current-time))))
13197 (when (= (incf nshift) nshiftmax)
13198 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13199 (user-error "Abort")))
13200 (org-timestamp-change n (cdr (assoc what whata)))
13201 (org-at-timestamp-p t)
13202 (setq ts (match-string 1))
13203 (setq time (save-match-data (org-time-string-to-time ts)))))
13204 (org-timestamp-change (- n) (cdr (assoc what whata)))
13205 ;; rematch, so that we have everything in place for the real shift
13206 (org-at-timestamp-p t)
13207 (setq ts (match-string 1))
13208 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13209 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13210 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13211 (setq org-log-post-message msg)
13212 (message "%s" msg))))
13214 (defun org-show-todo-tree (arg)
13215 "Make a compact tree which shows all headlines marked with TODO.
13216 The tree will show the lines where the regexp matches, and all higher
13217 headlines above the match.
13218 With a \\[universal-argument] prefix, prompt for a regexp to match.
13219 With a numeric prefix N, construct a sparse tree for the Nth element
13220 of `org-todo-keywords-1'."
13221 (interactive "P")
13222 (let ((case-fold-search nil)
13223 (kwd-re
13224 (cond ((null arg) org-not-done-regexp)
13225 ((equal arg '(4))
13226 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13227 (mapcar 'list org-todo-keywords-1))))
13228 (concat "\\("
13229 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13230 "\\)\\>")))
13231 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13232 (regexp-quote (nth (1- (prefix-numeric-value arg))
13233 org-todo-keywords-1)))
13234 (t (user-error "Invalid prefix argument: %s" arg)))))
13235 (message "%d TODO entries found"
13236 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13238 (defun org-deadline (arg &optional time)
13239 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13240 With one universal prefix argument, remove any deadline from the item.
13241 With two universal prefix arguments, prompt for a warning delay.
13242 With argument TIME, set the deadline at the corresponding date. TIME
13243 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13244 (interactive "P")
13245 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13246 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13247 'region-start-level 'region))
13248 org-loop-over-headlines-in-active-region)
13249 (org-map-entries
13250 `(org-deadline ',arg ,time)
13251 org-loop-over-headlines-in-active-region
13252 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13253 (let* ((old-date (org-entry-get nil "DEADLINE"))
13254 (old-date-time (if old-date (org-time-string-to-time old-date)))
13255 (repeater (and old-date
13256 (string-match
13257 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13258 old-date)
13259 (match-string 1 old-date))))
13260 (cond
13261 ((equal arg '(4))
13262 (when (and old-date org-log-redeadline)
13263 (org-add-log-setup 'deldeadline nil old-date 'findpos
13264 org-log-redeadline))
13265 (org-remove-timestamp-with-keyword org-deadline-string)
13266 (message "Item no longer has a deadline."))
13267 ((equal arg '(16))
13268 (save-excursion
13269 (org-back-to-heading t)
13270 (if (re-search-forward
13271 org-deadline-time-regexp
13272 (save-excursion (outline-next-heading) (point)) t)
13273 (let* ((rpl0 (match-string 1))
13274 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13275 (replace-match
13276 (concat org-deadline-string
13277 " <" rpl
13278 (format " -%dd"
13279 (abs
13280 (- (time-to-days
13281 (save-match-data
13282 (org-read-date nil t nil "Warn starting from" old-date-time)))
13283 (time-to-days old-date-time))))
13284 ">") t t))
13285 (user-error "No deadline information to update"))))
13287 (org-add-planning-info 'deadline time 'closed)
13288 (when (and old-date org-log-redeadline
13289 (not (equal old-date
13290 (substring org-last-inserted-timestamp 1 -1))))
13291 (org-add-log-setup 'redeadline nil old-date 'findpos
13292 org-log-redeadline))
13293 (when repeater
13294 (save-excursion
13295 (org-back-to-heading t)
13296 (when (re-search-forward (concat org-deadline-string " "
13297 org-last-inserted-timestamp)
13298 (save-excursion
13299 (outline-next-heading) (point)) t)
13300 (goto-char (1- (match-end 0)))
13301 (insert " " repeater)
13302 (setq org-last-inserted-timestamp
13303 (concat (substring org-last-inserted-timestamp 0 -1)
13304 " " repeater
13305 (substring org-last-inserted-timestamp -1))))))
13306 (message "Deadline on %s" org-last-inserted-timestamp))))))
13308 (defun org-schedule (arg &optional time)
13309 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13310 With one universal prefix argument, remove any scheduling date from the item.
13311 With two universal prefix arguments, prompt for a delay cookie.
13312 With argument TIME, scheduled at the corresponding date. TIME can
13313 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13314 (interactive "P")
13315 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13316 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13317 'region-start-level 'region))
13318 org-loop-over-headlines-in-active-region)
13319 (org-map-entries
13320 `(org-schedule ',arg ,time)
13321 org-loop-over-headlines-in-active-region
13322 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13323 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13324 (old-date-time (if old-date (org-time-string-to-time old-date)))
13325 (repeater (and old-date
13326 (string-match
13327 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13328 old-date)
13329 (match-string 1 old-date))))
13330 (cond
13331 ((equal arg '(4))
13332 (progn
13333 (when (and old-date org-log-reschedule)
13334 (org-add-log-setup 'delschedule nil old-date 'findpos
13335 org-log-reschedule))
13336 (org-remove-timestamp-with-keyword org-scheduled-string)
13337 (message "Item is no longer scheduled.")))
13338 ((equal arg '(16))
13339 (save-excursion
13340 (org-back-to-heading t)
13341 (if (re-search-forward
13342 org-scheduled-time-regexp
13343 (save-excursion (outline-next-heading) (point)) t)
13344 (let* ((rpl0 (match-string 1))
13345 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13346 (replace-match
13347 (concat org-scheduled-string
13348 " <" rpl
13349 (format " -%dd"
13350 (abs
13351 (- (time-to-days
13352 (save-match-data
13353 (org-read-date nil t nil "Delay until" old-date-time)))
13354 (time-to-days old-date-time))))
13355 ">") t t))
13356 (user-error "No scheduled information to update"))))
13358 (org-add-planning-info 'scheduled time 'closed)
13359 (when (and old-date org-log-reschedule
13360 (not (equal old-date
13361 (substring org-last-inserted-timestamp 1 -1))))
13362 (org-add-log-setup 'reschedule nil old-date 'findpos
13363 org-log-reschedule))
13364 (when repeater
13365 (save-excursion
13366 (org-back-to-heading t)
13367 (when (re-search-forward (concat org-scheduled-string " "
13368 org-last-inserted-timestamp)
13369 (save-excursion
13370 (outline-next-heading) (point)) t)
13371 (goto-char (1- (match-end 0)))
13372 (insert " " repeater)
13373 (setq org-last-inserted-timestamp
13374 (concat (substring org-last-inserted-timestamp 0 -1)
13375 " " repeater
13376 (substring org-last-inserted-timestamp -1))))))
13377 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13379 (defun org-get-scheduled-time (pom &optional inherit)
13380 "Get the scheduled time as a time tuple, of a format suitable
13381 for calling org-schedule with, or if there is no scheduling,
13382 returns nil."
13383 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13384 (when time
13385 (apply 'encode-time (org-parse-time-string time)))))
13387 (defun org-get-deadline-time (pom &optional inherit)
13388 "Get the deadline as a time tuple, of a format suitable for
13389 calling org-deadline with, or if there is no scheduling, returns
13390 nil."
13391 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13392 (when time
13393 (apply 'encode-time (org-parse-time-string time)))))
13395 (defun org-remove-timestamp-with-keyword (keyword)
13396 "Remove all time stamps with KEYWORD in the current entry."
13397 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13398 beg)
13399 (save-excursion
13400 (org-back-to-heading t)
13401 (setq beg (point))
13402 (outline-next-heading)
13403 (while (re-search-backward re beg t)
13404 (replace-match "")
13405 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13406 (equal (char-before) ?\ ))
13407 (backward-delete-char 1)
13408 (if (string-match "^[ \t]*$" (buffer-substring
13409 (point-at-bol) (point-at-eol)))
13410 (delete-region (point-at-bol)
13411 (min (point-max) (1+ (point-at-eol))))))))))
13413 (defvar org-time-was-given) ; dynamically scoped parameter
13414 (defvar org-end-time-was-given) ; dynamically scoped parameter
13416 (defun org-add-planning-info (what &optional time &rest remove)
13417 "Insert new timestamp with keyword in the line directly after the headline.
13418 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13419 If non is given, the user is prompted for a date.
13420 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13421 be removed."
13422 (interactive)
13423 (let (org-time-was-given org-end-time-was-given ts
13424 end default-time default-input)
13426 (catch 'exit
13427 (when (and (memq what '(scheduled deadline))
13428 (or (not time)
13429 (and (stringp time)
13430 (string-match "^[-+]+[0-9]" time))))
13431 ;; Try to get a default date/time from existing timestamp
13432 (save-excursion
13433 (org-back-to-heading t)
13434 (setq end (save-excursion (outline-next-heading) (point)))
13435 (when (re-search-forward (if (eq what 'scheduled)
13436 org-scheduled-time-regexp
13437 org-deadline-time-regexp)
13438 end t)
13439 (setq ts (match-string 1)
13440 default-time
13441 (apply 'encode-time (org-parse-time-string ts))
13442 default-input (and ts (org-get-compact-tod ts))))))
13443 (when what
13444 (setq time
13445 (if (stringp time)
13446 ;; This is a string (relative or absolute), set proper date
13447 (apply 'encode-time
13448 (org-read-date-analyze
13449 time default-time (decode-time default-time)))
13450 ;; If necessary, get the time from the user
13451 (or time (org-read-date nil 'to-time nil nil
13452 default-time default-input)))))
13454 (when (and org-insert-labeled-timestamps-at-point
13455 (member what '(scheduled deadline)))
13456 (insert
13457 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13458 (org-insert-time-stamp time org-time-was-given
13459 nil nil nil (list org-end-time-was-given))
13460 (setq what nil))
13461 (save-excursion
13462 (save-restriction
13463 (let (col list elt ts buffer-invisibility-spec)
13464 (org-back-to-heading t)
13465 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13466 (goto-char (match-end 1))
13467 (setq col (current-column))
13468 (goto-char (match-end 0))
13469 (if (eobp) (insert "\n") (forward-char 1))
13470 (when (and (not what)
13471 (not (looking-at
13472 (concat "[ \t]*"
13473 org-keyword-time-not-clock-regexp))))
13474 ;; Nothing to add, nothing to remove...... :-)
13475 (throw 'exit nil))
13476 (if (and (not (looking-at org-outline-regexp))
13477 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13478 "[^\r\n]*"))
13479 (not (equal (match-string 1) org-clock-string)))
13480 (narrow-to-region (match-beginning 0) (match-end 0))
13481 (insert-before-markers "\n")
13482 (backward-char 1)
13483 (narrow-to-region (point) (point))
13484 (and org-adapt-indentation (org-indent-to-column col)))
13485 ;; Check if we have to remove something.
13486 (setq list (cons what remove))
13487 (while list
13488 (setq elt (pop list))
13489 (when (or (and (eq elt 'scheduled)
13490 (re-search-forward org-scheduled-time-regexp nil t))
13491 (and (eq elt 'deadline)
13492 (re-search-forward org-deadline-time-regexp nil t))
13493 (and (eq elt 'closed)
13494 (re-search-forward org-closed-time-regexp nil t)))
13495 (replace-match "")
13496 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13497 (and (looking-at "[ \t]+") (replace-match ""))
13498 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13499 (when what
13500 (insert
13501 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13502 (cond ((eq what 'scheduled) org-scheduled-string)
13503 ((eq what 'deadline) org-deadline-string)
13504 ((eq what 'closed) org-closed-string))
13505 " ")
13506 (setq ts (org-insert-time-stamp
13507 time
13508 (or org-time-was-given
13509 (and (eq what 'closed) org-log-done-with-time))
13510 (eq what 'closed)
13511 nil nil (list org-end-time-was-given)))
13512 (insert
13513 (if (not (or (bolp) (eq (char-before) ?\ )
13514 (memq (char-after) '(32 10))
13515 (eobp))) " " ""))
13516 (end-of-line 1))
13517 (goto-char (point-min))
13518 (widen)
13519 (if (and (looking-at "[ \t]*\n")
13520 (equal (char-before) ?\n))
13521 (delete-region (1- (point)) (point-at-eol)))
13522 ts))))))
13524 (defvar org-log-note-marker (make-marker))
13525 (defvar org-log-note-purpose nil)
13526 (defvar org-log-note-state nil)
13527 (defvar org-log-note-previous-state nil)
13528 (defvar org-log-note-extra nil)
13529 (defvar org-log-note-window-configuration nil)
13530 (defvar org-log-note-return-to (make-marker))
13531 (defvar org-log-note-effective-time nil
13532 "Remembered current time so that dynamically scoped
13533 `org-extend-today-until' affects tha timestamps in state change
13534 log")
13536 (defvar org-log-post-message nil
13537 "Message to be displayed after a log note has been stored.
13538 The auto-repeater uses this.")
13540 (defun org-add-note ()
13541 "Add a note to the current entry.
13542 This is done in the same way as adding a state change note."
13543 (interactive)
13544 (org-add-log-setup 'note nil nil 'findpos nil))
13546 (defvar org-property-end-re)
13547 (defun org-add-log-setup (&optional purpose state prev-state
13548 findpos how extra)
13549 "Set up the post command hook to take a note.
13550 If this is about to TODO state change, the new state is expected in STATE.
13551 When FINDPOS is non-nil, find the correct position for the note in
13552 the current entry. If not, assume that it can be inserted at point.
13553 HOW is an indicator what kind of note should be created.
13554 EXTRA is additional text that will be inserted into the notes buffer."
13555 (let* ((org-log-into-drawer (org-log-into-drawer))
13556 (drawer (cond ((stringp org-log-into-drawer)
13557 org-log-into-drawer)
13558 (org-log-into-drawer "LOGBOOK"))))
13559 (save-restriction
13560 (save-excursion
13561 (when findpos
13562 (org-back-to-heading t)
13563 (narrow-to-region (point) (save-excursion
13564 (outline-next-heading) (point)))
13565 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13566 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13567 "[^\r\n]*\\)?"))
13568 (goto-char (match-end 0))
13569 (cond
13570 (drawer
13571 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13572 nil t)
13573 (progn
13574 (goto-char (match-end 0))
13575 (or org-log-states-order-reversed
13576 (and (re-search-forward org-property-end-re nil t)
13577 (goto-char (1- (match-beginning 0))))))
13578 (insert "\n:" drawer ":\n:END:")
13579 (beginning-of-line 0)
13580 (org-indent-line)
13581 (beginning-of-line 2)
13582 (org-indent-line)
13583 (end-of-line 0)))
13584 ((and org-log-state-notes-insert-after-drawers
13585 (save-excursion
13586 (forward-line) (looking-at org-drawer-regexp)))
13587 (forward-line)
13588 (while (looking-at org-drawer-regexp)
13589 (goto-char (match-end 0))
13590 (re-search-forward org-property-end-re (point-max) t)
13591 (forward-line))
13592 (forward-line -1)))
13593 (unless org-log-states-order-reversed
13594 (and (= (char-after) ?\n) (forward-char 1))
13595 (org-skip-over-state-notes)
13596 (skip-chars-backward " \t\n\r")))
13597 (move-marker org-log-note-marker (point))
13598 (setq org-log-note-purpose purpose
13599 org-log-note-state state
13600 org-log-note-previous-state prev-state
13601 org-log-note-how how
13602 org-log-note-extra extra
13603 org-log-note-effective-time (org-current-effective-time))
13604 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13606 (defun org-skip-over-state-notes ()
13607 "Skip past the list of State notes in an entry."
13608 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13609 (when (ignore-errors (goto-char (org-in-item-p)))
13610 (let* ((struct (org-list-struct))
13611 (prevs (org-list-prevs-alist struct)))
13612 (while (looking-at "[ \t]*- State")
13613 (goto-char (or (org-list-get-next-item (point) struct prevs)
13614 (org-list-get-item-end (point) struct)))))))
13616 (defun org-add-log-note (&optional purpose)
13617 "Pop up a window for taking a note, and add this note later at point."
13618 (remove-hook 'post-command-hook 'org-add-log-note)
13619 (setq org-log-note-window-configuration (current-window-configuration))
13620 (delete-other-windows)
13621 (move-marker org-log-note-return-to (point))
13622 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13623 (goto-char org-log-note-marker)
13624 (org-switch-to-buffer-other-window "*Org Note*")
13625 (erase-buffer)
13626 (if (memq org-log-note-how '(time state))
13627 (let (current-prefix-arg) (org-store-log-note))
13628 (let ((org-inhibit-startup t)) (org-mode))
13629 (insert (format "# Insert note for %s.
13630 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13631 (cond
13632 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13633 ((eq org-log-note-purpose 'done) "closed todo item")
13634 ((eq org-log-note-purpose 'state)
13635 (format "state change from \"%s\" to \"%s\""
13636 (or org-log-note-previous-state "")
13637 (or org-log-note-state "")))
13638 ((eq org-log-note-purpose 'reschedule)
13639 "rescheduling")
13640 ((eq org-log-note-purpose 'delschedule)
13641 "no longer scheduled")
13642 ((eq org-log-note-purpose 'redeadline)
13643 "changing deadline")
13644 ((eq org-log-note-purpose 'deldeadline)
13645 "removing deadline")
13646 ((eq org-log-note-purpose 'refile)
13647 "refiling")
13648 ((eq org-log-note-purpose 'note)
13649 "this entry")
13650 (t (error "This should not happen")))))
13651 (if org-log-note-extra (insert org-log-note-extra))
13652 (org-set-local 'org-finish-function 'org-store-log-note)
13653 (run-hooks 'org-log-buffer-setup-hook)))
13655 (defvar org-note-abort nil) ; dynamically scoped
13656 (defun org-store-log-note ()
13657 "Finish taking a log note, and insert it to where it belongs."
13658 (let ((txt (buffer-string)))
13659 (kill-buffer (current-buffer))
13660 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13661 lines ind bul)
13662 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13663 (setq txt (replace-match "" t t txt)))
13664 (if (string-match "\\s-+\\'" txt)
13665 (setq txt (replace-match "" t t txt)))
13666 (setq lines (org-split-string txt "\n"))
13667 (when (and note (string-match "\\S-" note))
13668 (setq note
13669 (org-replace-escapes
13670 note
13671 (list (cons "%u" (user-login-name))
13672 (cons "%U" user-full-name)
13673 (cons "%t" (format-time-string
13674 (org-time-stamp-format 'long 'inactive)
13675 org-log-note-effective-time))
13676 (cons "%T" (format-time-string
13677 (org-time-stamp-format 'long nil)
13678 org-log-note-effective-time))
13679 (cons "%d" (format-time-string
13680 (org-time-stamp-format nil 'inactive)
13681 org-log-note-effective-time))
13682 (cons "%D" (format-time-string
13683 (org-time-stamp-format nil nil)
13684 org-log-note-effective-time))
13685 (cons "%s" (if org-log-note-state
13686 (concat "\"" org-log-note-state "\"")
13687 ""))
13688 (cons "%S" (if org-log-note-previous-state
13689 (concat "\"" org-log-note-previous-state "\"")
13690 "\"\"")))))
13691 (if lines (setq note (concat note " \\\\")))
13692 (push note lines))
13693 (when (or current-prefix-arg org-note-abort)
13694 (when org-log-into-drawer
13695 (org-remove-empty-drawer-at org-log-note-marker))
13696 (setq lines nil))
13697 (when lines
13698 (with-current-buffer (marker-buffer org-log-note-marker)
13699 (save-excursion
13700 (goto-char org-log-note-marker)
13701 (move-marker org-log-note-marker nil)
13702 (end-of-line 1)
13703 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13704 (setq ind (save-excursion
13705 (if (ignore-errors (goto-char (org-in-item-p)))
13706 (let ((struct (org-list-struct)))
13707 (org-list-get-ind
13708 (org-list-get-top-point struct) struct))
13709 (skip-chars-backward " \r\t\n")
13710 (cond
13711 ((and (org-at-heading-p)
13712 org-adapt-indentation)
13713 (1+ (org-current-level)))
13714 ((org-at-heading-p) 0)
13715 (t (org-get-indentation))))))
13716 (setq bul (org-list-bullet-string "-"))
13717 (org-indent-line-to ind)
13718 (insert bul (pop lines))
13719 (let ((ind-body (+ (length bul) ind)))
13720 (while lines
13721 (insert "\n")
13722 (org-indent-line-to ind-body)
13723 (insert (pop lines))))
13724 (message "Note stored")
13725 (org-back-to-heading t)
13726 (org-cycle-hide-drawers 'children))
13727 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13728 ;; from within `org-add-log-note' because `buffer-undo-list'
13729 ;; is then modified outside of `org-with-remote-undo'.
13730 (when (eq this-command 'org-agenda-todo)
13731 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13732 ;; Don't add undo information when called from `org-agenda-todo'
13733 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13734 (set-window-configuration org-log-note-window-configuration)
13735 (with-current-buffer (marker-buffer org-log-note-return-to)
13736 (goto-char org-log-note-return-to))
13737 (move-marker org-log-note-return-to nil)
13738 (and org-log-post-message (message "%s" org-log-post-message))))
13740 (defun org-remove-empty-drawer-at (pos)
13741 "Remove an empty drawer at position POS.
13742 POS may also be a marker."
13743 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13744 (org-with-wide-buffer
13745 (goto-char pos)
13746 (let ((drawer (org-element-at-point)))
13747 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13748 (not (org-element-property :contents-begin drawer)))
13749 (delete-region (org-element-property :begin drawer)
13750 (progn (goto-char (org-element-property :end drawer))
13751 (skip-chars-backward " \r\t\n")
13752 (forward-line)
13753 (point))))))))
13755 (defvar org-ts-type nil)
13756 (defun org-sparse-tree (&optional arg type)
13757 "Create a sparse tree, prompt for the details.
13758 This command can create sparse trees. You first need to select the type
13759 of match used to create the tree:
13761 t Show all TODO entries.
13762 T Show entries with a specific TODO keyword.
13763 m Show entries selected by a tags/property match.
13764 p Enter a property name and its value (both with completion on existing
13765 names/values) and show entries with that property.
13766 r Show entries matching a regular expression (`/' can be used as well).
13767 b Show deadlines and scheduled items before a date.
13768 a Show deadlines and scheduled items after a date.
13769 d Show deadlines due within `org-deadline-warning-days'.
13770 D Show deadlines and scheduled items between a date range."
13771 (interactive "P")
13772 (setq type (or type org-sparse-tree-default-date-type))
13773 (setq org-ts-type type)
13774 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13775 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13776 [c]ycle through date types: %s"
13777 (case type
13778 (all "all timestamps")
13779 (scheduled "only scheduled")
13780 (deadline "only deadline")
13781 (active "only active timestamps")
13782 (inactive "only inactive timestamps")
13783 (scheduled-or-deadline "scheduled/deadline")
13784 (closed "with a closed time-stamp")
13785 (otherwise "scheduled/deadline")))
13786 (let ((answer (read-char-exclusive)))
13787 (case answer
13789 (org-sparse-tree
13791 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13792 inactive closed)))))
13793 (?d (call-interactively 'org-check-deadlines))
13794 (?b (call-interactively 'org-check-before-date))
13795 (?a (call-interactively 'org-check-after-date))
13796 (?D (call-interactively 'org-check-dates-range))
13797 (?t (call-interactively 'org-show-todo-tree))
13798 (?T (org-show-todo-tree '(4)))
13799 (?m (call-interactively 'org-match-sparse-tree))
13800 ((?p ?P)
13801 (let* ((kwd (org-icompleting-read
13802 "Property: " (mapcar 'list (org-buffer-property-keys))))
13803 (value (org-icompleting-read
13804 "Value: " (mapcar 'list (org-property-values kwd)))))
13805 (unless (string-match "\\`{.*}\\'" value)
13806 (setq value (concat "\"" value "\"")))
13807 (org-match-sparse-tree arg (concat kwd "=" value))))
13808 ((?r ?R ?/) (call-interactively 'org-occur))
13809 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13811 (defvar org-occur-highlights nil
13812 "List of overlays used for occur matches.")
13813 (make-variable-buffer-local 'org-occur-highlights)
13814 (defvar org-occur-parameters nil
13815 "Parameters of the active org-occur calls.
13816 This is a list, each call to org-occur pushes as cons cell,
13817 containing the regular expression and the callback, onto the list.
13818 The list can contain several entries if `org-occur' has been called
13819 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13820 will only contain one set of parameters. When the highlights are
13821 removed (for example with `C-c C-c', or with the next edit (depending
13822 on `org-remove-highlights-with-change'), this variable is emptied
13823 as well.")
13824 (make-variable-buffer-local 'org-occur-parameters)
13826 (defun org-occur (regexp &optional keep-previous callback)
13827 "Make a compact tree which shows all matches of REGEXP.
13828 The tree will show the lines where the regexp matches, and all higher
13829 headlines above the match. It will also show the heading after the match,
13830 to make sure editing the matching entry is easy.
13831 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13832 call to `org-occur' will be kept, to allow stacking of calls to this
13833 command.
13834 If CALLBACK is non-nil, it is a function which is called to confirm
13835 that the match should indeed be shown."
13836 (interactive "sRegexp: \nP")
13837 (when (equal regexp "")
13838 (user-error "Regexp cannot be empty"))
13839 (unless keep-previous
13840 (org-remove-occur-highlights nil nil t))
13841 (push (cons regexp callback) org-occur-parameters)
13842 (let ((cnt 0))
13843 (save-excursion
13844 (goto-char (point-min))
13845 (if (or (not keep-previous) ; do not want to keep
13846 (not org-occur-highlights)) ; no previous matches
13847 ;; hide everything
13848 (org-overview))
13849 (while (re-search-forward regexp nil t)
13850 (when (or (not callback)
13851 (save-match-data (funcall callback)))
13852 (setq cnt (1+ cnt))
13853 (when org-highlight-sparse-tree-matches
13854 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13855 (org-show-context 'occur-tree))))
13856 (when org-remove-highlights-with-change
13857 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13858 nil 'local))
13859 (unless org-sparse-tree-open-archived-trees
13860 (org-hide-archived-subtrees (point-min) (point-max)))
13861 (run-hooks 'org-occur-hook)
13862 (if (org-called-interactively-p 'interactive)
13863 (message "%d match(es) for regexp %s" cnt regexp))
13864 cnt))
13866 (defun org-occur-next-match (&optional n reset)
13867 "Function for `next-error-function' to find sparse tree matches.
13868 N is the number of matches to move, when negative move backwards.
13869 RESET is entirely ignored - this function always goes back to the
13870 starting point when no match is found."
13871 (let* ((limit (if (< n 0) (point-min) (point-max)))
13872 (search-func (if (< n 0)
13873 'previous-single-char-property-change
13874 'next-single-char-property-change))
13875 (n (abs n))
13876 (pos (point))
13878 (catch 'exit
13879 (while (setq p1 (funcall search-func (point) 'org-type))
13880 (when (equal p1 limit)
13881 (goto-char pos)
13882 (user-error "No more matches"))
13883 (when (equal (get-char-property p1 'org-type) 'org-occur)
13884 (setq n (1- n))
13885 (when (= n 0)
13886 (goto-char p1)
13887 (throw 'exit (point))))
13888 (goto-char p1))
13889 (goto-char p1)
13890 (user-error "No more matches"))))
13892 (defun org-show-context (&optional key)
13893 "Make sure point and context are visible.
13894 How much context is shown depends upon the variables
13895 `org-show-hierarchy-above', `org-show-following-heading',
13896 `org-show-entry-below' and `org-show-siblings'."
13897 (let ((heading-p (org-at-heading-p t))
13898 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13899 (following-p (org-get-alist-option org-show-following-heading key))
13900 (entry-p (org-get-alist-option org-show-entry-below key))
13901 (siblings-p (org-get-alist-option org-show-siblings key)))
13902 ;; Show heading or entry text
13903 (if (and heading-p (not entry-p))
13904 (org-flag-heading nil) ; only show the heading
13905 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13906 (org-show-hidden-entry))) ; show entire entry
13907 (when following-p
13908 ;; Show next sibling, or heading below text
13909 (save-excursion
13910 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13911 (org-flag-heading nil))))
13912 (when siblings-p (org-show-siblings))
13913 (when hierarchy-p
13914 ;; show all higher headings, possibly with siblings
13915 (save-excursion
13916 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13917 (not (bobp)))
13918 (org-flag-heading nil)
13919 (when siblings-p (org-show-siblings)))))))
13921 (defvar org-reveal-start-hook nil
13922 "Hook run before revealing a location.")
13924 (defun org-reveal (&optional siblings)
13925 "Show current entry, hierarchy above it, and the following headline.
13926 This can be used to show a consistent set of context around locations
13927 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13928 not t for the search context.
13930 With optional argument SIBLINGS, on each level of the hierarchy all
13931 siblings are shown. This repairs the tree structure to what it would
13932 look like when opened with hierarchical calls to `org-cycle'.
13933 With double optional argument \\[universal-argument] \\[universal-argument], \
13934 go to the parent and show the
13935 entire tree."
13936 (interactive "P")
13937 (run-hooks 'org-reveal-start-hook)
13938 (let ((org-show-hierarchy-above t)
13939 (org-show-following-heading t)
13940 (org-show-siblings (if siblings t org-show-siblings)))
13941 (org-show-context nil))
13942 (when (equal siblings '(16))
13943 (save-excursion
13944 (when (org-up-heading-safe)
13945 (org-show-subtree)
13946 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13948 (defun org-highlight-new-match (beg end)
13949 "Highlight from BEG to END and mark the highlight is an occur headline."
13950 (let ((ov (make-overlay beg end)))
13951 (overlay-put ov 'face 'secondary-selection)
13952 (overlay-put ov 'org-type 'org-occur)
13953 (push ov org-occur-highlights)))
13955 (defun org-remove-occur-highlights (&optional beg end noremove)
13956 "Remove the occur highlights from the buffer.
13957 BEG and END are ignored. If NOREMOVE is nil, remove this function
13958 from the `before-change-functions' in the current buffer."
13959 (interactive)
13960 (unless org-inhibit-highlight-removal
13961 (mapc 'delete-overlay org-occur-highlights)
13962 (setq org-occur-highlights nil)
13963 (setq org-occur-parameters nil)
13964 (unless noremove
13965 (remove-hook 'before-change-functions
13966 'org-remove-occur-highlights 'local))))
13968 ;;;; Priorities
13970 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13971 "Regular expression matching the priority indicator.")
13973 (defvar org-remove-priority-next-time nil)
13975 (defun org-priority-up ()
13976 "Increase the priority of the current item."
13977 (interactive)
13978 (org-priority 'up))
13980 (defun org-priority-down ()
13981 "Decrease the priority of the current item."
13982 (interactive)
13983 (org-priority 'down))
13985 (defun org-priority (&optional action show)
13986 "Change the priority of an item.
13987 ACTION can be `set', `up', `down', or a character."
13988 (interactive "P")
13989 (if (equal action '(4))
13990 (org-show-priority)
13991 (unless org-enable-priority-commands
13992 (user-error "Priority commands are disabled"))
13993 (setq action (or action 'set))
13994 (let (current new news have remove)
13995 (save-excursion
13996 (org-back-to-heading t)
13997 (if (looking-at org-priority-regexp)
13998 (setq current (string-to-char (match-string 2))
13999 have t))
14000 (cond
14001 ((eq action 'remove)
14002 (setq remove t new ?\ ))
14003 ((or (eq action 'set)
14004 (if (featurep 'xemacs) (characterp action) (integerp action)))
14005 (if (not (eq action 'set))
14006 (setq new action)
14007 (message "Priority %c-%c, SPC to remove: "
14008 org-highest-priority org-lowest-priority)
14009 (save-match-data
14010 (setq new (read-char-exclusive))))
14011 (if (and (= (upcase org-highest-priority) org-highest-priority)
14012 (= (upcase org-lowest-priority) org-lowest-priority))
14013 (setq new (upcase new)))
14014 (cond ((equal new ?\ ) (setq remove t))
14015 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14016 (user-error "Priority must be between `%c' and `%c'"
14017 org-highest-priority org-lowest-priority))))
14018 ((eq action 'up)
14019 (setq new (if have
14020 (1- current) ; normal cycling
14021 ;; last priority was empty
14022 (if (eq last-command this-command)
14023 org-lowest-priority ; wrap around empty to lowest
14024 ;; default
14025 (if org-priority-start-cycle-with-default
14026 org-default-priority
14027 (1- org-default-priority))))))
14028 ((eq action 'down)
14029 (setq new (if have
14030 (1+ current) ; normal cycling
14031 ;; last priority was empty
14032 (if (eq last-command this-command)
14033 org-highest-priority ; wrap around empty to highest
14034 ;; default
14035 (if org-priority-start-cycle-with-default
14036 org-default-priority
14037 (1+ org-default-priority))))))
14038 (t (user-error "Invalid action")))
14039 (if (or (< (upcase new) org-highest-priority)
14040 (> (upcase new) org-lowest-priority))
14041 (if (and (memq action '(up down))
14042 (not have) (not (eq last-command this-command)))
14043 ;; `new' is from default priority
14044 (error
14045 "The default can not be set, see `org-default-priority' why")
14046 ;; normal cycling: `new' is beyond highest/lowest priority
14047 ;; and is wrapped around to the empty priority
14048 (setq remove t)))
14049 (setq news (format "%c" new))
14050 (if have
14051 (if remove
14052 (replace-match "" t t nil 1)
14053 (replace-match news t t nil 2))
14054 (if remove
14055 (user-error "No priority cookie found in line")
14056 (let ((case-fold-search nil))
14057 (looking-at org-todo-line-regexp))
14058 (if (match-end 2)
14059 (progn
14060 (goto-char (match-end 2))
14061 (insert " [#" news "]"))
14062 (goto-char (match-beginning 3))
14063 (insert "[#" news "] "))))
14064 (org-set-tags nil 'align))
14065 (if remove
14066 (message "Priority removed")
14067 (message "Priority of current item set to %s" news)))))
14069 (defun org-show-priority ()
14070 "Show the priority of the current item.
14071 This priority is composed of the main priority given with the [#A] cookies,
14072 and by additional input from the age of a schedules or deadline entry."
14073 (interactive)
14074 (let ((pri (if (eq major-mode 'org-agenda-mode)
14075 (org-get-at-bol 'priority)
14076 (save-excursion
14077 (save-match-data
14078 (beginning-of-line)
14079 (and (looking-at org-heading-regexp)
14080 (org-get-priority (match-string 0))))))))
14081 (message "Priority is %d" (if pri pri -1000))))
14083 (defun org-get-priority (s)
14084 "Find priority cookie and return priority."
14085 (save-match-data
14086 (if (functionp org-get-priority-function)
14087 (funcall org-get-priority-function)
14088 (if (not (string-match org-priority-regexp s))
14089 (* 1000 (- org-lowest-priority org-default-priority))
14090 (* 1000 (- org-lowest-priority
14091 (string-to-char (match-string 2 s))))))))
14093 ;;;; Tags
14095 (defvar org-agenda-archives-mode)
14096 (defvar org-map-continue-from nil
14097 "Position from where mapping should continue.
14098 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14100 (defvar org-scanner-tags nil
14101 "The current tag list while the tags scanner is running.")
14102 (defvar org-trust-scanner-tags nil
14103 "Should `org-get-tags-at' use the tags for the scanner.
14104 This is for internal dynamical scoping only.
14105 When this is non-nil, the function `org-get-tags-at' will return the value
14106 of `org-scanner-tags' instead of building the list by itself. This
14107 can lead to large speed-ups when the tags scanner is used in a file with
14108 many entries, and when the list of tags is retrieved, for example to
14109 obtain a list of properties. Building the tags list for each entry in such
14110 a file becomes an N^2 operation - but with this variable set, it scales
14111 as N.")
14113 (defun org-scan-tags (action matcher todo-only &optional start-level)
14114 "Scan headline tags with inheritance and produce output ACTION.
14116 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14117 or `agenda' to produce an entry list for an agenda view. It can also be
14118 a Lisp form or a function that should be called at each matched headline, in
14119 this case the return value is a list of all return values from these calls.
14121 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14122 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14123 only lines with a not-done TODO keyword are included in the output.
14124 This should be the same variable that was scoped into
14125 and set by `org-make-tags-matcher' when it constructed MATCHER.
14127 START-LEVEL can be a string with asterisks, reducing the scope to
14128 headlines matching this string."
14129 (require 'org-agenda)
14130 (let* ((re (concat "^"
14131 (if start-level
14132 ;; Get the correct level to match
14133 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14134 org-outline-regexp)
14135 " *\\(\\<\\("
14136 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14137 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14138 (props (list 'face 'default
14139 'done-face 'org-agenda-done
14140 'undone-face 'default
14141 'mouse-face 'highlight
14142 'org-not-done-regexp org-not-done-regexp
14143 'org-todo-regexp org-todo-regexp
14144 'org-complex-heading-regexp org-complex-heading-regexp
14145 'help-echo
14146 (format "mouse-2 or RET jump to org file %s"
14147 (abbreviate-file-name
14148 (or (buffer-file-name (buffer-base-buffer))
14149 (buffer-name (buffer-base-buffer)))))))
14150 (org-map-continue-from nil)
14151 lspos tags tags-list
14152 (tags-alist (list (cons 0 org-file-tags)))
14153 (llast 0) rtn rtn1 level category i txt
14154 todo marker entry priority)
14155 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14156 (setq action (list 'lambda nil action)))
14157 (save-excursion
14158 (goto-char (point-min))
14159 (when (eq action 'sparse-tree)
14160 (org-overview)
14161 (org-remove-occur-highlights))
14162 (while (let (case-fold-search)
14163 (re-search-forward re nil t))
14164 (setq org-map-continue-from nil)
14165 (catch :skip
14166 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14167 tags (if (match-end 4) (org-match-string-no-properties 4)))
14168 (goto-char (setq lspos (match-beginning 0)))
14169 (setq level (org-reduced-level (org-outline-level))
14170 category (org-get-category))
14171 (setq i llast llast level)
14172 ;; remove tag lists from same and sublevels
14173 (while (>= i level)
14174 (when (setq entry (assoc i tags-alist))
14175 (setq tags-alist (delete entry tags-alist)))
14176 (setq i (1- i)))
14177 ;; add the next tags
14178 (when tags
14179 (setq tags (org-split-string tags ":")
14180 tags-alist
14181 (cons (cons level tags) tags-alist)))
14182 ;; compile tags for current headline
14183 (setq tags-list
14184 (if org-use-tag-inheritance
14185 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14186 tags)
14187 org-scanner-tags tags-list)
14188 (when org-use-tag-inheritance
14189 (setcdr (car tags-alist)
14190 (mapcar (lambda (x)
14191 (setq x (copy-sequence x))
14192 (org-add-prop-inherited x))
14193 (cdar tags-alist))))
14194 (when (and tags org-use-tag-inheritance
14195 (or (not (eq t org-use-tag-inheritance))
14196 org-tags-exclude-from-inheritance))
14197 ;; selective inheritance, remove uninherited ones
14198 (setcdr (car tags-alist)
14199 (org-remove-uninherited-tags (cdar tags-alist))))
14200 (when (and
14202 ;; eval matcher only when the todo condition is OK
14203 (and (or (not todo-only) (member todo org-not-done-keywords))
14204 (let ((case-fold-search t) (org-trust-scanner-tags t))
14205 (eval matcher)))
14207 ;; Call the skipper, but return t if it does not skip,
14208 ;; so that the `and' form continues evaluating
14209 (progn
14210 (unless (eq action 'sparse-tree) (org-agenda-skip))
14213 ;; Check if timestamps are deselecting this entry
14214 (or (not todo-only)
14215 (and (member todo org-not-done-keywords)
14216 (or (not org-agenda-tags-todo-honor-ignore-options)
14217 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14219 ;; select this headline
14220 (cond
14221 ((eq action 'sparse-tree)
14222 (and org-highlight-sparse-tree-matches
14223 (org-get-heading) (match-end 0)
14224 (org-highlight-new-match
14225 (match-beginning 1) (match-end 1)))
14226 (org-show-context 'tags-tree))
14227 ((eq action 'agenda)
14228 (setq txt (org-agenda-format-item
14230 (concat
14231 (if (eq org-tags-match-list-sublevels 'indented)
14232 (make-string (1- level) ?.) "")
14233 (org-get-heading))
14234 level category
14235 tags-list)
14236 priority (org-get-priority txt))
14237 (goto-char lspos)
14238 (setq marker (org-agenda-new-marker))
14239 (org-add-props txt props
14240 'org-marker marker 'org-hd-marker marker 'org-category category
14241 'todo-state todo
14242 'priority priority 'type "tagsmatch")
14243 (push txt rtn))
14244 ((functionp action)
14245 (setq org-map-continue-from nil)
14246 (save-excursion
14247 (setq rtn1 (funcall action))
14248 (push rtn1 rtn)))
14249 (t (user-error "Invalid action")))
14251 ;; if we are to skip sublevels, jump to end of subtree
14252 (unless org-tags-match-list-sublevels
14253 (org-end-of-subtree t)
14254 (backward-char 1))))
14255 ;; Get the correct position from where to continue
14256 (if org-map-continue-from
14257 (goto-char org-map-continue-from)
14258 (and (= (point) lspos) (end-of-line 1)))))
14259 (when (and (eq action 'sparse-tree)
14260 (not org-sparse-tree-open-archived-trees))
14261 (org-hide-archived-subtrees (point-min) (point-max)))
14262 (nreverse rtn)))
14264 (defun org-remove-uninherited-tags (tags)
14265 "Remove all tags that are not inherited from the list TAGS."
14266 (cond
14267 ((eq org-use-tag-inheritance t)
14268 (if org-tags-exclude-from-inheritance
14269 (org-delete-all org-tags-exclude-from-inheritance tags)
14270 tags))
14271 ((not org-use-tag-inheritance) nil)
14272 ((stringp org-use-tag-inheritance)
14273 (delq nil (mapcar
14274 (lambda (x)
14275 (if (and (string-match org-use-tag-inheritance x)
14276 (not (member x org-tags-exclude-from-inheritance)))
14277 x nil))
14278 tags)))
14279 ((listp org-use-tag-inheritance)
14280 (delq nil (mapcar
14281 (lambda (x)
14282 (if (member x org-use-tag-inheritance) x nil))
14283 tags)))))
14285 (defun org-match-sparse-tree (&optional todo-only match)
14286 "Create a sparse tree according to tags string MATCH.
14287 MATCH can contain positive and negative selection of tags, like
14288 \"+WORK+URGENT-WITHBOSS\".
14289 If optional argument TODO-ONLY is non-nil, only select lines that are
14290 also TODO lines."
14291 (interactive "P")
14292 (org-agenda-prepare-buffers (list (current-buffer)))
14293 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14295 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14297 (defvar org-cached-props nil)
14298 (defun org-cached-entry-get (pom property)
14299 (if (or (eq t org-use-property-inheritance)
14300 (and (stringp org-use-property-inheritance)
14301 (string-match org-use-property-inheritance property))
14302 (and (listp org-use-property-inheritance)
14303 (member property org-use-property-inheritance)))
14304 ;; Caching is not possible, check it directly
14305 (org-entry-get pom property 'inherit)
14306 ;; Get all properties, so that we can do complicated checks easily
14307 (cdr (assoc property (or org-cached-props
14308 (setq org-cached-props
14309 (org-entry-properties pom)))))))
14311 (defun org-global-tags-completion-table (&optional files)
14312 "Return the list of all tags in all agenda buffer/files.
14313 Optional FILES argument is a list of files which can be used
14314 instead of the agenda files."
14315 (save-excursion
14316 (org-uniquify
14317 (delq nil
14318 (apply 'append
14319 (mapcar
14320 (lambda (file)
14321 (set-buffer (find-file-noselect file))
14322 (append (org-get-buffer-tags)
14323 (mapcar (lambda (x) (if (stringp (car-safe x))
14324 (list (car-safe x)) nil))
14325 org-tag-alist)))
14326 (if (and files (car files))
14327 files
14328 (org-agenda-files))))))))
14330 (defun org-make-tags-matcher (match)
14331 "Create the TAGS/TODO matcher form for the selection string MATCH.
14333 The variable `todo-only' is scoped dynamically into this function.
14334 It will be set to t if the matcher restricts matching to TODO entries,
14335 otherwise will not be touched.
14337 Returns a cons of the selection string MATCH and the constructed
14338 lisp form implementing the matcher. The matcher is to be evaluated
14339 at an Org entry, with point on the headline, and returns t if the
14340 entry matches the selection string MATCH. The returned lisp form
14341 references two variables with information about the entry, which
14342 must be bound around the form's evaluation: todo, the TODO keyword
14343 at the entry (or nil of none); and tags-list, the list of all tags
14344 at the entry including inherited ones. Additionally, the category
14345 of the entry (if any) must be specified as the text property
14346 'org-category on the headline.
14348 See also `org-scan-tags'.
14350 (declare (special todo-only))
14351 (unless (boundp 'todo-only)
14352 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14353 (unless match
14354 ;; Get a new match request, with completion against the global
14355 ;; tags table and the local tags in current buffer
14356 (let ((org-last-tags-completion-table
14357 (org-uniquify
14358 (delq nil (append (org-get-buffer-tags)
14359 (org-global-tags-completion-table))))))
14360 (setq match (org-completing-read-no-i
14361 "Match: " 'org-tags-completion-function nil nil nil
14362 'org-tags-history))))
14364 ;; Parse the string and create a lisp form
14365 (let ((match0 match)
14366 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14367 minus tag mm
14368 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14369 orterms term orlist re-p str-p level-p level-op time-p
14370 prop-p pn pv po gv rest (start 0) (ss 0))
14371 ;; Expand group tags
14372 (setq match (org-tags-expand match))
14374 ;; Check if there is a TODO part of this match, which would be the
14375 ;; part after a "/". TO make sure that this slash is not part of
14376 ;; a property value to be matched against, we also check that there
14377 ;; is no " after that slash.
14378 ;; First, find the last slash
14379 (while (string-match "/+" match ss)
14380 (setq start (match-beginning 0) ss (match-end 0)))
14381 (if (and (string-match "/+" match start)
14382 (not (save-match-data (string-match "\"" match start))))
14383 ;; match contains also a todo-matching request
14384 (progn
14385 (setq tagsmatch (substring match 0 (match-beginning 0))
14386 todomatch (substring match (match-end 0)))
14387 (if (string-match "^!" todomatch)
14388 (setq todo-only t todomatch (substring todomatch 1)))
14389 (if (string-match "^\\s-*$" todomatch)
14390 (setq todomatch nil)))
14391 ;; only matching tags
14392 (setq tagsmatch match todomatch nil))
14394 ;; Make the tags matcher
14395 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14396 (setq tagsmatcher t)
14397 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14398 (while (setq term (pop orterms))
14399 (while (and (equal (substring term -1) "\\") orterms)
14400 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14401 (while (string-match re term)
14402 (setq rest (substring term (match-end 0))
14403 minus (and (match-end 1)
14404 (equal (match-string 1 term) "-"))
14405 tag (save-match-data (replace-regexp-in-string
14406 "\\\\-" "-"
14407 (match-string 2 term)))
14408 re-p (equal (string-to-char tag) ?{)
14409 level-p (match-end 4)
14410 prop-p (match-end 5)
14411 mm (cond
14412 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14413 (level-p
14414 (setq level-op (org-op-to-function (match-string 3 term)))
14415 `(,level-op level ,(string-to-number
14416 (match-string 4 term))))
14417 (prop-p
14418 (setq pn (match-string 5 term)
14419 po (match-string 6 term)
14420 pv (match-string 7 term)
14421 re-p (equal (string-to-char pv) ?{)
14422 str-p (equal (string-to-char pv) ?\")
14423 time-p (save-match-data
14424 (string-match "^\"[[<].*[]>]\"$" pv))
14425 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14426 (if time-p (setq pv (org-matcher-time pv)))
14427 (setq po (org-op-to-function po (if time-p 'time str-p)))
14428 (cond
14429 ((equal pn "CATEGORY")
14430 (setq gv '(get-text-property (point) 'org-category)))
14431 ((equal pn "TODO")
14432 (setq gv 'todo))
14434 (setq gv `(org-cached-entry-get nil ,pn))))
14435 (if re-p
14436 (if (eq po 'org<>)
14437 `(not (string-match ,pv (or ,gv "")))
14438 `(string-match ,pv (or ,gv "")))
14439 (if str-p
14440 `(,po (or ,gv "") ,pv)
14441 `(,po (string-to-number (or ,gv ""))
14442 ,(string-to-number pv) ))))
14443 (t `(member ,tag tags-list)))
14444 mm (if minus (list 'not mm) mm)
14445 term rest)
14446 (push mm tagsmatcher))
14447 (push (if (> (length tagsmatcher) 1)
14448 (cons 'and tagsmatcher)
14449 (car tagsmatcher))
14450 orlist)
14451 (setq tagsmatcher nil))
14452 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14453 (setq tagsmatcher
14454 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14455 ;; Make the todo matcher
14456 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14457 (setq todomatcher t)
14458 (setq orterms (org-split-string todomatch "|") orlist nil)
14459 (while (setq term (pop orterms))
14460 (while (string-match re term)
14461 (setq minus (and (match-end 1)
14462 (equal (match-string 1 term) "-"))
14463 kwd (match-string 2 term)
14464 re-p (equal (string-to-char kwd) ?{)
14465 term (substring term (match-end 0))
14466 mm (if re-p
14467 `(string-match ,(substring kwd 1 -1) todo)
14468 (list 'equal 'todo kwd))
14469 mm (if minus (list 'not mm) mm))
14470 (push mm todomatcher))
14471 (push (if (> (length todomatcher) 1)
14472 (cons 'and todomatcher)
14473 (car todomatcher))
14474 orlist)
14475 (setq todomatcher nil))
14476 (setq todomatcher (if (> (length orlist) 1)
14477 (cons 'or orlist) (car orlist))))
14479 ;; Return the string and lisp forms of the matcher
14480 (setq matcher (if todomatcher
14481 (list 'and tagsmatcher todomatcher)
14482 tagsmatcher))
14483 (when todo-only
14484 (setq matcher (list 'and '(member todo org-not-done-keywords)
14485 matcher)))
14486 (cons match0 matcher)))
14488 (defun org-tags-expand (match &optional single-as-list downcased)
14489 "Expand group tags in MATCH.
14491 This replaces every group tag in MATCH with a regexp tag search.
14492 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14493 will be replaced like this:
14495 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14496 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14497 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14499 Replacing by a regexp preserves the structure of the match.
14500 E.g., this expansion
14502 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14504 will match anything tagged with \"Lab\" and \"Home\", or tagged
14505 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14507 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14508 assumed to be a single group tag, and the function will return
14509 the list of tags in this group.
14511 When DOWNCASE is non-nil, expand downcased TAGS."
14512 (if org-group-tags
14513 (let* ((case-fold-search t)
14514 (stable org-mode-syntax-table)
14515 (tal (or org-tag-groups-alist-for-agenda
14516 org-tag-groups-alist))
14517 (tal (if downcased
14518 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14519 (tml (mapcar 'car tal))
14520 (rtnmatch match) rpl)
14521 ;; @ and _ are allowed as word-components in tags
14522 (modify-syntax-entry ?@ "w" stable)
14523 (modify-syntax-entry ?_ "w" stable)
14524 (while (and tml
14525 (with-syntax-table stable
14526 (string-match
14527 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14528 (regexp-opt tml) "\\>\\)") rtnmatch)))
14529 (let* ((dir (match-string 1 rtnmatch))
14530 (tag (match-string 2 rtnmatch))
14531 (tag (if downcased (downcase tag) tag)))
14532 (setq tml (delete tag tml))
14533 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14534 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14535 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14536 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14537 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14538 (if single-as-list
14539 (or (reverse rpl) (list rtnmatch))
14540 rtnmatch))
14541 (if single-as-list (list (if downcased (downcase match) match))
14542 match)))
14544 (defun org-op-to-function (op &optional stringp)
14545 "Turn an operator into the appropriate function."
14546 (setq op
14547 (cond
14548 ((equal op "<" ) '(< string< org-time<))
14549 ((equal op ">" ) '(> org-string> org-time>))
14550 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14551 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14552 ((member op '("=" "==")) '(= string= org-time=))
14553 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14554 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14556 (defun org<> (a b) (not (= a b)))
14557 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14558 (defun org-string>= (a b) (not (string< a b)))
14559 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14560 (defun org-string<> (a b) (not (string= 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) (<= a b)))
14564 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14565 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14566 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14567 (defun org-2ft (s)
14568 "Convert S to a floating point time.
14569 If S is already a number, just return it. If it is a string, parse
14570 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14571 (cond
14572 ((numberp s) s)
14573 ((stringp s)
14574 (condition-case nil
14575 (float-time (apply 'encode-time (org-parse-time-string s)))
14576 (error 0.)))
14577 (t 0.)))
14579 (defun org-time-today ()
14580 "Time in seconds today at 0:00.
14581 Returns the float number of seconds since the beginning of the
14582 epoch to the beginning of today (00:00)."
14583 (float-time (apply 'encode-time
14584 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14586 (defun org-matcher-time (s)
14587 "Interpret a time comparison value."
14588 (save-match-data
14589 (cond
14590 ((string= s "<now>") (float-time))
14591 ((string= s "<today>") (org-time-today))
14592 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14593 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14594 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14595 (+ (org-time-today)
14596 (* (string-to-number (match-string 1 s))
14597 (cdr (assoc (match-string 2 s)
14598 '(("d" . 86400.0) ("w" . 604800.0)
14599 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14600 (t (org-2ft s)))))
14602 (defun org-match-any-p (re list)
14603 "Does re match any element of list?"
14604 (setq list (mapcar (lambda (x) (string-match re x)) list))
14605 (delq nil list))
14607 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14608 (defvar org-tags-overlay (make-overlay 1 1))
14609 (org-detach-overlay org-tags-overlay)
14611 (defun org-get-local-tags-at (&optional pos)
14612 "Get a list of tags defined in the current headline."
14613 (org-get-tags-at pos 'local))
14615 (defun org-get-local-tags ()
14616 "Get a list of tags defined in the current headline."
14617 (org-get-tags-at nil 'local))
14619 (defun org-get-tags-at (&optional pos local)
14620 "Get a list of all headline tags applicable at POS.
14621 POS defaults to point. If tags are inherited, the list contains
14622 the targets in the same sequence as the headlines appear, i.e.
14623 the tags of the current headline come last.
14624 When LOCAL is non-nil, only return tags from the current headline,
14625 ignore inherited ones."
14626 (interactive)
14627 (if (and org-trust-scanner-tags
14628 (or (not pos) (equal pos (point)))
14629 (not local))
14630 org-scanner-tags
14631 (let (tags ltags lastpos parent)
14632 (save-excursion
14633 (save-restriction
14634 (widen)
14635 (goto-char (or pos (point)))
14636 (save-match-data
14637 (catch 'done
14638 (condition-case nil
14639 (progn
14640 (org-back-to-heading t)
14641 (while (not (equal lastpos (point)))
14642 (setq lastpos (point))
14643 (when (looking-at
14644 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14645 (setq ltags (org-split-string
14646 (org-match-string-no-properties 1) ":"))
14647 (when parent
14648 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14649 (setq tags (append
14650 (if parent
14651 (org-remove-uninherited-tags ltags)
14652 ltags)
14653 tags)))
14654 (or org-use-tag-inheritance (throw 'done t))
14655 (if local (throw 'done t))
14656 (or (org-up-heading-safe) (error nil))
14657 (setq parent t)))
14658 (error nil)))))
14659 (if local
14660 tags
14661 (reverse (delete-dups
14662 (reverse (append
14663 (org-remove-uninherited-tags
14664 org-file-tags) tags)))))))))
14666 (defun org-add-prop-inherited (s)
14667 (add-text-properties 0 (length s) '(inherited t) s)
14670 (defun org-toggle-tag (tag &optional onoff)
14671 "Toggle the tag TAG for the current line.
14672 If ONOFF is `on' or `off', don't toggle but set to this state."
14673 (let (res current)
14674 (save-excursion
14675 (org-back-to-heading t)
14676 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14677 (point-at-eol) t)
14678 (progn
14679 (setq current (match-string 1))
14680 (replace-match ""))
14681 (setq current ""))
14682 (setq current (nreverse (org-split-string current ":")))
14683 (cond
14684 ((eq onoff 'on)
14685 (setq res t)
14686 (or (member tag current) (push tag current)))
14687 ((eq onoff 'off)
14688 (or (not (member tag current)) (setq current (delete tag current))))
14689 (t (if (member tag current)
14690 (setq current (delete tag current))
14691 (setq res t)
14692 (push tag current))))
14693 (end-of-line 1)
14694 (if current
14695 (progn
14696 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14697 (org-set-tags nil t))
14698 (delete-horizontal-space))
14699 (run-hooks 'org-after-tags-change-hook))
14700 res))
14702 (defun org-align-tags-here (to-col)
14703 ;; Assumes that this is a headline
14704 "Align tags on the current headline to TO-COL."
14705 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14706 (beginning-of-line 1)
14707 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14708 (< pos (match-beginning 2)))
14709 (progn
14710 (setq tags-l (- (match-end 2) (match-beginning 2)))
14711 (goto-char (match-beginning 1))
14712 (insert " ")
14713 (delete-region (point) (1+ (match-beginning 2)))
14714 (setq ncol (max (current-column)
14715 (1+ col)
14716 (if (> to-col 0)
14717 to-col
14718 (- (abs to-col) tags-l))))
14719 (setq p (point))
14720 (insert (make-string (- ncol (current-column)) ?\ ))
14721 (setq ncol (current-column))
14722 (when indent-tabs-mode (tabify p (point-at-eol)))
14723 (org-move-to-column (min ncol col)))
14724 (goto-char pos))))
14726 (defun org-set-tags-command (&optional arg just-align)
14727 "Call the set-tags command for the current entry."
14728 (interactive "P")
14729 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14730 (org-set-tags arg just-align)
14731 (save-excursion
14732 (unless (and (org-region-active-p)
14733 org-loop-over-headlines-in-active-region)
14734 (org-back-to-heading t))
14735 (org-set-tags arg just-align))))
14737 (defun org-set-tags-to (data)
14738 "Set the tags of the current entry to DATA, replacing the current tags.
14739 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14740 If DATA is nil or the empty string, any tags will be removed."
14741 (interactive "sTags: ")
14742 (setq data
14743 (cond
14744 ((eq data nil) "")
14745 ((equal data "") "")
14746 ((stringp data)
14747 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14748 ":"))
14749 ((listp data)
14750 (concat ":" (mapconcat 'identity data ":") ":"))))
14751 (when data
14752 (save-excursion
14753 (org-back-to-heading t)
14754 (when (looking-at org-complex-heading-regexp)
14755 (if (match-end 5)
14756 (progn
14757 (goto-char (match-beginning 5))
14758 (insert data)
14759 (delete-region (point) (point-at-eol))
14760 (org-set-tags nil 'align))
14761 (goto-char (point-at-eol))
14762 (insert " " data)
14763 (org-set-tags nil 'align)))
14764 (beginning-of-line 1)
14765 (if (looking-at ".*?\\([ \t]+\\)$")
14766 (delete-region (match-beginning 1) (match-end 1))))))
14768 (defun org-align-all-tags ()
14769 "Align the tags i all headings."
14770 (interactive)
14771 (save-excursion
14772 (or (ignore-errors (org-back-to-heading t))
14773 (outline-next-heading))
14774 (if (org-at-heading-p)
14775 (org-set-tags t)
14776 (message "No headings"))))
14778 (defvar org-indent-indentation-per-level)
14779 (defun org-set-tags (&optional arg just-align)
14780 "Set the tags for the current headline.
14781 With prefix ARG, realign all tags in headings in the current buffer.
14782 When JUST-ALIGN is non-nil, only align tags."
14783 (interactive "P")
14784 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14785 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14786 'region-start-level 'region))
14787 org-loop-over-headlines-in-active-region)
14788 (org-map-entries
14789 ;; We don't use ARG and JUST-ALIGN here because these args
14790 ;; are not useful when looping over headlines.
14791 `(org-set-tags)
14792 org-loop-over-headlines-in-active-region
14793 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14794 (let* ((re org-outline-regexp-bol)
14795 (current (unless arg (org-get-tags-string)))
14796 (col (current-column))
14797 (org-setting-tags t)
14798 table current-tags inherited-tags ; computed below when needed
14799 tags p0 c0 c1 rpl di tc level)
14800 (if arg
14801 (save-excursion
14802 (goto-char (point-min))
14803 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14804 (while (re-search-forward re nil t)
14805 (org-set-tags nil t)
14806 (end-of-line 1)))
14807 (message "All tags realigned to column %d" org-tags-column))
14808 (if just-align
14809 (setq tags current)
14810 ;; Get a new set of tags from the user
14811 (save-excursion
14812 (setq table (append org-tag-persistent-alist
14813 (or org-tag-alist (org-get-buffer-tags))
14814 (and
14815 org-complete-tags-always-offer-all-agenda-tags
14816 (org-global-tags-completion-table
14817 (org-agenda-files))))
14818 org-last-tags-completion-table table
14819 current-tags (org-split-string current ":")
14820 inherited-tags (nreverse
14821 (nthcdr (length current-tags)
14822 (nreverse (org-get-tags-at))))
14823 tags
14824 (if (or (eq t org-use-fast-tag-selection)
14825 (and org-use-fast-tag-selection
14826 (delq nil (mapcar 'cdr table))))
14827 (org-fast-tag-selection
14828 current-tags inherited-tags table
14829 (if org-fast-tag-selection-include-todo
14830 org-todo-key-alist))
14831 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14832 (org-trim
14833 (org-icompleting-read "Tags: "
14834 'org-tags-completion-function
14835 nil nil current 'org-tags-history))))))
14836 (while (string-match "[-+&]+" tags)
14837 ;; No boolean logic, just a list
14838 (setq tags (replace-match ":" t t tags))))
14840 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14842 (if org-tags-sort-function
14843 (setq tags (mapconcat 'identity
14844 (sort (org-split-string
14845 tags (org-re "[^[:alnum:]_@#%]+"))
14846 org-tags-sort-function) ":")))
14848 (if (string-match "\\`[\t ]*\\'" tags)
14849 (setq tags "")
14850 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14851 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14853 ;; Insert new tags at the correct column
14854 (beginning-of-line 1)
14855 (setq level (or (and (looking-at org-outline-regexp)
14856 (- (match-end 0) (point) 1))
14858 (cond
14859 ((and (equal current "") (equal tags "")))
14860 ((re-search-forward
14861 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14862 (point-at-eol) t)
14863 (if (equal tags "")
14864 (setq rpl "")
14865 (goto-char (match-beginning 0))
14866 (setq c0 (current-column)
14867 ;; compute offset for the case of org-indent-mode active
14868 di (if (org-bound-and-true-p org-indent-mode)
14869 (* (1- org-indent-indentation-per-level) (1- level))
14871 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14872 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14873 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14874 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14875 (replace-match rpl t t)
14876 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14877 tags)
14878 (t (error "Tags alignment failed")))
14879 (org-move-to-column col)
14880 (unless just-align
14881 (run-hooks 'org-after-tags-change-hook))))))
14883 (defun org-change-tag-in-region (beg end tag off)
14884 "Add or remove TAG for each entry in the region.
14885 This works in the agenda, and also in an org-mode buffer."
14886 (interactive
14887 (list (region-beginning) (region-end)
14888 (let ((org-last-tags-completion-table
14889 (if (derived-mode-p 'org-mode)
14890 (org-uniquify
14891 (delq nil (append (org-get-buffer-tags)
14892 (org-global-tags-completion-table))))
14893 (org-global-tags-completion-table))))
14894 (org-icompleting-read
14895 "Tag: " 'org-tags-completion-function nil nil nil
14896 'org-tags-history))
14897 (progn
14898 (message "[s]et or [r]emove? ")
14899 (equal (read-char-exclusive) ?r))))
14900 (if (fboundp 'deactivate-mark) (deactivate-mark))
14901 (let ((agendap (equal major-mode 'org-agenda-mode))
14902 l1 l2 m buf pos newhead (cnt 0))
14903 (goto-char end)
14904 (setq l2 (1- (org-current-line)))
14905 (goto-char beg)
14906 (setq l1 (org-current-line))
14907 (loop for l from l1 to l2 do
14908 (org-goto-line l)
14909 (setq m (get-text-property (point) 'org-hd-marker))
14910 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14911 (and agendap m))
14912 (setq buf (if agendap (marker-buffer m) (current-buffer))
14913 pos (if agendap m (point)))
14914 (with-current-buffer buf
14915 (save-excursion
14916 (save-restriction
14917 (goto-char pos)
14918 (setq cnt (1+ cnt))
14919 (org-toggle-tag tag (if off 'off 'on))
14920 (setq newhead (org-get-heading)))))
14921 (and agendap (org-agenda-change-all-lines newhead m))))
14922 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14924 (defun org-tags-completion-function (string predicate &optional flag)
14925 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14926 (confirm (lambda (x) (stringp (car x)))))
14927 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14928 (setq s1 (match-string 1 string)
14929 s2 (match-string 2 string))
14930 (setq s1 "" s2 string))
14931 (cond
14932 ((eq flag nil)
14933 ;; try completion
14934 (setq rtn (try-completion s2 ctable confirm))
14935 (if (stringp rtn)
14936 (setq rtn
14937 (concat s1 s2 (substring rtn (length s2))
14938 (if (and org-add-colon-after-tag-completion
14939 (assoc rtn ctable))
14940 ":" ""))))
14941 rtn)
14942 ((eq flag t)
14943 ;; all-completions
14944 (all-completions s2 ctable confirm))
14945 ((eq flag 'lambda)
14946 ;; exact match?
14947 (assoc s2 ctable)))))
14949 (defun org-fast-tag-insert (kwd tags face &optional end)
14950 "Insert KDW, and the TAGS, the latter with face FACE.
14951 Also insert END."
14952 (insert (format "%-12s" (concat kwd ":"))
14953 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14954 (or end "")))
14956 (defun org-fast-tag-show-exit (flag)
14957 (save-excursion
14958 (org-goto-line 3)
14959 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14960 (replace-match ""))
14961 (when flag
14962 (end-of-line 1)
14963 (org-move-to-column (- (window-width) 19) t)
14964 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14966 (defun org-set-current-tags-overlay (current prefix)
14967 "Add an overlay to CURRENT tag with PREFIX."
14968 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14969 (if (featurep 'xemacs)
14970 (org-overlay-display org-tags-overlay (concat prefix s)
14971 'secondary-selection)
14972 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14973 (org-overlay-display org-tags-overlay (concat prefix s)))))
14975 (defvar org-last-tag-selection-key nil)
14976 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14977 "Fast tag selection with single keys.
14978 CURRENT is the current list of tags in the headline, INHERITED is the
14979 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14980 possibly with grouping information. TODO-TABLE is a similar table with
14981 TODO keywords, should these have keys assigned to them.
14982 If the keys are nil, a-z are automatically assigned.
14983 Returns the new tags string, or nil to not change the current settings."
14984 (let* ((fulltable (append table todo-table))
14985 (maxlen (apply 'max (mapcar
14986 (lambda (x)
14987 (if (stringp (car x)) (string-width (car x)) 0))
14988 fulltable)))
14989 (buf (current-buffer))
14990 (expert (eq org-fast-tag-selection-single-key 'expert))
14991 (buffer-tags nil)
14992 (fwidth (+ maxlen 3 1 3))
14993 (ncol (/ (- (window-width) 4) fwidth))
14994 (i-face 'org-done)
14995 (c-face 'org-todo)
14996 tg cnt e c char c1 c2 ntable tbl rtn
14997 ov-start ov-end ov-prefix
14998 (exit-after-next org-fast-tag-selection-single-key)
14999 (done-keywords org-done-keywords)
15000 groups ingroup)
15001 (save-excursion
15002 (beginning-of-line 1)
15003 (if (looking-at
15004 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15005 (setq ov-start (match-beginning 1)
15006 ov-end (match-end 1)
15007 ov-prefix "")
15008 (setq ov-start (1- (point-at-eol))
15009 ov-end (1+ ov-start))
15010 (skip-chars-forward "^\n\r")
15011 (setq ov-prefix
15012 (concat
15013 (buffer-substring (1- (point)) (point))
15014 (if (> (current-column) org-tags-column)
15016 (make-string (- org-tags-column (current-column)) ?\ ))))))
15017 (move-overlay org-tags-overlay ov-start ov-end)
15018 (save-window-excursion
15019 (if expert
15020 (set-buffer (get-buffer-create " *Org tags*"))
15021 (delete-other-windows)
15022 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15023 (org-switch-to-buffer-other-window " *Org tags*"))
15024 (erase-buffer)
15025 (org-set-local 'org-done-keywords done-keywords)
15026 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15027 (org-fast-tag-insert "Current" current c-face "\n\n")
15028 (org-fast-tag-show-exit exit-after-next)
15029 (org-set-current-tags-overlay current ov-prefix)
15030 (setq tbl fulltable char ?a cnt 0)
15031 (while (setq e (pop tbl))
15032 (cond
15033 ((equal (car e) :startgroup)
15034 (push '() groups) (setq ingroup t)
15035 (when (not (= cnt 0))
15036 (setq cnt 0)
15037 (insert "\n"))
15038 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15039 ((equal (car e) :endgroup)
15040 (setq ingroup nil cnt 0)
15041 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15042 ((equal e '(:newline))
15043 (when (not (= cnt 0))
15044 (setq cnt 0)
15045 (insert "\n")
15046 (setq e (car tbl))
15047 (while (equal (car tbl) '(:newline))
15048 (insert "\n")
15049 (setq tbl (cdr tbl)))))
15050 ((equal e '(:grouptags)) nil)
15052 (setq tg (copy-sequence (car e)) c2 nil)
15053 (if (cdr e)
15054 (setq c (cdr e))
15055 ;; automatically assign a character.
15056 (setq c1 (string-to-char
15057 (downcase (substring
15058 tg (if (= (string-to-char tg) ?@) 1 0)))))
15059 (if (or (rassoc c1 ntable) (rassoc c1 table))
15060 (while (or (rassoc char ntable) (rassoc char table))
15061 (setq char (1+ char)))
15062 (setq c2 c1))
15063 (setq c (or c2 char)))
15064 (if ingroup (push tg (car groups)))
15065 (setq tg (org-add-props tg nil 'face
15066 (cond
15067 ((not (assoc tg table))
15068 (org-get-todo-face tg))
15069 ((member tg current) c-face)
15070 ((member tg inherited) i-face))))
15071 (if (equal (caar tbl) :grouptags)
15072 (org-add-props tg nil 'face 'org-tag-group))
15073 (if (and (= cnt 0) (not ingroup)) (insert " "))
15074 (insert "[" c "] " tg (make-string
15075 (- fwidth 4 (length tg)) ?\ ))
15076 (push (cons tg c) ntable)
15077 (when (= (setq cnt (1+ cnt)) ncol)
15078 (insert "\n")
15079 (if ingroup (insert " "))
15080 (setq cnt 0)))))
15081 (setq ntable (nreverse ntable))
15082 (insert "\n")
15083 (goto-char (point-min))
15084 (if (not expert) (org-fit-window-to-buffer))
15085 (setq rtn
15086 (catch 'exit
15087 (while t
15088 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15089 (if (not groups) "no " "")
15090 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15091 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15092 (setq org-last-tag-selection-key c)
15093 (cond
15094 ((= c ?\r) (throw 'exit t))
15095 ((= c ?!)
15096 (setq groups (not groups))
15097 (goto-char (point-min))
15098 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15099 ((= c ?\C-c)
15100 (if (not expert)
15101 (org-fast-tag-show-exit
15102 (setq exit-after-next (not exit-after-next)))
15103 (setq expert nil)
15104 (delete-other-windows)
15105 (set-window-buffer (split-window-vertically) " *Org tags*")
15106 (org-switch-to-buffer-other-window " *Org tags*")
15107 (org-fit-window-to-buffer)))
15108 ((or (= c ?\C-g)
15109 (and (= c ?q) (not (rassoc c ntable))))
15110 (org-detach-overlay org-tags-overlay)
15111 (setq quit-flag t))
15112 ((= c ?\ )
15113 (setq current nil)
15114 (if exit-after-next (setq exit-after-next 'now)))
15115 ((= c ?\t)
15116 (condition-case nil
15117 (setq tg (org-icompleting-read
15118 "Tag: "
15119 (or buffer-tags
15120 (with-current-buffer buf
15121 (org-get-buffer-tags)))))
15122 (quit (setq tg "")))
15123 (when (string-match "\\S-" tg)
15124 (add-to-list 'buffer-tags (list tg))
15125 (if (member tg current)
15126 (setq current (delete tg current))
15127 (push tg current)))
15128 (if exit-after-next (setq exit-after-next 'now)))
15129 ((setq e (rassoc c todo-table) tg (car e))
15130 (with-current-buffer buf
15131 (save-excursion (org-todo tg)))
15132 (if exit-after-next (setq exit-after-next 'now)))
15133 ((setq e (rassoc c ntable) tg (car e))
15134 (if (member tg current)
15135 (setq current (delete tg current))
15136 (loop for g in groups do
15137 (if (member tg g)
15138 (mapc (lambda (x)
15139 (setq current (delete x current)))
15140 g)))
15141 (push tg current))
15142 (if exit-after-next (setq exit-after-next 'now))))
15144 ;; Create a sorted list
15145 (setq current
15146 (sort current
15147 (lambda (a b)
15148 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15149 (if (eq exit-after-next 'now) (throw 'exit t))
15150 (goto-char (point-min))
15151 (beginning-of-line 2)
15152 (delete-region (point) (point-at-eol))
15153 (org-fast-tag-insert "Current" current c-face)
15154 (org-set-current-tags-overlay current ov-prefix)
15155 (while (re-search-forward
15156 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15157 (setq tg (match-string 1))
15158 (add-text-properties
15159 (match-beginning 1) (match-end 1)
15160 (list 'face
15161 (cond
15162 ((member tg current) c-face)
15163 ((member tg inherited) i-face)
15164 (t (get-text-property (match-beginning 1) 'face))))))
15165 (goto-char (point-min)))))
15166 (org-detach-overlay org-tags-overlay)
15167 (if rtn
15168 (mapconcat 'identity current ":")
15169 nil))))
15171 (defun org-get-tags-string ()
15172 "Get the TAGS string in the current headline."
15173 (unless (org-at-heading-p t)
15174 (user-error "Not on a heading"))
15175 (save-excursion
15176 (beginning-of-line 1)
15177 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15178 (org-match-string-no-properties 1)
15179 "")))
15181 (defun org-get-tags ()
15182 "Get the list of tags specified in the current headline."
15183 (org-split-string (org-get-tags-string) ":"))
15185 (defun org-get-buffer-tags ()
15186 "Get a table of all tags used in the buffer, for completion."
15187 (let (tags)
15188 (save-excursion
15189 (goto-char (point-min))
15190 (while (re-search-forward
15191 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15192 (when (equal (char-after (point-at-bol 0)) ?*)
15193 (mapc (lambda (x) (add-to-list 'tags x))
15194 (org-split-string (org-match-string-no-properties 1) ":")))))
15195 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15196 (mapcar 'list tags)))
15198 ;;;; The mapping API
15200 (defun org-map-entries (func &optional match scope &rest skip)
15201 "Call FUNC at each headline selected by MATCH in SCOPE.
15203 FUNC is a function or a lisp form. The function will be called without
15204 arguments, with the cursor positioned at the beginning of the headline.
15205 The return values of all calls to the function will be collected and
15206 returned as a list.
15208 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15209 does not need to preserve point. After evaluation, the cursor will be
15210 moved to the end of the line (presumably of the headline of the
15211 processed entry) and search continues from there. Under some
15212 circumstances, this may not produce the wanted results. For example,
15213 if you have removed (e.g. archived) the current (sub)tree it could
15214 mean that the next entry will be skipped entirely. In such cases, you
15215 can specify the position from where search should continue by making
15216 FUNC set the variable `org-map-continue-from' to the desired buffer
15217 position.
15219 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15220 Only headlines that are matched by this query will be considered during
15221 the iteration. When MATCH is nil or t, all headlines will be
15222 visited by the iteration.
15224 SCOPE determines the scope of this command. It can be any of:
15226 nil The current buffer, respecting the restriction if any
15227 tree The subtree started with the entry at point
15228 region The entries within the active region, if any
15229 region-start-level
15230 The entries within the active region, but only those at
15231 the same level than the first one.
15232 file The current buffer, without restriction
15233 file-with-archives
15234 The current buffer, and any archives associated with it
15235 agenda All agenda files
15236 agenda-with-archives
15237 All agenda files with any archive files associated with them
15238 \(file1 file2 ...)
15239 If this is a list, all files in the list will be scanned
15241 The remaining args are treated as settings for the skipping facilities of
15242 the scanner. The following items can be given here:
15244 archive skip trees with the archive tag
15245 comment skip trees with the COMMENT keyword
15246 function or Emacs Lisp form:
15247 will be used as value for `org-agenda-skip-function', so
15248 whenever the function returns a position, FUNC will not be
15249 called for that entry and search will continue from the
15250 position returned
15252 If your function needs to retrieve the tags including inherited tags
15253 at the *current* entry, you can use the value of the variable
15254 `org-scanner-tags' which will be much faster than getting the value
15255 with `org-get-tags-at'. If your function gets properties with
15256 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15257 to t around the call to `org-entry-properties' to get the same speedup.
15258 Note that if your function moves around to retrieve tags and properties at
15259 a *different* entry, you cannot use these techniques."
15260 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15261 (not (org-region-active-p)))
15262 (let* ((org-agenda-archives-mode nil) ; just to make sure
15263 (org-agenda-skip-archived-trees (memq 'archive skip))
15264 (org-agenda-skip-comment-trees (memq 'comment skip))
15265 (org-agenda-skip-function
15266 (car (org-delete-all '(comment archive) skip)))
15267 (org-tags-match-list-sublevels t)
15268 (start-level (eq scope 'region-start-level))
15269 matcher file res
15270 org-todo-keywords-for-agenda
15271 org-done-keywords-for-agenda
15272 org-todo-keyword-alist-for-agenda
15273 org-tag-alist-for-agenda
15274 todo-only)
15276 (cond
15277 ((eq match t) (setq matcher t))
15278 ((eq match nil) (setq matcher t))
15279 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15281 (save-excursion
15282 (save-restriction
15283 (cond ((eq scope 'tree)
15284 (org-back-to-heading t)
15285 (org-narrow-to-subtree)
15286 (setq scope nil))
15287 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15288 (org-region-active-p))
15289 ;; If needed, set start-level to a string like "2"
15290 (when start-level
15291 (save-excursion
15292 (goto-char (region-beginning))
15293 (unless (org-at-heading-p) (outline-next-heading))
15294 (setq start-level (org-current-level))))
15295 (narrow-to-region (region-beginning)
15296 (save-excursion
15297 (goto-char (region-end))
15298 (unless (and (bolp) (org-at-heading-p))
15299 (outline-next-heading))
15300 (point)))
15301 (setq scope nil)))
15303 (if (not scope)
15304 (progn
15305 (org-agenda-prepare-buffers
15306 (list (buffer-file-name (current-buffer))))
15307 (setq res (org-scan-tags func matcher todo-only start-level)))
15308 ;; Get the right scope
15309 (cond
15310 ((and scope (listp scope) (symbolp (car scope)))
15311 (setq scope (eval scope)))
15312 ((eq scope 'agenda)
15313 (setq scope (org-agenda-files t)))
15314 ((eq scope 'agenda-with-archives)
15315 (setq scope (org-agenda-files t))
15316 (setq scope (org-add-archive-files scope)))
15317 ((eq scope 'file)
15318 (setq scope (list (buffer-file-name))))
15319 ((eq scope 'file-with-archives)
15320 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15321 (org-agenda-prepare-buffers scope)
15322 (while (setq file (pop scope))
15323 (with-current-buffer (org-find-base-buffer-visiting file)
15324 (save-excursion
15325 (save-restriction
15326 (widen)
15327 (goto-char (point-min))
15328 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15329 res)))
15331 ;;;; Properties
15333 ;;; Setting and retrieving properties
15335 (defconst org-special-properties
15336 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15337 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15338 "The special properties valid in Org-mode.
15340 These are properties that are not defined in the property drawer,
15341 but in some other way.")
15343 (defconst org-default-properties
15344 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15345 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15346 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15347 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15348 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15349 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15350 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15351 "Some properties that are used by Org-mode for various purposes.
15352 Being in this list makes sure that they are offered for completion.")
15354 (defun org-property-action ()
15355 "Do an action on properties."
15356 (interactive)
15357 (let (c)
15358 (org-at-property-p)
15359 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15360 (setq c (read-char-exclusive))
15361 (cond
15362 ((equal c ?s)
15363 (call-interactively 'org-set-property))
15364 ((equal c ?d)
15365 (call-interactively 'org-delete-property))
15366 ((equal c ?D)
15367 (call-interactively 'org-delete-property-globally))
15368 ((equal c ?c)
15369 (call-interactively 'org-compute-property-at-point))
15370 (t (user-error "No such property action %c" c)))))
15372 (defun org-inc-effort ()
15373 "Increment the value of the effort property in the current entry."
15374 (interactive)
15375 (org-set-effort nil t))
15377 (defvar org-clock-effort) ;; Defined in org-clock.el
15378 (defvar org-clock-current-task) ;; Defined in org-clock.el
15379 (defun org-set-effort (&optional value increment)
15380 "Set the effort property of the current entry.
15381 With numerical prefix arg, use the nth allowed value, 0 stands for the
15382 10th allowed value.
15384 When INCREMENT is non-nil, set the property to the next allowed value."
15385 (interactive "P")
15386 (if (equal value 0) (setq value 10))
15387 (let* ((completion-ignore-case t)
15388 (prop org-effort-property)
15389 (cur (org-entry-get nil prop))
15390 (allowed (org-property-get-allowed-values nil prop 'table))
15391 (existing (mapcar 'list (org-property-values prop)))
15392 (heading (nth 4 (org-heading-components)))
15394 (val (cond
15395 ((stringp value) value)
15396 ((and allowed (integerp value))
15397 (or (car (nth (1- value) allowed))
15398 (car (org-last allowed))))
15399 ((and allowed increment)
15400 (or (caadr (member (list cur) allowed))
15401 (user-error "Allowed effort values are not set")))
15402 (allowed
15403 (message "Select 1-9,0, [RET%s]: %s"
15404 (if cur (concat "=" cur) "")
15405 (mapconcat 'car allowed " "))
15406 (setq rpl (read-char-exclusive))
15407 (if (equal rpl ?\r)
15409 (setq rpl (- rpl ?0))
15410 (if (equal rpl 0) (setq rpl 10))
15411 (if (and (> rpl 0) (<= rpl (length allowed)))
15412 (car (nth (1- rpl) allowed))
15413 (org-completing-read "Effort: " allowed nil))))
15415 (let (org-completion-use-ido org-completion-use-iswitchb)
15416 (org-completing-read
15417 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15418 (concat "[" cur "]") "")
15419 ": ")
15420 existing nil nil "" nil cur))))))
15421 (unless (equal (org-entry-get nil prop) val)
15422 (org-entry-put nil prop val))
15423 (org-refresh-property
15424 '((effort . identity)
15425 (effort-minutes . org-duration-string-to-minutes))
15426 val)
15427 (when (string= heading org-clock-current-task)
15428 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15429 (org-clock-update-mode-line))
15430 (message "%s is now %s" prop val)))
15432 (defun org-at-property-p ()
15433 "Non-nil when point is inside a property drawer.
15434 See `org-property-re' for match data, if applicable."
15435 (when (eq (org-element-type (org-element-at-point)) 'node-property)
15436 (save-excursion
15437 (beginning-of-line)
15438 (looking-at org-property-re))))
15440 (defun org-get-property-block (&optional beg end force)
15441 "Return the (beg . end) range of the body of the property drawer.
15442 BEG and END are the beginning and end of the current subtree, or of
15443 the part before the first headline. If they are not given, they will
15444 be found. If the drawer does not exist and FORCE is non-nil, create
15445 the drawer."
15446 (catch 'exit
15447 (save-excursion
15448 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15449 (progn (org-back-to-heading t) (point))))
15450 (end (or end (and (not (outline-next-heading)) (point-max))
15451 (point))))
15452 (goto-char beg)
15453 (if (re-search-forward org-property-start-re end t)
15454 (setq beg (1+ (match-end 0)))
15455 (if force
15456 (save-excursion
15457 (org-insert-property-drawer)
15458 (setq end (progn (outline-next-heading) (point))))
15459 (throw 'exit nil))
15460 (goto-char beg)
15461 (if (re-search-forward org-property-start-re end t)
15462 (setq beg (1+ (match-end 0)))))
15463 (if (re-search-forward org-property-end-re end t)
15464 (setq end (match-beginning 0))
15465 (or force (throw 'exit nil))
15466 (goto-char beg)
15467 (setq end beg)
15468 (org-indent-line)
15469 (insert ":END:\n"))
15470 (cons beg end)))))
15472 (defun org-entry-properties (&optional pom which specific)
15473 "Get all properties of the entry at point-or-marker POM.
15474 This includes the TODO keyword, the tags, time strings for deadline,
15475 scheduled, and clocking, and any additional properties defined in the
15476 entry. The return value is an alist, keys may occur multiple times
15477 if the property key was used several times.
15478 POM may also be nil, in which case the current entry is used.
15479 If WHICH is nil or `all', get all properties. If WHICH is
15480 `special' or `standard', only get that subclass. If WHICH
15481 is a string only get exactly this property. SPECIFIC can be a string, the
15482 specific property we are interested in. Specifying it can speed
15483 things up because then unnecessary parsing is avoided."
15484 (setq which (or which 'all))
15485 (org-with-wide-buffer
15486 (org-with-point-at pom
15487 (let ((clockstr (substring org-clock-string 0 -1))
15488 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15489 (case-fold-search nil)
15490 beg end range props sum-props key key1 value string clocksum clocksumt)
15491 (when (and (derived-mode-p 'org-mode)
15492 (ignore-errors (org-back-to-heading t)))
15493 (setq beg (point))
15494 (setq sum-props (get-text-property (point) 'org-summaries))
15495 (setq clocksum (get-text-property (point) :org-clock-minutes)
15496 clocksumt (get-text-property (point) :org-clock-minutes-today))
15497 (outline-next-heading)
15498 (setq end (point))
15499 (when (memq which '(all special))
15500 ;; Get the special properties, like TODO and tags
15501 (goto-char beg)
15502 (when (and (or (not specific) (string= specific "TODO"))
15503 (looking-at org-todo-line-regexp) (match-end 2))
15504 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15505 (when (and (or (not specific) (string= specific "PRIORITY"))
15506 (looking-at org-priority-regexp))
15507 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15508 (when (or (not specific) (string= specific "FILE"))
15509 (push (cons "FILE" buffer-file-name) props))
15510 (when (and (or (not specific) (string= specific "TAGS"))
15511 (setq value (org-get-tags-string))
15512 (string-match "\\S-" value))
15513 (push (cons "TAGS" value) props))
15514 (when (and (or (not specific) (string= specific "ALLTAGS"))
15515 (setq value (org-get-tags-at)))
15516 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15517 ":"))
15518 props))
15519 (when (or (not specific) (string= specific "BLOCKED"))
15520 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15521 (when (or (not specific)
15522 (member specific
15523 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15524 "TIMESTAMP" "TIMESTAMP_IA")))
15525 (catch 'match
15526 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15527 (not (text-property-any 0 (length (match-string 0))
15528 'face 'font-lock-comment-face
15529 (match-string 0))))
15530 (setq key (if (match-end 1)
15531 (substring (org-match-string-no-properties 1)
15532 0 -1))
15533 string (if (equal key clockstr)
15534 (org-trim
15535 (buffer-substring-no-properties
15536 (match-beginning 3) (goto-char
15537 (point-at-eol))))
15538 (substring (org-match-string-no-properties 3)
15539 1 -1)))
15540 ;; Get the correct property name from the key. This is
15541 ;; necessary if the user has configured time keywords.
15542 (setq key1 (concat key ":"))
15543 (cond
15544 ((not key)
15545 (setq key
15546 (if (= (char-after (match-beginning 3)) ?\[)
15547 "TIMESTAMP_IA" "TIMESTAMP")))
15548 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15549 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15550 ((equal key1 org-closed-string) (setq key "CLOSED"))
15551 ((equal key1 org-clock-string) (setq key "CLOCK")))
15552 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15553 (progn
15554 (push (cons key string) props)
15555 ;; no need to search further if match is found
15556 (throw 'match t))
15557 (when (or (equal key "CLOCK") (not (assoc key props)))
15558 (push (cons key string) props)))))))
15560 (when (memq which '(all standard))
15561 ;; Get the standard properties, like :PROP: ...
15562 (setq range (org-get-property-block beg end))
15563 (when range
15564 (goto-char (car range))
15565 (while (re-search-forward org-property-re
15566 (cdr range) t)
15567 (setq key (org-match-string-no-properties 2)
15568 value (org-trim (or (org-match-string-no-properties 3) "")))
15569 (unless (member key excluded)
15570 (push (cons key (or value "")) props)))))
15571 (if clocksum
15572 (push (cons "CLOCKSUM"
15573 (org-columns-number-to-string (/ (float clocksum) 60.)
15574 'add_times))
15575 props))
15576 (if clocksumt
15577 (push (cons "CLOCKSUM_T"
15578 (org-columns-number-to-string (/ (float clocksumt) 60.)
15579 'add_times))
15580 props))
15581 (unless (assoc "CATEGORY" props)
15582 (push (cons "CATEGORY" (org-get-category)) props))
15583 (append sum-props (nreverse props)))))))
15585 (defun org-entry-get (pom property &optional inherit literal-nil)
15586 "Get value of PROPERTY for entry or content at point-or-marker POM.
15587 If INHERIT is non-nil and the entry does not have the property,
15588 then also check higher levels of the hierarchy.
15589 If INHERIT is the symbol `selective', use inheritance only if the setting
15590 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15591 If the property is present but empty, the return value is the empty string.
15592 If the property is not present at all, nil is returned.
15594 Return the value as a string.
15596 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15597 do not interpret it as the list atom nil. This is used for inheritance
15598 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15599 (org-with-point-at pom
15600 (if (and inherit (if (eq inherit 'selective)
15601 (org-property-inherit-p property)
15603 (org-entry-get-with-inheritance property literal-nil)
15604 (if (member property org-special-properties)
15605 ;; We need a special property. Use `org-entry-properties'
15606 ;; to retrieve it, but specify the wanted property
15607 (cdr (assoc property (org-entry-properties nil 'special property)))
15608 (org-with-wide-buffer
15609 (let ((range (org-get-property-block)))
15610 (when (and range (not (eq (car range) (cdr range)))
15611 (save-excursion
15612 (goto-char (car range))
15613 (re-search-forward
15614 (concat (org-re-property property) "\\|"
15615 (org-re-property (concat property "+")))
15616 (cdr range) t)))
15617 (let* ((props
15618 (list (or (assoc property org-file-properties)
15619 (assoc property org-global-properties)
15620 (assoc property org-global-properties-fixed))))
15621 (ap (lambda (key)
15622 (when (re-search-forward
15623 (org-re-property key) (cdr range) t)
15624 (setq props
15625 (org-update-property-plist
15627 (if (match-end 3)
15628 (org-match-string-no-properties 3) "")
15629 props)))))
15630 val)
15631 (goto-char (car range))
15632 (funcall ap property)
15633 (goto-char (car range))
15634 (while (funcall ap (concat property "+")))
15635 (setq val (cdr (assoc property props)))
15636 (when val (if literal-nil val (org-not-nil val)))))))))))
15638 (defun org-property-or-variable-value (var &optional inherit)
15639 "Check if there is a property fixing the value of VAR.
15640 If yes, return this value. If not, return the current value of the variable."
15641 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15642 (if (and prop (stringp prop) (string-match "\\S-" prop))
15643 (read prop)
15644 (symbol-value var))))
15646 (defun org-entry-delete (pom property)
15647 "Delete the property PROPERTY from entry at point-or-marker POM."
15648 (unless (member property org-special-properties)
15649 (org-with-point-at pom
15650 (let ((range (org-get-property-block)))
15651 (if (and range
15652 (goto-char (car range))
15653 (re-search-forward
15654 (org-re-property property nil t)
15655 (cdr range) t))
15656 (progn
15657 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15658 (org-remove-empty-drawer-at (car range))
15660 nil)))))
15662 ;; Multi-values properties are properties that contain multiple values
15663 ;; These values are assumed to be single words, separated by whitespace.
15664 (defun org-entry-add-to-multivalued-property (pom property value)
15665 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15666 (let* ((old (org-entry-get pom property))
15667 (values (and old (org-split-string old "[ \t]"))))
15668 (setq value (org-entry-protect-space value))
15669 (unless (member value values)
15670 (setq values (append values (list value)))
15671 (org-entry-put pom property
15672 (mapconcat 'identity values " ")))))
15674 (defun org-entry-remove-from-multivalued-property (pom property value)
15675 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15676 (let* ((old (org-entry-get pom property))
15677 (values (and old (org-split-string old "[ \t]"))))
15678 (setq value (org-entry-protect-space value))
15679 (when (member value values)
15680 (setq values (delete value values))
15681 (org-entry-put pom property
15682 (mapconcat 'identity values " ")))))
15684 (defun org-entry-member-in-multivalued-property (pom property value)
15685 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15686 (let* ((old (org-entry-get pom property))
15687 (values (and old (org-split-string old "[ \t]"))))
15688 (setq value (org-entry-protect-space value))
15689 (member value values)))
15691 (defun org-entry-get-multivalued-property (pom property)
15692 "Return a list of values in a multivalued property."
15693 (let* ((value (org-entry-get pom property))
15694 (values (and value (org-split-string value "[ \t]"))))
15695 (mapcar 'org-entry-restore-space values)))
15697 (defun org-entry-put-multivalued-property (pom property &rest values)
15698 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15699 VALUES should be a list of strings. Spaces will be protected."
15700 (org-entry-put pom property
15701 (mapconcat 'org-entry-protect-space values " "))
15702 (let* ((value (org-entry-get pom property))
15703 (values (and value (org-split-string value "[ \t]"))))
15704 (mapcar 'org-entry-restore-space values)))
15706 (defun org-entry-protect-space (s)
15707 "Protect spaces and newline in string S."
15708 (while (string-match " " s)
15709 (setq s (replace-match "%20" t t s)))
15710 (while (string-match "\n" s)
15711 (setq s (replace-match "%0A" t t s)))
15714 (defun org-entry-restore-space (s)
15715 "Restore spaces and newline in string S."
15716 (while (string-match "%20" s)
15717 (setq s (replace-match " " t t s)))
15718 (while (string-match "%0A" s)
15719 (setq s (replace-match "\n" t t s)))
15722 (defvar org-entry-property-inherited-from (make-marker)
15723 "Marker pointing to the entry from where a property was inherited.
15724 Each call to `org-entry-get-with-inheritance' will set this marker to the
15725 location of the entry where the inheritance search matched. If there was
15726 no match, the marker will point nowhere.
15727 Note that also `org-entry-get' calls this function, if the INHERIT flag
15728 is set.")
15730 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15731 "Get PROPERTY of entry or content at point, search higher levels if needed.
15732 The search will stop at the first ancestor which has the property defined.
15733 If the value found is \"nil\", return nil to show that the property
15734 should be considered as undefined (this is the meaning of nil here).
15735 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15736 (move-marker org-entry-property-inherited-from nil)
15737 (let (tmp)
15738 (save-excursion
15739 (save-restriction
15740 (widen)
15741 (catch 'ex
15742 (while t
15743 (when (setq tmp (org-entry-get nil property nil literal-nil))
15744 (or (ignore-errors (org-back-to-heading t))
15745 (goto-char (point-min)))
15746 (move-marker org-entry-property-inherited-from (point))
15747 (throw 'ex tmp))
15748 (or (ignore-errors (org-up-heading-safe))
15749 (throw 'ex nil))))))
15750 (setq tmp (or tmp
15751 (cdr (assoc property org-file-properties))
15752 (cdr (assoc property org-global-properties))
15753 (cdr (assoc property org-global-properties-fixed))))
15754 (if literal-nil tmp (org-not-nil tmp))))
15756 (defvar org-property-changed-functions nil
15757 "Hook called when the value of a property has changed.
15758 Each hook function should accept two arguments, the name of the property
15759 and the new value.")
15761 (defun org-entry-put (pom property value)
15762 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15763 If the value is `nil', it is converted to the empty string.
15764 If it is not a string, an error is raised."
15765 (cond ((null value) (setq value ""))
15766 ((not (stringp value))
15767 (error "Properties values should be strings.")))
15768 (org-with-point-at pom
15769 (org-back-to-heading t)
15770 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15771 range)
15772 (cond
15773 ((equal property "TODO")
15774 (when (and (string-match "\\S-" value)
15775 (not (member value org-todo-keywords-1)))
15776 (user-error "\"%s\" is not a valid TODO state" value))
15777 (if (or (not value)
15778 (not (string-match "\\S-" value)))
15779 (setq value 'none))
15780 (org-todo value)
15781 (org-set-tags nil 'align))
15782 ((equal property "PRIORITY")
15783 (org-priority (if (and value (string-match "\\S-" value))
15784 (string-to-char value) ?\ ))
15785 (org-set-tags nil 'align))
15786 ((equal property "CLOCKSUM")
15787 (if (not (re-search-forward
15788 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15789 (error "Cannot find a clock log")
15790 (goto-char (- (match-end 1) 2))
15791 (cond
15792 ((eq value 'earlier) (org-timestamp-down))
15793 ((eq value 'later) (org-timestamp-up)))
15794 (org-clock-sum-current-item)))
15795 ((equal property "SCHEDULED")
15796 (if (re-search-forward org-scheduled-time-regexp end t)
15797 (cond
15798 ((eq value 'earlier) (org-timestamp-change -1 'day))
15799 ((eq value 'later) (org-timestamp-change 1 'day))
15800 (t (call-interactively 'org-schedule)))
15801 (call-interactively 'org-schedule)))
15802 ((equal property "DEADLINE")
15803 (if (re-search-forward org-deadline-time-regexp end t)
15804 (cond
15805 ((eq value 'earlier) (org-timestamp-change -1 'day))
15806 ((eq value 'later) (org-timestamp-change 1 'day))
15807 (t (call-interactively 'org-deadline)))
15808 (call-interactively 'org-deadline)))
15809 ((member property org-special-properties)
15810 (error "The %s property can not yet be set with `org-entry-put'"
15811 property))
15812 (t ; a non-special property
15813 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15814 (setq range (org-get-property-block beg end 'force))
15815 (goto-char (car range))
15816 (if (re-search-forward
15817 (org-re-property property nil t) (cdr range) t)
15818 (progn
15819 (delete-region (match-beginning 0) (match-end 0))
15820 (goto-char (match-beginning 0)))
15821 (goto-char (cdr range))
15822 (insert "\n")
15823 (backward-char 1)
15824 (org-indent-line))
15825 (insert ":" property ":")
15826 (and value (insert " " value))
15827 (org-indent-line)))))
15828 (run-hook-with-args 'org-property-changed-functions property value)))
15830 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15831 "Get all property keys in the current buffer.
15832 With INCLUDE-SPECIALS, also list the special properties that reflect things
15833 like tags and TODO state.
15834 With INCLUDE-DEFAULTS, also include properties that has special meaning
15835 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15836 and others.
15837 With INCLUDE-COLUMNS, also include property names given in COLUMN
15838 formats in the current buffer."
15839 (let (rtn range cfmt s p)
15840 (save-excursion
15841 (save-restriction
15842 (widen)
15843 (goto-char (point-min))
15844 (while (re-search-forward org-property-start-re nil t)
15845 (catch 'cont
15846 (setq range (or (org-get-property-block)
15847 (if (y-or-n-p
15848 (format "Malformed drawer at %d, repair?" (point)))
15849 (org-get-property-block nil nil t)
15850 (throw 'cont nil))))
15851 (goto-char (car range))
15852 (while (re-search-forward org-property-re
15853 (cdr range) t)
15854 (add-to-list 'rtn (org-match-string-no-properties 2)))
15855 (outline-next-heading)))))
15857 (when include-specials
15858 (setq rtn (append org-special-properties rtn)))
15860 (when include-defaults
15861 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15862 (add-to-list 'rtn org-effort-property))
15864 (when include-columns
15865 (save-excursion
15866 (save-restriction
15867 (widen)
15868 (goto-char (point-min))
15869 (while (re-search-forward
15870 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15871 nil t)
15872 (setq cfmt (match-string 2) s 0)
15873 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15874 cfmt s)
15875 (setq s (match-end 0)
15876 p (match-string 1 cfmt))
15877 (unless (or (equal p "ITEM")
15878 (member p org-special-properties))
15879 (add-to-list 'rtn (match-string 1 cfmt))))))))
15881 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15883 (defun org-property-values (key)
15884 "Return a list of all values of property KEY in the current buffer."
15885 (save-excursion
15886 (save-restriction
15887 (widen)
15888 (goto-char (point-min))
15889 (let ((re (org-re-property key))
15890 values)
15891 (while (re-search-forward re nil t)
15892 (add-to-list 'values (org-trim (match-string 3))))
15893 (delete "" values)))))
15895 (defun org-insert-property-drawer ()
15896 "Insert a property drawer into the current entry."
15897 (org-back-to-heading t)
15898 (looking-at org-outline-regexp)
15899 (let ((indent (if org-adapt-indentation
15900 (- (match-end 0) (match-beginning 0))
15902 (beg (point))
15903 (re (concat "^[ \t]*" org-keyword-time-regexp))
15904 (org-clock-re (format "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|%s\\|:END:\\)"
15905 org-clock-string))
15906 (org-skip-line-list (list org-clock-string ":END:"))
15907 end hiddenp)
15908 (outline-next-heading)
15909 (setq end (point))
15910 (goto-char beg)
15911 (while (re-search-forward re end t))
15912 (setq hiddenp (outline-invisible-p))
15913 (end-of-line 1)
15914 (and (equal (char-after) ?\n) (forward-char 1))
15915 (while (looking-at org-clock-re)
15916 (if (member (match-string 1) org-skip-line-list)
15917 ;; just skip this line
15918 (beginning-of-line 2)
15919 ;; Drawer start, find the end
15920 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15921 (beginning-of-line 1)))
15922 (org-skip-over-state-notes)
15923 (skip-chars-backward " \t\n\r")
15924 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15925 (forward-char 1))
15926 (goto-char (point-at-eol))
15927 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15928 (beginning-of-line 0)
15929 (org-indent-to-column indent)
15930 (beginning-of-line 2)
15931 (org-indent-to-column indent)
15932 (beginning-of-line 0)
15933 (if hiddenp
15934 (save-excursion
15935 (org-back-to-heading t)
15936 (hide-entry))
15937 (org-flag-drawer t))))
15939 (defun org-insert-drawer (&optional arg drawer)
15940 "Insert a drawer at point.
15942 Optional argument DRAWER, when non-nil, is a string representing
15943 drawer's name. Otherwise, the user is prompted for a name.
15945 If a region is active, insert the drawer around that region
15946 instead.
15948 Point is left between drawer's boundaries."
15949 (interactive "P")
15950 (let* ((drawer (if arg "PROPERTIES"
15951 (or drawer (read-from-minibuffer "Drawer: ")))))
15952 (cond
15953 ;; With C-u, fall back on `org-insert-property-drawer'
15954 (arg (org-insert-property-drawer))
15956 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15957 (user-error "Invalid drawer name"))
15958 ;; With an active region, insert a drawer at point.
15959 ((not (org-region-active-p))
15960 (progn
15961 (unless (bolp) (insert "\n"))
15962 (insert (format ":%s:\n\n:END:\n" drawer))
15963 (forward-line -2)))
15964 ;; Otherwise, insert the drawer at point
15966 (let ((rbeg (region-beginning))
15967 (rend (copy-marker (region-end))))
15968 (unwind-protect
15969 (progn
15970 (goto-char rbeg)
15971 (beginning-of-line)
15972 (when (save-excursion
15973 (re-search-forward org-outline-regexp-bol rend t))
15974 (user-error "Drawers cannot contain headlines"))
15975 ;; Position point at the beginning of the first
15976 ;; non-blank line in region. Insert drawer's opening
15977 ;; there, then indent it.
15978 (org-skip-whitespace)
15979 (beginning-of-line)
15980 (insert ":" drawer ":\n")
15981 (forward-line -1)
15982 (indent-for-tab-command)
15983 ;; Move point to the beginning of the first blank line
15984 ;; after the last non-blank line in region. Insert
15985 ;; drawer's closing, then indent it.
15986 (goto-char rend)
15987 (skip-chars-backward " \r\t\n")
15988 (insert "\n:END:")
15989 (deactivate-mark t)
15990 (indent-for-tab-command)
15991 (unless (eolp) (insert "\n")))
15992 ;; Clear marker, whatever the outcome of insertion is.
15993 (set-marker rend nil)))))))
15995 (defvar org-property-set-functions-alist nil
15996 "Property set function alist.
15997 Each entry should have the following format:
15999 (PROPERTY . READ-FUNCTION)
16001 The read function will be called with the same argument as
16002 `org-completing-read'.")
16004 (defun org-set-property-function (property)
16005 "Get the function that should be used to set PROPERTY.
16006 This is computed according to `org-property-set-functions-alist'."
16007 (or (cdr (assoc property org-property-set-functions-alist))
16008 'org-completing-read))
16010 (defun org-read-property-value (property)
16011 "Read PROPERTY value from user."
16012 (let* ((completion-ignore-case t)
16013 (allowed (org-property-get-allowed-values nil property 'table))
16014 (cur (org-entry-get nil property))
16015 (prompt (concat property " value"
16016 (if (and cur (string-match "\\S-" cur))
16017 (concat " [" cur "]") "") ": "))
16018 (set-function (org-set-property-function property))
16019 (val (if allowed
16020 (funcall set-function prompt allowed nil
16021 (not (get-text-property 0 'org-unrestricted
16022 (caar allowed))))
16023 (let (org-completion-use-ido org-completion-use-iswitchb)
16024 (funcall set-function prompt
16025 (mapcar 'list (org-property-values property))
16026 nil nil "" nil cur)))))
16027 (org-trim val)))
16029 (defvar org-last-set-property nil)
16030 (defvar org-last-set-property-value nil)
16031 (defun org-read-property-name ()
16032 "Read a property name."
16033 (let* ((completion-ignore-case t)
16034 (keys (org-buffer-property-keys nil t t))
16035 (default-prop (or (save-excursion
16036 (save-match-data
16037 (beginning-of-line)
16038 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16039 (null (string= (match-string 1) "END"))
16040 (match-string 1))))
16041 org-last-set-property))
16042 (property (org-icompleting-read
16043 (concat "Property"
16044 (if default-prop (concat " [" default-prop "]") "")
16045 ": ")
16046 (mapcar 'list keys)
16047 nil nil nil nil
16048 default-prop)))
16049 (if (member property keys)
16050 property
16051 (or (cdr (assoc (downcase property)
16052 (mapcar (lambda (x) (cons (downcase x) x))
16053 keys)))
16054 property))))
16056 (defun org-set-property-and-value (use-last)
16057 "Allow to set [PROPERTY]: [value] direction from prompt.
16058 When use-default, don't even ask, just use the last
16059 \"[PROPERTY]: [value]\" string from the history."
16060 (interactive "P")
16061 (let* ((completion-ignore-case t)
16062 (pv (or (and use-last org-last-set-property-value)
16063 (org-completing-read
16064 "Enter a \"[Property]: [value]\" pair: "
16065 nil nil nil nil nil
16066 org-last-set-property-value)))
16067 prop val)
16068 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16069 (setq prop (match-string 1 pv)
16070 val (match-string 2 pv))
16071 (org-set-property prop val))))
16073 (defun org-set-property (property value)
16074 "In the current entry, set PROPERTY to VALUE.
16075 When called interactively, this will prompt for a property name, offering
16076 completion on existing and default properties. And then it will prompt
16077 for a value, offering completion either on allowed values (via an inherited
16078 xxx_ALL property) or on existing values in other instances of this property
16079 in the current file."
16080 (interactive (list nil nil))
16081 (let* ((property (or property (org-read-property-name)))
16082 (value (or value (org-read-property-value property)))
16083 (fn (cdr (assoc property org-properties-postprocess-alist))))
16084 (setq org-last-set-property property)
16085 (setq org-last-set-property-value (concat property ": " value))
16086 ;; Possibly postprocess the inserted value:
16087 (when fn (setq value (funcall fn value)))
16088 (unless (equal (org-entry-get nil property) value)
16089 (org-entry-put nil property value))))
16091 (defun org-delete-property (property)
16092 "In the current entry, delete PROPERTY."
16093 (interactive
16094 (let* ((completion-ignore-case t)
16095 (cat (org-entry-get (point) "CATEGORY"))
16096 (props0 (org-entry-properties nil 'standard))
16097 (props (if cat props0
16098 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16099 (prop (if (< 1 (length props))
16100 (org-icompleting-read "Property: " props nil t)
16101 (caar props))))
16102 (list prop)))
16103 (if (not property)
16104 (message "No property to delete in this entry")
16105 (org-entry-delete nil property)
16106 (message "Property \"%s\" deleted" property)))
16108 (defun org-delete-property-globally (property)
16109 "Remove PROPERTY globally, from all entries."
16110 (interactive
16111 (let* ((completion-ignore-case t)
16112 (prop (org-icompleting-read
16113 "Globally remove property: "
16114 (mapcar 'list (org-buffer-property-keys)))))
16115 (list prop)))
16116 (save-excursion
16117 (save-restriction
16118 (widen)
16119 (goto-char (point-min))
16120 (let ((cnt 0))
16121 (while (re-search-forward
16122 (org-re-property property)
16123 nil t)
16124 (setq cnt (1+ cnt))
16125 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16126 (message "Property \"%s\" removed from %d entries" property cnt)))))
16128 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16130 (defun org-compute-property-at-point ()
16131 "Compute the property at point.
16132 This looks for an enclosing column format, extracts the operator and
16133 then applies it to the property in the column format's scope."
16134 (interactive)
16135 (unless (org-at-property-p)
16136 (user-error "Not at a property"))
16137 (let ((prop (org-match-string-no-properties 2)))
16138 (org-columns-get-format-and-top-level)
16139 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16140 (user-error "No operator defined for property %s" prop))
16141 (org-columns-compute prop)))
16143 (defvar org-property-allowed-value-functions nil
16144 "Hook for functions supplying allowed values for a specific property.
16145 The functions must take a single argument, the name of the property, and
16146 return a flat list of allowed values. If \":ETC\" is one of
16147 the values, this means that these values are intended as defaults for
16148 completion, but that other values should be allowed too.
16149 The functions must return nil if they are not responsible for this
16150 property.")
16152 (defun org-property-get-allowed-values (pom property &optional table)
16153 "Get allowed values for the property PROPERTY.
16154 When TABLE is non-nil, return an alist that can directly be used for
16155 completion."
16156 (let (vals)
16157 (cond
16158 ((equal property "TODO")
16159 (setq vals (org-with-point-at pom
16160 (append org-todo-keywords-1 '("")))))
16161 ((equal property "PRIORITY")
16162 (let ((n org-lowest-priority))
16163 (while (>= n org-highest-priority)
16164 (push (char-to-string n) vals)
16165 (setq n (1- n)))))
16166 ((member property org-special-properties))
16167 ((setq vals (run-hook-with-args-until-success
16168 'org-property-allowed-value-functions property)))
16170 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16171 (when (and vals (string-match "\\S-" vals))
16172 (setq vals (car (read-from-string (concat "(" vals ")"))))
16173 (setq vals (mapcar (lambda (x)
16174 (cond ((stringp x) x)
16175 ((numberp x) (number-to-string x))
16176 ((symbolp x) (symbol-name x))
16177 (t "???")))
16178 vals)))))
16179 (when (member ":ETC" vals)
16180 (setq vals (remove ":ETC" vals))
16181 (org-add-props (car vals) '(org-unrestricted t)))
16182 (if table (mapcar 'list vals) vals)))
16184 (defun org-property-previous-allowed-value (&optional previous)
16185 "Switch to the next allowed value for this property."
16186 (interactive)
16187 (org-property-next-allowed-value t))
16189 (defun org-property-next-allowed-value (&optional previous)
16190 "Switch to the next allowed value for this property."
16191 (interactive)
16192 (unless (org-at-property-p)
16193 (user-error "Not at a property"))
16194 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16195 (key (match-string 2))
16196 (value (match-string 3))
16197 (allowed (or (org-property-get-allowed-values (point) key)
16198 (and (member value '("[ ]" "[-]" "[X]"))
16199 '("[ ]" "[X]"))))
16200 (heading (save-match-data (nth 4 (org-heading-components))))
16201 nval)
16202 (unless allowed
16203 (user-error "Allowed values for this property have not been defined"))
16204 (if previous (setq allowed (reverse allowed)))
16205 (if (member value allowed)
16206 (setq nval (car (cdr (member value allowed)))))
16207 (setq nval (or nval (car allowed)))
16208 (if (equal nval value)
16209 (user-error "Only one allowed value for this property"))
16210 (org-at-property-p)
16211 (replace-match (concat " :" key ": " nval) t t)
16212 (org-indent-line)
16213 (beginning-of-line 1)
16214 (skip-chars-forward " \t")
16215 (when (equal prop org-effort-property)
16216 (org-refresh-property
16217 '((effort . identity)
16218 (effort-minutes . org-duration-string-to-minutes))
16219 nval)
16220 (when (string= org-clock-current-task heading)
16221 (setq org-clock-effort nval)
16222 (org-clock-update-mode-line)))
16223 (run-hook-with-args 'org-property-changed-functions key nval)))
16225 (defun org-find-olp (path &optional this-buffer)
16226 "Return a marker pointing to the entry at outline path OLP.
16227 If anything goes wrong, throw an error.
16228 You can wrap this call to catch the error like this:
16230 (condition-case msg
16231 (org-mobile-locate-entry (match-string 4))
16232 (error (nth 1 msg)))
16234 The return value will then be either a string with the error message,
16235 or a marker if everything is OK.
16237 If THIS-BUFFER is set, the outline path does not contain a file,
16238 only headings."
16239 (let* ((file (if this-buffer buffer-file-name (pop path)))
16240 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16241 (level 1)
16242 (lmin 1)
16243 (lmax 1)
16244 limit re end found pos heading cnt flevel)
16245 (unless buffer (error "File not found :%s" file))
16246 (with-current-buffer buffer
16247 (save-excursion
16248 (save-restriction
16249 (widen)
16250 (setq limit (point-max))
16251 (goto-char (point-min))
16252 (while (setq heading (pop path))
16253 (setq re (format org-complex-heading-regexp-format
16254 (regexp-quote heading)))
16255 (setq cnt 0 pos (point))
16256 (while (re-search-forward re end t)
16257 (setq level (- (match-end 1) (match-beginning 1)))
16258 (if (and (>= level lmin) (<= level lmax))
16259 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16260 (when (= cnt 0) (error "Heading not found on level %d: %s"
16261 lmax heading))
16262 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16263 lmax heading))
16264 (goto-char found)
16265 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16266 (setq end (save-excursion (org-end-of-subtree t t))))
16267 (when (org-at-heading-p)
16268 (point-marker)))))))
16270 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16271 "Find node HEADING in BUFFER.
16272 Return a marker to the heading if it was found, or nil if not.
16273 If POS-ONLY is set, return just the position instead of a marker.
16275 The heading text must match exact, but it may have a TODO keyword,
16276 a priority cookie and tags in the standard locations."
16277 (with-current-buffer (or buffer (current-buffer))
16278 (save-excursion
16279 (save-restriction
16280 (widen)
16281 (goto-char (point-min))
16282 (let (case-fold-search)
16283 (if (re-search-forward
16284 (format org-complex-heading-regexp-format
16285 (regexp-quote heading)) nil t)
16286 (if pos-only
16287 (match-beginning 0)
16288 (move-marker (make-marker) (match-beginning 0)))))))))
16290 (defun org-find-exact-heading-in-directory (heading &optional dir)
16291 "Find Org node headline HEADING in all .org files in directory DIR.
16292 When the target headline is found, return a marker to this location."
16293 (let ((files (directory-files (or dir default-directory)
16294 t "\\`[^.#].*\\.org\\'"))
16295 file visiting m buffer)
16296 (catch 'found
16297 (while (setq file (pop files))
16298 (message "trying %s" file)
16299 (setq visiting (org-find-base-buffer-visiting file))
16300 (setq buffer (or visiting (find-file-noselect file)))
16301 (setq m (org-find-exact-headline-in-buffer
16302 heading buffer))
16303 (when (and (not m) (not visiting)) (kill-buffer buffer))
16304 (and m (throw 'found m))))))
16306 (defun org-find-entry-with-id (ident)
16307 "Locate the entry that contains the ID property with exact value IDENT.
16308 IDENT can be a string, a symbol or a number, this function will search for
16309 the string representation of it.
16310 Return the position where this entry starts, or nil if there is no such entry."
16311 (interactive "sID: ")
16312 (let ((id (cond
16313 ((stringp ident) ident)
16314 ((symbol-name ident) (symbol-name ident))
16315 ((numberp ident) (number-to-string ident))
16316 (t (error "IDENT %s must be a string, symbol or number" ident))))
16317 (case-fold-search nil))
16318 (save-excursion
16319 (save-restriction
16320 (widen)
16321 (goto-char (point-min))
16322 (when (re-search-forward
16323 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16324 nil t)
16325 (org-back-to-heading t)
16326 (point))))))
16328 ;;;; Timestamps
16330 (defvar org-last-changed-timestamp nil)
16331 (defvar org-last-inserted-timestamp nil
16332 "The last time stamp inserted with `org-insert-time-stamp'.")
16333 (defvar org-ts-what) ; dynamically scoped parameter
16335 (defun org-time-stamp (arg &optional inactive)
16336 "Prompt for a date/time and insert a time stamp.
16337 If the user specifies a time like HH:MM or if this command is
16338 called with at least one prefix argument, the time stamp contains
16339 the date and the time. Otherwise, only the date is be included.
16341 All parts of a date not specified by the user is filled in from
16342 the current date/time. So if you just press return without
16343 typing anything, the time stamp will represent the current
16344 date/time.
16346 If there is already a timestamp at the cursor, it will be
16347 modified.
16349 With two universal prefix arguments, insert an active timestamp
16350 with the current time without prompting the user.
16352 When called from lisp, the timestamp is inactive if INACTIVE is
16353 non-nil."
16354 (interactive "P")
16355 (let* ((ts nil)
16356 (default-time
16357 ;; Default time is either today, or, when entering a range,
16358 ;; the range start.
16359 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16360 (save-excursion
16361 (re-search-backward
16362 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16363 (- (point) 20) t)))
16364 (apply 'encode-time (org-parse-time-string (match-string 1)))
16365 (current-time)))
16366 (default-input (and ts (org-get-compact-tod ts)))
16367 (repeater (save-excursion
16368 (save-match-data
16369 (beginning-of-line)
16370 (when (re-search-forward
16371 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16372 (save-excursion (progn (end-of-line) (point))) t)
16373 (match-string 0)))))
16374 org-time-was-given org-end-time-was-given time)
16375 (cond
16376 ((and (org-at-timestamp-p t)
16377 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16378 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16379 (insert "--")
16380 (setq time (let ((this-command this-command))
16381 (org-read-date arg 'totime nil nil
16382 default-time default-input inactive)))
16383 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16384 ((org-at-timestamp-p t)
16385 (setq time (let ((this-command this-command))
16386 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16387 (when (org-at-timestamp-p t) ; just to get the match data
16388 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16389 (replace-match "")
16390 (setq org-last-changed-timestamp
16391 (org-insert-time-stamp
16392 time (or org-time-was-given arg)
16393 inactive nil nil (list org-end-time-was-given)))
16394 (when repeater (goto-char (1- (point))) (insert " " repeater)
16395 (setq org-last-changed-timestamp
16396 (concat (substring org-last-inserted-timestamp 0 -1)
16397 " " repeater ">"))))
16398 (message "Timestamp updated"))
16399 ((equal arg '(16))
16400 (org-insert-time-stamp (current-time) t inactive))
16402 (setq time (let ((this-command this-command))
16403 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16404 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16405 nil nil (list org-end-time-was-given))))))
16407 ;; FIXME: can we use this for something else, like computing time differences?
16408 (defun org-get-compact-tod (s)
16409 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16410 (let* ((t1 (match-string 1 s))
16411 (h1 (string-to-number (match-string 2 s)))
16412 (m1 (string-to-number (match-string 3 s)))
16413 (t2 (and (match-end 4) (match-string 5 s)))
16414 (h2 (and t2 (string-to-number (match-string 6 s))))
16415 (m2 (and t2 (string-to-number (match-string 7 s))))
16416 dh dm)
16417 (if (not t2)
16419 (setq dh (- h2 h1) dm (- m2 m1))
16420 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16421 (concat t1 "+" (number-to-string dh)
16422 (and (/= 0 dm) (format ":%02d" dm)))))))
16424 (defun org-time-stamp-inactive (&optional arg)
16425 "Insert an inactive time stamp.
16426 An inactive time stamp is enclosed in square brackets instead of angle
16427 brackets. It is inactive in the sense that it does not trigger agenda entries,
16428 does not link to the calendar and cannot be changed with the S-cursor keys.
16429 So these are more for recording a certain time/date."
16430 (interactive "P")
16431 (org-time-stamp arg 'inactive))
16433 (defvar org-date-ovl (make-overlay 1 1))
16434 (overlay-put org-date-ovl 'face 'org-date-selected)
16435 (org-detach-overlay org-date-ovl)
16437 (defvar org-ans1) ; dynamically scoped parameter
16438 (defvar org-ans2) ; dynamically scoped parameter
16440 (defvar org-plain-time-of-day-regexp) ; defined below
16442 (defvar org-overriding-default-time nil) ; dynamically scoped
16443 (defvar org-read-date-overlay nil)
16444 (defvar org-dcst nil) ; dynamically scoped
16445 (defvar org-read-date-history nil)
16446 (defvar org-read-date-final-answer nil)
16447 (defvar org-read-date-analyze-futurep nil)
16448 (defvar org-read-date-analyze-forced-year nil)
16449 (defvar org-read-date-inactive)
16451 (defvar org-read-date-minibuffer-local-map
16452 (let* ((org-replace-disputed-keys nil)
16453 (map (make-sparse-keymap)))
16454 (set-keymap-parent map minibuffer-local-map)
16455 (org-defkey map (kbd ".")
16456 (lambda () (interactive)
16457 ;; Are we at the beginning of the prompt?
16458 (if (looking-back "^[^:]+: ")
16459 (org-eval-in-calendar '(calendar-goto-today))
16460 (insert "."))))
16461 (org-defkey map (kbd "C-.")
16462 (lambda () (interactive)
16463 (org-eval-in-calendar '(calendar-goto-today))))
16464 (org-defkey map [(meta shift left)]
16465 (lambda () (interactive)
16466 (org-eval-in-calendar '(calendar-backward-month 1))))
16467 (org-defkey map [(meta shift right)]
16468 (lambda () (interactive)
16469 (org-eval-in-calendar '(calendar-forward-month 1))))
16470 (org-defkey map [(meta shift up)]
16471 (lambda () (interactive)
16472 (org-eval-in-calendar '(calendar-backward-year 1))))
16473 (org-defkey map [(meta shift down)]
16474 (lambda () (interactive)
16475 (org-eval-in-calendar '(calendar-forward-year 1))))
16476 (org-defkey map [?\e (shift left)]
16477 (lambda () (interactive)
16478 (org-eval-in-calendar '(calendar-backward-month 1))))
16479 (org-defkey map [?\e (shift right)]
16480 (lambda () (interactive)
16481 (org-eval-in-calendar '(calendar-forward-month 1))))
16482 (org-defkey map [?\e (shift up)]
16483 (lambda () (interactive)
16484 (org-eval-in-calendar '(calendar-backward-year 1))))
16485 (org-defkey map [?\e (shift down)]
16486 (lambda () (interactive)
16487 (org-eval-in-calendar '(calendar-forward-year 1))))
16488 (org-defkey map [(shift up)]
16489 (lambda () (interactive)
16490 (org-eval-in-calendar '(calendar-backward-week 1))))
16491 (org-defkey map [(shift down)]
16492 (lambda () (interactive)
16493 (org-eval-in-calendar '(calendar-forward-week 1))))
16494 (org-defkey map [(shift left)]
16495 (lambda () (interactive)
16496 (org-eval-in-calendar '(calendar-backward-day 1))))
16497 (org-defkey map [(shift right)]
16498 (lambda () (interactive)
16499 (org-eval-in-calendar '(calendar-forward-day 1))))
16500 (org-defkey map "!"
16501 (lambda () (interactive)
16502 (org-eval-in-calendar '(diary-view-entries))
16503 (message "")))
16504 (org-defkey map ">"
16505 (lambda () (interactive)
16506 (org-eval-in-calendar '(calendar-scroll-left 1))))
16507 (org-defkey map "<"
16508 (lambda () (interactive)
16509 (org-eval-in-calendar '(calendar-scroll-right 1))))
16510 (org-defkey map "\C-v"
16511 (lambda () (interactive)
16512 (org-eval-in-calendar
16513 '(calendar-scroll-left-three-months 1))))
16514 (org-defkey map "\M-v"
16515 (lambda () (interactive)
16516 (org-eval-in-calendar
16517 '(calendar-scroll-right-three-months 1))))
16518 map)
16519 "Keymap for minibuffer commands when using `org-read-date'.")
16521 (defvar org-def)
16522 (defvar org-defdecode)
16523 (defvar org-with-time)
16525 (defun org-read-date (&optional org-with-time to-time from-string prompt
16526 default-time default-input inactive)
16527 "Read a date, possibly a time, and make things smooth for the user.
16528 The prompt will suggest to enter an ISO date, but you can also enter anything
16529 which will at least partially be understood by `parse-time-string'.
16530 Unrecognized parts of the date will default to the current day, month, year,
16531 hour and minute. If this command is called to replace a timestamp at point,
16532 or to enter the second timestamp of a range, the default time is taken
16533 from the existing stamp. Furthermore, the command prefers the future,
16534 so if you are giving a date where the year is not given, and the day-month
16535 combination is already past in the current year, it will assume you
16536 mean next year. For details, see the manual. A few examples:
16538 3-2-5 --> 2003-02-05
16539 feb 15 --> currentyear-02-15
16540 2/15 --> currentyear-02-15
16541 sep 12 9 --> 2009-09-12
16542 12:45 --> today 12:45
16543 22 sept 0:34 --> currentyear-09-22 0:34
16544 12 --> currentyear-currentmonth-12
16545 Fri --> nearest Friday after today
16546 -Tue --> last Tuesday
16547 etc.
16549 Furthermore you can specify a relative date by giving, as the *first* thing
16550 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16551 change in days weeks, months, years.
16552 With a single plus or minus, the date is relative to today. With a double
16553 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16554 +4d --> four days from today
16555 +4 --> same as above
16556 +2w --> two weeks from today
16557 ++5 --> five days from default date
16559 The function understands only English month and weekday abbreviations.
16561 While prompting, a calendar is popped up - you can also select the
16562 date with the mouse (button 1). The calendar shows a period of three
16563 months. To scroll it to other months, use the keys `>' and `<'.
16564 If you don't like the calendar, turn it off with
16565 \(setq org-read-date-popup-calendar nil)
16567 With optional argument TO-TIME, the date will immediately be converted
16568 to an internal time.
16569 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16570 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16571 still enter a time, and this function will inform the calling routine
16572 about this change. The calling routine may then choose to change the
16573 format used to insert the time stamp into the buffer to include the time.
16574 With optional argument FROM-STRING, read from this string instead from
16575 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16576 the time/date that is used for everything that is not specified by the
16577 user."
16578 (require 'parse-time)
16579 (let* ((org-time-stamp-rounding-minutes
16580 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16581 (org-dcst org-display-custom-times)
16582 (ct (org-current-time))
16583 (org-def (or org-overriding-default-time default-time ct))
16584 (org-defdecode (decode-time org-def))
16585 (dummy (progn
16586 (when (< (nth 2 org-defdecode) org-extend-today-until)
16587 (setcar (nthcdr 2 org-defdecode) -1)
16588 (setcar (nthcdr 1 org-defdecode) 59)
16589 (setq org-def (apply 'encode-time org-defdecode)
16590 org-defdecode (decode-time org-def)))))
16591 (mouse-autoselect-window nil) ; Don't let the mouse jump
16592 (calendar-frame-setup nil)
16593 (calendar-setup nil)
16594 (calendar-move-hook nil)
16595 (calendar-view-diary-initially-flag nil)
16596 (calendar-view-holidays-initially-flag nil)
16597 (timestr (format-time-string
16598 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16599 (prompt (concat (if prompt (concat prompt " ") "")
16600 (format "Date+time [%s]: " timestr)))
16601 ans (org-ans0 "") org-ans1 org-ans2 final)
16603 (cond
16604 (from-string (setq ans from-string))
16605 (org-read-date-popup-calendar
16606 (save-excursion
16607 (save-window-excursion
16608 (calendar)
16609 (org-eval-in-calendar '(setq cursor-type nil) t)
16610 (unwind-protect
16611 (progn
16612 (calendar-forward-day (- (time-to-days org-def)
16613 (calendar-absolute-from-gregorian
16614 (calendar-current-date))))
16615 (org-eval-in-calendar nil t)
16616 (let* ((old-map (current-local-map))
16617 (map (copy-keymap calendar-mode-map))
16618 (minibuffer-local-map
16619 (copy-keymap org-read-date-minibuffer-local-map)))
16620 (org-defkey map (kbd "RET") 'org-calendar-select)
16621 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16622 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16623 (unwind-protect
16624 (progn
16625 (use-local-map map)
16626 (setq org-read-date-inactive inactive)
16627 (add-hook 'post-command-hook 'org-read-date-display)
16628 (setq org-ans0 (read-string prompt default-input
16629 'org-read-date-history nil))
16630 ;; org-ans0: from prompt
16631 ;; org-ans1: from mouse click
16632 ;; org-ans2: from calendar motion
16633 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16634 (remove-hook 'post-command-hook 'org-read-date-display)
16635 (use-local-map old-map)
16636 (when org-read-date-overlay
16637 (delete-overlay org-read-date-overlay)
16638 (setq org-read-date-overlay nil)))))
16639 (bury-buffer "*Calendar*")))))
16641 (t ; Naked prompt only
16642 (unwind-protect
16643 (setq ans (read-string prompt default-input
16644 'org-read-date-history timestr))
16645 (when org-read-date-overlay
16646 (delete-overlay org-read-date-overlay)
16647 (setq org-read-date-overlay nil)))))
16649 (setq final (org-read-date-analyze ans org-def org-defdecode))
16651 (when org-read-date-analyze-forced-year
16652 (message "Year was forced into %s"
16653 (if org-read-date-force-compatible-dates
16654 "compatible range (1970-2037)"
16655 "range representable on this machine"))
16656 (ding))
16658 ;; One round trip to get rid of 34th of August and stuff like that....
16659 (setq final (decode-time (apply 'encode-time final)))
16661 (setq org-read-date-final-answer ans)
16663 (if to-time
16664 (apply 'encode-time final)
16665 (if (and (boundp 'org-time-was-given) org-time-was-given)
16666 (format "%04d-%02d-%02d %02d:%02d"
16667 (nth 5 final) (nth 4 final) (nth 3 final)
16668 (nth 2 final) (nth 1 final))
16669 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16671 (defun org-read-date-display ()
16672 "Display the current date prompt interpretation in the minibuffer."
16673 (when org-read-date-display-live
16674 (when org-read-date-overlay
16675 (delete-overlay org-read-date-overlay))
16676 (when (minibufferp (current-buffer))
16677 (save-excursion
16678 (end-of-line 1)
16679 (while (not (equal (buffer-substring
16680 (max (point-min) (- (point) 4)) (point))
16681 " "))
16682 (insert " ")))
16683 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16684 " " (or org-ans1 org-ans2)))
16685 (org-end-time-was-given nil)
16686 (f (org-read-date-analyze ans org-def org-defdecode))
16687 (fmts (if org-dcst
16688 org-time-stamp-custom-formats
16689 org-time-stamp-formats))
16690 (fmt (if (or org-with-time
16691 (and (boundp 'org-time-was-given) org-time-was-given))
16692 (cdr fmts)
16693 (car fmts)))
16694 (txt (format-time-string fmt (apply 'encode-time f)))
16695 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16696 (txt (concat "=> " txt)))
16697 (when (and org-end-time-was-given
16698 (string-match org-plain-time-of-day-regexp txt))
16699 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16700 org-end-time-was-given
16701 (substring txt (match-end 0)))))
16702 (when org-read-date-analyze-futurep
16703 (setq txt (concat txt " (=>F)")))
16704 (setq org-read-date-overlay
16705 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16706 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16708 (defun org-read-date-analyze (ans org-def org-defdecode)
16709 "Analyze the combined answer of the date prompt."
16710 ;; FIXME: cleanup and comment
16711 (let ((nowdecode (decode-time (current-time)))
16712 delta deltan deltaw deltadef year month day
16713 hour minute second wday pm h2 m2 tl wday1
16714 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16715 (setq org-read-date-analyze-futurep nil
16716 org-read-date-analyze-forced-year nil)
16717 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16718 (setq ans "+0"))
16720 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16721 (setq ans (replace-match "" t t ans)
16722 deltan (car delta)
16723 deltaw (nth 1 delta)
16724 deltadef (nth 2 delta)))
16726 ;; Check if there is an iso week date in there. If yes, store the
16727 ;; info and postpone interpreting it until the rest of the parsing
16728 ;; is done.
16729 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16730 (setq iso-year (if (match-end 1)
16731 (org-small-year-to-year
16732 (string-to-number (match-string 1 ans))))
16733 iso-weekday (if (match-end 3)
16734 (string-to-number (match-string 3 ans)))
16735 iso-week (string-to-number (match-string 2 ans)))
16736 (setq ans (replace-match "" t t ans)))
16738 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16739 (when (string-match
16740 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16741 (setq year (if (match-end 2)
16742 (string-to-number (match-string 2 ans))
16743 (progn (setq kill-year t)
16744 (string-to-number (format-time-string "%Y"))))
16745 month (string-to-number (match-string 3 ans))
16746 day (string-to-number (match-string 4 ans)))
16747 (if (< year 100) (setq year (+ 2000 year)))
16748 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16749 t nil ans)))
16751 ;; Help matching dotted european dates
16752 (when (string-match
16753 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16754 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16755 (setq kill-year t)
16756 (string-to-number (format-time-string "%Y")))
16757 day (string-to-number (match-string 1 ans))
16758 month (string-to-number (match-string 2 ans))
16759 ans (replace-match (format "%04d-%02d-%02d" year month day)
16760 t nil ans)))
16762 ;; Help matching american dates, like 5/30 or 5/30/7
16763 (when (string-match
16764 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16765 (setq year (if (match-end 4)
16766 (string-to-number (match-string 4 ans))
16767 (progn (setq kill-year t)
16768 (string-to-number (format-time-string "%Y"))))
16769 month (string-to-number (match-string 1 ans))
16770 day (string-to-number (match-string 2 ans)))
16771 (if (< year 100) (setq year (+ 2000 year)))
16772 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16773 t nil ans)))
16774 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16775 ;; If there is a time with am/pm, and *no* time without it, we convert
16776 ;; so that matching will be successful.
16777 (loop for i from 1 to 2 do ; twice, for end time as well
16778 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16779 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16780 (setq hour (string-to-number (match-string 1 ans))
16781 minute (if (match-end 3)
16782 (string-to-number (match-string 3 ans))
16784 pm (equal ?p
16785 (string-to-char (downcase (match-string 4 ans)))))
16786 (if (and (= hour 12) (not pm))
16787 (setq hour 0)
16788 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16789 (setq ans (replace-match (format "%02d:%02d" hour minute)
16790 t t ans))))
16792 ;; Check if a time range is given as a duration
16793 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16794 (setq hour (string-to-number (match-string 1 ans))
16795 h2 (+ hour (string-to-number (match-string 3 ans)))
16796 minute (string-to-number (match-string 2 ans))
16797 m2 (+ minute (if (match-end 5) (string-to-number
16798 (match-string 5 ans))0)))
16799 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16800 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16801 t t ans)))
16803 ;; Check if there is a time range
16804 (when (boundp 'org-end-time-was-given)
16805 (setq org-time-was-given nil)
16806 (when (and (string-match org-plain-time-of-day-regexp ans)
16807 (match-end 8))
16808 (setq org-end-time-was-given (match-string 8 ans))
16809 (setq ans (concat (substring ans 0 (match-beginning 7))
16810 (substring ans (match-end 7))))))
16812 (setq tl (parse-time-string ans)
16813 day (or (nth 3 tl) (nth 3 org-defdecode))
16814 month (or (nth 4 tl)
16815 (if (and org-read-date-prefer-future
16816 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16817 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16818 (nth 4 org-defdecode)))
16819 year (or (and (not kill-year) (nth 5 tl))
16820 (if (and org-read-date-prefer-future
16821 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16822 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16823 (nth 5 org-defdecode)))
16824 hour (or (nth 2 tl) (nth 2 org-defdecode))
16825 minute (or (nth 1 tl) (nth 1 org-defdecode))
16826 second (or (nth 0 tl) 0)
16827 wday (nth 6 tl))
16829 (when (and (eq org-read-date-prefer-future 'time)
16830 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16831 (equal day (nth 3 nowdecode))
16832 (equal month (nth 4 nowdecode))
16833 (equal year (nth 5 nowdecode))
16834 (nth 2 tl)
16835 (or (< (nth 2 tl) (nth 2 nowdecode))
16836 (and (= (nth 2 tl) (nth 2 nowdecode))
16837 (nth 1 tl)
16838 (< (nth 1 tl) (nth 1 nowdecode)))))
16839 (setq day (1+ day)
16840 futurep t))
16842 ;; Special date definitions below
16843 (cond
16844 (iso-week
16845 ;; There was an iso week
16846 (require 'cal-iso)
16847 (setq futurep nil)
16848 (setq year (or iso-year year)
16849 day (or iso-weekday wday 1)
16850 wday nil ; to make sure that the trigger below does not match
16851 iso-date (calendar-gregorian-from-absolute
16852 (calendar-absolute-from-iso
16853 (list iso-week day year))))
16854 ; FIXME: Should we also push ISO weeks into the future?
16855 ; (when (and org-read-date-prefer-future
16856 ; (not iso-year)
16857 ; (< (calendar-absolute-from-gregorian iso-date)
16858 ; (time-to-days (current-time))))
16859 ; (setq year (1+ year)
16860 ; iso-date (calendar-gregorian-from-absolute
16861 ; (calendar-absolute-from-iso
16862 ; (list iso-week day year)))))
16863 (setq month (car iso-date)
16864 year (nth 2 iso-date)
16865 day (nth 1 iso-date)))
16866 (deltan
16867 (setq futurep nil)
16868 (unless deltadef
16869 (let ((now (decode-time (current-time))))
16870 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16871 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16872 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16873 ((equal deltaw "m") (setq month (+ month deltan)))
16874 ((equal deltaw "y") (setq year (+ year deltan)))))
16875 ((and wday (not (nth 3 tl)))
16876 ;; Weekday was given, but no day, so pick that day in the week
16877 ;; on or after the derived date.
16878 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16879 (unless (equal wday wday1)
16880 (setq day (+ day (% (- wday wday1 -7) 7))))))
16881 (if (and (boundp 'org-time-was-given)
16882 (nth 2 tl))
16883 (setq org-time-was-given t))
16884 (if (< year 100) (setq year (+ 2000 year)))
16885 ;; Check of the date is representable
16886 (if org-read-date-force-compatible-dates
16887 (progn
16888 (if (< year 1970)
16889 (setq year 1970 org-read-date-analyze-forced-year t))
16890 (if (> year 2037)
16891 (setq year 2037 org-read-date-analyze-forced-year t)))
16892 (condition-case nil
16893 (ignore (encode-time second minute hour day month year))
16894 (error
16895 (setq year (nth 5 org-defdecode))
16896 (setq org-read-date-analyze-forced-year t))))
16897 (setq org-read-date-analyze-futurep futurep)
16898 (list second minute hour day month year)))
16900 (defvar parse-time-weekdays)
16901 (defun org-read-date-get-relative (s today default)
16902 "Check string S for special relative date string.
16903 TODAY and DEFAULT are internal times, for today and for a default.
16904 Return shift list (N what def-flag)
16905 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16906 N is the number of WHATs to shift.
16907 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16908 the DEFAULT date rather than TODAY."
16909 (require 'parse-time)
16910 (when (and
16911 (string-match
16912 (concat
16913 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16914 "\\([0-9]+\\)?"
16915 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16916 "\\([ \t]\\|$\\)") s)
16917 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16918 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16919 (string-to-char (substring (match-string 1 s) -1))
16920 ?+))
16921 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16922 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16923 (what (if (match-end 3) (match-string 3 s) "d"))
16924 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16925 (date (if rel default today))
16926 (wday (nth 6 (decode-time date)))
16927 delta)
16928 (if wday1
16929 (progn
16930 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16931 (if (= delta 0) (setq delta 7))
16932 (if (= dir ?-)
16933 (progn
16934 (setq delta (- delta 7))
16935 (if (= delta 0) (setq delta -7))))
16936 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16937 (list delta "d" rel))
16938 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16940 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16941 "Turn a user-specified date into the internal representation.
16942 The internal representation needed by the calendar is (month day year).
16943 This is a wrapper to handle the brain-dead convention in calendar that
16944 user function argument order change dependent on argument order."
16945 (if (boundp 'calendar-date-style)
16946 (cond
16947 ((eq calendar-date-style 'american)
16948 (list arg1 arg2 arg3))
16949 ((eq calendar-date-style 'european)
16950 (list arg2 arg1 arg3))
16951 ((eq calendar-date-style 'iso)
16952 (list arg2 arg3 arg1)))
16953 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16954 (if (org-bound-and-true-p european-calendar-style)
16955 (list arg2 arg1 arg3)
16956 (list arg1 arg2 arg3)))))
16958 (defun org-eval-in-calendar (form &optional keepdate)
16959 "Eval FORM in the calendar window and return to current window.
16960 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16961 otherwise stick to the current value of `org-ans2'."
16962 (let ((sf (selected-frame))
16963 (sw (selected-window)))
16964 (select-window (get-buffer-window "*Calendar*" t))
16965 (eval form)
16966 (when (and (not keepdate) (calendar-cursor-to-date))
16967 (let* ((date (calendar-cursor-to-date))
16968 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16969 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16970 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16971 (select-window sw)
16972 (org-select-frame-set-input-focus sf)))
16974 (defun org-calendar-select ()
16975 "Return to `org-read-date' with the date currently selected.
16976 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16977 (interactive)
16978 (when (calendar-cursor-to-date)
16979 (let* ((date (calendar-cursor-to-date))
16980 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16981 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16982 (if (active-minibuffer-window) (exit-minibuffer))))
16984 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16985 "Insert a date stamp for the date given by the internal TIME.
16986 WITH-HM means use the stamp format that includes the time of the day.
16987 INACTIVE means use square brackets instead of angular ones, so that the
16988 stamp will not contribute to the agenda.
16989 PRE and POST are optional strings to be inserted before and after the
16990 stamp.
16991 The command returns the inserted time stamp."
16992 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16993 stamp)
16994 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16995 (insert-before-markers (or pre ""))
16996 (when (listp extra)
16997 (setq extra (car extra))
16998 (if (and (stringp extra)
16999 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17000 (setq extra (format "-%02d:%02d"
17001 (string-to-number (match-string 1 extra))
17002 (string-to-number (match-string 2 extra))))
17003 (setq extra nil)))
17004 (when extra
17005 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17006 (insert-before-markers (setq stamp (format-time-string fmt time)))
17007 (insert-before-markers (or post ""))
17008 (setq org-last-inserted-timestamp stamp)))
17010 (defun org-toggle-time-stamp-overlays ()
17011 "Toggle the use of custom time stamp formats."
17012 (interactive)
17013 (setq org-display-custom-times (not org-display-custom-times))
17014 (unless org-display-custom-times
17015 (let ((p (point-min)) (bmp (buffer-modified-p)))
17016 (while (setq p (next-single-property-change p 'display))
17017 (if (and (get-text-property p 'display)
17018 (eq (get-text-property p 'face) 'org-date))
17019 (remove-text-properties
17020 p (setq p (next-single-property-change p 'display))
17021 '(display t))))
17022 (set-buffer-modified-p bmp)))
17023 (if (featurep 'xemacs)
17024 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17025 (org-restart-font-lock)
17026 (setq org-table-may-need-update t)
17027 (if org-display-custom-times
17028 (message "Time stamps are overlaid with custom format")
17029 (message "Time stamp overlays removed")))
17031 (defun org-display-custom-time (beg end)
17032 "Overlay modified time stamp format over timestamp between BEG and END."
17033 (let* ((ts (buffer-substring beg end))
17034 t1 w1 with-hm tf time str w2 (off 0))
17035 (save-match-data
17036 (setq t1 (org-parse-time-string ts t))
17037 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17038 (setq off (- (match-end 0) (match-beginning 0)))))
17039 (setq end (- end off))
17040 (setq w1 (- end beg)
17041 with-hm (and (nth 1 t1) (nth 2 t1))
17042 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17043 time (org-fix-decoded-time t1)
17044 str (org-add-props
17045 (format-time-string
17046 (substring tf 1 -1) (apply 'encode-time time))
17047 nil 'mouse-face 'highlight)
17048 w2 (length str))
17049 (if (not (= w2 w1))
17050 (add-text-properties (1+ beg) (+ 2 beg)
17051 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17052 (if (featurep 'xemacs)
17053 (progn
17054 (put-text-property beg end 'invisible t)
17055 (put-text-property beg end 'end-glyph (make-glyph str)))
17056 (put-text-property beg end 'display str))))
17058 (defun org-translate-time (string)
17059 "Translate all timestamps in STRING to custom format.
17060 But do this only if the variable `org-display-custom-times' is set."
17061 (when org-display-custom-times
17062 (save-match-data
17063 (let* ((start 0)
17064 (re org-ts-regexp-both)
17065 t1 with-hm inactive tf time str beg end)
17066 (while (setq start (string-match re string start))
17067 (setq beg (match-beginning 0)
17068 end (match-end 0)
17069 t1 (save-match-data
17070 (org-parse-time-string (substring string beg end) t))
17071 with-hm (and (nth 1 t1) (nth 2 t1))
17072 inactive (equal (substring string beg (1+ beg)) "[")
17073 tf (funcall (if with-hm 'cdr 'car)
17074 org-time-stamp-custom-formats)
17075 time (org-fix-decoded-time t1)
17076 str (format-time-string
17077 (concat
17078 (if inactive "[" "<") (substring tf 1 -1)
17079 (if inactive "]" ">"))
17080 (apply 'encode-time time))
17081 string (replace-match str t t string)
17082 start (+ start (length str)))))))
17083 string)
17085 (defun org-fix-decoded-time (time)
17086 "Set 0 instead of nil for the first 6 elements of time.
17087 Don't touch the rest."
17088 (let ((n 0))
17089 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17091 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17093 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17094 "Difference between TIMESTAMP-STRING and now in days.
17095 If SECONDS is non-nil, return the difference in seconds."
17096 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17097 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17098 (funcall fdiff (current-time)))))
17100 (defun org-deadline-close (timestamp-string &optional ndays)
17101 "Is the time in TIMESTAMP-STRING close to the current date?"
17102 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17103 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17104 (not (org-entry-is-done-p))))
17106 (defun org-get-wdays (ts &optional delay zero-delay)
17107 "Get the deadline lead time appropriate for timestring TS.
17108 When DELAY is non-nil, get the delay time for scheduled items
17109 instead of the deadline lead time. When ZERO-DELAY is non-nil
17110 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17111 don't try to find the delay cookie in the scheduled timestamp."
17112 (let ((tv (if delay org-scheduled-delay-days
17113 org-deadline-warning-days)))
17114 (cond
17115 ((or (and delay (< tv 0))
17116 (and delay zero-delay (<= tv 0))
17117 (and (not delay) (<= tv 0)))
17118 ;; Enforce this value no matter what
17119 (- tv))
17120 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17121 ;; lead time is specified.
17122 (floor (* (string-to-number (match-string 1 ts))
17123 (cdr (assoc (match-string 2 ts)
17124 '(("d" . 1) ("w" . 7)
17125 ("m" . 30.4) ("y" . 365.25)
17126 ("h" . 0.041667)))))))
17127 ;; go for the default.
17128 (t tv))))
17130 (defun org-calendar-select-mouse (ev)
17131 "Return to `org-read-date' with the date currently selected.
17132 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17133 (interactive "e")
17134 (mouse-set-point ev)
17135 (when (calendar-cursor-to-date)
17136 (let* ((date (calendar-cursor-to-date))
17137 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17138 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17139 (if (active-minibuffer-window) (exit-minibuffer))))
17141 (defun org-check-deadlines (ndays)
17142 "Check if there are any deadlines due or past due.
17143 A deadline is considered due if it happens within `org-deadline-warning-days'
17144 days from today's date. If the deadline appears in an entry marked DONE,
17145 it is not shown. The prefix arg NDAYS can be used to test that many
17146 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17147 (interactive "P")
17148 (let* ((org-warn-days
17149 (cond
17150 ((equal ndays '(4)) 100000)
17151 (ndays (prefix-numeric-value ndays))
17152 (t (abs org-deadline-warning-days))))
17153 (case-fold-search nil)
17154 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17155 (callback
17156 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17158 (message "%d deadlines past-due or due within %d days"
17159 (org-occur regexp nil callback)
17160 org-warn-days)))
17162 (defsubst org-re-timestamp (type)
17163 "Return a regexp for timestamp TYPE.
17164 Allowed values for TYPE are:
17166 all: all timestamps
17167 active: only active timestamps (<...>)
17168 inactive: only inactive timestamps ([...])
17169 scheduled: only scheduled timestamps
17170 deadline: only deadline timestamps
17171 closed: only closed time-stamps
17173 When TYPE is nil, fall back on returning a regexp that matches
17174 both scheduled and deadline timestamps."
17175 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17176 ((eq type 'active) org-ts-regexp)
17177 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17178 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17179 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17180 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17181 ((eq type 'scheduled-or-deadline)
17182 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17184 (defun org-check-before-date (date)
17185 "Check if there are deadlines or scheduled entries before DATE."
17186 (interactive (list (org-read-date)))
17187 (let ((case-fold-search nil)
17188 (regexp (org-re-timestamp org-ts-type))
17189 (callback
17190 (lambda () (time-less-p
17191 (org-time-string-to-time (match-string 1))
17192 (org-time-string-to-time date)))))
17193 (message "%d entries before %s"
17194 (org-occur regexp nil callback) date)))
17196 (defun org-check-after-date (date)
17197 "Check if there are deadlines or scheduled entries after DATE."
17198 (interactive (list (org-read-date)))
17199 (let ((case-fold-search nil)
17200 (regexp (org-re-timestamp org-ts-type))
17201 (callback
17202 (lambda () (not
17203 (time-less-p
17204 (org-time-string-to-time (match-string 1))
17205 (org-time-string-to-time date))))))
17206 (message "%d entries after %s"
17207 (org-occur regexp nil callback) date)))
17209 (defun org-check-dates-range (start-date end-date)
17210 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17211 (interactive (list (org-read-date nil nil nil "Range starts")
17212 (org-read-date nil nil nil "Range end")))
17213 (let ((case-fold-search nil)
17214 (regexp (org-re-timestamp org-ts-type))
17215 (callback
17216 (lambda ()
17217 (let ((match (match-string 1)))
17218 (and
17219 (not (time-less-p
17220 (org-time-string-to-time match)
17221 (org-time-string-to-time start-date)))
17222 (time-less-p
17223 (org-time-string-to-time match)
17224 (org-time-string-to-time end-date)))))))
17225 (message "%d entries between %s and %s"
17226 (org-occur regexp nil callback) start-date end-date)))
17228 (defun org-evaluate-time-range (&optional to-buffer)
17229 "Evaluate a time range by computing the difference between start and end.
17230 Normally the result is just printed in the echo area, but with prefix arg
17231 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17232 If the time range is actually in a table, the result is inserted into the
17233 next column.
17234 For time difference computation, a year is assumed to be exactly 365
17235 days in order to avoid rounding problems."
17236 (interactive "P")
17238 (org-clock-update-time-maybe)
17239 (save-excursion
17240 (unless (org-at-date-range-p t)
17241 (goto-char (point-at-bol))
17242 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17243 (if (not (org-at-date-range-p t))
17244 (user-error "Not at a time-stamp range, and none found in current line")))
17245 (let* ((ts1 (match-string 1))
17246 (ts2 (match-string 2))
17247 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17248 (match-end (match-end 0))
17249 (time1 (org-time-string-to-time ts1))
17250 (time2 (org-time-string-to-time ts2))
17251 (t1 (org-float-time time1))
17252 (t2 (org-float-time time2))
17253 (diff (abs (- t2 t1)))
17254 (negative (< (- t2 t1) 0))
17255 ;; (ys (floor (* 365 24 60 60)))
17256 (ds (* 24 60 60))
17257 (hs (* 60 60))
17258 (fy "%dy %dd %02d:%02d")
17259 (fy1 "%dy %dd")
17260 (fd "%dd %02d:%02d")
17261 (fd1 "%dd")
17262 (fh "%02d:%02d")
17263 y d h m align)
17264 (if havetime
17265 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17267 d (floor (/ diff ds)) diff (mod diff ds)
17268 h (floor (/ diff hs)) diff (mod diff hs)
17269 m (floor (/ diff 60)))
17270 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17272 d (floor (+ (/ diff ds) 0.5))
17273 h 0 m 0))
17274 (if (not to-buffer)
17275 (message "%s" (org-make-tdiff-string y d h m))
17276 (if (org-at-table-p)
17277 (progn
17278 (goto-char match-end)
17279 (setq align t)
17280 (and (looking-at " *|") (goto-char (match-end 0))))
17281 (goto-char match-end))
17282 (if (looking-at
17283 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17284 (replace-match ""))
17285 (if negative (insert " -"))
17286 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17287 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17288 (insert " " (format fh h m))))
17289 (if align (org-table-align))
17290 (message "Time difference inserted")))))
17292 (defun org-make-tdiff-string (y d h m)
17293 (let ((fmt "")
17294 (l nil))
17295 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17296 l (push y l)))
17297 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17298 l (push d l)))
17299 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17300 l (push h l)))
17301 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17302 l (push m l)))
17303 (apply 'format fmt (nreverse l))))
17305 (defun org-time-string-to-time (s &optional buffer pos)
17306 "Convert a timestamp string into internal time."
17307 (condition-case errdata
17308 (apply 'encode-time (org-parse-time-string s))
17309 (error (error "Bad timestamp `%s'%s\nError was: %s"
17310 s (if (not (and buffer pos))
17312 (format " at %d in buffer `%s'" pos buffer))
17313 (cdr errdata)))))
17315 (defun org-time-string-to-seconds (s)
17316 "Convert a timestamp string to a number of seconds."
17317 (org-float-time (org-time-string-to-time s)))
17319 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17320 "Convert a time stamp to an absolute day number.
17321 If there is a specifier for a cyclic time stamp, get the closest
17322 date to DAYNR.
17323 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17324 The variable `date' is bound by the calendar when this is called."
17325 (cond
17326 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17327 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17328 daynr
17329 (+ daynr 1000)))
17330 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17331 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17332 (time-to-days (current-time))) (match-string 0 s)
17333 prefer show-all))
17334 (t (time-to-days
17335 (condition-case errdata
17336 (apply 'encode-time (org-parse-time-string s))
17337 (error (error "Bad timestamp `%s'%s\nError was: %s"
17338 s (if (not (and buffer pos))
17340 (format " at %d in buffer `%s'" pos buffer))
17341 (cdr errdata))))))))
17343 (defun org-days-to-iso-week (days)
17344 "Return the iso week number."
17345 (require 'cal-iso)
17346 (car (calendar-iso-from-absolute days)))
17348 (defun org-small-year-to-year (year)
17349 "Convert 2-digit years into 4-digit years.
17350 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17351 The year 2000 cannot be abbreviated. Any year larger than 99
17352 is returned unchanged."
17353 (if (< year 38)
17354 (setq year (+ 2000 year))
17355 (if (< year 100)
17356 (setq year (+ 1900 year))))
17357 year)
17359 (defun org-time-from-absolute (d)
17360 "Return the time corresponding to date D.
17361 D may be an absolute day number, or a calendar-type list (month day year)."
17362 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17363 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17365 (defun org-calendar-holiday ()
17366 "List of holidays, for Diary display in Org-mode."
17367 (require 'holidays)
17368 (let ((hl (funcall
17369 (if (fboundp 'calendar-check-holidays)
17370 'calendar-check-holidays 'check-calendar-holidays) date)))
17371 (if hl (mapconcat 'identity hl "; "))))
17373 (defun org-diary-sexp-entry (sexp entry date)
17374 "Process a SEXP diary ENTRY for DATE."
17375 (require 'diary-lib)
17376 (let ((result (if calendar-debug-sexp
17377 (let ((stack-trace-on-error t))
17378 (eval (car (read-from-string sexp))))
17379 (condition-case nil
17380 (eval (car (read-from-string sexp)))
17381 (error
17382 (beep)
17383 (message "Bad sexp at line %d in %s: %s"
17384 (org-current-line)
17385 (buffer-file-name) sexp)
17386 (sleep-for 2))))))
17387 (cond ((stringp result) (split-string result "; "))
17388 ((and (consp result)
17389 (not (consp (cdr result)))
17390 (stringp (cdr result))) (cdr result))
17391 ((and (consp result)
17392 (stringp (car result))) result)
17393 (result entry))))
17395 (defun org-diary-to-ical-string (frombuf)
17396 "Get iCalendar entries from diary entries in buffer FROMBUF.
17397 This uses the icalendar.el library."
17398 (let* ((tmpdir (if (featurep 'xemacs)
17399 (temp-directory)
17400 temporary-file-directory))
17401 (tmpfile (make-temp-name
17402 (expand-file-name "orgics" tmpdir)))
17403 buf rtn b e)
17404 (with-current-buffer frombuf
17405 (icalendar-export-region (point-min) (point-max) tmpfile)
17406 (setq buf (find-buffer-visiting tmpfile))
17407 (set-buffer buf)
17408 (goto-char (point-min))
17409 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17410 (setq b (match-beginning 0)))
17411 (goto-char (point-max))
17412 (if (re-search-backward "^END:VEVENT" nil t)
17413 (setq e (match-end 0)))
17414 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17415 (kill-buffer buf)
17416 (delete-file tmpfile)
17417 rtn))
17419 (defun org-closest-date (start current change prefer show-all)
17420 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17421 When PREFER is `past', return a date that is either CURRENT or past.
17422 When PREFER is `future', return a date that is either CURRENT or future.
17423 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17424 ;; Make the proper lists from the dates
17425 (catch 'exit
17426 (let ((a1 '(("h" . hour)
17427 ("d" . day)
17428 ("w" . week)
17429 ("m" . month)
17430 ("y" . year)))
17431 (shour (nth 2 (org-parse-time-string start)))
17432 dn dw sday cday n1 n2 n0
17433 d m y y1 y2 date1 date2 nmonths nm ny m2)
17435 (setq start (org-date-to-gregorian start)
17436 current (org-date-to-gregorian
17437 (if show-all
17438 current
17439 (time-to-days (current-time))))
17440 sday (calendar-absolute-from-gregorian start)
17441 cday (calendar-absolute-from-gregorian current))
17443 (if (<= cday sday) (throw 'exit sday))
17445 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17446 (setq dn (string-to-number (match-string 1 change))
17447 dw (cdr (assoc (match-string 2 change) a1)))
17448 (user-error "Invalid change specifier: %s" change))
17449 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17450 (cond
17451 ((eq dw 'hour)
17452 (let ((missing-hours
17453 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17454 dn)))
17455 (setq n1 (if (zerop missing-hours) cday
17456 (- cday (1+ (floor (/ missing-hours 24)))))
17457 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17458 ((eq dw 'day)
17459 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17460 n2 (+ n1 dn)))
17461 ((eq dw 'year)
17462 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17463 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17464 (setq date1 (list m d y1)
17465 n1 (calendar-absolute-from-gregorian date1)
17466 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17467 n2 (calendar-absolute-from-gregorian date2)))
17468 ((eq dw 'month)
17469 ;; approx number of month between the two dates
17470 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17471 ;; How often does dn fit in there?
17472 (setq d (nth 1 start) m (car start) y (nth 2 start)
17473 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17474 m (+ m nm)
17475 ny (floor (/ m 12))
17476 y (+ y ny)
17477 m (- m (* ny 12)))
17478 (while (> m 12) (setq m (- m 12) y (1+ y)))
17479 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17480 (setq m2 (+ m dn) y2 y)
17481 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17482 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17483 (while (<= n2 cday)
17484 (setq n1 n2 m m2 y y2)
17485 (setq m2 (+ m dn) y2 y)
17486 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17487 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17488 ;; Make sure n1 is the earlier date
17489 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17490 (if show-all
17491 (cond
17492 ((eq prefer 'past) (if (= cday n2) n2 n1))
17493 ((eq prefer 'future) (if (= cday n1) n1 n2))
17494 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17495 (cond
17496 ((eq prefer 'past) (if (= cday n2) n2 n1))
17497 ((eq prefer 'future) (if (= cday n1) n1 n2))
17498 (t (if (= cday n1) n1 n2)))))))
17500 (defun org-date-to-gregorian (date)
17501 "Turn any specification of DATE into a Gregorian date for the calendar."
17502 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17503 ((and (listp date) (= (length date) 3)) date)
17504 ((stringp date)
17505 (setq date (org-parse-time-string date))
17506 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17507 ((listp date)
17508 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17510 (defun org-parse-time-string (s &optional nodefault)
17511 "Parse the standard Org-mode time string.
17512 This should be a lot faster than the normal `parse-time-string'.
17513 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17514 hour and minute fields will be nil if not given."
17515 (cond ((string-match org-ts-regexp0 s)
17516 (list 0
17517 (if (or (match-beginning 8) (not nodefault))
17518 (string-to-number (or (match-string 8 s) "0")))
17519 (if (or (match-beginning 7) (not nodefault))
17520 (string-to-number (or (match-string 7 s) "0")))
17521 (string-to-number (match-string 4 s))
17522 (string-to-number (match-string 3 s))
17523 (string-to-number (match-string 2 s))
17524 nil nil nil))
17525 ((string-match "^<[^>]+>$" s)
17526 (decode-time (seconds-to-time (org-matcher-time s))))
17527 (t (error "Not a standard Org-mode time string: %s" s))))
17529 (defun org-timestamp-up (&optional arg)
17530 "Increase 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-down (&optional arg)
17538 "Decrease the date item at the cursor by one.
17539 If the cursor is on the year, change the year. If it is on the month,
17540 the day or the time, change that.
17541 With prefix ARG, change by that many units."
17542 (interactive "p")
17543 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17545 (defun org-timestamp-up-day (&optional arg)
17546 "Increase the date in the time stamp by one day.
17547 With prefix ARG, change that many days."
17548 (interactive "p")
17549 (if (and (not (org-at-timestamp-p t))
17550 (org-at-heading-p))
17551 (org-todo 'up)
17552 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17554 (defun org-timestamp-down-day (&optional arg)
17555 "Decrease the date in the time stamp by one day.
17556 With prefix ARG, change that many days."
17557 (interactive "p")
17558 (if (and (not (org-at-timestamp-p t))
17559 (org-at-heading-p))
17560 (org-todo 'down)
17561 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17563 (defun org-at-timestamp-p (&optional inactive-ok)
17564 "Determine if the cursor is in or at a timestamp."
17565 (interactive)
17566 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17567 (pos (point))
17568 (ans (or (looking-at tsr)
17569 (save-excursion
17570 (skip-chars-backward "^[<\n\r\t")
17571 (if (> (point) (point-min)) (backward-char 1))
17572 (and (looking-at tsr)
17573 (> (- (match-end 0) pos) -1))))))
17574 (and ans
17575 (boundp 'org-ts-what)
17576 (setq org-ts-what
17577 (cond
17578 ((= pos (match-beginning 0)) 'bracket)
17579 ;; Point is considered to be "on the bracket" whether
17580 ;; it's really on it or right after it.
17581 ((= pos (1- (match-end 0))) 'bracket)
17582 ((= pos (match-end 0)) 'after)
17583 ((org-pos-in-match-range pos 2) 'year)
17584 ((org-pos-in-match-range pos 3) 'month)
17585 ((org-pos-in-match-range pos 7) 'hour)
17586 ((org-pos-in-match-range pos 8) 'minute)
17587 ((or (org-pos-in-match-range pos 4)
17588 (org-pos-in-match-range pos 5)) 'day)
17589 ((and (> pos (or (match-end 8) (match-end 5)))
17590 (< pos (match-end 0)))
17591 (- pos (or (match-end 8) (match-end 5))))
17592 (t 'day))))
17593 ans))
17595 (defun org-toggle-timestamp-type ()
17596 "Toggle the type (<active> or [inactive]) of a time stamp."
17597 (interactive)
17598 (when (org-at-timestamp-p t)
17599 (let ((beg (match-beginning 0)) (end (match-end 0))
17600 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17601 (save-excursion
17602 (goto-char beg)
17603 (while (re-search-forward "[][<>]" end t)
17604 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17605 t t)))
17606 (message "Timestamp is now %sactive"
17607 (if (equal (char-after beg) ?<) "" "in")))))
17609 (defun org-at-clock-log-p nil
17610 "Is the cursor on the clock log line?"
17611 (save-excursion
17612 (move-beginning-of-line 1)
17613 (looking-at org-clock-line-re)))
17615 (defvar org-clock-history) ; defined in org-clock.el
17616 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17617 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17618 "Change the date in the time stamp at point.
17619 The date will be changed by N times WHAT. WHAT can be `day', `month',
17620 `year', `minute', `second'. If WHAT is not given, the cursor position
17621 in the timestamp determines what will be changed.
17622 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17623 (let ((origin (point)) origin-cat
17624 with-hm inactive
17625 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17626 org-ts-what
17627 extra rem
17628 ts time time0 fixnext clrgx)
17629 (if (not (org-at-timestamp-p t))
17630 (user-error "Not at a timestamp"))
17631 (if (and (not what) (eq org-ts-what 'bracket))
17632 (org-toggle-timestamp-type)
17633 ;; Point isn't on brackets. Remember the part of the time-stamp
17634 ;; the point was in. Indeed, size of time-stamps may change,
17635 ;; but point must be kept in the same category nonetheless.
17636 (setq origin-cat org-ts-what)
17637 (if (and (not what) (not (eq org-ts-what 'day))
17638 org-display-custom-times
17639 (get-text-property (point) 'display)
17640 (not (get-text-property (1- (point)) 'display)))
17641 (setq org-ts-what 'day))
17642 (setq org-ts-what (or what org-ts-what)
17643 inactive (= (char-after (match-beginning 0)) ?\[)
17644 ts (match-string 0))
17645 (replace-match "")
17646 (when (string-match
17647 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17649 (setq extra (match-string 1 ts))
17650 (if suppress-tmp-delay
17651 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17652 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17653 (setq with-hm t))
17654 (setq time0 (org-parse-time-string ts))
17655 (when (and updown
17656 (eq org-ts-what 'minute)
17657 (not current-prefix-arg))
17658 ;; This looks like s-up and s-down. Change by one rounding step.
17659 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17660 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17661 (setcar (cdr time0) (+ (nth 1 time0)
17662 (if (> n 0) (- rem) (- dm rem))))))
17663 (setq time
17664 (encode-time (or (car time0) 0)
17665 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17666 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17667 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17668 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17669 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17670 (nthcdr 6 time0)))
17671 (when (and (member org-ts-what '(hour minute))
17672 extra
17673 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17674 (setq extra (org-modify-ts-extra
17675 extra
17676 (if (eq org-ts-what 'hour) 2 5)
17677 n dm)))
17678 (when (integerp org-ts-what)
17679 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17680 (if (eq what 'calendar)
17681 (let ((cal-date (org-get-date-from-calendar)))
17682 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17683 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17684 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17685 (setcar time0 (or (car time0) 0))
17686 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17687 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17688 (setq time (apply 'encode-time time0))))
17689 ;; Insert the new time-stamp, and ensure point stays in the same
17690 ;; category as before (i.e. not after the last position in that
17691 ;; category).
17692 (let ((pos (point)))
17693 ;; Stay before inserted string. `save-excursion' is of no use.
17694 (setq org-last-changed-timestamp
17695 (org-insert-time-stamp time with-hm inactive nil nil extra))
17696 (goto-char pos))
17697 (save-match-data
17698 (looking-at org-ts-regexp3)
17699 (goto-char (cond
17700 ;; `day' category ends before `hour' if any, or at
17701 ;; the end of the day name.
17702 ((eq origin-cat 'day)
17703 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17704 ((eq origin-cat 'hour) (min (match-end 7) origin))
17705 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17706 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17707 ;; `year' and `month' have both fixed size: point
17708 ;; couldn't have moved into another part.
17709 (t origin))))
17710 ;; Update clock if on a CLOCK line.
17711 (org-clock-update-time-maybe)
17712 ;; Maybe adjust the closest clock in `org-clock-history'
17713 (when org-clock-adjust-closest
17714 (if (not (and (org-at-clock-log-p)
17715 (< 1 (length (delq nil (mapcar 'marker-position
17716 org-clock-history))))))
17717 (message "No clock to adjust")
17718 (cond ((save-excursion ; fix previous clock?
17719 (re-search-backward org-ts-regexp0 nil t)
17720 (org-looking-back (concat org-clock-string " \\[")))
17721 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17722 ((save-excursion ; fix next clock?
17723 (re-search-backward org-ts-regexp0 nil t)
17724 (looking-at (concat org-ts-regexp0 "\\] =>")))
17725 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17726 (save-window-excursion
17727 ;; Find closest clock to point, adjust the previous/next one in history
17728 (let* ((p (save-excursion (org-back-to-heading t)))
17729 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17730 (clfixnth
17731 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17732 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17733 (if (not clfixpos)
17734 (message "No clock to adjust")
17735 (save-excursion
17736 (org-goto-marker-or-bmk clfixpos)
17737 (org-show-subtree)
17738 (when (re-search-forward clrgx nil t)
17739 (goto-char (match-beginning 1))
17740 (let (org-clock-adjust-closest)
17741 (org-timestamp-change n org-ts-what updown))
17742 (message "Clock adjusted in %s for heading: %s"
17743 (file-name-nondirectory (buffer-file-name))
17744 (org-get-heading t t)))))))))
17745 ;; Try to recenter the calendar window, if any.
17746 (if (and org-calendar-follow-timestamp-change
17747 (get-buffer-window "*Calendar*" t)
17748 (memq org-ts-what '(day month year)))
17749 (org-recenter-calendar (time-to-days time))))))
17751 (defun org-modify-ts-extra (s pos n dm)
17752 "Change the different parts of the lead-time and repeat fields in timestamp."
17753 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17754 ng h m new rem)
17755 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17756 (cond
17757 ((or (org-pos-in-match-range pos 2)
17758 (org-pos-in-match-range pos 3))
17759 (setq m (string-to-number (match-string 3 s))
17760 h (string-to-number (match-string 2 s)))
17761 (if (org-pos-in-match-range pos 2)
17762 (setq h (+ h n))
17763 (setq n (* dm (org-no-warnings (signum n))))
17764 (when (not (= 0 (setq rem (% m dm))))
17765 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17766 (setq m (+ m n)))
17767 (if (< m 0) (setq m (+ m 60) h (1- h)))
17768 (if (> m 59) (setq m (- m 60) h (1+ h)))
17769 (setq h (min 24 (max 0 h)))
17770 (setq ng 1 new (format "-%02d:%02d" h m)))
17771 ((org-pos-in-match-range pos 6)
17772 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17773 ((org-pos-in-match-range pos 5)
17774 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17776 ((org-pos-in-match-range pos 9)
17777 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17778 ((org-pos-in-match-range pos 8)
17779 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17781 (when ng
17782 (setq s (concat
17783 (substring s 0 (match-beginning ng))
17785 (substring s (match-end ng))))))
17788 (defun org-recenter-calendar (date)
17789 "If the calendar is visible, recenter it to DATE."
17790 (let ((cwin (get-buffer-window "*Calendar*" t)))
17791 (when cwin
17792 (let ((calendar-move-hook nil))
17793 (with-selected-window cwin
17794 (calendar-goto-date (if (listp date) date
17795 (calendar-gregorian-from-absolute date))))))))
17797 (defun org-goto-calendar (&optional arg)
17798 "Go to the Emacs calendar at the current date.
17799 If there is a time stamp in the current line, go to that date.
17800 A prefix ARG can be used to force the current date."
17801 (interactive "P")
17802 (let ((tsr org-ts-regexp) diff
17803 (calendar-move-hook nil)
17804 (calendar-view-holidays-initially-flag nil)
17805 (calendar-view-diary-initially-flag nil))
17806 (if (or (org-at-timestamp-p)
17807 (save-excursion
17808 (beginning-of-line 1)
17809 (looking-at (concat ".*" tsr))))
17810 (let ((d1 (time-to-days (current-time)))
17811 (d2 (time-to-days
17812 (org-time-string-to-time (match-string 1)))))
17813 (setq diff (- d2 d1))))
17814 (calendar)
17815 (calendar-goto-today)
17816 (if (and diff (not arg)) (calendar-forward-day diff))))
17818 (defun org-get-date-from-calendar ()
17819 "Return a list (month day year) of date at point in calendar."
17820 (with-current-buffer "*Calendar*"
17821 (save-match-data
17822 (calendar-cursor-to-date))))
17824 (defun org-date-from-calendar ()
17825 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17826 If there is already a time stamp at the cursor position, update it."
17827 (interactive)
17828 (if (org-at-timestamp-p t)
17829 (org-timestamp-change 0 'calendar)
17830 (let ((cal-date (org-get-date-from-calendar)))
17831 (org-insert-time-stamp
17832 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17834 (defcustom org-effort-durations
17835 `(("h" . 60)
17836 ("d" . ,(* 60 8))
17837 ("w" . ,(* 60 8 5))
17838 ("m" . ,(* 60 8 5 4))
17839 ("y" . ,(* 60 8 5 40)))
17840 "Conversion factor to minutes for an effort modifier.
17842 Each entry has the form (MODIFIER . MINUTES).
17844 In an effort string, a number followed by MODIFIER is multiplied
17845 by the specified number of MINUTES to obtain an effort in
17846 minutes.
17848 For example, if the value of this variable is ((\"hours\" . 60)), then an
17849 effort string \"2hours\" is equivalent to 120 minutes."
17850 :group 'org-agenda
17851 :version "24.1"
17852 :type '(alist :key-type (string :tag "Modifier")
17853 :value-type (number :tag "Minutes")))
17855 (defun org-minutes-to-clocksum-string (m)
17856 "Format number of minutes as a clocksum string.
17857 The format is determined by `org-time-clocksum-format',
17858 `org-time-clocksum-use-fractional' and
17859 `org-time-clocksum-fractional-format' and
17860 `org-time-clocksum-use-effort-durations'."
17861 (let ((clocksum "")
17862 (m (round m)) ; Don't allow fractions of minutes
17863 h d w mo y fmt n)
17864 (setq h (if org-time-clocksum-use-effort-durations
17865 (cdr (assoc "h" org-effort-durations)) 60)
17866 d (if org-time-clocksum-use-effort-durations
17867 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17868 w (if org-time-clocksum-use-effort-durations
17869 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17870 mo (if org-time-clocksum-use-effort-durations
17871 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17872 y (if org-time-clocksum-use-effort-durations
17873 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17874 ;; fractional format
17875 (if org-time-clocksum-use-fractional
17876 (cond
17877 ;; single format string
17878 ((stringp org-time-clocksum-fractional-format)
17879 (format org-time-clocksum-fractional-format (/ m (float h))))
17880 ;; choice of fractional formats for different time units
17881 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17882 (> (/ (truncate m) (* y d h)) 0))
17883 (format fmt (/ m (* y d (float h)))))
17884 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17885 (> (/ (truncate m) (* mo d h)) 0))
17886 (format fmt (/ m (* mo d (float h)))))
17887 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17888 (> (/ (truncate m) (* w d h)) 0))
17889 (format fmt (/ m (* w d (float h)))))
17890 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17891 (> (/ (truncate m) (* d h)) 0))
17892 (format fmt (/ m (* d (float h)))))
17893 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17894 (> (/ (truncate m) h) 0))
17895 (format fmt (/ m (float h))))
17896 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17897 (format fmt m))
17898 ;; fall back to smallest time unit with a format
17899 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17900 (format fmt (/ m (float h))))
17901 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17902 (format fmt (/ m (* d (float h)))))
17903 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17904 (format fmt (/ m (* w d (float h)))))
17905 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17906 (format fmt (/ m (* mo d (float h)))))
17907 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17908 (format fmt (/ m (* y d (float h))))))
17909 ;; standard (non-fractional) format, with single format string
17910 (if (stringp org-time-clocksum-format)
17911 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17912 ;; separate formats components
17913 (and (setq fmt (plist-get org-time-clocksum-format :years))
17914 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17915 (plist-get org-time-clocksum-format :require-years))
17916 (setq clocksum (concat clocksum (format fmt n))
17917 m (- m (* n y d h))))
17918 (and (setq fmt (plist-get org-time-clocksum-format :months))
17919 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17920 (plist-get org-time-clocksum-format :require-months))
17921 (setq clocksum (concat clocksum (format fmt n))
17922 m (- m (* n mo d h))))
17923 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17924 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17925 (plist-get org-time-clocksum-format :require-weeks))
17926 (setq clocksum (concat clocksum (format fmt n))
17927 m (- m (* n w d h))))
17928 (and (setq fmt (plist-get org-time-clocksum-format :days))
17929 (or (> (setq n (/ (truncate m) (* d h))) 0)
17930 (plist-get org-time-clocksum-format :require-days))
17931 (setq clocksum (concat clocksum (format fmt n))
17932 m (- m (* n d h))))
17933 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17934 (or (> (setq n (/ (truncate m) h)) 0)
17935 (plist-get org-time-clocksum-format :require-hours))
17936 (setq clocksum (concat clocksum (format fmt n))
17937 m (- m (* n h))))
17938 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17939 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17940 (setq clocksum (concat clocksum (format fmt m))))
17941 ;; return formatted time duration
17942 clocksum))))
17944 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17945 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17946 "Org mode version 8.0")
17948 (defun org-hours-to-clocksum-string (n)
17949 (org-minutes-to-clocksum-string (* n 60)))
17951 (defun org-hh:mm-string-to-minutes (s)
17952 "Convert a string H:MM to a number of minutes.
17953 If the string is just a number, interpret it as minutes.
17954 In fact, the first hh:mm or number in the string will be taken,
17955 there can be extra stuff in the string.
17956 If no number is found, the return value is 0."
17957 (cond
17958 ((integerp s) s)
17959 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17960 (+ (* (string-to-number (match-string 1 s)) 60)
17961 (string-to-number (match-string 2 s))))
17962 ((string-match "\\([0-9]+\\)" s)
17963 (string-to-number (match-string 1 s)))
17964 (t 0)))
17966 (defcustom org-image-actual-width t
17967 "Should we use the actual width of images when inlining them?
17969 When set to `t', always use the image width.
17971 When set to a number, use imagemagick (when available) to set
17972 the image's width to this value.
17974 When set to a number in a list, try to get the width from any
17975 #+ATTR.* keyword if it matches a width specification like
17977 #+ATTR_HTML: :width 300px
17979 and fall back on that number if none is found.
17981 When set to nil, try to get the width from an #+ATTR.* keyword
17982 and fall back on the original width if none is found.
17984 This requires Emacs >= 24.1, build with imagemagick support."
17985 :group 'org-appearance
17986 :version "24.4"
17987 :package-version '(Org . "8.0")
17988 :type '(choice
17989 (const :tag "Use the image width" t)
17990 (integer :tag "Use a number of pixels")
17991 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17992 (const :tag "Use #+ATTR* or don't resize" nil)))
17994 (defcustom org-agenda-inhibit-startup nil
17995 "Inhibit startup when preparing agenda buffers.
17996 When this variable is `t', the initialization of the Org agenda
17997 buffers is inhibited: e.g. the visibility state is not set, the
17998 tables are not re-aligned, etc."
17999 :type 'boolean
18000 :version "24.3"
18001 :group 'org-agenda)
18003 (define-obsolete-variable-alias
18004 'org-agenda-ignore-drawer-properties
18005 'org-agenda-ignore-properties "24.5")
18007 (defcustom org-agenda-ignore-properties nil
18008 "Avoid updating text properties when building the agenda.
18009 Properties are used to prepare buffers for effort estimates,
18010 appointments, statistics and subtree-local categories.
18011 If you don't use these in the agenda, you can add them to this
18012 list and agenda building will be a bit faster.
18013 The value is a list, with zero or more of the symbols `effort', `appt',
18014 `stats' or `category'."
18015 :type '(set :greedy t
18016 (const effort)
18017 (const appt)
18018 (const stats)
18019 (const category))
18020 :version "24.5"
18021 :package-version '(Org . "8.3")
18022 :group 'org-agenda)
18024 (defun org-duration-string-to-minutes (s &optional output-to-string)
18025 "Convert a duration string S to minutes.
18027 A bare number is interpreted as minutes, modifiers can be set by
18028 customizing `org-effort-durations' (which see).
18030 Entries containing a colon are interpreted as H:MM by
18031 `org-hh:mm-string-to-minutes'."
18032 (let ((result 0)
18033 (re (concat "\\([0-9.]+\\) *\\("
18034 (regexp-opt (mapcar 'car org-effort-durations))
18035 "\\)")))
18036 (while (string-match re s)
18037 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18038 (string-to-number (match-string 1 s))))
18039 (setq s (replace-match "" nil t s)))
18040 (setq result (floor result))
18041 (incf result (org-hh:mm-string-to-minutes s))
18042 (if output-to-string (number-to-string result) result)))
18044 ;;;; Files
18046 (defun org-save-all-org-buffers ()
18047 "Save all Org-mode buffers without user confirmation."
18048 (interactive)
18049 (message "Saving all Org-mode buffers...")
18050 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18051 (when (featurep 'org-id) (org-id-locations-save))
18052 (message "Saving all Org-mode buffers... done"))
18054 (defun org-revert-all-org-buffers ()
18055 "Revert all Org-mode buffers.
18056 Prompt for confirmation when there are unsaved changes.
18057 Be sure you know what you are doing before letting this function
18058 overwrite your changes.
18060 This function is useful in a setup where one tracks org files
18061 with a version control system, to revert on one machine after pulling
18062 changes from another. I believe the procedure must be like this:
18064 1. M-x org-save-all-org-buffers
18065 2. Pull changes from the other machine, resolve conflicts
18066 3. M-x org-revert-all-org-buffers"
18067 (interactive)
18068 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18069 (user-error "Abort"))
18070 (save-excursion
18071 (save-window-excursion
18072 (mapc
18073 (lambda (b)
18074 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18075 (with-current-buffer b buffer-file-name))
18076 (org-pop-to-buffer-same-window b)
18077 (revert-buffer t 'no-confirm)))
18078 (buffer-list))
18079 (when (and (featurep 'org-id) org-id-track-globally)
18080 (org-id-locations-load)))))
18082 ;;;; Agenda files
18084 ;;;###autoload
18085 (defun org-switchb (&optional arg)
18086 "Switch between Org buffers.
18087 With one prefix argument, restrict available buffers to files.
18088 With two prefix arguments, restrict available buffers to agenda files.
18090 Defaults to `iswitchb' for buffer name completion.
18091 Set `org-completion-use-ido' to make it use ido instead."
18092 (interactive "P")
18093 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18094 ((equal arg '(16)) (org-buffer-list 'agenda))
18095 (t (org-buffer-list))))
18096 (org-completion-use-iswitchb org-completion-use-iswitchb)
18097 (org-completion-use-ido org-completion-use-ido))
18098 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18099 (setq org-completion-use-iswitchb t))
18100 (org-pop-to-buffer-same-window
18101 (org-icompleting-read "Org buffer: "
18102 (mapcar 'list (mapcar 'buffer-name blist))
18103 nil t))))
18105 ;;; Define some older names previously used for this functionality
18106 ;;;###autoload
18107 (defalias 'org-ido-switchb 'org-switchb)
18108 ;;;###autoload
18109 (defalias 'org-iswitchb 'org-switchb)
18111 (defun org-buffer-list (&optional predicate exclude-tmp)
18112 "Return a list of Org buffers.
18113 PREDICATE can be `export', `files' or `agenda'.
18115 export restrict the list to Export buffers.
18116 files restrict the list to buffers visiting Org files.
18117 agenda restrict the list to buffers visiting agenda files.
18119 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18120 (let* ((bfn nil)
18121 (agenda-files (and (eq predicate 'agenda)
18122 (mapcar 'file-truename (org-agenda-files t))))
18123 (filter
18124 (cond
18125 ((eq predicate 'files)
18126 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18127 ((eq predicate 'export)
18128 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18129 ((eq predicate 'agenda)
18130 (lambda (b)
18131 (with-current-buffer b
18132 (and (derived-mode-p 'org-mode)
18133 (setq bfn (buffer-file-name b))
18134 (member (file-truename bfn) agenda-files)))))
18135 (t (lambda (b) (with-current-buffer b
18136 (or (derived-mode-p 'org-mode)
18137 (string-match "\*Org .*Export"
18138 (buffer-name b)))))))))
18139 (delq nil
18140 (mapcar
18141 (lambda(b)
18142 (if (and (funcall filter b)
18143 (or (not exclude-tmp)
18144 (not (string-match "tmp" (buffer-name b)))))
18146 nil))
18147 (buffer-list)))))
18149 (defun org-agenda-files (&optional unrestricted archives)
18150 "Get the list of agenda files.
18151 Optional UNRESTRICTED means return the full list even if a restriction
18152 is currently in place.
18153 When ARCHIVES is t, include all archive files that are really being
18154 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18155 `org-agenda-archives-mode' is t."
18156 (let ((files
18157 (cond
18158 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18159 ((stringp org-agenda-files) (org-read-agenda-file-list))
18160 ((listp org-agenda-files) org-agenda-files)
18161 (t (error "Invalid value of `org-agenda-files'")))))
18162 (setq files (apply 'append
18163 (mapcar (lambda (f)
18164 (if (file-directory-p f)
18165 (directory-files
18166 f t org-agenda-file-regexp)
18167 (list f)))
18168 files)))
18169 (when org-agenda-skip-unavailable-files
18170 (setq files (delq nil
18171 (mapcar (function
18172 (lambda (file)
18173 (and (file-readable-p file) file)))
18174 files))))
18175 (when (or (eq archives t)
18176 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18177 (setq files (org-add-archive-files files)))
18178 files))
18180 (defun org-agenda-file-p (&optional file)
18181 "Return non-nil, if FILE is an agenda file.
18182 If FILE is omitted, use the file associated with the current
18183 buffer."
18184 (let ((fname (or file (buffer-file-name))))
18185 (and fname
18186 (member (file-truename fname)
18187 (mapcar #'file-truename (org-agenda-files t))))))
18189 (defun org-edit-agenda-file-list ()
18190 "Edit the list of agenda files.
18191 Depending on setup, this either uses customize to edit the variable
18192 `org-agenda-files', or it visits the file that is holding the list. In the
18193 latter case, the buffer is set up in a way that saving it automatically kills
18194 the buffer and restores the previous window configuration."
18195 (interactive)
18196 (if (stringp org-agenda-files)
18197 (let ((cw (current-window-configuration)))
18198 (find-file org-agenda-files)
18199 (org-set-local 'org-window-configuration cw)
18200 (org-add-hook 'after-save-hook
18201 (lambda ()
18202 (set-window-configuration
18203 (prog1 org-window-configuration
18204 (kill-buffer (current-buffer))))
18205 (org-install-agenda-files-menu)
18206 (message "New agenda file list installed"))
18207 nil 'local)
18208 (message "%s" (substitute-command-keys
18209 "Edit list and finish with \\[save-buffer]")))
18210 (customize-variable 'org-agenda-files)))
18212 (defun org-store-new-agenda-file-list (list)
18213 "Set new value for the agenda file list and save it correctly."
18214 (if (stringp org-agenda-files)
18215 (let ((fe (org-read-agenda-file-list t)) b u)
18216 (while (setq b (find-buffer-visiting org-agenda-files))
18217 (kill-buffer b))
18218 (with-temp-file org-agenda-files
18219 (insert
18220 (mapconcat
18221 (lambda (f) ;; Keep un-expanded entries.
18222 (if (setq u (assoc f fe))
18223 (cdr u)
18225 list "\n")
18226 "\n")))
18227 (let ((org-mode-hook nil) (org-inhibit-startup t)
18228 (org-insert-mode-line-in-empty-file nil))
18229 (setq org-agenda-files list)
18230 (customize-save-variable 'org-agenda-files org-agenda-files))))
18232 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18233 "Read the list of agenda files from a file.
18234 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18235 filenames, used by `org-store-new-agenda-file-list' to write back
18236 un-expanded file names."
18237 (when (file-directory-p org-agenda-files)
18238 (error "`org-agenda-files' cannot be a single directory"))
18239 (when (stringp org-agenda-files)
18240 (with-temp-buffer
18241 (insert-file-contents org-agenda-files)
18242 (mapcar
18243 (lambda (f)
18244 (let ((e (expand-file-name (substitute-in-file-name f)
18245 org-directory)))
18246 (if pair-with-expansion
18247 (cons e f)
18248 e)))
18249 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18251 ;;;###autoload
18252 (defun org-cycle-agenda-files ()
18253 "Cycle through the files in `org-agenda-files'.
18254 If the current buffer visits an agenda file, find the next one in the list.
18255 If the current buffer does not, find the first agenda file."
18256 (interactive)
18257 (let* ((fs (org-agenda-files t))
18258 (files (append fs (list (car fs))))
18259 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18260 file)
18261 (unless files (user-error "No agenda files"))
18262 (catch 'exit
18263 (while (setq file (pop files))
18264 (if (equal (file-truename file) tcf)
18265 (when (car files)
18266 (find-file (car files))
18267 (throw 'exit t))))
18268 (find-file (car fs)))
18269 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18271 (defun org-agenda-file-to-front (&optional to-end)
18272 "Move/add the current file to the top of the agenda file list.
18273 If the file is not present in the list, it is added to the front. If it is
18274 present, it is moved there. With optional argument TO-END, add/move to the
18275 end of the list."
18276 (interactive "P")
18277 (let ((org-agenda-skip-unavailable-files nil)
18278 (file-alist (mapcar (lambda (x)
18279 (cons (file-truename x) x))
18280 (org-agenda-files t)))
18281 (ctf (file-truename
18282 (or buffer-file-name
18283 (user-error "Please save the current buffer to a file"))))
18284 x had)
18285 (setq x (assoc ctf file-alist) had x)
18287 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18288 (if to-end
18289 (setq file-alist (append (delq x file-alist) (list x)))
18290 (setq file-alist (cons x (delq x file-alist))))
18291 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18292 (org-install-agenda-files-menu)
18293 (message "File %s to %s of agenda file list"
18294 (if had "moved" "added") (if to-end "end" "front"))))
18296 (defun org-remove-file (&optional file)
18297 "Remove current file from the list of files in variable `org-agenda-files'.
18298 These are the files which are being checked for agenda entries.
18299 Optional argument FILE means use this file instead of the current."
18300 (interactive)
18301 (let* ((org-agenda-skip-unavailable-files nil)
18302 (file (or file buffer-file-name
18303 (user-error "Current buffer does not visit a file")))
18304 (true-file (file-truename file))
18305 (afile (abbreviate-file-name file))
18306 (files (delq nil (mapcar
18307 (lambda (x)
18308 (if (equal true-file
18309 (file-truename x))
18310 nil x))
18311 (org-agenda-files t)))))
18312 (if (not (= (length files) (length (org-agenda-files t))))
18313 (progn
18314 (org-store-new-agenda-file-list files)
18315 (org-install-agenda-files-menu)
18316 (message "Removed file: %s" afile))
18317 (message "File was not in list: %s (not removed)" afile))))
18319 (defun org-file-menu-entry (file)
18320 (vector file (list 'find-file file) t))
18322 (defun org-check-agenda-file (file)
18323 "Make sure FILE exists. If not, ask user what to do."
18324 (when (not (file-exists-p file))
18325 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18326 (abbreviate-file-name file))
18327 (let ((r (downcase (read-char-exclusive))))
18328 (cond
18329 ((equal r ?r)
18330 (org-remove-file file)
18331 (throw 'nextfile t))
18332 (t (user-error "Abort"))))))
18334 (defun org-get-agenda-file-buffer (file)
18335 "Get an agenda buffer visiting FILE.
18336 If the buffer needs to be created, add it to the list of buffers
18337 which might be released later."
18338 (let ((buf (org-find-base-buffer-visiting file)))
18339 (if buf
18340 buf ; just return it
18341 ;; Make a new buffer and remember it
18342 (setq buf (find-file-noselect file))
18343 (if buf (push buf org-agenda-new-buffers))
18344 buf)))
18346 (defun org-release-buffers (blist)
18347 "Release all buffers in list, asking the user for confirmation when needed.
18348 When a buffer is unmodified, it is just killed. When modified, it is saved
18349 \(if the user agrees) and then killed."
18350 (let (buf file)
18351 (while (setq buf (pop blist))
18352 (setq file (buffer-file-name buf))
18353 (when (and (buffer-modified-p buf)
18354 file
18355 (y-or-n-p (format "Save file %s? " file)))
18356 (with-current-buffer buf (save-buffer)))
18357 (kill-buffer buf))))
18359 (defun org-agenda-prepare-buffers (files)
18360 "Create buffers for all agenda files, protect archived trees and comments."
18361 (interactive)
18362 (let ((pa '(:org-archived t))
18363 (pc '(:org-comment t))
18364 (pall '(:org-archived t :org-comment t))
18365 (inhibit-read-only t)
18366 (org-inhibit-startup org-agenda-inhibit-startup)
18367 (rea (concat ":" org-archive-tag ":"))
18368 file re pos)
18369 (setq org-tag-alist-for-agenda nil
18370 org-tag-groups-alist-for-agenda nil)
18371 (save-excursion
18372 (save-restriction
18373 (while (setq file (pop files))
18374 (catch 'nextfile
18375 (if (bufferp file)
18376 (set-buffer file)
18377 (org-check-agenda-file file)
18378 (set-buffer (org-get-agenda-file-buffer file)))
18379 (widen)
18380 (org-set-regexps-and-options-for-tags)
18381 (setq pos (point))
18382 (goto-char (point-min))
18383 (let ((case-fold-search t))
18384 (when (search-forward "#+setupfile" nil t)
18385 ;; Don't set all regexps and options systematically as
18386 ;; this is only run for setting agenda tags from setup
18387 ;; file
18388 (org-set-regexps-and-options)))
18389 (or (memq 'category org-agenda-ignore-properties)
18390 (org-refresh-category-properties))
18391 (or (memq 'stats org-agenda-ignore-properties)
18392 (org-refresh-stats-properties))
18393 (or (memq 'effort org-agenda-ignore-properties)
18394 (org-refresh-effort-properties))
18395 (or (memq 'appt org-agenda-ignore-properties)
18396 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18397 (setq org-todo-keywords-for-agenda
18398 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18399 (setq org-done-keywords-for-agenda
18400 (append org-done-keywords-for-agenda org-done-keywords))
18401 (setq org-todo-keyword-alist-for-agenda
18402 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18403 (setq org-tag-alist-for-agenda
18404 (org-uniquify
18405 (append org-tag-alist-for-agenda
18406 org-tag-alist
18407 org-tag-persistent-alist)))
18408 (if org-group-tags
18409 (setq org-tag-groups-alist-for-agenda
18410 (org-uniquify-alist
18411 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18412 (org-with-silent-modifications
18413 (save-excursion
18414 (remove-text-properties (point-min) (point-max) pall)
18415 (when org-agenda-skip-archived-trees
18416 (goto-char (point-min))
18417 (while (re-search-forward rea nil t)
18418 (if (org-at-heading-p t)
18419 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18420 (goto-char (point-min))
18421 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18422 (while (re-search-forward re nil t)
18423 (when (save-match-data (org-in-commented-heading-p t))
18424 (add-text-properties
18425 (match-beginning 0) (org-end-of-subtree t) pc)))))
18426 (goto-char pos)))))
18427 (setq org-todo-keywords-for-agenda
18428 (org-uniquify org-todo-keywords-for-agenda))
18429 (setq org-todo-keyword-alist-for-agenda
18430 (org-uniquify org-todo-keyword-alist-for-agenda))))
18433 ;;;; CDLaTeX minor mode
18435 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18436 "Keymap for the minor `org-cdlatex-mode'.")
18438 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18439 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18440 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18441 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18442 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18444 (defvar org-cdlatex-texmathp-advice-is-done nil
18445 "Flag remembering if we have applied the advice to texmathp already.")
18447 (define-minor-mode org-cdlatex-mode
18448 "Toggle the minor `org-cdlatex-mode'.
18449 This mode supports entering LaTeX environment and math in LaTeX fragments
18450 in Org-mode.
18451 \\{org-cdlatex-mode-map}"
18452 nil " OCDL" nil
18453 (when org-cdlatex-mode
18454 (require 'cdlatex)
18455 (run-hooks 'cdlatex-mode-hook)
18456 (cdlatex-compute-tables))
18457 (unless org-cdlatex-texmathp-advice-is-done
18458 (setq org-cdlatex-texmathp-advice-is-done t)
18459 (defadvice texmathp (around org-math-always-on activate)
18460 "Always return t in org-mode buffers.
18461 This is because we want to insert math symbols without dollars even outside
18462 the LaTeX math segments. If Orgmode thinks that point is actually inside
18463 an embedded LaTeX fragment, let texmathp do its job.
18464 \\[org-cdlatex-mode-map]"
18465 (interactive)
18466 (let (p)
18467 (cond
18468 ((not (derived-mode-p 'org-mode)) ad-do-it)
18469 ((eq this-command 'cdlatex-math-symbol)
18470 (setq ad-return-value t
18471 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18473 (let ((p (org-inside-LaTeX-fragment-p)))
18474 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18475 (setq ad-return-value t
18476 texmathp-why '("Org-mode embedded math" . 0))
18477 (if p ad-do-it)))))))))
18479 (defun turn-on-org-cdlatex ()
18480 "Unconditionally turn on `org-cdlatex-mode'."
18481 (org-cdlatex-mode 1))
18483 (defun org-try-cdlatex-tab ()
18484 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18485 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18486 - inside a LaTeX fragment, or
18487 - after the first word in a line, where an abbreviation expansion could
18488 insert a LaTeX environment."
18489 (when org-cdlatex-mode
18490 (cond
18491 ;; Before any word on the line: No expansion possible.
18492 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18493 ;; Just after first word on the line: Expand it. Make sure it
18494 ;; cannot happen on headlines, though.
18495 ((save-excursion
18496 (skip-chars-backward "a-zA-Z0-9*")
18497 (skip-chars-backward " \t")
18498 (and (bolp) (not (org-at-heading-p))))
18499 (cdlatex-tab) t)
18500 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18502 (defun org-cdlatex-underscore-caret (&optional arg)
18503 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18504 Revert to the normal definition outside of these fragments."
18505 (interactive "P")
18506 (if (org-inside-LaTeX-fragment-p)
18507 (call-interactively 'cdlatex-sub-superscript)
18508 (let (org-cdlatex-mode)
18509 (call-interactively (key-binding (vector last-input-event))))))
18511 (defun org-cdlatex-math-modify (&optional arg)
18512 "Execute `cdlatex-math-modify' in LaTeX fragments.
18513 Revert to the normal definition outside of these fragments."
18514 (interactive "P")
18515 (if (org-inside-LaTeX-fragment-p)
18516 (call-interactively 'cdlatex-math-modify)
18517 (let (org-cdlatex-mode)
18518 (call-interactively (key-binding (vector last-input-event))))))
18520 (defun org-cdlatex-environment-indent (&optional environment item)
18521 "Execute `cdlatex-environment' and indent the inserted environment."
18522 (interactive)
18523 (cdlatex-environment environment item)
18524 (let ((element (org-element-at-point)))
18525 (org-indent-region (org-element-property :begin element)
18526 (org-element-property :end element))))
18529 ;;;; LaTeX fragments
18531 (defun org-inside-LaTeX-fragment-p ()
18532 "Test if point is inside a LaTeX fragment.
18533 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18534 sequence appearing also before point.
18535 Even though the matchers for math are configurable, this function assumes
18536 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18537 delimiters are skipped when they have been removed by customization.
18538 The return value is nil, or a cons cell with the delimiter and the
18539 position of this delimiter.
18541 This function does a reasonably good job, but can locally be fooled by
18542 for example currency specifications. For example it will assume being in
18543 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18544 fragments that are properly closed, but during editing, we have to live
18545 with the uncertainty caused by missing closing delimiters. This function
18546 looks only before point, not after."
18547 (catch 'exit
18548 (let ((pos (point))
18549 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18550 (lim (progn
18551 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18552 (point)))
18553 dd-on str (start 0) m re)
18554 (goto-char pos)
18555 (when dodollar
18556 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18557 re (nth 1 (assoc "$" org-latex-regexps)))
18558 (while (string-match re str start)
18559 (cond
18560 ((= (match-end 0) (length str))
18561 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18562 ((= (match-end 0) (- (length str) 5))
18563 (throw 'exit nil))
18564 (t (setq start (match-end 0))))))
18565 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18566 (goto-char pos)
18567 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18568 (and (match-beginning 2) (throw 'exit nil))
18569 ;; count $$
18570 (while (re-search-backward "\\$\\$" lim t)
18571 (setq dd-on (not dd-on)))
18572 (goto-char pos)
18573 (if dd-on (cons "$$" m))))))
18575 (defun org-inside-latex-macro-p ()
18576 "Is point inside a LaTeX macro or its arguments?"
18577 (save-match-data
18578 (org-in-regexp
18579 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18581 (defvar org-latex-fragment-image-overlays nil
18582 "List of overlays carrying the images of latex fragments.")
18583 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18585 (defun org-remove-latex-fragment-image-overlays ()
18586 "Remove all overlays with LaTeX fragment images in current buffer."
18587 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18588 (setq org-latex-fragment-image-overlays nil))
18590 (define-obsolete-function-alias
18591 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18592 (defun org-toggle-latex-fragment (&optional subtree)
18593 "Preview the LaTeX fragment at point, or all locally or globally.
18594 If the cursor is in a LaTeX fragment, create the image and overlay
18595 it over the source code. If there is no fragment at point, display
18596 all fragments in the current text, from one headline to the next. With
18597 prefix SUBTREE, display all fragments in the current subtree. With a
18598 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18599 the cursor is before the first headline,
18600 display all fragments in the buffer.
18601 The images can be removed again with \\[org-toggle-latex-fragment]."
18602 (interactive "P")
18603 (unless buffer-file-name
18604 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18605 (if org-latex-fragment-image-overlays
18606 (progn (org-remove-latex-fragment-image-overlays)
18607 (message "LaTeX fragments images removed"))
18608 (when (display-graphic-p)
18609 (org-remove-latex-fragment-image-overlays)
18610 (save-excursion
18611 (save-restriction
18612 (let (beg end at msg)
18613 (cond
18614 ((or (equal subtree '(16))
18615 (not (save-excursion
18616 (re-search-backward org-outline-regexp-bol nil t))))
18617 (setq beg (point-min) end (point-max)
18618 msg "Creating images for buffer...%s"))
18619 ((equal subtree '(4))
18620 (org-back-to-heading)
18621 (setq beg (point) end (org-end-of-subtree t)
18622 msg "Creating images for subtree...%s"))
18624 (if (setq at (org-inside-LaTeX-fragment-p))
18625 (goto-char (max (point-min) (- (cdr at) 2)))
18626 (org-back-to-heading))
18627 (setq beg (point) end (progn (outline-next-heading) (point))
18628 msg (if at "Creating image...%s"
18629 "Creating images for entry...%s"))))
18630 (message msg "")
18631 (narrow-to-region beg end)
18632 (goto-char beg)
18633 (org-format-latex
18634 (concat org-latex-preview-ltxpng-directory
18635 (file-name-sans-extension
18636 (file-name-nondirectory buffer-file-name)))
18637 default-directory 'overlays msg at 'forbuffer
18638 org-latex-create-formula-image-program)
18639 (message msg "done. Use `C-c C-x C-l' to remove images.")))))))
18641 (defun org-format-latex (prefix &optional dir overlays msg at
18642 forbuffer processing-type)
18643 "Replace LaTeX fragments with links to an image, and produce images.
18644 Some of the options can be changed using the variable
18645 `org-format-latex-options'."
18646 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18647 (let* ((prefixnodir (file-name-nondirectory prefix))
18648 (absprefix (expand-file-name prefix dir))
18649 (todir (file-name-directory absprefix))
18650 (opt org-format-latex-options)
18651 (optnew org-format-latex-options)
18652 (matchers (plist-get opt :matchers))
18653 (re-list org-latex-regexps)
18654 (cnt 0) txt hash link beg end re e checkdir
18655 string
18656 m n block-type block linkfile movefile ov)
18657 ;; Check the different regular expressions
18658 (while (setq e (pop re-list))
18659 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18660 block (if block-type "\n\n" ""))
18661 (when (member m matchers)
18662 (goto-char (point-min))
18663 (while (re-search-forward re nil t)
18664 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18665 (or (not overlays)
18666 (not (eq (get-char-property (match-beginning n)
18667 'org-overlay-type)
18668 'org-latex-overlay))))
18669 (cond
18670 ((eq processing-type 'verbatim))
18671 ((eq processing-type 'mathjax)
18672 ;; Prepare for MathJax processing.
18673 (setq string (match-string n))
18674 (when (member m '("$" "$1"))
18675 (save-excursion
18676 (delete-region (match-beginning n) (match-end n))
18677 (goto-char (match-beginning n))
18678 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18679 ((or (eq processing-type 'dvipng)
18680 (eq processing-type 'imagemagick))
18681 ;; Process to an image.
18682 (setq txt (match-string n)
18683 beg (match-beginning n) end (match-end n)
18684 cnt (1+ cnt))
18685 (let ((face (face-at-point))
18686 (fg (plist-get opt :foreground))
18687 (bg (plist-get opt :background))
18688 ;; Ensure full list is printed.
18689 print-length print-level)
18690 (when forbuffer
18691 ;; Get the colors from the face at point.
18692 (goto-char beg)
18693 (when (eq fg 'auto)
18694 (setq fg (face-attribute face :foreground nil 'default)))
18695 (when (eq bg 'auto)
18696 (setq bg (face-attribute face :background nil 'default)))
18697 (setq optnew (copy-sequence opt))
18698 (plist-put optnew :foreground fg)
18699 (plist-put optnew :background bg))
18700 (setq hash (sha1 (prin1-to-string
18701 (list org-format-latex-header
18702 org-latex-default-packages-alist
18703 org-latex-packages-alist
18704 org-format-latex-options
18705 forbuffer txt fg bg)))
18706 linkfile (format "%s_%s.png" prefix hash)
18707 movefile (format "%s_%s.png" absprefix hash)))
18708 (setq link (concat block "[[file:" linkfile "]]" block))
18709 (if msg (message msg cnt))
18710 (goto-char beg)
18711 (unless checkdir ; Ensure the directory exists.
18712 (setq checkdir t)
18713 (or (file-directory-p todir) (make-directory todir t)))
18714 (unless (file-exists-p movefile)
18715 (org-create-formula-image
18716 txt movefile optnew forbuffer processing-type))
18717 (if overlays
18718 (progn
18719 (mapc (lambda (o)
18720 (if (eq (overlay-get o 'org-overlay-type)
18721 'org-latex-overlay)
18722 (delete-overlay o)))
18723 (overlays-in beg end))
18724 (setq ov (make-overlay beg end))
18725 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18726 (if (featurep 'xemacs)
18727 (progn
18728 (overlay-put ov 'invisible t)
18729 (overlay-put
18730 ov 'end-glyph
18731 (make-glyph (vector 'png :file movefile))))
18732 (overlay-put
18733 ov 'display
18734 (list 'image :type 'png :file movefile :ascent 'center)))
18735 (push ov org-latex-fragment-image-overlays)
18736 (goto-char end))
18737 (delete-region beg end)
18738 (insert (org-add-props link
18739 (list 'org-latex-src
18740 (replace-regexp-in-string
18741 "\"" "" txt)
18742 'org-latex-src-embed-type
18743 (if block-type 'paragraph 'character))))))
18744 ((eq processing-type 'mathml)
18745 ;; Process to MathML
18746 (unless (save-match-data (org-format-latex-mathml-available-p))
18747 (user-error "LaTeX to MathML converter not configured"))
18748 (setq txt (match-string n)
18749 beg (match-beginning n) end (match-end n)
18750 cnt (1+ cnt))
18751 (if msg (message msg cnt))
18752 (goto-char beg)
18753 (delete-region beg end)
18754 (insert (org-format-latex-as-mathml
18755 txt block-type prefix dir)))
18757 (error "Unknown conversion type %s for LaTeX fragments"
18758 processing-type)))))))))
18760 (defun org-create-math-formula (latex-frag &optional mathml-file)
18761 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18762 Use `org-latex-to-mathml-convert-command'. If the conversion is
18763 sucessful, return the portion between \"<math...> </math>\"
18764 elements otherwise return nil. When MATHML-FILE is specified,
18765 write the results in to that file. When invoked as an
18766 interactive command, prompt for LATEX-FRAG, with initial value
18767 set to the current active region and echo the results for user
18768 inspection."
18769 (interactive (list (let ((frag (when (org-region-active-p)
18770 (buffer-substring-no-properties
18771 (region-beginning) (region-end)))))
18772 (read-string "LaTeX Fragment: " frag nil frag))))
18773 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18774 (let* ((tmp-in-file (file-relative-name
18775 (make-temp-name (expand-file-name "ltxmathml-in"))))
18776 (ignore (write-region latex-frag nil tmp-in-file))
18777 (tmp-out-file (file-relative-name
18778 (make-temp-name (expand-file-name "ltxmathml-out"))))
18779 (cmd (format-spec
18780 org-latex-to-mathml-convert-command
18781 `((?j . ,(shell-quote-argument
18782 (expand-file-name org-latex-to-mathml-jar-file)))
18783 (?I . ,(shell-quote-argument tmp-in-file))
18784 (?o . ,(shell-quote-argument tmp-out-file)))))
18785 mathml shell-command-output)
18786 (when (org-called-interactively-p 'any)
18787 (unless (org-format-latex-mathml-available-p)
18788 (user-error "LaTeX to MathML converter not configured")))
18789 (message "Running %s" cmd)
18790 (setq shell-command-output (shell-command-to-string cmd))
18791 (setq mathml
18792 (when (file-readable-p tmp-out-file)
18793 (with-current-buffer (find-file-noselect tmp-out-file t)
18794 (goto-char (point-min))
18795 (when (re-search-forward
18796 (concat
18797 (regexp-quote
18798 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18799 "\\(.\\|\n\\)*"
18800 (regexp-quote "</math>")) nil t)
18801 (prog1 (match-string 0) (kill-buffer))))))
18802 (cond
18803 (mathml
18804 (setq mathml
18805 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18806 (when mathml-file
18807 (write-region mathml nil mathml-file))
18808 (when (org-called-interactively-p 'any)
18809 (message mathml)))
18810 ((message "LaTeX to MathML conversion failed")
18811 (message shell-command-output)))
18812 (delete-file tmp-in-file)
18813 (when (file-exists-p tmp-out-file)
18814 (delete-file tmp-out-file))
18815 mathml))
18817 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18818 prefix &optional dir)
18819 "Use `org-create-math-formula' but check local cache first."
18820 (let* ((absprefix (expand-file-name prefix dir))
18821 (print-length nil) (print-level nil)
18822 (formula-id (concat
18823 "formula-"
18824 (sha1
18825 (prin1-to-string
18826 (list latex-frag
18827 org-latex-to-mathml-convert-command)))))
18828 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18829 (formula-cache-dir (file-name-directory formula-cache)))
18831 (unless (file-directory-p formula-cache-dir)
18832 (make-directory formula-cache-dir t))
18834 (unless (file-exists-p formula-cache)
18835 (org-create-math-formula latex-frag formula-cache))
18837 (if (file-exists-p formula-cache)
18838 ;; Successful conversion. Return the link to MathML file.
18839 (org-add-props
18840 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18841 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18842 'org-latex-src-embed-type (if latex-frag-type
18843 'paragraph 'character)))
18844 ;; Failed conversion. Return the LaTeX fragment verbatim
18845 latex-frag)))
18847 (defun org-create-formula-image (string tofile options buffer &optional type)
18848 "Create an image from LaTeX source using dvipng or convert.
18849 This function calls either `org-create-formula-image-with-dvipng'
18850 or `org-create-formula-image-with-imagemagick' depending on the
18851 value of `org-latex-create-formula-image-program' or on the value
18852 of the optional TYPE variable.
18854 Note: ultimately these two function should be combined as they
18855 share a good deal of logic."
18856 (org-check-external-command
18857 "latex" "needed to convert LaTeX fragments to images")
18858 (funcall
18859 (case (or type org-latex-create-formula-image-program)
18860 ('dvipng
18861 (org-check-external-command
18862 "dvipng" "needed to convert LaTeX fragments to images")
18863 'org-create-formula-image-with-dvipng)
18864 ('imagemagick
18865 (org-check-external-command
18866 "convert" "you need to install imagemagick")
18867 'org-create-formula-image-with-imagemagick)
18868 (t (error
18869 "Invalid value of `org-latex-create-formula-image-program'")))
18870 string tofile options buffer))
18872 (declare-function org-export-get-backend "ox" (name))
18873 (declare-function org-export--get-global-options "ox" (&optional backend))
18874 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18875 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18876 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18877 (defun org-create-formula--latex-header ()
18878 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18879 (let ((info (org-combine-plists (org-export--get-global-options
18880 (org-export-get-backend 'latex))
18881 (org-export--get-inbuffer-options
18882 (org-export-get-backend 'latex)))))
18883 (org-latex-guess-babel-language
18884 (org-latex-guess-inputenc
18885 (org-splice-latex-header
18886 org-format-latex-header
18887 org-latex-default-packages-alist
18888 org-latex-packages-alist t
18889 (plist-get info :latex-header)))
18890 info)))
18892 ;; This function borrows from Ganesh Swami's latex2png.el
18893 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18894 "This calls dvipng."
18895 (require 'ox-latex)
18896 (let* ((tmpdir (if (featurep 'xemacs)
18897 (temp-directory)
18898 temporary-file-directory))
18899 (texfilebase (make-temp-name
18900 (expand-file-name "orgtex" tmpdir)))
18901 (texfile (concat texfilebase ".tex"))
18902 (dvifile (concat texfilebase ".dvi"))
18903 (pngfile (concat texfilebase ".png"))
18904 (fnh (if (featurep 'xemacs)
18905 (font-height (face-font 'default))
18906 (face-attribute 'default :height nil)))
18907 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18908 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18909 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18910 "Black"))
18911 (bg (or (plist-get options (if buffer :background :html-background))
18912 "Transparent")))
18913 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18914 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18915 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18916 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18917 (let ((latex-header (org-create-formula--latex-header)))
18918 (with-temp-file texfile
18919 (insert latex-header)
18920 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18921 (let ((dir default-directory))
18922 (ignore-errors
18923 (cd tmpdir)
18924 (call-process "latex" nil nil nil texfile))
18925 (cd dir))
18926 (if (not (file-exists-p dvifile))
18927 (progn (message "Failed to create dvi file from %s" texfile) nil)
18928 (ignore-errors
18929 (if (featurep 'xemacs)
18930 (call-process "dvipng" nil nil nil
18931 "-fg" fg "-bg" bg
18932 "-T" "tight"
18933 "-o" pngfile
18934 dvifile)
18935 (call-process "dvipng" nil nil nil
18936 "-fg" fg "-bg" bg
18937 "-D" dpi
18938 ;;"-x" scale "-y" scale
18939 "-T" "tight"
18940 "-o" pngfile
18941 dvifile)))
18942 (if (not (file-exists-p pngfile))
18943 (if org-format-latex-signal-error
18944 (error "Failed to create png file from %s" texfile)
18945 (message "Failed to create png file from %s" texfile)
18946 nil)
18947 ;; Use the requested file name and clean up
18948 (copy-file pngfile tofile 'replace)
18949 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18950 (if (file-exists-p (concat texfilebase e))
18951 (delete-file (concat texfilebase e))))
18952 pngfile))))
18954 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18955 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18956 "This calls convert, which is included into imagemagick."
18957 (require 'ox-latex)
18958 (let* ((tmpdir (if (featurep 'xemacs)
18959 (temp-directory)
18960 temporary-file-directory))
18961 (texfilebase (make-temp-name
18962 (expand-file-name "orgtex" tmpdir)))
18963 (texfile (concat texfilebase ".tex"))
18964 (pdffile (concat texfilebase ".pdf"))
18965 (pngfile (concat texfilebase ".png"))
18966 (fnh (if (featurep 'xemacs)
18967 (font-height (face-font 'default))
18968 (face-attribute 'default :height nil)))
18969 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18970 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18971 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18972 "black"))
18973 (bg (or (plist-get options (if buffer :background :html-background))
18974 "white")))
18975 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18976 (setq fg (org-latex-color-format fg)))
18977 (if (eq bg 'default) (setq bg (org-latex-color :background))
18978 (setq bg (org-latex-color-format
18979 (if (string= bg "Transparent") "white" bg))))
18980 (let ((latex-header (org-create-formula--latex-header)))
18981 (with-temp-file texfile
18982 (insert latex-header)
18983 (insert "\n\\begin{document}\n"
18984 "\\definecolor{fg}{rgb}{" fg "}\n"
18985 "\\definecolor{bg}{rgb}{" bg "}\n"
18986 "\n\\pagecolor{bg}\n"
18987 "\n{\\color{fg}\n"
18988 string
18989 "\n}\n"
18990 "\n\\end{document}\n")))
18991 (org-latex-compile texfile t)
18992 (if (not (file-exists-p pdffile))
18993 (progn (message "Failed to create pdf file from %s" texfile) nil)
18994 (ignore-errors
18995 (if (featurep 'xemacs)
18996 (call-process "convert" nil nil nil
18997 "-density" "96"
18998 "-trim"
18999 "-antialias"
19000 pdffile
19001 "-quality" "100"
19002 ;; "-sharpen" "0x1.0"
19003 pngfile)
19004 (call-process "convert" nil nil nil
19005 "-density" dpi
19006 "-trim"
19007 "-antialias"
19008 pdffile
19009 "-quality" "100"
19010 ;; "-sharpen" "0x1.0"
19011 pngfile)))
19012 (if (not (file-exists-p pngfile))
19013 (if org-format-latex-signal-error
19014 (error "Failed to create png file from %s" texfile)
19015 (message "Failed to create png file from %s" texfile)
19016 nil)
19017 ;; Use the requested file name and clean up
19018 (copy-file pngfile tofile 'replace)
19019 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19020 (if (file-exists-p (concat texfilebase e))
19021 (delete-file (concat texfilebase e))))
19022 pngfile))))
19024 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19025 "Fill a LaTeX header template TPL.
19026 In the template, the following place holders will be recognized:
19028 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19029 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19030 [PACKAGES] \\usepackage statements for PKG
19031 [NO-PACKAGES] do not include PKG
19032 [EXTRA] the string EXTRA
19033 [NO-EXTRA] do not include EXTRA
19035 For backward compatibility, if both the positive and the negative place
19036 holder is missing, the positive one (without the \"NO-\") will be
19037 assumed to be present at the end of the template.
19038 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19039 EXTRA is a string.
19040 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19041 (let (rpl (end ""))
19042 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19043 (setq rpl (if (or (match-end 1) (not def-pkg))
19044 "" (org-latex-packages-to-string def-pkg snippets-p t))
19045 tpl (replace-match rpl t t tpl))
19046 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19048 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19049 (setq rpl (if (or (match-end 1) (not pkg))
19050 "" (org-latex-packages-to-string pkg snippets-p t))
19051 tpl (replace-match rpl t t tpl))
19052 (if pkg (setq end
19053 (concat end "\n"
19054 (org-latex-packages-to-string pkg snippets-p)))))
19056 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19057 (setq rpl (if (or (match-end 1) (not extra))
19058 "" (concat extra "\n"))
19059 tpl (replace-match rpl t t tpl))
19060 (if (and extra (string-match "\\S-" extra))
19061 (setq end (concat end "\n" extra))))
19063 (if (string-match "\\S-" end)
19064 (concat tpl "\n" end)
19065 tpl)))
19067 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19068 "Turn an alist of packages into a string with the \\usepackage macros."
19069 (setq pkg (mapconcat (lambda(p)
19070 (cond
19071 ((stringp p) p)
19072 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19073 (format "%% Package %s omitted" (cadr p)))
19074 ((equal "" (car p))
19075 (format "\\usepackage{%s}" (cadr p)))
19077 (format "\\usepackage[%s]{%s}"
19078 (car p) (cadr p)))))
19080 "\n"))
19081 (if newline (concat pkg "\n") pkg))
19083 (defun org-dvipng-color (attr)
19084 "Return a RGB color specification for dvipng."
19085 (apply 'format "rgb %s %s %s"
19086 (mapcar 'org-normalize-color
19087 (if (featurep 'xemacs)
19088 (color-rgb-components
19089 (face-property 'default
19090 (cond ((eq attr :foreground) 'foreground)
19091 ((eq attr :background) 'background))))
19092 (color-values (face-attribute 'default attr nil))))))
19094 (defun org-dvipng-color-format (color-name)
19095 "Convert COLOR-NAME to a RGB color value for dvipng."
19096 (apply 'format "rgb %s %s %s"
19097 (mapcar 'org-normalize-color
19098 (color-values color-name))))
19100 (defun org-latex-color (attr)
19101 "Return a RGB color for the LaTeX color package."
19102 (apply 'format "%s,%s,%s"
19103 (mapcar 'org-normalize-color
19104 (if (featurep 'xemacs)
19105 (color-rgb-components
19106 (face-property 'default
19107 (cond ((eq attr :foreground) 'foreground)
19108 ((eq attr :background) 'background))))
19109 (color-values (face-attribute 'default attr nil))))))
19111 (defun org-latex-color-format (color-name)
19112 "Convert COLOR-NAME to a RGB color value."
19113 (apply 'format "%s,%s,%s"
19114 (mapcar 'org-normalize-color
19115 (color-values color-name))))
19117 (defun org-normalize-color (value)
19118 "Return string to be used as color value for an RGB component."
19119 (format "%g" (/ value 65535.0)))
19123 ;; Image display
19125 (defvar org-inline-image-overlays nil)
19126 (make-variable-buffer-local 'org-inline-image-overlays)
19128 (defun org-toggle-inline-images (&optional include-linked)
19129 "Toggle the display of inline images.
19130 INCLUDE-LINKED is passed to `org-display-inline-images'."
19131 (interactive "P")
19132 (if org-inline-image-overlays
19133 (progn
19134 (org-remove-inline-images)
19135 (message "Inline image display turned off"))
19136 (org-display-inline-images include-linked)
19137 (if (and (org-called-interactively-p)
19138 org-inline-image-overlays)
19139 (message "%d images displayed inline"
19140 (length org-inline-image-overlays))
19141 (message "No images to display inline"))))
19143 (defun org-redisplay-inline-images ()
19144 "Refresh the display of inline images."
19145 (interactive)
19146 (if (not org-inline-image-overlays)
19147 (org-toggle-inline-images)
19148 (org-toggle-inline-images)
19149 (org-toggle-inline-images)))
19151 (defun org-display-inline-images (&optional include-linked refresh beg end)
19152 "Display inline images.
19154 An inline image is a link which follows either of these
19155 conventions:
19157 1. Its path is a file with an extension matching return value
19158 from `image-file-name-regexp' and it has no contents.
19160 2. Its description consists in a single link of the previous
19161 type.
19163 When optional argument INCLUDE-LINKED is non-nil, also links with
19164 a text description part will be inlined. This can be nice for
19165 a quick look at those images, but it does not reflect what
19166 exported files will look like.
19168 When optional argument REFRESH is non-nil, refresh existing
19169 images between BEG and END. This will create new image displays
19170 only if necessary. BEG and END default to the buffer
19171 boundaries."
19172 (interactive "P")
19173 (when (display-graphic-p)
19174 (unless refresh
19175 (org-remove-inline-images)
19176 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19177 (org-with-wide-buffer
19178 (goto-char (or beg (point-min)))
19179 (let ((case-fold-search t)
19180 (file-extension-re (org-image-file-name-regexp)))
19181 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19182 (let ((link (save-match-data (org-element-context))))
19183 ;; Check if we're at an inline image.
19184 (when (and (equal (org-element-property :type link) "file")
19185 (or include-linked
19186 (not (org-element-property :contents-begin link)))
19187 (let ((parent (org-element-property :parent link)))
19188 (or (not (eq (org-element-type parent) 'link))
19189 (not (cdr (org-element-contents parent)))))
19190 (org-string-match-p file-extension-re
19191 (org-element-property :path link)))
19192 (let ((file (expand-file-name (org-element-property :path link))))
19193 (when (file-exists-p file)
19194 (let ((width
19195 ;; Apply `org-image-actual-width' specifications.
19196 (cond
19197 ((not (image-type-available-p 'imagemagick)) nil)
19198 ((eq org-image-actual-width t) nil)
19199 ((listp org-image-actual-width)
19201 ;; First try to find a width among
19202 ;; attributes associated to the paragraph
19203 ;; containing link.
19204 (let ((paragraph
19205 (let ((e link))
19206 (while (and (setq e (org-element-property
19207 :parent e))
19208 (not (eq (org-element-type e)
19209 'paragraph))))
19210 e)))
19211 (when paragraph
19212 (save-excursion
19213 (goto-char (org-element-property :begin paragraph))
19214 (when
19215 (re-search-forward
19216 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19217 (org-element-property
19218 :post-affiliated paragraph)
19220 (string-to-number (match-string 1))))))
19221 ;; Otherwise, fall-back to provided number.
19222 (car org-image-actual-width)))
19223 ((numberp org-image-actual-width)
19224 org-image-actual-width)))
19225 (old (get-char-property-and-overlay
19226 (org-element-property :begin link)
19227 'org-image-overlay)))
19228 (if (and (car-safe old) refresh)
19229 (image-refresh (overlay-get (cdr old) 'display))
19230 (let ((image (create-image file
19231 (and width 'imagemagick)
19233 :width width)))
19234 (when image
19235 (let* ((link
19236 ;; If inline image is the description
19237 ;; of another link, be sure to
19238 ;; consider the latter as the one to
19239 ;; apply the overlay on.
19240 (let ((parent
19241 (org-element-property :parent link)))
19242 (if (eq (org-element-type parent) 'link)
19243 parent
19244 link)))
19245 (ov (make-overlay
19246 (org-element-property :begin link)
19247 (progn
19248 (goto-char
19249 (org-element-property :end link))
19250 (skip-chars-backward " \t")
19251 (point)))))
19252 (overlay-put ov 'display image)
19253 (overlay-put ov 'face 'default)
19254 (overlay-put ov 'org-image-overlay t)
19255 (overlay-put
19256 ov 'modification-hooks
19257 (list 'org-display-inline-remove-overlay))
19258 (push ov org-inline-image-overlays)))))))))))))))
19260 (define-obsolete-function-alias
19261 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19263 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19264 "Remove inline-display overlay if a corresponding region is modified."
19265 (let ((inhibit-modification-hooks t))
19266 (when (and ov after)
19267 (delete ov org-inline-image-overlays)
19268 (delete-overlay ov))))
19270 (defun org-remove-inline-images ()
19271 "Remove inline display of images."
19272 (interactive)
19273 (mapc 'delete-overlay org-inline-image-overlays)
19274 (setq org-inline-image-overlays nil))
19276 ;;;; Key bindings
19278 ;; Outline functions from `outline-mode-prefix-map'
19279 ;; that can be remapped in Org:
19280 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19281 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19282 (define-key org-mode-map [remap outline-forward-same-level]
19283 'org-forward-heading-same-level)
19284 (define-key org-mode-map [remap outline-backward-same-level]
19285 'org-backward-heading-same-level)
19286 (define-key org-mode-map [remap show-branches]
19287 'org-kill-note-or-show-branches)
19288 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19289 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19290 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19292 ;; Outline functions from `outline-mode-prefix-map' that can not
19293 ;; be remapped in Org:
19295 ;; - the column "key binding" shows whether the Outline function is still
19296 ;; available in Org mode on the same key that it has been bound to in
19297 ;; Outline mode:
19298 ;; - "overridden": key used for a different functionality in Org mode
19299 ;; - else: key still bound to the same Outline function in Org mode
19301 ;; | Outline function | key binding | Org replacement |
19302 ;; |------------------------------------+-------------+-----------------------|
19303 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19304 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19305 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19306 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19307 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19308 ;; | `show-entry' | overridden | no replacement |
19309 ;; | `show-children' | `C-c C-i' | visibility cycling |
19310 ;; | `show-branches' | `C-c C-k' | still same function |
19311 ;; | `show-subtree' | overridden | visibility cycling |
19312 ;; | `show-all' | overridden | no replacement |
19313 ;; | `hide-subtree' | overridden | visibility cycling |
19314 ;; | `hide-body' | overridden | no replacement |
19315 ;; | `hide-entry' | overridden | visibility cycling |
19316 ;; | `hide-leaves' | overridden | no replacement |
19317 ;; | `hide-sublevels' | overridden | no replacement |
19318 ;; | `hide-other' | overridden | no replacement |
19320 ;; Make `C-c C-x' a prefix key
19321 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19323 ;; TAB key with modifiers
19324 (org-defkey org-mode-map "\C-i" 'org-cycle)
19325 (org-defkey org-mode-map [(tab)] 'org-cycle)
19326 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19327 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19328 ;; The following line is necessary under Suse GNU/Linux
19329 (unless (featurep 'xemacs)
19330 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19331 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19332 (define-key org-mode-map [backtab] 'org-shifttab)
19334 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19335 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19336 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19338 ;; Cursor keys with modifiers
19339 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19340 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19341 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19342 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19344 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19345 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19346 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19347 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19348 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19349 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19351 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19352 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19353 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19354 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19356 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19357 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19358 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19359 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19361 ;; Babel keys
19362 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19363 (mapc (lambda (pair)
19364 (define-key org-babel-map (car pair) (cdr pair)))
19365 org-babel-key-bindings)
19367 ;;; Extra keys for tty access.
19368 ;; We only set them when really needed because otherwise the
19369 ;; menus don't show the simple keys
19371 (when (or org-use-extra-keys
19372 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19373 (not window-system))
19374 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19375 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19376 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19377 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19378 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19379 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19380 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19381 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19382 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19383 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19384 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19385 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19386 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19387 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19388 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19389 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19390 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19391 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19392 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19393 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19394 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19395 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19396 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19397 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19398 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19399 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19400 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19401 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19403 ;; All the other keys
19405 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19406 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19407 (if (boundp 'narrow-map)
19408 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19409 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19410 (if (boundp 'narrow-map)
19411 (org-defkey narrow-map "b" 'org-narrow-to-block)
19412 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19413 (if (boundp 'narrow-map)
19414 (org-defkey narrow-map "e" 'org-narrow-to-element)
19415 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19416 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19417 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19418 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19419 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19420 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19421 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19422 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19423 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19424 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19425 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19426 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19427 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19428 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19429 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19430 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19431 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19432 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19433 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19434 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19435 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19436 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19437 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19438 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19439 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19440 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19441 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19442 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19443 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19444 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19445 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19446 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19447 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19448 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19449 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19450 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19451 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19452 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19453 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19454 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19455 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19456 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19457 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19458 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19459 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19460 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19461 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19462 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19463 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19464 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19465 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19466 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19467 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19468 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19469 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19470 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19471 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19472 (org-defkey org-mode-map "\C-c^" 'org-sort)
19473 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19474 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19475 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19476 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19477 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19478 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19479 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19480 (org-defkey org-mode-map "\C-m" 'org-return)
19481 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19482 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19483 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19484 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19485 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19486 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19487 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19488 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19489 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19490 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19491 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19492 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19493 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19494 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19495 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19496 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19497 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19498 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19499 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19500 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19501 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19502 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19503 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19504 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19505 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19507 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19508 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19509 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19511 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19512 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19513 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19514 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19515 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19516 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19517 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19518 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19519 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19520 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19521 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19522 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19523 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19524 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19525 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19526 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19527 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19528 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19529 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19530 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19531 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19532 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19533 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19535 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19536 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19537 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19538 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19539 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19541 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19543 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19545 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19546 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19548 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19551 (when (featurep 'xemacs)
19552 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19555 (defconst org-speed-commands-default
19557 ("Outline Navigation")
19558 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19559 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19560 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19561 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19562 ("F" . org-next-block)
19563 ("B" . org-previous-block)
19564 ("u" . (org-speed-move-safe 'outline-up-heading))
19565 ("j" . org-goto)
19566 ("g" . (org-refile t))
19567 ("Outline Visibility")
19568 ("c" . org-cycle)
19569 ("C" . org-shifttab)
19570 (" " . org-display-outline-path)
19571 ("s" . org-narrow-to-subtree)
19572 ("=" . org-columns)
19573 ("Outline Structure Editing")
19574 ("U" . org-metaup)
19575 ("D" . org-metadown)
19576 ("r" . org-metaright)
19577 ("l" . org-metaleft)
19578 ("R" . org-shiftmetaright)
19579 ("L" . org-shiftmetaleft)
19580 ("i" . (progn (forward-char 1) (call-interactively
19581 'org-insert-heading-respect-content)))
19582 ("^" . org-sort)
19583 ("w" . org-refile)
19584 ("a" . org-archive-subtree-default-with-confirmation)
19585 ("@" . org-mark-subtree)
19586 ("#" . org-toggle-comment)
19587 ("Clock Commands")
19588 ("I" . org-clock-in)
19589 ("O" . org-clock-out)
19590 ("Meta Data Editing")
19591 ("t" . org-todo)
19592 ("," . (org-priority))
19593 ("0" . (org-priority ?\ ))
19594 ("1" . (org-priority ?A))
19595 ("2" . (org-priority ?B))
19596 ("3" . (org-priority ?C))
19597 (":" . org-set-tags-command)
19598 ("e" . org-set-effort)
19599 ("E" . org-inc-effort)
19600 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19601 (org-entry-put (point) "APPT_WARNTIME" m)))
19602 ("Agenda Views etc")
19603 ("v" . org-agenda)
19604 ("/" . org-sparse-tree)
19605 ("Misc")
19606 ("o" . org-open-at-point)
19607 ("?" . org-speed-command-help)
19608 ("<" . (org-agenda-set-restriction-lock 'subtree))
19609 (">" . (org-agenda-remove-restriction-lock))
19611 "The default speed commands.")
19613 (defun org-print-speed-command (e)
19614 (if (> (length (car e)) 1)
19615 (progn
19616 (princ "\n")
19617 (princ (car e))
19618 (princ "\n")
19619 (princ (make-string (length (car e)) ?-))
19620 (princ "\n"))
19621 (princ (car e))
19622 (princ " ")
19623 (if (symbolp (cdr e))
19624 (princ (symbol-name (cdr e)))
19625 (prin1 (cdr e)))
19626 (princ "\n")))
19628 (defun org-speed-command-help ()
19629 "Show the available speed commands."
19630 (interactive)
19631 (if (not org-use-speed-commands)
19632 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19633 (with-output-to-temp-buffer "*Help*"
19634 (princ "User-defined Speed commands\n===========================\n")
19635 (mapc 'org-print-speed-command org-speed-commands-user)
19636 (princ "\n")
19637 (princ "Built-in Speed commands\n=======================\n")
19638 (mapc 'org-print-speed-command org-speed-commands-default))
19639 (with-current-buffer "*Help*"
19640 (setq truncate-lines t))))
19642 (defun org-speed-move-safe (cmd)
19643 "Execute CMD, but make sure that the cursor always ends up in a headline.
19644 If not, return to the original position and throw an error."
19645 (interactive)
19646 (let ((pos (point)))
19647 (call-interactively cmd)
19648 (unless (and (bolp) (org-at-heading-p))
19649 (goto-char pos)
19650 (error "Boundary reached while executing %s" cmd))))
19652 (defvar org-self-insert-command-undo-counter 0)
19654 (defvar org-table-auto-blank-field) ; defined in org-table.el
19655 (defvar org-speed-command nil)
19657 (define-obsolete-function-alias
19658 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19660 (defun org-speed-command-activate (keys)
19661 "Hook for activating single-letter speed commands.
19662 `org-speed-commands-default' specifies a minimal command set.
19663 Use `org-speed-commands-user' for further customization."
19664 (when (or (and (bolp) (looking-at org-outline-regexp))
19665 (and (functionp org-use-speed-commands)
19666 (funcall org-use-speed-commands)))
19667 (cdr (assoc keys (append org-speed-commands-user
19668 org-speed-commands-default)))))
19670 (define-obsolete-function-alias
19671 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19673 (defun org-babel-speed-command-activate (keys)
19674 "Hook for activating single-letter code block commands."
19675 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19676 (cdr (assoc keys org-babel-key-bindings))))
19678 (defcustom org-speed-command-hook
19679 '(org-speed-command-default-hook org-babel-speed-command-hook)
19680 "Hook for activating speed commands at strategic locations.
19681 Hook functions are called in sequence until a valid handler is
19682 found.
19684 Each hook takes a single argument, a user-pressed command key
19685 which is also a `self-insert-command' from the global map.
19687 Within the hook, examine the cursor position and the command key
19688 and return nil or a valid handler as appropriate. Handler could
19689 be one of an interactive command, a function, or a form.
19691 Set `org-use-speed-commands' to non-nil value to enable this
19692 hook. The default setting is `org-speed-command-activate'."
19693 :group 'org-structure
19694 :version "24.1"
19695 :type 'hook)
19697 (defun org-self-insert-command (N)
19698 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19699 If the cursor is in a table looking at whitespace, the whitespace is
19700 overwritten, and the table is not marked as requiring realignment."
19701 (interactive "p")
19702 (org-check-before-invisible-edit 'insert)
19703 (cond
19704 ((and org-use-speed-commands
19705 (let ((kv (this-command-keys-vector)))
19706 (setq org-speed-command
19707 (run-hook-with-args-until-success
19708 'org-speed-command-hook
19709 (make-string 1 (aref kv (1- (length kv))))))))
19710 (cond
19711 ((commandp org-speed-command)
19712 (setq this-command org-speed-command)
19713 (call-interactively org-speed-command))
19714 ((functionp org-speed-command)
19715 (funcall org-speed-command))
19716 ((and org-speed-command (listp org-speed-command))
19717 (eval org-speed-command))
19718 (t (let (org-use-speed-commands)
19719 (call-interactively 'org-self-insert-command)))))
19720 ((and
19721 (org-table-p)
19722 (progn
19723 ;; check if we blank the field, and if that triggers align
19724 (and (featurep 'org-table) org-table-auto-blank-field
19725 (member last-command
19726 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas-expand))
19727 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19728 ;; got extra space, this field does not determine column width
19729 (let (org-table-may-need-update) (org-table-blank-field))
19730 ;; no extra space, this field may determine column width
19731 (org-table-blank-field)))
19733 (eq N 1)
19734 (looking-at "[^|\n]* |"))
19735 (let (org-table-may-need-update)
19736 (goto-char (1- (match-end 0)))
19737 (backward-delete-char 1)
19738 (goto-char (match-beginning 0))
19739 (self-insert-command N)))
19741 (setq org-table-may-need-update t)
19742 (self-insert-command N)
19743 (org-fix-tags-on-the-fly)
19744 (if org-self-insert-cluster-for-undo
19745 (if (not (eq last-command 'org-self-insert-command))
19746 (setq org-self-insert-command-undo-counter 1)
19747 (if (>= org-self-insert-command-undo-counter 20)
19748 (setq org-self-insert-command-undo-counter 1)
19749 (and (> org-self-insert-command-undo-counter 0)
19750 buffer-undo-list (listp buffer-undo-list)
19751 (not (cadr buffer-undo-list)) ; remove nil entry
19752 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19753 (setq org-self-insert-command-undo-counter
19754 (1+ org-self-insert-command-undo-counter))))))))
19756 (defun org-check-before-invisible-edit (kind)
19757 "Check is editing if kind KIND would be dangerous with invisible text around.
19758 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19759 ;; First, try to get out of here as quickly as possible, to reduce overhead
19760 (if (and org-catch-invisible-edits
19761 (or (not (boundp 'visible-mode)) (not visible-mode))
19762 (or (get-char-property (point) 'invisible)
19763 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19764 ;; OK, we need to take a closer look
19765 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19766 (invisible-before-point (if (bobp) nil (get-char-property
19767 (1- (point)) 'invisible)))
19768 (border-and-ok-direction
19770 ;; Check if we are acting predictably before invisible text
19771 (and invisible-at-point (not invisible-before-point)
19772 (memq kind '(insert delete-backward)))
19773 ;; Check if we are acting predictably after invisible text
19774 ;; This works not well, and I have turned it off. It seems
19775 ;; better to always show and stop after invisible text.
19776 ;; (and (not invisible-at-point) invisible-before-point
19777 ;; (memq kind '(insert delete)))
19779 (when (or (memq invisible-at-point '(outline org-hide-block t))
19780 (memq invisible-before-point '(outline org-hide-block t)))
19781 (if (eq org-catch-invisible-edits 'error)
19782 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19783 (if (and org-custom-properties-overlays
19784 (y-or-n-p "Display invisible properties in this buffer? "))
19785 (org-toggle-custom-properties-visibility)
19786 ;; Make the area visible
19787 (save-excursion
19788 (if invisible-before-point
19789 (goto-char (previous-single-char-property-change
19790 (point) 'invisible)))
19791 (show-subtree))
19792 (cond
19793 ((eq org-catch-invisible-edits 'show)
19794 ;; That's it, we do the edit after showing
19795 (message
19796 "Unfolding invisible region around point before editing")
19797 (sit-for 1))
19798 ((and (eq org-catch-invisible-edits 'smart)
19799 border-and-ok-direction)
19800 (message "Unfolding invisible region around point before editing"))
19802 ;; Don't do the edit, make the user repeat it in full visibility
19803 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19805 (defun org-fix-tags-on-the-fly ()
19806 (when (and (equal (char-after (point-at-bol)) ?*)
19807 (org-at-heading-p))
19808 (org-align-tags-here org-tags-column)))
19810 (defun org-delete-backward-char (N)
19811 "Like `delete-backward-char', insert whitespace at field end in tables.
19812 When deleting backwards, in tables this function will insert whitespace in
19813 front of the next \"|\" separator, to keep the table aligned. The table will
19814 still be marked for re-alignment if the field did fill the entire column,
19815 because, in this case the deletion might narrow the column."
19816 (interactive "p")
19817 (save-match-data
19818 (org-check-before-invisible-edit 'delete-backward)
19819 (if (and (org-table-p)
19820 (eq N 1)
19821 (string-match "|" (buffer-substring (point-at-bol) (point)))
19822 (looking-at ".*?|"))
19823 (let ((pos (point))
19824 (noalign (looking-at "[^|\n\r]* |"))
19825 (c org-table-may-need-update))
19826 (backward-delete-char N)
19827 (if (not overwrite-mode)
19828 (progn
19829 (skip-chars-forward "^|")
19830 (insert " ")
19831 (goto-char (1- pos))))
19832 ;; noalign: if there were two spaces at the end, this field
19833 ;; does not determine the width of the column.
19834 (if noalign (setq org-table-may-need-update c)))
19835 (backward-delete-char N)
19836 (org-fix-tags-on-the-fly))))
19838 (defun org-delete-char (N)
19839 "Like `delete-char', but insert whitespace at field end in tables.
19840 When deleting characters, in tables this function will insert whitespace in
19841 front of the next \"|\" separator, to keep the table aligned. The table will
19842 still be marked for re-alignment if the field did fill the entire column,
19843 because, in this case the deletion might narrow the column."
19844 (interactive "p")
19845 (save-match-data
19846 (org-check-before-invisible-edit 'delete)
19847 (if (and (org-table-p)
19848 (not (bolp))
19849 (not (= (char-after) ?|))
19850 (eq N 1))
19851 (if (looking-at ".*?|")
19852 (let ((pos (point))
19853 (noalign (looking-at "[^|\n\r]* |"))
19854 (c org-table-may-need-update))
19855 (replace-match
19856 (concat (substring (match-string 0) 1 -1) " |") nil t)
19857 (goto-char pos)
19858 ;; noalign: if there were two spaces at the end, this field
19859 ;; does not determine the width of the column.
19860 (if noalign (setq org-table-may-need-update c)))
19861 (delete-char N))
19862 (delete-char N)
19863 (org-fix-tags-on-the-fly))))
19865 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19866 (put 'org-self-insert-command 'delete-selection
19867 (lambda ()
19868 (not (run-hook-with-args-until-success
19869 'self-insert-uses-region-functions))))
19870 (put 'orgtbl-self-insert-command 'delete-selection
19871 (lambda ()
19872 (not (run-hook-with-args-until-success
19873 'self-insert-uses-region-functions))))
19874 (put 'org-delete-char 'delete-selection 'supersede)
19875 (put 'org-delete-backward-char 'delete-selection 'supersede)
19876 (put 'org-yank 'delete-selection 'yank)
19878 ;; Make `flyspell-mode' delay after some commands
19879 (put 'org-self-insert-command 'flyspell-delayed t)
19880 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19881 (put 'org-delete-char 'flyspell-delayed t)
19882 (put 'org-delete-backward-char 'flyspell-delayed t)
19884 ;; Make pabbrev-mode expand after org-mode commands
19885 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19886 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19888 (defun org-remap (map &rest commands)
19889 "In MAP, remap the functions given in COMMANDS.
19890 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19891 (let (new old)
19892 (while commands
19893 (setq old (pop commands) new (pop commands))
19894 (if (fboundp 'command-remapping)
19895 (org-defkey map (vector 'remap old) new)
19896 (substitute-key-definition old new map global-map)))))
19898 (defun org-transpose-words ()
19899 "Transpose words for Org.
19900 This uses the `org-mode-transpose-word-syntax-table' syntax
19901 table, which interprets characters in `org-emphasis-alist' as
19902 word constituents."
19903 (interactive)
19904 (with-syntax-table org-mode-transpose-word-syntax-table
19905 (call-interactively 'transpose-words)))
19906 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19908 (when (eq org-enable-table-editor 'optimized)
19909 ;; If the user wants maximum table support, we need to hijack
19910 ;; some standard editing functions
19911 (org-remap org-mode-map
19912 'self-insert-command 'org-self-insert-command
19913 'delete-char 'org-delete-char
19914 'delete-backward-char 'org-delete-backward-char)
19915 (org-defkey org-mode-map "|" 'org-force-self-insert))
19917 (defvar org-ctrl-c-ctrl-c-hook nil
19918 "Hook for functions attaching themselves to `C-c C-c'.
19920 This can be used to add additional functionality to the C-c C-c
19921 key which executes context-dependent commands. This hook is run
19922 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19923 run after the last test.
19925 Each function will be called with no arguments. The function
19926 must check if the context is appropriate for it to act. If yes,
19927 it should do its thing and then return a non-nil value. If the
19928 context is wrong, just do nothing and return nil.")
19930 (defvar org-ctrl-c-ctrl-c-final-hook nil
19931 "Hook for functions attaching themselves to `C-c C-c'.
19933 This can be used to add additional functionality to the C-c C-c
19934 key which executes context-dependent commands. This hook is run
19935 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19936 before the first test.
19938 Each function will be called with no arguments. The function
19939 must check if the context is appropriate for it to act. If yes,
19940 it should do its thing and then return a non-nil value. If the
19941 context is wrong, just do nothing and return nil.")
19943 (defvar org-tab-first-hook nil
19944 "Hook for functions to attach themselves to TAB.
19945 See `org-ctrl-c-ctrl-c-hook' for more information.
19946 This hook runs as the first action when TAB is pressed, even before
19947 `org-cycle' messes around with the `outline-regexp' to cater for
19948 inline tasks and plain list item folding.
19949 If any function in this hook returns t, any other actions that
19950 would have been caused by TAB (such as table field motion or visibility
19951 cycling) will not occur.")
19953 (defvar org-tab-after-check-for-table-hook nil
19954 "Hook for functions to attach themselves to TAB.
19955 See `org-ctrl-c-ctrl-c-hook' for more information.
19956 This hook runs after it has been established that the cursor is not in a
19957 table, but before checking if the cursor is in a headline or if global cycling
19958 should be done.
19959 If any function in this hook returns t, not other actions like visibility
19960 cycling will be done.")
19962 (defvar org-tab-after-check-for-cycling-hook nil
19963 "Hook for functions to attach themselves to TAB.
19964 See `org-ctrl-c-ctrl-c-hook' for more information.
19965 This hook runs after it has been established that not table field motion and
19966 not visibility should be done because of current context. This is probably
19967 the place where a package like yasnippets can hook in.")
19969 (defvar org-tab-before-tab-emulation-hook nil
19970 "Hook for functions to attach themselves to TAB.
19971 See `org-ctrl-c-ctrl-c-hook' for more information.
19972 This hook runs after every other options for TAB have been exhausted, but
19973 before indentation and \t insertion takes place.")
19975 (defvar org-metaleft-hook nil
19976 "Hook for functions attaching themselves to `M-left'.
19977 See `org-ctrl-c-ctrl-c-hook' for more information.")
19978 (defvar org-metaright-hook nil
19979 "Hook for functions attaching themselves to `M-right'.
19980 See `org-ctrl-c-ctrl-c-hook' for more information.")
19981 (defvar org-metaup-hook nil
19982 "Hook for functions attaching themselves to `M-up'.
19983 See `org-ctrl-c-ctrl-c-hook' for more information.")
19984 (defvar org-metadown-hook nil
19985 "Hook for functions attaching themselves to `M-down'.
19986 See `org-ctrl-c-ctrl-c-hook' for more information.")
19987 (defvar org-shiftmetaleft-hook nil
19988 "Hook for functions attaching themselves to `M-S-left'.
19989 See `org-ctrl-c-ctrl-c-hook' for more information.")
19990 (defvar org-shiftmetaright-hook nil
19991 "Hook for functions attaching themselves to `M-S-right'.
19992 See `org-ctrl-c-ctrl-c-hook' for more information.")
19993 (defvar org-shiftmetaup-hook nil
19994 "Hook for functions attaching themselves to `M-S-up'.
19995 See `org-ctrl-c-ctrl-c-hook' for more information.")
19996 (defvar org-shiftmetadown-hook nil
19997 "Hook for functions attaching themselves to `M-S-down'.
19998 See `org-ctrl-c-ctrl-c-hook' for more information.")
19999 (defvar org-metareturn-hook nil
20000 "Hook for functions attaching themselves to `M-RET'.
20001 See `org-ctrl-c-ctrl-c-hook' for more information.")
20002 (defvar org-shiftup-hook nil
20003 "Hook for functions attaching themselves to `S-up'.
20004 See `org-ctrl-c-ctrl-c-hook' for more information.")
20005 (defvar org-shiftup-final-hook nil
20006 "Hook for functions attaching themselves to `S-up'.
20007 This one runs after all other options except shift-select have been excluded.
20008 See `org-ctrl-c-ctrl-c-hook' for more information.")
20009 (defvar org-shiftdown-hook nil
20010 "Hook for functions attaching themselves to `S-down'.
20011 See `org-ctrl-c-ctrl-c-hook' for more information.")
20012 (defvar org-shiftdown-final-hook nil
20013 "Hook for functions attaching themselves to `S-down'.
20014 This one runs after all other options except shift-select have been excluded.
20015 See `org-ctrl-c-ctrl-c-hook' for more information.")
20016 (defvar org-shiftleft-hook nil
20017 "Hook for functions attaching themselves to `S-left'.
20018 See `org-ctrl-c-ctrl-c-hook' for more information.")
20019 (defvar org-shiftleft-final-hook nil
20020 "Hook for functions attaching themselves to `S-left'.
20021 This one runs after all other options except shift-select have been excluded.
20022 See `org-ctrl-c-ctrl-c-hook' for more information.")
20023 (defvar org-shiftright-hook nil
20024 "Hook for functions attaching themselves to `S-right'.
20025 See `org-ctrl-c-ctrl-c-hook' for more information.")
20026 (defvar org-shiftright-final-hook nil
20027 "Hook for functions attaching themselves to `S-right'.
20028 This one runs after all other options except shift-select have been excluded.
20029 See `org-ctrl-c-ctrl-c-hook' for more information.")
20031 (defun org-modifier-cursor-error ()
20032 "Throw an error, a modified cursor command was applied in wrong context."
20033 (user-error "This command is active in special context like tables, headlines or items"))
20035 (defun org-shiftselect-error ()
20036 "Throw an error because Shift-Cursor command was applied in wrong context."
20037 (if (and (boundp 'shift-select-mode) shift-select-mode)
20038 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20039 (user-error "This command works only in special context like headlines or timestamps")))
20041 (defun org-call-for-shift-select (cmd)
20042 (let ((this-command-keys-shift-translated t))
20043 (call-interactively cmd)))
20045 (defun org-shifttab (&optional arg)
20046 "Global visibility cycling or move to previous table field.
20047 Call `org-table-previous-field' within a table.
20048 When ARG is nil, cycle globally through visibility states.
20049 When ARG is a numeric prefix, show contents of this level."
20050 (interactive "P")
20051 (cond
20052 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20053 ((integerp arg)
20054 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20055 (message "Content view to level: %d" arg)
20056 (org-content (prefix-numeric-value arg2))
20057 (org-cycle-show-empty-lines t)
20058 (setq org-cycle-global-status 'overview)))
20059 (t (call-interactively 'org-global-cycle))))
20061 (defun org-shiftmetaleft ()
20062 "Promote subtree or delete table column.
20063 Calls `org-promote-subtree', `org-outdent-item-tree', or
20064 `org-table-delete-column', depending on context. See the
20065 individual commands for more information."
20066 (interactive)
20067 (cond
20068 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20069 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20070 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20071 ((if (not (org-region-active-p)) (org-at-item-p)
20072 (save-excursion (goto-char (region-beginning))
20073 (org-at-item-p)))
20074 (call-interactively 'org-outdent-item-tree))
20075 (t (org-modifier-cursor-error))))
20077 (defun org-shiftmetaright ()
20078 "Demote subtree or insert table column.
20079 Calls `org-demote-subtree', `org-indent-item-tree', or
20080 `org-table-insert-column', depending on context. See the
20081 individual commands for more information."
20082 (interactive)
20083 (cond
20084 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20085 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20086 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20087 ((if (not (org-region-active-p)) (org-at-item-p)
20088 (save-excursion (goto-char (region-beginning))
20089 (org-at-item-p)))
20090 (call-interactively 'org-indent-item-tree))
20091 (t (org-modifier-cursor-error))))
20093 (defun org-shiftmetaup (&optional arg)
20094 "Drag the line at point up.
20095 In a table, kill the current row.
20096 On a clock timestamp, update the value of the timestamp like `S-<up>'
20097 but also adjust the previous clocked item in the clock history.
20098 Everywhere else, drag the line at point up."
20099 (interactive "P")
20100 (cond
20101 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20102 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20103 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20104 (call-interactively 'org-timestamp-up)))
20105 (t (call-interactively 'org-drag-line-backward))))
20107 (defun org-shiftmetadown (&optional arg)
20108 "Drag the line at point down.
20109 In a table, insert an empty row at the current line.
20110 On a clock timestamp, update the value of the timestamp like `S-<down>'
20111 but also adjust the previous clocked item in the clock history.
20112 Everywhere else, drag the line at point down."
20113 (interactive "P")
20114 (cond
20115 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20116 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20117 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20118 (call-interactively 'org-timestamp-down)))
20119 (t (call-interactively 'org-drag-line-forward))))
20121 (defsubst org-hidden-tree-error ()
20122 (user-error
20123 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20125 (defun org-metaleft (&optional arg)
20126 "Promote heading or move table column to left.
20127 Calls `org-do-promote' or `org-table-move-column', depending on context.
20128 With no specific context, calls the Emacs default `backward-word'.
20129 See the individual commands for more information."
20130 (interactive "P")
20131 (cond
20132 ((run-hook-with-args-until-success 'org-metaleft-hook))
20133 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20134 ((org-with-limited-levels
20135 (or (org-at-heading-p)
20136 (and (org-region-active-p)
20137 (save-excursion
20138 (goto-char (region-beginning))
20139 (org-at-heading-p)))))
20140 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20141 (call-interactively 'org-do-promote))
20142 ;; At an inline task.
20143 ((org-at-heading-p)
20144 (call-interactively 'org-inlinetask-promote))
20145 ((or (org-at-item-p)
20146 (and (org-region-active-p)
20147 (save-excursion
20148 (goto-char (region-beginning))
20149 (org-at-item-p))))
20150 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20151 (call-interactively 'org-outdent-item))
20152 (t (call-interactively 'backward-word))))
20154 (defun org-metaright (&optional arg)
20155 "Demote a subtree, a list item or move table column to right.
20156 In front of a drawer or a block keyword, indent it correctly.
20157 With no specific context, calls the Emacs default `forward-word'.
20158 See the individual commands for more information."
20159 (interactive "P")
20160 (cond
20161 ((run-hook-with-args-until-success 'org-metaright-hook))
20162 ((org-at-table-p) (call-interactively 'org-table-move-column))
20163 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20164 ((org-at-block-p) (call-interactively 'org-indent-block))
20165 ((org-with-limited-levels
20166 (or (org-at-heading-p)
20167 (and (org-region-active-p)
20168 (save-excursion
20169 (goto-char (region-beginning))
20170 (org-at-heading-p)))))
20171 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20172 (call-interactively 'org-do-demote))
20173 ;; At an inline task.
20174 ((org-at-heading-p)
20175 (call-interactively 'org-inlinetask-demote))
20176 ((or (org-at-item-p)
20177 (and (org-region-active-p)
20178 (save-excursion
20179 (goto-char (region-beginning))
20180 (org-at-item-p))))
20181 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20182 (call-interactively 'org-indent-item))
20183 (t (call-interactively 'forward-word))))
20185 (defun org-check-for-hidden (what)
20186 "Check if there are hidden headlines/items in the current visual line.
20187 WHAT can be either `headlines' or `items'. If the current line is
20188 an outline or item heading and it has a folded subtree below it,
20189 this function returns t, nil otherwise."
20190 (let ((re (cond
20191 ((eq what 'headlines) org-outline-regexp-bol)
20192 ((eq what 'items) (org-item-beginning-re))
20193 (t (error "This should not happen"))))
20194 beg end)
20195 (save-excursion
20196 (catch 'exit
20197 (unless (org-region-active-p)
20198 (setq beg (point-at-bol))
20199 (beginning-of-line 2)
20200 (while (and (not (eobp)) ;; this is like `next-line'
20201 (get-char-property (1- (point)) 'invisible))
20202 (beginning-of-line 2))
20203 (setq end (point))
20204 (goto-char beg)
20205 (goto-char (point-at-eol))
20206 (setq end (max end (point)))
20207 (while (re-search-forward re end t)
20208 (if (get-char-property (match-beginning 0) 'invisible)
20209 (throw 'exit t))))
20210 nil))))
20212 (defun org-metaup (&optional arg)
20213 "Move subtree up or move table row up.
20214 Calls `org-move-subtree-up' or `org-table-move-row' or
20215 `org-move-item-up', depending on context. See the individual commands
20216 for more information."
20217 (interactive "P")
20218 (cond
20219 ((run-hook-with-args-until-success 'org-metaup-hook))
20220 ((org-region-active-p)
20221 (let* ((a (min (region-beginning) (region-end)))
20222 (b (1- (max (region-beginning) (region-end))))
20223 (c (save-excursion (goto-char a)
20224 (move-beginning-of-line 0)))
20225 (d (save-excursion (goto-char a)
20226 (move-end-of-line 0) (point))))
20227 (transpose-regions a b c d)
20228 (goto-char c)))
20229 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20230 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20231 ((org-at-item-p) (call-interactively 'org-move-item-up))
20232 (t (org-drag-element-backward))))
20234 (defun org-metadown (&optional arg)
20235 "Move subtree down or move table row down.
20236 Calls `org-move-subtree-down' or `org-table-move-row' or
20237 `org-move-item-down', depending on context. See the individual
20238 commands for more information."
20239 (interactive "P")
20240 (cond
20241 ((run-hook-with-args-until-success 'org-metadown-hook))
20242 ((org-region-active-p)
20243 (let* ((a (min (region-beginning) (region-end)))
20244 (b (max (region-beginning) (region-end)))
20245 (c (save-excursion (goto-char b)
20246 (move-beginning-of-line 1)))
20247 (d (save-excursion (goto-char b)
20248 (move-end-of-line 1) (1+ (point)))))
20249 (transpose-regions a b c d)
20250 (goto-char d)))
20251 ((org-at-table-p) (call-interactively 'org-table-move-row))
20252 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20253 ((org-at-item-p) (call-interactively 'org-move-item-down))
20254 (t (org-drag-element-forward))))
20256 (defun org-shiftup (&optional arg)
20257 "Increase item in timestamp or increase priority of current headline.
20258 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20259 depending on context. See the individual commands for more information."
20260 (interactive "P")
20261 (cond
20262 ((run-hook-with-args-until-success 'org-shiftup-hook))
20263 ((and org-support-shift-select (org-region-active-p))
20264 (org-call-for-shift-select 'previous-line))
20265 ((org-at-timestamp-p t)
20266 (call-interactively (if org-edit-timestamp-down-means-later
20267 'org-timestamp-down 'org-timestamp-up)))
20268 ((and (not (eq org-support-shift-select 'always))
20269 org-enable-priority-commands
20270 (org-at-heading-p))
20271 (call-interactively 'org-priority-up))
20272 ((and (not org-support-shift-select) (org-at-item-p))
20273 (call-interactively 'org-previous-item))
20274 ((org-clocktable-try-shift 'up arg))
20275 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20276 (org-support-shift-select
20277 (org-call-for-shift-select 'previous-line))
20278 (t (org-shiftselect-error))))
20280 (defun org-shiftdown (&optional arg)
20281 "Decrease item in timestamp or decrease priority of current headline.
20282 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20283 depending on context. See the individual commands for more information."
20284 (interactive "P")
20285 (cond
20286 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20287 ((and org-support-shift-select (org-region-active-p))
20288 (org-call-for-shift-select 'next-line))
20289 ((org-at-timestamp-p t)
20290 (call-interactively (if org-edit-timestamp-down-means-later
20291 'org-timestamp-up 'org-timestamp-down)))
20292 ((and (not (eq org-support-shift-select 'always))
20293 org-enable-priority-commands
20294 (org-at-heading-p))
20295 (call-interactively 'org-priority-down))
20296 ((and (not org-support-shift-select) (org-at-item-p))
20297 (call-interactively 'org-next-item))
20298 ((org-clocktable-try-shift 'down arg))
20299 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20300 (org-support-shift-select
20301 (org-call-for-shift-select 'next-line))
20302 (t (org-shiftselect-error))))
20304 (defun org-shiftright (&optional arg)
20305 "Cycle the thing at point or in the current line, depending on context.
20306 Depending on context, this does one of the following:
20308 - switch a timestamp at point one day into the future
20309 - on a headline, switch to the next TODO keyword.
20310 - on an item, switch entire list to the next bullet type
20311 - on a property line, switch to the next allowed value
20312 - on a clocktable definition line, move time block into the future"
20313 (interactive "P")
20314 (cond
20315 ((run-hook-with-args-until-success 'org-shiftright-hook))
20316 ((and org-support-shift-select (org-region-active-p))
20317 (org-call-for-shift-select 'forward-char))
20318 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20319 ((and (not (eq org-support-shift-select 'always))
20320 (org-at-heading-p))
20321 (let ((org-inhibit-logging
20322 (not org-treat-S-cursor-todo-selection-as-state-change))
20323 (org-inhibit-blocking
20324 (not org-treat-S-cursor-todo-selection-as-state-change)))
20325 (org-call-with-arg 'org-todo 'right)))
20326 ((or (and org-support-shift-select
20327 (not (eq org-support-shift-select 'always))
20328 (org-at-item-bullet-p))
20329 (and (not org-support-shift-select) (org-at-item-p)))
20330 (org-call-with-arg 'org-cycle-list-bullet nil))
20331 ((and (not (eq org-support-shift-select 'always))
20332 (org-at-property-p))
20333 (call-interactively 'org-property-next-allowed-value))
20334 ((org-clocktable-try-shift 'right arg))
20335 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20336 (org-support-shift-select
20337 (org-call-for-shift-select 'forward-char))
20338 (t (org-shiftselect-error))))
20340 (defun org-shiftleft (&optional arg)
20341 "Cycle the thing at point or in the current line, depending on context.
20342 Depending on context, this does one of the following:
20344 - switch a timestamp at point one day into the past
20345 - on a headline, switch to the previous TODO keyword.
20346 - on an item, switch entire list to the previous bullet type
20347 - on a property line, switch to the previous allowed value
20348 - on a clocktable definition line, move time block into the past"
20349 (interactive "P")
20350 (cond
20351 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20352 ((and org-support-shift-select (org-region-active-p))
20353 (org-call-for-shift-select 'backward-char))
20354 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20355 ((and (not (eq org-support-shift-select 'always))
20356 (org-at-heading-p))
20357 (let ((org-inhibit-logging
20358 (not org-treat-S-cursor-todo-selection-as-state-change))
20359 (org-inhibit-blocking
20360 (not org-treat-S-cursor-todo-selection-as-state-change)))
20361 (org-call-with-arg 'org-todo 'left)))
20362 ((or (and org-support-shift-select
20363 (not (eq org-support-shift-select 'always))
20364 (org-at-item-bullet-p))
20365 (and (not org-support-shift-select) (org-at-item-p)))
20366 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20367 ((and (not (eq org-support-shift-select 'always))
20368 (org-at-property-p))
20369 (call-interactively 'org-property-previous-allowed-value))
20370 ((org-clocktable-try-shift 'left arg))
20371 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20372 (org-support-shift-select
20373 (org-call-for-shift-select 'backward-char))
20374 (t (org-shiftselect-error))))
20376 (defun org-shiftcontrolright ()
20377 "Switch to next TODO set."
20378 (interactive)
20379 (cond
20380 ((and org-support-shift-select (org-region-active-p))
20381 (org-call-for-shift-select 'forward-word))
20382 ((and (not (eq org-support-shift-select 'always))
20383 (org-at-heading-p))
20384 (org-call-with-arg 'org-todo 'nextset))
20385 (org-support-shift-select
20386 (org-call-for-shift-select 'forward-word))
20387 (t (org-shiftselect-error))))
20389 (defun org-shiftcontrolleft ()
20390 "Switch to previous TODO set."
20391 (interactive)
20392 (cond
20393 ((and org-support-shift-select (org-region-active-p))
20394 (org-call-for-shift-select 'backward-word))
20395 ((and (not (eq org-support-shift-select 'always))
20396 (org-at-heading-p))
20397 (org-call-with-arg 'org-todo 'previousset))
20398 (org-support-shift-select
20399 (org-call-for-shift-select 'backward-word))
20400 (t (org-shiftselect-error))))
20402 (defun org-shiftcontrolup (&optional n)
20403 "Change timestamps synchronously up in CLOCK log lines.
20404 Optional argument N tells to change by that many units."
20405 (interactive "P")
20406 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20407 (let (org-support-shift-select)
20408 (org-clock-timestamps-up n))
20409 (user-error "Not at a clock log")))
20411 (defun org-shiftcontroldown (&optional n)
20412 "Change timestamps synchronously down in CLOCK log lines.
20413 Optional argument N tells to change by that many units."
20414 (interactive "P")
20415 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20416 (let (org-support-shift-select)
20417 (org-clock-timestamps-down n))
20418 (user-error "Not at a clock log")))
20420 (defun org-increase-number-at-point (&optional inc)
20421 "Increment the number at point.
20422 With an optional prefix numeric argument INC, increment using
20423 this numeric value."
20424 (interactive "p")
20425 (if (not (number-at-point))
20426 (user-error "Not on a number")
20427 (unless inc (setq inc 1))
20428 (let ((pos (point))
20429 (beg (skip-chars-backward "-+^/*0-9eE."))
20430 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20431 (setq nap (buffer-substring-no-properties
20432 (+ pos beg) (+ pos beg end)))
20433 (delete-region (+ pos beg) (+ pos beg end))
20434 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20435 (when (org-at-table-p)
20436 (org-table-align)
20437 (org-table-end-of-field 1))))
20439 (defun org-decrease-number-at-point (&optional inc)
20440 "Decrement the number at point.
20441 With an optional prefix numeric argument INC, decrement using
20442 this numeric value."
20443 (interactive "p")
20444 (org-increase-number-at-point (- inc)))
20446 (defun org-ctrl-c-ret ()
20447 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20448 (interactive)
20449 (cond
20450 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20451 (t (call-interactively 'org-insert-heading))))
20453 (defun org-find-visible ()
20454 (let ((s (point)))
20455 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20456 (get-char-property s 'invisible)))
20458 (defun org-find-invisible ()
20459 (let ((s (point)))
20460 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20461 (not (get-char-property s 'invisible))))
20464 (defun org-copy-visible (beg end)
20465 "Copy the visible parts of the region."
20466 (interactive "r")
20467 (let (snippets s)
20468 (save-excursion
20469 (save-restriction
20470 (narrow-to-region beg end)
20471 (setq s (goto-char (point-min)))
20472 (while (not (= (point) (point-max)))
20473 (goto-char (org-find-invisible))
20474 (push (buffer-substring s (point)) snippets)
20475 (setq s (goto-char (org-find-visible))))))
20476 (kill-new (apply 'concat (nreverse snippets)))))
20478 (defun org-copy-special ()
20479 "Copy region in table or copy current subtree.
20480 Calls `org-table-copy' or `org-copy-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-copy-region 'org-copy-subtree)))
20486 (defun org-cut-special ()
20487 "Cut region in table or cut current subtree.
20488 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20489 See the individual commands for more information."
20490 (interactive)
20491 (call-interactively
20492 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20494 (defun org-paste-special (arg)
20495 "Paste rectangular region into table, or past subtree relative to level.
20496 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20497 See the individual commands for more information."
20498 (interactive "P")
20499 (if (org-at-table-p)
20500 (org-table-paste-rectangle)
20501 (org-paste-subtree arg)))
20503 (defsubst org-in-fixed-width-region-p ()
20504 "Is point in a fixed-width region?"
20505 (save-match-data
20506 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20508 (defun org-edit-special (&optional arg)
20509 "Call a special editor for the element at point.
20510 When at a table, call the formula editor with `org-table-edit-formulas'.
20511 When in a source code block, call `org-edit-src-code'.
20512 When in a fixed-width region, call `org-edit-fixed-width-region'.
20513 When at an #+INCLUDE keyword, visit the included file.
20514 On a link, call `ffap' to visit the link at point.
20515 Otherwise, return a user error."
20516 (interactive "P")
20517 (let ((element (org-element-at-point)))
20518 (assert (not buffer-read-only) nil
20519 "Buffer is read-only: %s" (buffer-name))
20520 (case (org-element-type element)
20521 (src-block
20522 (if (not arg) (org-edit-src-code)
20523 (let* ((info (org-babel-get-src-block-info))
20524 (lang (nth 0 info))
20525 (params (nth 2 info))
20526 (session (cdr (assq :session params))))
20527 (if (not session) (org-edit-src-code)
20528 ;; At a src-block with a session and function called with
20529 ;; an ARG: switch to the buffer related to the inferior
20530 ;; process.
20531 (switch-to-buffer
20532 (funcall (intern (concat "org-babel-prep-session:" lang))
20533 session params))))))
20534 (keyword
20535 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20536 (org-open-link-from-string
20537 (format "[[%s]]"
20538 (expand-file-name
20539 (let ((value (org-element-property :value element)))
20540 (cond ((not (org-string-nw-p value))
20541 (user-error "No file to edit"))
20542 ((string-match "\\`\"\\(.*?\\)\"" value)
20543 (match-string 1 value))
20544 ((string-match "\\`[^ \t\"]\\S-*" value)
20545 (match-string 0 value))
20546 (t (user-error "No valid file specified")))))))
20547 (user-error "No special environment to edit here")))
20548 (table
20549 (if (eq (org-element-property :type element) 'table.el)
20550 (org-edit-src-code)
20551 (call-interactively 'org-table-edit-formulas)))
20552 ;; Only Org tables contain `table-row' type elements.
20553 (table-row (call-interactively 'org-table-edit-formulas))
20554 ((example-block export-block) (org-edit-src-code))
20555 (fixed-width (org-edit-fixed-width-region))
20556 (otherwise
20557 ;; No notable element at point. Though, we may be at a link,
20558 ;; which is an object. Thus, scan deeper.
20559 (if (eq (org-element-type (org-element-context element)) 'link)
20560 (call-interactively 'ffap)
20561 (user-error "No special environment to edit here"))))))
20563 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20564 (defun org-ctrl-c-ctrl-c (&optional arg)
20565 "Set tags in headline, or update according to changed information at point.
20567 This command does many different things, depending on context:
20569 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20570 this is what we do.
20572 - If the cursor is on a statistics cookie, update it.
20574 - If the cursor is in a headline, prompt for tags and insert them
20575 into the current line, aligned to `org-tags-column'. When called
20576 with prefix arg, realign all tags in the current buffer.
20578 - If the cursor is in one of the special #+KEYWORD lines, this
20579 triggers scanning the buffer for these lines and updating the
20580 information.
20582 - If the cursor is inside a table, realign the table. This command
20583 works even if the automatic table editor has been turned off.
20585 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20586 the entire table.
20588 - If the cursor is at a footnote reference or definition, jump to
20589 the corresponding definition or references, respectively.
20591 - If the cursor is a the beginning of a dynamic block, update it.
20593 - If the current buffer is a capture buffer, close note and file it.
20595 - If the cursor is on a <<<target>>>, update radio targets and
20596 corresponding links in this buffer.
20598 - If the cursor is on a numbered item in a plain list, renumber the
20599 ordered list.
20601 - If the cursor is on a checkbox, toggle it.
20603 - If the cursor is on a code block, evaluate it. The variable
20604 `org-confirm-babel-evaluate' can be used to control prompting
20605 before code block evaluation, by default every code block
20606 evaluation requires confirmation. Code block evaluation can be
20607 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20608 (interactive "P")
20609 (cond
20610 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20611 org-occur-highlights)
20612 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20613 (org-remove-occur-highlights)
20614 (message "Temporary highlights/overlays removed from current buffer"))
20615 ((and (local-variable-p 'org-finish-function (current-buffer))
20616 (fboundp org-finish-function))
20617 (funcall org-finish-function))
20618 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20620 (let* ((context (org-element-context)) (type (org-element-type context)))
20621 ;; Test if point is within a blank line.
20622 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20623 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20624 (user-error "C-c C-c can do nothing useful at this location"))
20625 (case type
20626 ;; When at a link, act according to the parent instead.
20627 (link (setq context (org-element-property :parent context))
20628 (setq type (org-element-type context)))
20629 ;; Unsupported object types: refer to the first supported
20630 ;; element or object containing it.
20631 ((bold code entity export-snippet inline-babel-call inline-src-block
20632 italic latex-fragment line-break macro strike-through subscript
20633 superscript underline verbatim)
20634 (while (and (setq context (org-element-property :parent context))
20635 (not (memq (setq type (org-element-type context))
20636 '(radio-target paragraph verse-block
20637 table-cell)))))))
20638 ;; For convenience: at the first line of a paragraph on the
20639 ;; same line as an item, apply function on that item instead.
20640 (when (eq type 'paragraph)
20641 (let ((parent (org-element-property :parent context)))
20642 (when (and (eq (org-element-type parent) 'item)
20643 (= (point-at-bol) (org-element-property :begin parent)))
20644 (setq context parent type 'item))))
20645 ;; Act according to type of element or object at point.
20646 (case type
20647 (clock (org-clock-update-time-maybe))
20648 (dynamic-block
20649 (save-excursion
20650 (goto-char (org-element-property :post-affiliated context))
20651 (org-update-dblock)))
20652 (footnote-definition
20653 (goto-char (org-element-property :post-affiliated context))
20654 (call-interactively 'org-footnote-action))
20655 (footnote-reference (call-interactively 'org-footnote-action))
20656 ((headline inlinetask)
20657 (save-excursion (goto-char (org-element-property :begin context))
20658 (call-interactively 'org-set-tags)))
20659 (item
20660 ;; At an item: a double C-u set checkbox to "[-]"
20661 ;; unconditionally, whereas a single one will toggle its
20662 ;; presence. Without an universal argument, if the item
20663 ;; has a checkbox, toggle it. Otherwise repair the list.
20664 (let* ((box (org-element-property :checkbox context))
20665 (struct (org-element-property :structure context))
20666 (old-struct (copy-tree struct))
20667 (parents (org-list-parents-alist struct))
20668 (prevs (org-list-prevs-alist struct))
20669 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20670 (org-list-set-checkbox
20671 (org-element-property :begin context) struct
20672 (cond ((equal arg '(16)) "[-]")
20673 ((and (not box) (equal arg '(4))) "[ ]")
20674 ((or (not box) (equal arg '(4))) nil)
20675 ((eq box 'on) "[ ]")
20676 (t "[X]")))
20677 ;; Mimic `org-list-write-struct' but with grabbing
20678 ;; a return value from `org-list-struct-fix-box'.
20679 (org-list-struct-fix-ind struct parents 2)
20680 (org-list-struct-fix-item-end struct)
20681 (org-list-struct-fix-bul struct prevs)
20682 (org-list-struct-fix-ind struct parents)
20683 (let ((block-item
20684 (org-list-struct-fix-box struct parents prevs orderedp)))
20685 (if (and box (equal struct old-struct))
20686 (if (equal arg '(16))
20687 (message "Checkboxes already reset")
20688 (user-error "Cannot toggle this checkbox: %s"
20689 (if (eq box 'on)
20690 "all subitems checked"
20691 "unchecked subitems")))
20692 (org-list-struct-apply-struct struct old-struct)
20693 (org-update-checkbox-count-maybe))
20694 (when block-item
20695 (message "Checkboxes were removed due to empty box at line %d"
20696 (org-current-line block-item))))))
20697 (keyword
20698 (let ((org-inhibit-startup-visibility-stuff t)
20699 (org-startup-align-all-tables nil))
20700 (when (boundp 'org-table-coordinate-overlays)
20701 (mapc 'delete-overlay org-table-coordinate-overlays)
20702 (setq org-table-coordinate-overlays nil))
20703 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20704 (message "Local setup has been refreshed"))
20705 (plain-list
20706 ;; At a plain list, with a double C-u argument, set
20707 ;; checkboxes of each item to "[-]", whereas a single one
20708 ;; will toggle their presence according to the state of the
20709 ;; first item in the list. Without an argument, repair the
20710 ;; list.
20711 (let* ((begin (org-element-property :contents-begin context))
20712 (beginm (move-marker (make-marker) begin))
20713 (struct (org-element-property :structure context))
20714 (old-struct (copy-tree struct))
20715 (first-box (save-excursion
20716 (goto-char begin)
20717 (looking-at org-list-full-item-re)
20718 (match-string-no-properties 3)))
20719 (new-box (cond ((equal arg '(16)) "[-]")
20720 ((equal arg '(4)) (unless first-box "[ ]"))
20721 ((equal first-box "[X]") "[ ]")
20722 (t "[X]"))))
20723 (cond
20724 (arg
20725 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20726 (org-list-get-all-items
20727 begin struct (org-list-prevs-alist struct))))
20728 ((and first-box (eq (point) begin))
20729 ;; For convenience, when point is at bol on the first
20730 ;; item of the list and no argument is provided, simply
20731 ;; toggle checkbox of that item, if any.
20732 (org-list-set-checkbox begin struct new-box)))
20733 (org-list-write-struct
20734 struct (org-list-parents-alist struct) old-struct)
20735 (org-update-checkbox-count-maybe)
20736 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20737 ((property-drawer node-property)
20738 (call-interactively 'org-property-action))
20739 ((radio-target target)
20740 (call-interactively 'org-update-radio-target-regexp))
20741 (statistics-cookie
20742 (call-interactively 'org-update-statistics-cookies))
20743 ((table table-cell table-row)
20744 ;; At a table, recalculate every field and align it. Also
20745 ;; send the table if necessary. If the table has
20746 ;; a `table.el' type, just give up. At a table row or
20747 ;; cell, maybe recalculate line but always align table.
20748 (if (eq (org-element-property :type context) 'table.el)
20749 (message "Use C-c ' to edit table.el tables")
20750 (let ((org-enable-table-editor t))
20751 (if (or (eq type 'table)
20752 ;; Check if point is at a TBLFM line.
20753 (and (eq type 'table-row)
20754 (= (point) (org-element-property :end context))))
20755 (save-excursion
20756 (if (org-at-TBLFM-p)
20757 (progn (require 'org-table)
20758 (org-table-calc-current-TBLFM))
20759 (goto-char (org-element-property :contents-begin context))
20760 (org-call-with-arg 'org-table-recalculate (or arg t))
20761 (orgtbl-send-table 'maybe)))
20762 (org-table-maybe-eval-formula)
20763 (cond (arg (call-interactively 'org-table-recalculate))
20764 ((org-table-maybe-recalculate-line))
20765 (t (org-table-align)))))))
20766 (timestamp (org-timestamp-change 0 'day))
20767 (otherwise
20768 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20769 (user-error
20770 "C-c C-c can do nothing useful at this location")))))))))
20772 (defun org-mode-restart ()
20773 (interactive)
20774 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20775 (funcall major-mode)
20776 (hack-local-variables)
20777 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20778 (org-indent-mode -1)))
20779 (message "%s restarted" major-mode))
20781 (defun org-kill-note-or-show-branches ()
20782 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20783 (interactive)
20784 (if (not org-finish-function)
20785 (progn
20786 (hide-subtree)
20787 (call-interactively 'show-branches))
20788 (let ((org-note-abort t))
20789 (funcall org-finish-function))))
20791 (defun org-open-line (n)
20792 "Insert a new row in tables, call `open-line' elsewhere.
20793 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20794 (interactive "*p")
20795 (cond
20796 ((not org-special-ctrl-o)
20797 (open-line n))
20798 ((org-at-table-p)
20799 (org-table-insert-row))
20801 (open-line n))))
20803 (defun org-return (&optional indent)
20804 "Goto next table row or insert a newline.
20805 Calls `org-table-next-row' or `newline', depending on context.
20806 See the individual commands for more information."
20807 (interactive)
20808 (let (org-ts-what)
20809 (cond
20810 ((or (bobp) (org-in-src-block-p))
20811 (if indent (newline-and-indent) (newline)))
20812 ((org-at-table-p)
20813 (org-table-justify-field-maybe)
20814 (call-interactively 'org-table-next-row))
20815 ;; when `newline-and-indent' is called within a list, make sure
20816 ;; text moved stays inside the item.
20817 ((and (org-in-item-p) indent)
20818 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20819 (progn
20820 (save-match-data (newline))
20821 (org-indent-line-to (length (match-string 0))))
20822 (let ((ind (org-get-indentation)))
20823 (newline)
20824 (if (org-looking-back org-list-end-re)
20825 (org-indent-line)
20826 (org-indent-line-to ind)))))
20827 ((and org-return-follows-link
20828 (org-at-timestamp-p t)
20829 (not (eq org-ts-what 'after)))
20830 (org-follow-timestamp-link))
20831 ((and org-return-follows-link
20832 (let ((tprop (get-text-property (point) 'face)))
20833 (or (eq tprop 'org-link)
20834 (and (listp tprop) (memq 'org-link tprop)))))
20835 (call-interactively 'org-open-at-point))
20836 ((and (org-at-heading-p)
20837 (looking-at
20838 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20839 (org-show-entry)
20840 (end-of-line 1)
20841 (newline))
20842 (t (if indent (newline-and-indent) (newline))))))
20844 (defun org-return-indent ()
20845 "Goto next table row or insert a newline and indent.
20846 Calls `org-table-next-row' or `newline-and-indent', depending on
20847 context. See the individual commands for more information."
20848 (interactive)
20849 (org-return t))
20851 (defun org-ctrl-c-star ()
20852 "Compute table, or change heading status of lines.
20853 Calls `org-table-recalculate' or `org-toggle-heading',
20854 depending on context."
20855 (interactive)
20856 (cond
20857 ((org-at-table-p)
20858 (call-interactively 'org-table-recalculate))
20860 ;; Convert all lines in region to list items
20861 (call-interactively 'org-toggle-heading))))
20863 (defun org-ctrl-c-minus ()
20864 "Insert separator line in table or modify bullet status of line.
20865 Also turns a plain line or a region of lines into list items.
20866 Calls `org-table-insert-hline', `org-toggle-item', or
20867 `org-cycle-list-bullet', depending on context."
20868 (interactive)
20869 (cond
20870 ((org-at-table-p)
20871 (call-interactively 'org-table-insert-hline))
20872 ((org-region-active-p)
20873 (call-interactively 'org-toggle-item))
20874 ((org-in-item-p)
20875 (call-interactively 'org-cycle-list-bullet))
20877 (call-interactively 'org-toggle-item))))
20879 (defun org-toggle-item (arg)
20880 "Convert headings or normal lines to items, items to normal lines.
20881 If there is no active region, only the current line is considered.
20883 If the first non blank line in the region is a headline, convert
20884 all headlines to items, shifting text accordingly.
20886 If it is an item, convert all items to normal lines.
20888 If it is normal text, change region into a list of items.
20889 With a prefix argument ARG, change the region in a single item."
20890 (interactive "P")
20891 (let ((shift-text
20892 (function
20893 ;; Shift text in current section to IND, from point to END.
20894 ;; The function leaves point to END line.
20895 (lambda (ind end)
20896 (let ((min-i 1000) (end (copy-marker end)))
20897 ;; First determine the minimum indentation (MIN-I) of
20898 ;; the text.
20899 (save-excursion
20900 (catch 'exit
20901 (while (< (point) end)
20902 (let ((i (org-get-indentation)))
20903 (cond
20904 ;; Skip blank lines and inline tasks.
20905 ((looking-at "^[ \t]*$"))
20906 ((looking-at org-outline-regexp-bol))
20907 ;; We can't find less than 0 indentation.
20908 ((zerop i) (throw 'exit (setq min-i 0)))
20909 ((< i min-i) (setq min-i i))))
20910 (forward-line))))
20911 ;; Then indent each line so that a line indented to
20912 ;; MIN-I becomes indented to IND. Ignore blank lines
20913 ;; and inline tasks in the process.
20914 (let ((delta (- ind min-i)))
20915 (while (< (point) end)
20916 (unless (or (looking-at "^[ \t]*$")
20917 (looking-at org-outline-regexp-bol))
20918 (org-indent-line-to (+ (org-get-indentation) delta)))
20919 (forward-line)))))))
20920 (skip-blanks
20921 (function
20922 ;; Return beginning of first non-blank line, starting from
20923 ;; line at POS.
20924 (lambda (pos)
20925 (save-excursion
20926 (goto-char pos)
20927 (skip-chars-forward " \r\t\n")
20928 (point-at-bol)))))
20929 beg end)
20930 ;; Determine boundaries of changes.
20931 (if (org-region-active-p)
20932 (setq beg (funcall skip-blanks (region-beginning))
20933 end (copy-marker (region-end)))
20934 (setq beg (funcall skip-blanks (point-at-bol))
20935 end (copy-marker (point-at-eol))))
20936 ;; Depending on the starting line, choose an action on the text
20937 ;; between BEG and END.
20938 (org-with-limited-levels
20939 (save-excursion
20940 (goto-char beg)
20941 (cond
20942 ;; Case 1. Start at an item: de-itemize. Note that it only
20943 ;; happens when a region is active: `org-ctrl-c-minus'
20944 ;; would call `org-cycle-list-bullet' otherwise.
20945 ((org-at-item-p)
20946 (while (< (point) end)
20947 (when (org-at-item-p)
20948 (skip-chars-forward " \t")
20949 (delete-region (point) (match-end 0)))
20950 (forward-line)))
20951 ;; Case 2. Start at an heading: convert to items.
20952 ((org-at-heading-p)
20953 (let* ((bul (org-list-bullet-string "-"))
20954 (bul-len (length bul))
20955 (done (org-entry-is-done-p))
20956 (todo (org-entry-is-todo-p))
20957 ;; Indentation of the first heading. It should be
20958 ;; relative to the indentation of its parent, if any.
20959 (start-ind (save-excursion
20960 (cond
20961 ((not org-adapt-indentation) 0)
20962 ((not (outline-previous-heading)) 0)
20963 (t (length (match-string 0))))))
20964 ;; Level of first heading. Further headings will be
20965 ;; compared to it to determine hierarchy in the list.
20966 (ref-level (org-reduced-level (org-outline-level))))
20967 (when (or done todo) (org-todo ""))
20968 (while (< (point) end)
20969 (let* ((level (org-reduced-level (org-outline-level)))
20970 (delta (max 0 (- level ref-level))))
20971 ;; If current headline is less indented than the first
20972 ;; one, set it as reference, in order to preserve
20973 ;; subtrees.
20974 (when (< level ref-level) (setq ref-level level))
20975 (replace-match bul t t)
20976 (org-indent-line-to (+ start-ind (* delta bul-len)))
20977 (when (or done todo)
20978 (let* ((struct (org-list-struct))
20979 (old (copy-tree struct)))
20980 (org-list-set-checkbox (line-beginning-position)
20981 struct
20982 (if done "[X]" "[ ]"))
20983 (org-list-write-struct struct
20984 (org-list-parents-alist struct)
20985 old)))
20986 ;; Ensure all text down to END (or SECTION-END) belongs
20987 ;; to the newly created item.
20988 (let ((section-end (save-excursion
20989 (or (outline-next-heading) (point)))))
20990 (forward-line)
20991 (funcall shift-text
20992 (+ start-ind (* (1+ delta) bul-len))
20993 (min end section-end)))))))
20994 ;; Case 3. Normal line with ARG: make the first line of region
20995 ;; an item, and shift indentation of others lines to
20996 ;; set them as item's body.
20997 (arg (let* ((bul (org-list-bullet-string "-"))
20998 (bul-len (length bul))
20999 (ref-ind (org-get-indentation)))
21000 (skip-chars-forward " \t")
21001 (insert bul)
21002 (forward-line)
21003 (while (< (point) end)
21004 ;; Ensure that lines less indented than first one
21005 ;; still get included in item body.
21006 (funcall shift-text
21007 (+ ref-ind bul-len)
21008 (min end (save-excursion (or (outline-next-heading)
21009 (point)))))
21010 (forward-line))))
21011 ;; Case 4. Normal line without ARG: turn each non-item line
21012 ;; into an item.
21014 (while (< (point) end)
21015 (unless (or (org-at-heading-p) (org-at-item-p))
21016 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21017 (replace-match
21018 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21019 (forward-line))))))))
21021 (defun org-toggle-heading (&optional nstars)
21022 "Convert headings to normal text, or items or text to headings.
21023 If there is no active region, only convert the current line.
21025 With a \\[universal-argument] prefix, convert the whole list at
21026 point into heading.
21028 In a region:
21030 - If the first non blank line is a headline, remove the stars
21031 from all headlines in the region.
21033 - If it is a normal line, turn each and every normal line (i.e.,
21034 not an heading or an item) in the region into headings. If you
21035 want to convert only the first line of this region, use one
21036 universal prefix argument.
21038 - If it is a plain list item, turn all plain list items into headings.
21040 When converting a line into a heading, the number of stars is chosen
21041 such that the lines become children of the current entry. However,
21042 when a numeric prefix argument is given, its value determines the
21043 number of stars to add."
21044 (interactive "P")
21045 (let ((skip-blanks
21046 (function
21047 ;; Return beginning of first non-blank line, starting from
21048 ;; line at POS.
21049 (lambda (pos)
21050 (save-excursion
21051 (goto-char pos)
21052 (while (org-at-comment-p) (forward-line))
21053 (skip-chars-forward " \r\t\n")
21054 (point-at-bol)))))
21055 beg end toggled)
21056 ;; Determine boundaries of changes. If a universal prefix has
21057 ;; been given, put the list in a region. If region ends at a bol,
21058 ;; do not consider the last line to be in the region.
21060 (when (and current-prefix-arg (org-at-item-p))
21061 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21062 (org-mark-element))
21064 (if (org-region-active-p)
21065 (setq beg (funcall skip-blanks (region-beginning))
21066 end (copy-marker (save-excursion
21067 (goto-char (region-end))
21068 (if (bolp) (point) (point-at-eol)))))
21069 (setq beg (funcall skip-blanks (point-at-bol))
21070 end (copy-marker (point-at-eol))))
21071 ;; Ensure inline tasks don't count as headings.
21072 (org-with-limited-levels
21073 (save-excursion
21074 (goto-char beg)
21075 (cond
21076 ;; Case 1. Started at an heading: de-star headings.
21077 ((org-at-heading-p)
21078 (while (< (point) end)
21079 (when (org-at-heading-p t)
21080 (looking-at org-outline-regexp) (replace-match "")
21081 (setq toggled t))
21082 (forward-line)))
21083 ;; Case 2. Started at an item: change items into headlines.
21084 ;; One star will be added by `org-list-to-subtree'.
21085 ((org-at-item-p)
21086 (let* ((stars (make-string
21087 ;; subtract the star that will be added again by
21088 ;; `org-list-to-subtree'
21089 (if (numberp nstars) (1- nstars)
21090 (or (org-current-level) 0))
21091 ?*))
21092 (add-stars
21093 (cond (nstars "") ; stars from prefix only
21094 ((equal stars "") "") ; before first heading
21095 (org-odd-levels-only "*") ; inside heading, odd
21096 (t "")))) ; inside heading, oddeven
21097 (while (< (point) end)
21098 (when (org-at-item-p)
21099 ;; Pay attention to cases when region ends before list.
21100 (let* ((struct (org-list-struct))
21101 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21102 (save-restriction
21103 (narrow-to-region (point) list-end)
21104 (insert
21105 (org-list-to-subtree
21106 (org-list-parse-list t)
21107 '(:istart (concat stars add-stars (funcall get-stars depth))
21108 :icount (concat stars add-stars (funcall get-stars depth)))))))
21109 (setq toggled t))
21110 (forward-line))))
21111 ;; Case 3. Started at normal text: make every line an heading,
21112 ;; skipping headlines and items.
21113 (t (let* ((stars
21114 (make-string
21115 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21116 (add-stars
21117 (cond (nstars "") ; stars from prefix only
21118 ((equal stars "") "*") ; before first heading
21119 (org-odd-levels-only "**") ; inside heading, odd
21120 (t "*"))) ; inside heading, oddeven
21121 (rpl (concat stars add-stars " "))
21122 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21123 (while (< (point) (if (equal nstars '(4)) lend end))
21124 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21125 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21126 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21127 (forward-line)))))))
21128 (unless toggled (message "Cannot toggle heading from here"))))
21130 (defun org-meta-return (&optional arg)
21131 "Insert a new heading or wrap a region in a table.
21132 Calls `org-insert-heading' or `org-table-wrap-region', depending
21133 on context. See the individual commands for more information."
21134 (interactive "P")
21135 (org-check-before-invisible-edit 'insert)
21136 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21137 (let* ((element (org-element-at-point))
21138 (type (org-element-type element)))
21139 (when (eq type 'table-row)
21140 (setq element (org-element-property :parent element))
21141 (setq type 'table))
21142 (if (and (eq type 'table)
21143 (eq (org-element-property :type element) 'org)
21144 (>= (point) (org-element-property :contents-begin element))
21145 (< (point) (org-element-property :contents-end element)))
21146 (call-interactively 'org-table-wrap-region)
21147 (call-interactively 'org-insert-heading)))))
21149 ;;; Menu entries
21151 (defsubst org-in-subtree-not-table-p ()
21152 "Are we in a subtree and not in a table?"
21153 (and (not (org-before-first-heading-p))
21154 (not (org-at-table-p))))
21156 ;; Define the Org-mode menus
21157 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21158 '("Tbl"
21159 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21160 ["Next Field" org-cycle (org-at-table-p)]
21161 ["Previous Field" org-shifttab (org-at-table-p)]
21162 ["Next Row" org-return (org-at-table-p)]
21163 "--"
21164 ["Blank Field" org-table-blank-field (org-at-table-p)]
21165 ["Edit Field" org-table-edit-field (org-at-table-p)]
21166 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21167 "--"
21168 ("Column"
21169 ["Move Column Left" org-metaleft (org-at-table-p)]
21170 ["Move Column Right" org-metaright (org-at-table-p)]
21171 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21172 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21173 ("Row"
21174 ["Move Row Up" org-metaup (org-at-table-p)]
21175 ["Move Row Down" org-metadown (org-at-table-p)]
21176 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21177 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21178 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21179 "--"
21180 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21181 ("Rectangle"
21182 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21183 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21184 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21185 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21186 "--"
21187 ("Calculate"
21188 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21189 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21190 ["Edit Formulas" org-edit-special (org-at-table-p)]
21191 "--"
21192 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21193 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21194 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21195 "--"
21196 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21197 "--"
21198 ["Sum Column/Rectangle" org-table-sum
21199 (or (org-at-table-p) (org-region-active-p))]
21200 ["Which Column?" org-table-current-column (org-at-table-p)])
21201 ["Debug Formulas"
21202 org-table-toggle-formula-debugger
21203 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21204 ["Show Col/Row Numbers"
21205 org-table-toggle-coordinate-overlays
21206 :style toggle
21207 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21208 "--"
21209 ["Create" org-table-create (and (not (org-at-table-p))
21210 org-enable-table-editor)]
21211 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21212 ["Import from File" org-table-import (not (org-at-table-p))]
21213 ["Export to File" org-table-export (org-at-table-p)]
21214 "--"
21215 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21216 "--"
21217 ("Plot"
21218 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21219 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21221 (easy-menu-define org-org-menu org-mode-map "Org menu"
21222 '("Org"
21223 ("Show/Hide"
21224 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21225 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21226 ["Sparse Tree..." org-sparse-tree t]
21227 ["Reveal Context" org-reveal t]
21228 ["Show All" show-all t]
21229 "--"
21230 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21231 "--"
21232 ["New Heading" org-insert-heading t]
21233 ("Navigate Headings"
21234 ["Up" outline-up-heading t]
21235 ["Next" outline-next-visible-heading t]
21236 ["Previous" outline-previous-visible-heading t]
21237 ["Next Same Level" outline-forward-same-level t]
21238 ["Previous Same Level" outline-backward-same-level t]
21239 "--"
21240 ["Jump" org-goto t])
21241 ("Edit Structure"
21242 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21243 "--"
21244 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21245 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21246 "--"
21247 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21248 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21249 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21250 "--"
21251 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21252 "--"
21253 ["Copy visible text" org-copy-visible t]
21254 "--"
21255 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21256 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21257 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21258 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21259 "--"
21260 ["Sort Region/Children" org-sort t]
21261 "--"
21262 ["Convert to odd levels" org-convert-to-odd-levels t]
21263 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21264 ("Editing"
21265 ["Emphasis..." org-emphasize t]
21266 ["Edit Source Example" org-edit-special t]
21267 "--"
21268 ["Footnote new/jump" org-footnote-action t]
21269 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21270 ("Archive"
21271 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21272 "--"
21273 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21274 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21275 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21277 "--"
21278 ("Hyperlinks"
21279 ["Store Link (Global)" org-store-link t]
21280 ["Find existing link to here" org-occur-link-in-agenda-files t]
21281 ["Insert Link" org-insert-link t]
21282 ["Follow Link" org-open-at-point t]
21283 "--"
21284 ["Next link" org-next-link t]
21285 ["Previous link" org-previous-link t]
21286 "--"
21287 ["Descriptive Links"
21288 org-toggle-link-display
21289 :style radio
21290 :selected org-descriptive-links
21292 ["Literal Links"
21293 org-toggle-link-display
21294 :style radio
21295 :selected (not org-descriptive-links)])
21296 "--"
21297 ("TODO Lists"
21298 ["TODO/DONE/-" org-todo t]
21299 ("Select keyword"
21300 ["Next keyword" org-shiftright (org-at-heading-p)]
21301 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21302 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21303 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21304 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21305 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21306 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21307 "--"
21308 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21309 :selected org-enforce-todo-dependencies :style toggle :active t]
21310 "Settings for tree at point"
21311 ["Do Children sequentially" org-toggle-ordered-property :style radio
21312 :selected (org-entry-get nil "ORDERED")
21313 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21314 ["Do Children parallel" org-toggle-ordered-property :style radio
21315 :selected (not (org-entry-get nil "ORDERED"))
21316 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21317 "--"
21318 ["Set Priority" org-priority t]
21319 ["Priority Up" org-shiftup t]
21320 ["Priority Down" org-shiftdown t]
21321 "--"
21322 ["Get news from all feeds" org-feed-update-all t]
21323 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21324 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21325 ("TAGS and Properties"
21326 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21327 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21328 "--"
21329 ["Set property" org-set-property (not (org-before-first-heading-p))]
21330 ["Column view of properties" org-columns t]
21331 ["Insert Column View DBlock" org-insert-columns-dblock t])
21332 ("Dates and Scheduling"
21333 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21334 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21335 ("Change Date"
21336 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21337 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21338 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21339 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21340 ["Compute Time Range" org-evaluate-time-range t]
21341 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21342 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21343 "--"
21344 ["Custom time format" org-toggle-time-stamp-overlays
21345 :style radio :selected org-display-custom-times]
21346 "--"
21347 ["Goto Calendar" org-goto-calendar t]
21348 ["Date from Calendar" org-date-from-calendar t]
21349 "--"
21350 ["Start/Restart Timer" org-timer-start t]
21351 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21352 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21353 ["Insert Timer String" org-timer t]
21354 ["Insert Timer Item" org-timer-item t])
21355 ("Logging work"
21356 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21357 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21358 ["Clock out" org-clock-out t]
21359 ["Clock cancel" org-clock-cancel t]
21360 "--"
21361 ["Mark as default task" org-clock-mark-default-task t]
21362 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21363 ["Goto running clock" org-clock-goto t]
21364 "--"
21365 ["Display times" org-clock-display t]
21366 ["Create clock table" org-clock-report t]
21367 "--"
21368 ["Record DONE time"
21369 (progn (setq org-log-done (not org-log-done))
21370 (message "Switching to %s will %s record a timestamp"
21371 (car org-done-keywords)
21372 (if org-log-done "automatically" "not")))
21373 :style toggle :selected org-log-done])
21374 "--"
21375 ["Agenda Command..." org-agenda t]
21376 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21377 ("File List for Agenda")
21378 ("Special views current file"
21379 ["TODO Tree" org-show-todo-tree t]
21380 ["Check Deadlines" org-check-deadlines t]
21381 ["Timeline" org-timeline t]
21382 ["Tags/Property tree" org-match-sparse-tree t])
21383 "--"
21384 ["Export/Publish..." org-export-dispatch t]
21385 ("LaTeX"
21386 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21387 :selected org-cdlatex-mode]
21388 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21389 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21390 ["Modify math symbol" org-cdlatex-math-modify
21391 (org-inside-LaTeX-fragment-p)]
21392 ["Insert citation" org-reftex-citation t]
21393 "--"
21394 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21395 "--"
21396 ("MobileOrg"
21397 ["Push Files and Views" org-mobile-push t]
21398 ["Get Captured and Flagged" org-mobile-pull t]
21399 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21400 "--"
21401 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21402 "--"
21403 ("Documentation"
21404 ["Show Version" org-version t]
21405 ["Info Documentation" org-info t])
21406 ("Customize"
21407 ["Browse Org Group" org-customize t]
21408 "--"
21409 ["Expand This Menu" org-create-customize-menu
21410 (fboundp 'customize-menu-create)])
21411 ["Send bug report" org-submit-bug-report t]
21412 "--"
21413 ("Refresh/Reload"
21414 ["Refresh setup current buffer" org-mode-restart t]
21415 ["Reload Org (after update)" org-reload t]
21416 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21419 (defun org-info (&optional node)
21420 "Read documentation for Org-mode in the info system.
21421 With optional NODE, go directly to that node."
21422 (interactive)
21423 (info (format "(org)%s" (or node ""))))
21425 ;;;###autoload
21426 (defun org-submit-bug-report ()
21427 "Submit a bug report on Org-mode via mail.
21429 Don't hesitate to report any problems or inaccurate documentation.
21431 If you don't have setup sending mail from (X)Emacs, please copy the
21432 output buffer into your mail program, as it gives us important
21433 information about your Org-mode version and configuration."
21434 (interactive)
21435 (require 'reporter)
21436 (org-load-modules-maybe)
21437 (org-require-autoloaded-modules)
21438 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21439 (reporter-submit-bug-report
21440 "emacs-orgmode@gnu.org"
21441 (org-version nil 'full)
21442 (let (list)
21443 (save-window-excursion
21444 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21445 (delete-other-windows)
21446 (erase-buffer)
21447 (insert "You are about to submit a bug report to the Org-mode mailing list.
21449 We would like to add your full Org-mode and Outline configuration to the
21450 bug report. This greatly simplifies the work of the maintainer and
21451 other experts on the mailing list.
21453 HOWEVER, some variables you have customized may contain private
21454 information. The names of customers, colleagues, or friends, might
21455 appear in the form of file names, tags, todo states, or search strings.
21456 If you answer yes to the prompt, you might want to check and remove
21457 such private information before sending the email.")
21458 (add-text-properties (point-min) (point-max) '(face org-warning))
21459 (when (yes-or-no-p "Include your Org-mode configuration ")
21460 (mapatoms
21461 (lambda (v)
21462 (and (boundp v)
21463 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21464 (or (and (symbol-value v)
21465 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21466 (and
21467 (get v 'custom-type) (get v 'standard-value)
21468 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21469 (push v list)))))
21470 (kill-buffer (get-buffer "*Warn about privacy*"))
21471 list))
21472 nil nil
21473 "Remember to cover the basics, that is, what you expected to happen and
21474 what in fact did happen. You don't know how to make a good report? See
21476 http://orgmode.org/manual/Feedback.html#Feedback
21478 Your bug report will be posted to the Org-mode mailing list.
21479 ------------------------------------------------------------------------")
21480 (save-excursion
21481 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21482 (replace-match "\\1Bug: \\3 [\\2]")))))
21485 (defun org-install-agenda-files-menu ()
21486 (let ((bl (buffer-list)))
21487 (save-excursion
21488 (while bl
21489 (set-buffer (pop bl))
21490 (if (derived-mode-p 'org-mode) (setq bl nil)))
21491 (when (derived-mode-p 'org-mode)
21492 (easy-menu-change
21493 '("Org") "File List for Agenda"
21494 (append
21495 (list
21496 ["Edit File List" (org-edit-agenda-file-list) t]
21497 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21498 ["Remove Current File from List" org-remove-file t]
21499 ["Cycle through agenda files" org-cycle-agenda-files t]
21500 ["Occur in all agenda files" org-occur-in-agenda-files t]
21501 "--")
21502 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21504 ;;;; Documentation
21506 (defun org-require-autoloaded-modules ()
21507 (interactive)
21508 (mapc 'require
21509 '(org-agenda org-archive org-attach org-clock org-colview org-id
21510 org-table org-timer)))
21512 ;;;###autoload
21513 (defun org-reload (&optional uncompiled)
21514 "Reload all org lisp files.
21515 With prefix arg UNCOMPILED, load the uncompiled versions."
21516 (interactive "P")
21517 (require 'loadhist)
21518 (let* ((org-dir (org-find-library-dir "org"))
21519 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21520 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21521 (remove-re (mapconcat 'identity
21522 (mapcar (lambda (f) (concat "^" f "$"))
21523 (list (if (featurep 'xemacs)
21524 "org-colview"
21525 "org-colview-xemacs")
21526 "org" "org-loaddefs" "org-version"))
21527 "\\|"))
21528 (feats (delete-dups
21529 (mapcar 'file-name-sans-extension
21530 (mapcar 'file-name-nondirectory
21531 (delq nil
21532 (mapcar 'feature-file
21533 features))))))
21534 (lfeat (append
21535 (sort
21536 (setq feats
21537 (delq nil (mapcar
21538 (lambda (f)
21539 (if (and (string-match feature-re f)
21540 (not (string-match remove-re f)))
21541 f nil))
21542 feats)))
21543 'string-lessp)
21544 (list "org-version" "org")))
21545 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21546 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21547 load-uncore load-misses)
21548 (setq load-misses
21549 (delq 't
21550 (mapcar (lambda (f)
21551 (or (org-load-noerror-mustsuffix (concat org-dir f))
21552 (and (string= org-dir contrib-dir)
21553 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21554 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21555 (add-to-list 'load-uncore f 'append)
21558 lfeat)))
21559 (if load-uncore
21560 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21561 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21562 (if load-misses
21563 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21564 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21565 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21567 ;;;###autoload
21568 (defun org-customize ()
21569 "Call the customize function with org as argument."
21570 (interactive)
21571 (org-load-modules-maybe)
21572 (org-require-autoloaded-modules)
21573 (customize-browse 'org))
21575 (defun org-create-customize-menu ()
21576 "Create a full customization menu for Org-mode, insert it into the menu."
21577 (interactive)
21578 (org-load-modules-maybe)
21579 (org-require-autoloaded-modules)
21580 (if (fboundp 'customize-menu-create)
21581 (progn
21582 (easy-menu-change
21583 '("Org") "Customize"
21584 `(["Browse Org group" org-customize t]
21585 "--"
21586 ,(customize-menu-create 'org)
21587 ["Set" Custom-set t]
21588 ["Save" Custom-save t]
21589 ["Reset to Current" Custom-reset-current t]
21590 ["Reset to Saved" Custom-reset-saved t]
21591 ["Reset to Standard Settings" Custom-reset-standard t]))
21592 (message "\"Org\"-menu now contains full customization menu"))
21593 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21595 ;;;; Miscellaneous stuff
21597 ;;; Generally useful functions
21599 (defsubst org-get-at-eol (property n)
21600 "Get text property PROPERTY at the end of line less N characters."
21601 (get-text-property (- (point-at-eol) n) property))
21603 (defun org-find-text-property-in-string (prop s)
21604 "Return the first non-nil value of property PROP in string S."
21605 (or (get-text-property 0 prop s)
21606 (get-text-property (or (next-single-property-change 0 prop s) 0)
21607 prop s)))
21609 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21610 "Display the given MESSAGE as a warning."
21611 (if (fboundp 'display-warning)
21612 (display-warning 'org message
21613 (if (featurep 'xemacs) 'warning :warning))
21614 (let ((buf (get-buffer-create "*Org warnings*")))
21615 (with-current-buffer buf
21616 (goto-char (point-max))
21617 (insert "Warning (Org): " message)
21618 (unless (bolp)
21619 (newline)))
21620 (display-buffer buf)
21621 (sit-for 0))))
21623 (defun org-eval (form)
21624 "Eval FORM and return result."
21625 (condition-case error
21626 (eval form)
21627 (error (format "%%![Error: %s]" error))))
21629 (defun org-in-clocktable-p ()
21630 "Check if the cursor is in a clocktable."
21631 (let ((pos (point)) start)
21632 (save-excursion
21633 (end-of-line 1)
21634 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21635 (setq start (match-beginning 0))
21636 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21637 (>= (match-end 0) pos)
21638 start))))
21640 (defun org-in-verbatim-emphasis ()
21641 (save-match-data
21642 (and (org-in-regexp org-emph-re 2)
21643 (>= (point) (match-beginning 3))
21644 (<= (point) (match-end 4))
21645 (member (match-string 3) '("=" "~")))))
21647 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21648 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21649 (if (and marker (marker-buffer marker)
21650 (buffer-live-p (marker-buffer marker)))
21651 (progn
21652 (org-pop-to-buffer-same-window (marker-buffer marker))
21653 (if (or (> marker (point-max)) (< marker (point-min)))
21654 (widen))
21655 (goto-char marker)
21656 (org-show-context 'org-goto))
21657 (if bookmark
21658 (bookmark-jump bookmark)
21659 (error "Cannot find location"))))
21661 (defun org-quote-csv-field (s)
21662 "Quote field for inclusion in CSV material."
21663 (if (string-match "[\",]" s)
21664 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21667 (defun org-force-self-insert (N)
21668 "Needed to enforce self-insert under remapping."
21669 (interactive "p")
21670 (self-insert-command N))
21672 (defun org-string-width (s)
21673 "Compute width of string, ignoring invisible characters.
21674 This ignores character with invisibility property `org-link', and also
21675 characters with property `org-cwidth', because these will become invisible
21676 upon the next fontification round."
21677 (let (b l)
21678 (when (or (eq t buffer-invisibility-spec)
21679 (assq 'org-link buffer-invisibility-spec))
21680 (while (setq b (text-property-any 0 (length s)
21681 'invisible 'org-link s))
21682 (setq s (concat (substring s 0 b)
21683 (substring s (or (next-single-property-change
21684 b 'invisible s) (length s)))))))
21685 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21686 (setq s (concat (substring s 0 b)
21687 (substring s (or (next-single-property-change
21688 b 'org-cwidth s) (length s))))))
21689 (setq l (string-width s) b -1)
21690 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21691 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21694 (defun org-shorten-string (s maxlength)
21695 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21696 If the string is shorter or has length MAXLENGTH, just return the
21697 original string. If it is longer, the functions finds a space in the
21698 string, breaks this string off at that locations and adds three dots
21699 as ellipsis. Including the ellipsis, the string will not be longer
21700 than MAXLENGTH. If finding a good breaking point in the string does
21701 not work, the string is just chopped off in the middle of a word
21702 if necessary."
21703 (if (<= (length s) maxlength)
21705 (let* ((n (max (- maxlength 4) 1))
21706 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21707 (if (string-match re s)
21708 (concat (match-string 1 s) "...")
21709 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21711 (defun org-get-indentation (&optional line)
21712 "Get the indentation of the current line, interpreting tabs.
21713 When LINE is given, assume it represents a line and compute its indentation."
21714 (if line
21715 (if (string-match "^ *" (org-remove-tabs line))
21716 (match-end 0))
21717 (save-excursion
21718 (beginning-of-line 1)
21719 (skip-chars-forward " \t")
21720 (current-column))))
21722 (defun org-get-string-indentation (s)
21723 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21724 (let ((n -1) (i 0) (w tab-width) c)
21725 (catch 'exit
21726 (while (< (setq n (1+ n)) (length s))
21727 (setq c (aref s n))
21728 (cond ((= c ?\ ) (setq i (1+ i)))
21729 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21730 (t (throw 'exit t)))))
21733 (defun org-remove-tabs (s &optional width)
21734 "Replace tabulators in S with spaces.
21735 Assumes that s is a single line, starting in column 0."
21736 (setq width (or width tab-width))
21737 (while (string-match "\t" s)
21738 (setq s (replace-match
21739 (make-string
21740 (- (* width (/ (+ (match-beginning 0) width) width))
21741 (match-beginning 0)) ?\ )
21742 t t s)))
21745 (defun org-fix-indentation (line ind)
21746 "Fix indentation in LINE.
21747 IND is a cons cell with target and minimum indentation.
21748 If the current indentation in LINE is smaller than the minimum,
21749 leave it alone. If it is larger than ind, set it to the target."
21750 (let* ((l (org-remove-tabs line))
21751 (i (org-get-indentation l))
21752 (i1 (car ind)) (i2 (cdr ind)))
21753 (if (>= i i2) (setq l (substring line i2)))
21754 (if (> i1 0)
21755 (concat (make-string i1 ?\ ) l)
21756 l)))
21758 (defun org-remove-indentation (code &optional n)
21759 "Remove the maximum common indentation from the lines in CODE.
21760 N may optionally be the number of spaces to remove."
21761 (with-temp-buffer
21762 (insert code)
21763 (org-do-remove-indentation n)
21764 (buffer-string)))
21766 (defun org-do-remove-indentation (&optional n)
21767 "Remove the maximum common indentation from the buffer."
21768 (untabify (point-min) (point-max))
21769 (let ((min 10000) re)
21770 (if n
21771 (setq min n)
21772 (goto-char (point-min))
21773 (while (re-search-forward "^ *[^ \n]" nil t)
21774 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21775 (unless (or (= min 0) (= min 10000))
21776 (setq re (format "^ \\{%d\\}" min))
21777 (goto-char (point-min))
21778 (while (re-search-forward re nil t)
21779 (replace-match "")
21780 (end-of-line 1))
21781 min)))
21783 (defun org-fill-template (template alist)
21784 "Find each %key of ALIST in TEMPLATE and replace it."
21785 (let ((case-fold-search nil)
21786 entry key value)
21787 (setq alist (sort (copy-sequence alist)
21788 (lambda (a b) (< (length (car a)) (length (car b))))))
21789 (while (setq entry (pop alist))
21790 (setq template
21791 (replace-regexp-in-string
21792 (concat "%" (regexp-quote (car entry)))
21793 (or (cdr entry) "") template t t)))
21794 template))
21796 (defun org-base-buffer (buffer)
21797 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21798 (if (not buffer)
21799 buffer
21800 (or (buffer-base-buffer buffer)
21801 buffer)))
21803 (defun org-wrap (string &optional width lines)
21804 "Wrap string to either a number of lines, or a width in characters.
21805 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21806 that costs. If there is a word longer than WIDTH, the text is actually
21807 wrapped to the length of that word.
21808 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21809 many lines, whatever width that takes.
21810 The return value is a list of lines, without newlines at the end."
21811 (let* ((words (org-split-string string "[ \t\n]+"))
21812 (maxword (apply 'max (mapcar 'org-string-width words)))
21813 w ll)
21814 (cond (width
21815 (org-do-wrap words (max maxword width)))
21816 (lines
21817 (setq w maxword)
21818 (setq ll (org-do-wrap words maxword))
21819 (if (<= (length ll) lines)
21821 (setq ll words)
21822 (while (> (length ll) lines)
21823 (setq w (1+ w))
21824 (setq ll (org-do-wrap words w)))
21825 ll))
21826 (t (error "Cannot wrap this")))))
21828 (defun org-do-wrap (words width)
21829 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21830 (let (lines line)
21831 (while words
21832 (setq line (pop words))
21833 (while (and words (< (+ (length line) (length (car words))) width))
21834 (setq line (concat line " " (pop words))))
21835 (setq lines (push line lines)))
21836 (nreverse lines)))
21838 (defun org-split-string (string &optional separators)
21839 "Splits STRING into substrings at SEPARATORS.
21840 No empty strings are returned if there are matches at the beginning
21841 and end of string."
21842 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21843 (start 0)
21844 notfirst
21845 (list nil))
21846 (while (and (string-match rexp string
21847 (if (and notfirst
21848 (= start (match-beginning 0))
21849 (< start (length string)))
21850 (1+ start) start))
21851 (< (match-beginning 0) (length string)))
21852 (setq notfirst t)
21853 (or (eq (match-beginning 0) 0)
21854 (and (eq (match-beginning 0) (match-end 0))
21855 (eq (match-beginning 0) start))
21856 (setq list
21857 (cons (substring string start (match-beginning 0))
21858 list)))
21859 (setq start (match-end 0)))
21860 (or (eq start (length string))
21861 (setq list
21862 (cons (substring string start)
21863 list)))
21864 (nreverse list)))
21866 (defun org-quote-vert (s)
21867 "Replace \"|\" with \"\\vert\"."
21868 (while (string-match "|" s)
21869 (setq s (replace-match "\\vert" t t s)))
21872 (defun org-uuidgen-p (s)
21873 "Is S an ID created by UUIDGEN?"
21874 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21876 (defun org-in-src-block-p (&optional inside)
21877 "Whether point is in a code source block.
21878 When INSIDE is non-nil, don't consider we are within a src block
21879 when point is at #+BEGIN_SRC or #+END_SRC."
21880 (let ((case-fold-search t) ov)
21881 (or (and (eq (get-char-property (point) 'src-block) t))
21882 (and (not inside)
21883 (save-match-data
21884 (save-excursion
21885 (beginning-of-line)
21886 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21888 (defun org-context ()
21889 "Return a list of contexts of the current cursor position.
21890 If several contexts apply, all are returned.
21891 Each context entry is a list with a symbol naming the context, and
21892 two positions indicating start and end of the context. Possible
21893 contexts are:
21895 :headline anywhere in a headline
21896 :headline-stars on the leading stars in a headline
21897 :todo-keyword on a TODO keyword (including DONE) in a headline
21898 :tags on the TAGS in a headline
21899 :priority on the priority cookie in a headline
21900 :item on the first line of a plain list item
21901 :item-bullet on the bullet/number of a plain list item
21902 :checkbox on the checkbox in a plain list item
21903 :table in an org-mode table
21904 :table-special on a special filed in a table
21905 :table-table in a table.el table
21906 :clocktable in a clocktable
21907 :src-block in a source block
21908 :link on a hyperlink
21909 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21910 :target on a <<target>>
21911 :radio-target on a <<<radio-target>>>
21912 :latex-fragment on a LaTeX fragment
21913 :latex-preview on a LaTeX fragment with overlaid preview image
21915 This function expects the position to be visible because it uses font-lock
21916 faces as a help to recognize the following contexts: :table-special, :link,
21917 and :keyword."
21918 (let* ((f (get-text-property (point) 'face))
21919 (faces (if (listp f) f (list f)))
21920 (case-fold-search t)
21921 (p (point)) clist o)
21922 ;; First the large context
21923 (cond
21924 ((org-at-heading-p t)
21925 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21926 (when (progn
21927 (beginning-of-line 1)
21928 (looking-at org-todo-line-tags-regexp))
21929 (push (org-point-in-group p 1 :headline-stars) clist)
21930 (push (org-point-in-group p 2 :todo-keyword) clist)
21931 (push (org-point-in-group p 4 :tags) clist))
21932 (goto-char p)
21933 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21934 (if (looking-at "\\[#[A-Z0-9]\\]")
21935 (push (org-point-in-group p 0 :priority) clist)))
21937 ((org-at-item-p)
21938 (push (org-point-in-group p 2 :item-bullet) clist)
21939 (push (list :item (point-at-bol)
21940 (save-excursion (org-end-of-item) (point)))
21941 clist)
21942 (and (org-at-item-checkbox-p)
21943 (push (org-point-in-group p 0 :checkbox) clist)))
21945 ((org-at-table-p)
21946 (push (list :table (org-table-begin) (org-table-end)) clist)
21947 (if (memq 'org-formula faces)
21948 (push (list :table-special
21949 (previous-single-property-change p 'face)
21950 (next-single-property-change p 'face)) clist)))
21951 ((org-at-table-p 'any)
21952 (push (list :table-table) clist)))
21953 (goto-char p)
21955 (let ((case-fold-search t))
21956 ;; New the "medium" contexts: clocktables, source blocks
21957 (cond ((org-in-clocktable-p)
21958 (push (list :clocktable
21959 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21960 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21961 (match-beginning 1))
21962 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21963 (match-end 0))) clist))
21964 ((org-in-src-block-p)
21965 (push (list :src-block
21966 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21967 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21968 (match-beginning 1))
21969 (and (search-forward "#+END_SRC" nil t)
21970 (match-beginning 0))) clist))))
21971 (goto-char p)
21973 ;; Now the small context
21974 (cond
21975 ((org-at-timestamp-p)
21976 (push (org-point-in-group p 0 :timestamp) clist))
21977 ((memq 'org-link faces)
21978 (push (list :link
21979 (previous-single-property-change p 'face)
21980 (next-single-property-change p 'face)) clist))
21981 ((memq 'org-special-keyword faces)
21982 (push (list :keyword
21983 (previous-single-property-change p 'face)
21984 (next-single-property-change p 'face)) clist))
21985 ((org-at-target-p)
21986 (push (org-point-in-group p 0 :target) clist)
21987 (goto-char (1- (match-beginning 0)))
21988 (if (looking-at org-radio-target-regexp)
21989 (push (org-point-in-group p 0 :radio-target) clist))
21990 (goto-char p))
21991 ((setq o (car (delq nil
21992 (mapcar
21993 (lambda (x)
21994 (if (memq x org-latex-fragment-image-overlays) x))
21995 (overlays-at (point))))))
21996 (push (list :latex-fragment
21997 (overlay-start o) (overlay-end o)) clist)
21998 (push (list :latex-preview
21999 (overlay-start o) (overlay-end o)) clist))
22000 ((org-inside-LaTeX-fragment-p)
22001 ;; FIXME: positions wrong.
22002 (push (list :latex-fragment (point) (point)) clist)))
22004 (setq clist (nreverse (delq nil clist)))
22005 clist))
22007 ;; FIXME: Compare with at-regexp-p Do we need both?
22008 (defun org-in-regexp (re &optional nlines visually)
22009 "Check if point is inside a match of regexp.
22010 Normally only the current line is checked, but you can include NLINES extra
22011 lines both before and after point into the search.
22012 If VISUALLY is set, require that the cursor is not after the match but
22013 really on, so that the block visually is on the match."
22014 (catch 'exit
22015 (let ((pos (point))
22016 (eol (point-at-eol (+ 1 (or nlines 0))))
22017 (inc (if visually 1 0)))
22018 (save-excursion
22019 (beginning-of-line (- 1 (or nlines 0)))
22020 (while (re-search-forward re eol t)
22021 (if (and (<= (match-beginning 0) pos)
22022 (>= (+ inc (match-end 0)) pos))
22023 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
22025 (defun org-at-regexp-p (regexp)
22026 "Is point inside a match of REGEXP in the current line?"
22027 (catch 'exit
22028 (save-excursion
22029 (let ((pos (point)) (end (point-at-eol)))
22030 (beginning-of-line 1)
22031 (while (re-search-forward regexp end t)
22032 (if (and (<= (match-beginning 0) pos)
22033 (>= (match-end 0) pos))
22034 (throw 'exit t)))
22035 nil))))
22037 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22038 "Non-nil when point is between matches of START-RE and END-RE.
22040 Also return a non-nil value when point is on one of the matches.
22042 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22043 buffer positions. Default values are the positions of headlines
22044 surrounding the point.
22046 The functions returns a cons cell whose car (resp. cdr) is the
22047 position before START-RE (resp. after END-RE)."
22048 (save-match-data
22049 (let ((pos (point))
22050 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22051 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22052 beg end)
22053 (save-excursion
22054 ;; Point is on a block when on START-RE or if START-RE can be
22055 ;; found before it...
22056 (and (or (org-at-regexp-p start-re)
22057 (re-search-backward start-re limit-up t))
22058 (setq beg (match-beginning 0))
22059 ;; ... and END-RE after it...
22060 (goto-char (match-end 0))
22061 (re-search-forward end-re limit-down t)
22062 (> (setq end (match-end 0)) pos)
22063 ;; ... without another START-RE in-between.
22064 (goto-char (match-beginning 0))
22065 (not (re-search-backward start-re (1+ beg) t))
22066 ;; Return value.
22067 (cons beg end))))))
22069 (defun org-in-block-p (names)
22070 "Non-nil when point belongs to a block whose name belongs to NAMES.
22072 NAMES is a list of strings containing names of blocks.
22074 Return first block name matched, or nil. Beware that in case of
22075 nested blocks, the returned name may not belong to the closest
22076 block from point."
22077 (save-match-data
22078 (catch 'exit
22079 (let ((case-fold-search t)
22080 (lim-up (save-excursion (outline-previous-heading)))
22081 (lim-down (save-excursion (outline-next-heading))))
22082 (mapc (lambda (name)
22083 (let ((n (regexp-quote name)))
22084 (when (org-between-regexps-p
22085 (concat "^[ \t]*#\\+begin_" n)
22086 (concat "^[ \t]*#\\+end_" n)
22087 lim-up lim-down)
22088 (throw 'exit n))))
22089 names))
22090 nil)))
22092 (defun org-in-drawer-p ()
22093 "Non-nil if point is within a drawer.
22094 If point is within a drawer, return it, as parsed data."
22095 (let ((element (save-match-data (org-element-at-point))))
22096 (while (and element (not (memq (org-element-type element)
22097 '(drawer property-drawer))))
22098 (setq element (org-element-property :parent element)))
22099 element))
22101 (defun org-occur-in-agenda-files (regexp &optional nlines)
22102 "Call `multi-occur' with buffers for all agenda files."
22103 (interactive "sOrg-files matching: \np")
22104 (let* ((files (org-agenda-files))
22105 (tnames (mapcar 'file-truename files))
22106 (extra org-agenda-text-search-extra-files)
22108 (when (eq (car extra) 'agenda-archives)
22109 (setq extra (cdr extra))
22110 (setq files (org-add-archive-files files)))
22111 (while (setq f (pop extra))
22112 (unless (member (file-truename f) tnames)
22113 (add-to-list 'files f 'append)
22114 (add-to-list 'tnames (file-truename f) 'append)))
22115 (multi-occur
22116 (mapcar (lambda (x)
22117 (with-current-buffer
22118 (or (get-file-buffer x) (find-file-noselect x))
22119 (widen)
22120 (current-buffer)))
22121 files)
22122 regexp)))
22124 (if (boundp 'occur-mode-find-occurrence-hook)
22125 ;; Emacs 23
22126 (add-hook 'occur-mode-find-occurrence-hook
22127 (lambda ()
22128 (when (derived-mode-p 'org-mode)
22129 (org-reveal))))
22130 ;; Emacs 22
22131 (defadvice occur-mode-goto-occurrence
22132 (after org-occur-reveal activate)
22133 (and (derived-mode-p 'org-mode) (org-reveal)))
22134 (defadvice occur-mode-goto-occurrence-other-window
22135 (after org-occur-reveal activate)
22136 (and (derived-mode-p 'org-mode) (org-reveal)))
22137 (defadvice occur-mode-display-occurrence
22138 (after org-occur-reveal activate)
22139 (when (derived-mode-p 'org-mode)
22140 (let ((pos (occur-mode-find-occurrence)))
22141 (with-current-buffer (marker-buffer pos)
22142 (save-excursion
22143 (goto-char pos)
22144 (org-reveal)))))))
22146 (defun org-occur-link-in-agenda-files ()
22147 "Create a link and search for it in the agendas.
22148 The link is not stored in `org-stored-links', it is just created
22149 for the search purpose."
22150 (interactive)
22151 (let ((link (condition-case nil
22152 (org-store-link nil)
22153 (error "Unable to create a link to here"))))
22154 (org-occur-in-agenda-files (regexp-quote link))))
22156 (defun org-reverse-string (string)
22157 "Return the reverse of STRING."
22158 (apply 'string (reverse (string-to-list string))))
22160 ;; defsubst org-uniquify must be defined before first use
22162 (defun org-uniquify-alist (alist)
22163 "Merge elements of ALIST with the same key.
22165 For example, in this alist:
22167 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22168 => '((a 1 3) (b 2))
22170 merge (a 1) and (a 3) into (a 1 3).
22172 The function returns the new ALIST."
22173 (let (rtn)
22174 (mapc
22175 (lambda (e)
22176 (let (n)
22177 (if (not (assoc (car e) rtn))
22178 (push e rtn)
22179 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22180 (setq rtn (assq-delete-all (car e) rtn))
22181 (push n rtn))))
22182 alist)
22183 rtn))
22185 (defun org-delete-all (elts list)
22186 "Remove all elements in ELTS from LIST."
22187 (while elts
22188 (setq list (delete (pop elts) list)))
22189 list)
22191 (defun org-count (cl-item cl-seq)
22192 "Count the number of occurrences of ITEM in SEQ.
22193 Taken from `count' in cl-seq.el with all keyword arguments removed."
22194 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22195 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22196 (while (< cl-start cl-end)
22197 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22198 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22199 (setq cl-start (1+ cl-start)))
22200 cl-count))
22202 (defun org-remove-if (predicate seq)
22203 "Remove everything from SEQ that fulfills PREDICATE."
22204 (let (res e)
22205 (while seq
22206 (setq e (pop seq))
22207 (if (not (funcall predicate e)) (push e res)))
22208 (nreverse res)))
22210 (defun org-remove-if-not (predicate seq)
22211 "Remove everything from SEQ that does not fulfill PREDICATE."
22212 (let (res e)
22213 (while seq
22214 (setq e (pop seq))
22215 (if (funcall predicate e) (push e res)))
22216 (nreverse res)))
22218 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22219 "Reduce two-argument FUNCTION across SEQ.
22220 Taken from `reduce' in cl-seq.el with all keyword arguments but
22221 \":initial-value\" removed."
22222 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22223 (cadr (memq :initial-value cl-keys)))
22224 (cl-seq (pop cl-seq))
22225 (t (funcall cl-func)))))
22226 (while cl-seq
22227 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22228 cl-accum))
22230 (defun org-every (pred seq)
22231 "Return true if PREDICATE is true of every element of SEQ.
22232 Adapted from `every' in cl.el."
22233 (catch 'org-every
22234 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22237 (defun org-some (pred seq)
22238 "Return true if PREDICATE is true of any element of SEQ.
22239 Adapted from `some' in cl.el."
22240 (catch 'org-some
22241 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22242 nil))
22244 (defun org-back-over-empty-lines ()
22245 "Move backwards over whitespace, to the beginning of the first empty line.
22246 Returns the number of empty lines passed."
22247 (let ((pos (point)))
22248 (if (cdr (assoc 'heading org-blank-before-new-entry))
22249 (skip-chars-backward " \t\n\r")
22250 (unless (eobp)
22251 (forward-line -1)))
22252 (beginning-of-line 2)
22253 (goto-char (min (point) pos))
22254 (count-lines (point) pos)))
22256 (defun org-skip-whitespace ()
22257 (skip-chars-forward " \t\n\r"))
22259 (defun org-point-in-group (point group &optional context)
22260 "Check if POINT is in match-group GROUP.
22261 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22262 match. If the match group does not exist or point is not inside it,
22263 return nil."
22264 (and (match-beginning group)
22265 (>= point (match-beginning group))
22266 (<= point (match-end group))
22267 (if context
22268 (list context (match-beginning group) (match-end group))
22269 t)))
22271 (defun org-switch-to-buffer-other-window (&rest args)
22272 "Switch to buffer in a second window on the current frame.
22273 In particular, do not allow pop-up frames.
22274 Returns the newly created buffer."
22275 (org-no-popups
22276 (apply 'switch-to-buffer-other-window args)))
22278 (defun org-combine-plists (&rest plists)
22279 "Create a single property list from all plists in PLISTS.
22280 The process starts by copying the first list, and then setting properties
22281 from the other lists. Settings in the last list are the most significant
22282 ones and overrule settings in the other lists."
22283 (let ((rtn (copy-sequence (pop plists)))
22284 p v ls)
22285 (while plists
22286 (setq ls (pop plists))
22287 (while ls
22288 (setq p (pop ls) v (pop ls))
22289 (setq rtn (plist-put rtn p v))))
22290 rtn))
22292 (defun org-replace-escapes (string table)
22293 "Replace %-escapes in STRING with values in TABLE.
22294 TABLE is an association list with keys like \"%a\" and string values.
22295 The sequences in STRING may contain normal field width and padding information,
22296 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22297 so values can contain further %-escapes if they are define later in TABLE."
22298 (let ((tbl (copy-alist table))
22299 (case-fold-search nil)
22300 (pchg 0)
22301 e re rpl)
22302 (while (setq e (pop tbl))
22303 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22304 (when (and (cdr e) (string-match re (cdr e)))
22305 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22306 (safe "SREF"))
22307 (add-text-properties 0 3 (list 'sref sref) safe)
22308 (setcdr e (replace-match safe t t (cdr e)))))
22309 (while (string-match re string)
22310 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22311 (cdr e)))
22312 (setq string (replace-match rpl t t string))))
22313 (while (setq pchg (next-property-change pchg string))
22314 (let ((sref (get-text-property pchg 'sref string)))
22315 (when (and sref (string-match "SREF" string pchg))
22316 (setq string (replace-match sref t t string)))))
22317 string))
22319 (defun org-sublist (list start end)
22320 "Return a section of LIST, from START to END.
22321 Counting starts at 1."
22322 (let (rtn (c start))
22323 (setq list (nthcdr (1- start) list))
22324 (while (and list (<= c end))
22325 (push (pop list) rtn)
22326 (setq c (1+ c)))
22327 (nreverse rtn)))
22329 (defun org-find-base-buffer-visiting (file)
22330 "Like `find-buffer-visiting' but always return the base buffer and
22331 not an indirect buffer."
22332 (let ((buf (or (get-file-buffer file)
22333 (find-buffer-visiting file))))
22334 (if buf
22335 (or (buffer-base-buffer buf) buf)
22336 nil)))
22338 (defun org-image-file-name-regexp (&optional extensions)
22339 "Return regexp matching the file names of images.
22340 If EXTENSIONS is given, only match these."
22341 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22342 (image-file-name-regexp)
22343 (let ((image-file-name-extensions
22344 (or extensions
22345 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22346 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22347 (concat "\\."
22348 (regexp-opt (nconc (mapcar 'upcase
22349 image-file-name-extensions)
22350 image-file-name-extensions)
22352 "\\'"))))
22354 (defun org-file-image-p (file &optional extensions)
22355 "Return non-nil if FILE is an image."
22356 (save-match-data
22357 (string-match (org-image-file-name-regexp extensions) file)))
22359 (defun org-get-cursor-date (&optional with-time)
22360 "Return the date at cursor in as a time.
22361 This works in the calendar and in the agenda, anywhere else it just
22362 returns the current time.
22363 If WITH-TIME is non-nil, returns the time of the event at point (in
22364 the agenda) or the current time of the day."
22365 (let (date day defd tp tm hod mod)
22366 (when with-time
22367 (setq tp (get-text-property (point) 'time))
22368 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22369 (setq hod (string-to-number (match-string 1 tp))
22370 mod (string-to-number (match-string 2 tp))))
22371 (or tp (setq hod (nth 2 (decode-time (current-time)))
22372 mod (nth 1 (decode-time (current-time))))))
22373 (cond
22374 ((eq major-mode 'calendar-mode)
22375 (setq date (calendar-cursor-to-date)
22376 defd (encode-time 0 (or mod 0) (or hod 0)
22377 (nth 1 date) (nth 0 date) (nth 2 date))))
22378 ((eq major-mode 'org-agenda-mode)
22379 (setq day (get-text-property (point) 'day))
22380 (if day
22381 (setq date (calendar-gregorian-from-absolute day)
22382 defd (encode-time 0 (or mod 0) (or hod 0)
22383 (nth 1 date) (nth 0 date) (nth 2 date))))))
22384 (or defd (current-time))))
22386 (defun org-mark-subtree (&optional up)
22387 "Mark the current subtree.
22388 This puts point at the start of the current subtree, and mark at
22389 the end. If a numeric prefix UP is given, move up into the
22390 hierarchy of headlines by UP levels before marking the subtree."
22391 (interactive "P")
22392 (org-with-limited-levels
22393 (cond ((org-at-heading-p) (beginning-of-line))
22394 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22395 (t (outline-previous-visible-heading 1))))
22396 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22397 (if (org-called-interactively-p 'any)
22398 (call-interactively 'org-mark-element)
22399 (org-mark-element)))
22402 ;;; Indentation
22404 (defun org--get-expected-indentation (element contentsp)
22405 "Expected indentation column for current line, according to ELEMENT.
22406 ELEMENT is an element containing point. CONTENTSP is non-nil
22407 when indentation is to be computed according to contents of
22408 ELEMENT."
22409 (let ((type (org-element-type element))
22410 (start (org-element-property :begin element)))
22411 (org-with-wide-buffer
22412 (cond
22413 (contentsp
22414 (case type
22415 (footnote-definition 0)
22416 ((headline inlinetask nil)
22417 (if (not org-adapt-indentation) 0
22418 (let ((level (org-current-level)))
22419 (if level (1+ level) 0))))
22420 (item
22421 (org-list-item-body-column
22422 (org-element-property :post-affiliated element)))
22423 (plain-list
22424 (save-excursion
22425 (goto-char (org-element-property :post-affiliated element))
22426 (org-get-indentation)))
22427 (otherwise
22428 (goto-char start)
22429 (org-get-indentation))))
22430 ((memq type '(headline inlinetask nil))
22431 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22432 (org--get-expected-indentation element t)
22434 ((eq type 'footnote-definition) 0)
22435 ;; First paragraph of a footnote definition or an item.
22436 ;; Indent like parent.
22437 ((< (line-beginning-position) start)
22438 (org--get-expected-indentation
22439 (org-element-property :parent element) t))
22440 ;; At first line: indent according to previous sibling, if any,
22441 ;; ignoring footnote definitions and inline tasks, or parent's
22442 ;; contents.
22443 ((= (line-beginning-position) start)
22444 (catch 'exit
22445 (while t
22446 (if (= (point-min) start) (throw 'exit 0)
22447 (goto-char (1- start))
22448 (let* ((previous (org-element-at-point))
22449 (parent previous))
22450 (while (and parent (<= (org-element-property :end parent) start))
22451 (setq previous parent
22452 parent (org-element-property :parent parent)))
22453 (cond
22454 ((not previous) (throw 'exit 0))
22455 ((> (org-element-property :end previous) start)
22456 (throw 'exit (org--get-expected-indentation previous t)))
22457 ((memq (org-element-type previous)
22458 '(footnote-definition inlinetask))
22459 (setq start (org-element-property :begin previous)))
22460 (t (goto-char (org-element-property :begin previous))
22461 (throw 'exit
22462 (if (bolp) (org-get-indentation)
22463 ;; At first paragraph in an item or
22464 ;; a footnote definition.
22465 (org--get-expected-indentation
22466 (org-element-property :parent previous) t))))))))))
22467 ;; Otherwise, move to the first non-blank line above.
22469 (beginning-of-line)
22470 (let ((pos (point)))
22471 (skip-chars-backward " \r\t\n")
22472 (cond
22473 ;; Two blank lines end a footnote definition or a plain
22474 ;; list. When we indent an empty line after them, the
22475 ;; containing list or footnote definition is over, so it
22476 ;; qualifies as a previous sibling. Therefore, we indent
22477 ;; like its first line.
22478 ((and (memq type '(footnote-definition plain-list))
22479 (> (count-lines (point) pos) 2))
22480 (goto-char start)
22481 (org-get-indentation))
22482 ;; Line above is the first one of a paragraph at the
22483 ;; beginning of an item or a footnote definition. Indent
22484 ;; like parent.
22485 ((< (line-beginning-position) start)
22486 (org--get-expected-indentation
22487 (org-element-property :parent element) t))
22488 ;; POS is after contents in a greater element. Indent like
22489 ;; the beginning of the element.
22491 ;; As a special case, if point is at the end of a footnote
22492 ;; definition or an item, indent like the very last element
22493 ;; within.
22494 ((let ((cend (org-element-property :contents-end element)))
22495 (and cend (<= cend pos)))
22496 (if (memq type '(footnote-definition item plain-list))
22497 (org--get-expected-indentation (org-element-at-point) nil)
22498 (goto-char start)
22499 (org-get-indentation)))
22500 ;; In any other case, indent like the current line.
22501 (t (org-get-indentation)))))))))
22503 (defun org--align-node-property ()
22504 "Align node property at point.
22505 Alignment is done according to `org-property-format', which see."
22506 (when (save-excursion
22507 (beginning-of-line)
22508 (looking-at org-property-re))
22509 (replace-match
22510 (concat (match-string 4)
22511 (org-trim
22512 (format org-property-format (match-string 1) (match-string 3))))
22513 t t)))
22515 (defun org-indent-line ()
22516 "Indent line depending on context.
22518 Indentation is done according to the following rules:
22520 - Footnote definitions, headlines and inline tasks have to
22521 start at column 0.
22523 - On the very first line of an element, consider, in order, the
22524 next rules until one matches:
22526 1. If there's a sibling element before, ignoring footnote
22527 definitions and inline tasks, indent like its first line.
22529 2. If element has a parent, indent like its contents. More
22530 precisely, if parent is an item, indent after the
22531 description part, if any, or the bullet (see
22532 ``org-list-description-max-indent'). Else, indent like
22533 parent's first line.
22535 3. Otherwise, indent relatively to current level, if
22536 `org-adapt-indentation' is non-nil, or to left margin.
22538 - On a blank line at the end of a plain list, an item, or
22539 a footnote definition, indent like the very last element
22540 within.
22542 - In the code part of a source block, use language major mode
22543 to indent current line if `org-src-tab-acts-natively' is
22544 non-nil. If it is nil, do nothing.
22546 - Otherwise, indent like the first non-blank line above.
22548 The function doesn't indent an item as it could break the whole
22549 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22550 \\[org-shiftmetaright].
22552 Also align node properties according to `org-property-format'."
22553 (interactive)
22554 (cond
22555 (orgstruct-is-++
22556 (let ((indent-line-function
22557 (cadadr (assq 'indent-line-function org-fb-vars))))
22558 (indent-according-to-mode)))
22559 ((org-at-heading-p) 'noindent)
22561 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22562 (type (org-element-type element)))
22563 (cond ((and (memq type '(plain-list item))
22564 (= (line-beginning-position)
22565 (org-element-property :post-affiliated element)))
22566 'noindent)
22567 ((and (eq type 'src-block)
22568 org-src-tab-acts-natively
22569 (> (line-beginning-position)
22570 (org-element-property :post-affiliated element))
22571 (< (line-beginning-position)
22572 (org-with-wide-buffer
22573 (goto-char (org-element-property :end element))
22574 (skip-chars-backward " \r\t\n")
22575 (line-beginning-position))))
22576 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22577 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))))
22579 (let ((column (org--get-expected-indentation element nil)))
22580 ;; Preserve current column.
22581 (if (<= (current-column) (current-indentation))
22582 (org-indent-line-to column)
22583 (save-excursion (org-indent-line-to column))))
22584 ;; Align node property. Also preserve current column.
22585 (when (eq type 'node-property)
22586 (let ((column (current-column)))
22587 (org--align-node-property)
22588 (org-move-to-column column)))))))))
22590 (defun org-indent-region (start end)
22591 "Indent each non-blank line in the region.
22592 Called from a program, START and END specify the region to
22593 indent. The function will not indent contents of example blocks,
22594 verse blocks and export blocks as leading white spaces are
22595 assumed to be significant there."
22596 (interactive "r")
22597 (save-excursion
22598 (goto-char start)
22599 (skip-chars-forward " \r\t\n")
22600 (unless (eobp) (beginning-of-line))
22601 (let ((indent-to
22602 (lambda (ind pos)
22603 ;; Set IND as indentation for all lines between point and
22604 ;; POS or END, whichever comes first. Blank lines are
22605 ;; ignored. Leave point after POS once done.
22606 (let ((limit (copy-marker (min end pos))))
22607 (while (< (point) limit)
22608 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22609 (forward-line))
22610 (set-marker limit nil))))
22611 (end (copy-marker end)))
22612 (while (< (point) end)
22613 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22614 (let* ((element (org-element-at-point))
22615 (type (org-element-type element))
22616 (element-end (copy-marker (org-element-property :end element)))
22617 (ind (org--get-expected-indentation element nil)))
22618 (cond
22619 ((or (memq type '(paragraph table table-row))
22620 (not (or (org-element-property :contents-begin element)
22621 (memq type
22622 '(example-block export-block src-block)))))
22623 ;; Elements here are indented as a single block. Also
22624 ;; align node properties.
22625 (when (eq type 'node-property)
22626 (org--align-node-property)
22627 (beginning-of-line))
22628 (funcall indent-to ind element-end))
22630 ;; Elements in this category consist of three parts:
22631 ;; before the contents, the contents, and after the
22632 ;; contents. The contents are treated specially,
22633 ;; according to the element type, or not indented at
22634 ;; all. Other parts are indented as a single block.
22635 (let* ((post (copy-marker
22636 (org-element-property :post-affiliated element)))
22637 (cbeg
22638 (copy-marker
22639 (cond
22640 ((not (org-element-property :contents-begin element))
22641 ;; Fake contents for source blocks.
22642 (org-with-wide-buffer
22643 (goto-char post)
22644 (forward-line)
22645 (point)))
22646 ((memq type '(footnote-definition item plain-list))
22647 ;; Contents in these elements could start on
22648 ;; the same line as the beginning of the
22649 ;; element. Make sure we start indenting
22650 ;; from the second line.
22651 (org-with-wide-buffer
22652 (goto-char post)
22653 (end-of-line)
22654 (skip-chars-forward " \r\t\n")
22655 (if (eobp) (point) (line-beginning-position))))
22656 (t (org-element-property :contents-begin element)))))
22657 (cend (copy-marker
22658 (or (org-element-property :contents-end element)
22659 ;; Fake contents for source blocks.
22660 (org-with-wide-buffer
22661 (goto-char element-end)
22662 (skip-chars-backward " \r\t\n")
22663 (line-beginning-position))))))
22664 ;; Do not change items indentation individually as it
22665 ;; might break the list as a whole. On the other
22666 ;; hand, when at a plain list, indent it as a whole.
22667 (cond ((eq type 'plain-list)
22668 (let ((offset (- ind (org-get-indentation))))
22669 (unless (zerop offset)
22670 (indent-rigidly (org-element-property :begin element)
22671 (org-element-property :end element)
22672 offset))
22673 (goto-char cbeg)))
22674 ((eq type 'item) (goto-char cbeg))
22675 (t (funcall indent-to ind cbeg)))
22676 (when (< (point) end)
22677 (case type
22678 ((example-block export-block verse-block))
22679 (src-block
22680 ;; In a source block, indent source code
22681 ;; according to language major mode, but only if
22682 ;; `org-src-tab-acts-natively' is non-nil.
22683 (when (and (< (point) end) org-src-tab-acts-natively)
22684 (ignore-errors
22685 (let (org-src-strip-leading-and-trailing-blank-lines
22686 ;; Region boundaries in edit buffer.
22687 (start (1+ (- (point) cbeg)))
22688 (end (- (min cend end) cbeg)))
22689 (org-babel-do-in-edit-buffer
22690 (indent-region start end))))))
22691 (t (org-indent-region (point) (min cend end))))
22692 (goto-char (min cend end))
22693 (when (< (point) end) (funcall indent-to ind element-end)))
22694 (set-marker post nil)
22695 (set-marker cbeg nil)
22696 (set-marker cend nil))))
22697 (set-marker element-end nil))))
22698 (set-marker end nil))))
22700 (defun org-indent-drawer ()
22701 "Indent the drawer at point."
22702 (interactive)
22703 (unless (save-excursion
22704 (beginning-of-line)
22705 (org-looking-at-p org-drawer-regexp))
22706 (user-error "Not at a drawer"))
22707 (let ((element (org-element-at-point)))
22708 (unless (memq (org-element-type element) '(drawer property-drawer))
22709 (user-error "Not at a drawer"))
22710 (org-with-wide-buffer
22711 (org-indent-region (org-element-property :begin element)
22712 (org-element-property :end element))))
22713 (message "Drawer at point indented"))
22715 (defun org-indent-block ()
22716 "Indent the block at point."
22717 (interactive)
22718 (unless (save-excursion
22719 (beginning-of-line)
22720 (let ((case-fold-search t))
22721 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22722 (user-error "Not at a block"))
22723 (let ((element (org-element-at-point)))
22724 (unless (memq (org-element-type element)
22725 '(comment-block center-block dynamic-block example-block
22726 export-block quote-block special-block
22727 src-block verse-block))
22728 (user-error "Not at a block"))
22729 (org-with-wide-buffer
22730 (org-indent-region (org-element-property :begin element)
22731 (org-element-property :end element))))
22732 (message "Block at point indented"))
22735 ;;; Filling
22737 ;; We use our own fill-paragraph and auto-fill functions.
22739 ;; `org-fill-paragraph' relies on adaptive filling and context
22740 ;; checking. Appropriate `fill-prefix' is computed with
22741 ;; `org-adaptive-fill-function'.
22743 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22744 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22745 ;; `org-adaptive-fill-function' value. Internally,
22746 ;; `org-comment-line-break-function' breaks the line.
22748 ;; `org-setup-filling' installs filling and auto-filling related
22749 ;; variables during `org-mode' initialization.
22751 (defvar org-element-paragraph-separate) ; org-element.el
22752 (defun org-setup-filling ()
22753 (require 'org-element)
22754 ;; Prevent auto-fill from inserting unwanted new items.
22755 (when (boundp 'fill-nobreak-predicate)
22756 (org-set-local
22757 'fill-nobreak-predicate
22758 (org-uniquify
22759 (append fill-nobreak-predicate
22760 '(org-fill-line-break-nobreak-p
22761 org-fill-paragraph-with-timestamp-nobreak-p)))))
22762 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22763 (org-set-local 'paragraph-start paragraph-ending)
22764 (org-set-local 'paragraph-separate paragraph-ending))
22765 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22766 (org-set-local 'auto-fill-inhibit-regexp nil)
22767 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22768 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22769 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22771 (defun org-fill-line-break-nobreak-p ()
22772 "Non-nil when a new line at point would create an Org line break."
22773 (save-excursion
22774 (skip-chars-backward "[ \t]")
22775 (skip-chars-backward "\\\\")
22776 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22778 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22779 "Non-nil when a new line at point would split a timestamp."
22780 (and (org-at-timestamp-p t)
22781 (not (looking-at org-ts-regexp-both))))
22783 (declare-function message-in-body-p "message" ())
22784 (defvar orgtbl-line-start-regexp) ; From org-table.el
22785 (defun org-adaptive-fill-function ()
22786 "Compute a fill prefix for the current line.
22787 Return fill prefix, as a string, or nil if current line isn't
22788 meant to be filled. For convenience, if `adaptive-fill-regexp'
22789 matches in paragraphs or comments, use it."
22790 (catch 'exit
22791 (when (derived-mode-p 'message-mode)
22792 (save-excursion
22793 (beginning-of-line)
22794 (cond ((or (not (message-in-body-p))
22795 (looking-at orgtbl-line-start-regexp))
22796 (throw 'exit nil))
22797 ((looking-at message-cite-prefix-regexp)
22798 (throw 'exit (match-string-no-properties 0)))
22799 ((looking-at org-outline-regexp)
22800 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22801 (org-with-wide-buffer
22802 (unless (org-at-heading-p)
22803 (let* ((p (line-beginning-position))
22804 (element (save-excursion
22805 (beginning-of-line)
22806 (org-element-at-point)))
22807 (type (org-element-type element))
22808 (post-affiliated (org-element-property :post-affiliated element)))
22809 (unless (< p post-affiliated)
22810 (case type
22811 (comment
22812 (save-excursion
22813 (beginning-of-line)
22814 (looking-at "[ \t]*")
22815 (concat (match-string 0) "# ")))
22816 (footnote-definition "")
22817 ((item plain-list)
22818 (make-string (org-list-item-body-column post-affiliated) ?\s))
22819 (paragraph
22820 ;; Fill prefix is usually the same as the current line,
22821 ;; unless the paragraph is at the beginning of an item.
22822 (let ((parent (org-element-property :parent element)))
22823 (save-excursion
22824 (beginning-of-line)
22825 (cond ((eq (org-element-type parent) 'item)
22826 (make-string (org-list-item-body-column
22827 (org-element-property :begin parent))
22828 ?\s))
22829 ((and adaptive-fill-regexp
22830 ;; Locally disable
22831 ;; `adaptive-fill-function' to let
22832 ;; `fill-context-prefix' handle
22833 ;; `adaptive-fill-regexp' variable.
22834 (let (adaptive-fill-function)
22835 (fill-context-prefix
22836 post-affiliated
22837 (org-element-property :end element)))))
22838 ((looking-at "[ \t]+") (match-string 0))
22839 (t "")))))
22840 (comment-block
22841 ;; Only fill contents if P is within block boundaries.
22842 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22843 (forward-line)
22844 (point)))
22845 (cend (save-excursion
22846 (goto-char (org-element-property :end element))
22847 (skip-chars-backward " \r\t\n")
22848 (line-beginning-position))))
22849 (when (and (>= p cbeg) (< p cend))
22850 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22851 (match-string 0)
22852 "")))))))))))
22854 (declare-function message-goto-body "message" ())
22855 (defvar message-cite-prefix-regexp) ; From message.el
22856 (defun org-fill-paragraph (&optional justify)
22857 "Fill element at point, when applicable.
22859 This function only applies to comment blocks, comments, example
22860 blocks and paragraphs. Also, as a special case, re-align table
22861 when point is at one.
22863 If JUSTIFY is non-nil (interactively, with prefix argument),
22864 justify as well. If `sentence-end-double-space' is non-nil, then
22865 period followed by one space does not end a sentence, so don't
22866 break a line there. The variable `fill-column' controls the
22867 width for filling.
22869 For convenience, when point is at a plain list, an item or
22870 a footnote definition, try to fill the first paragraph within."
22871 (interactive)
22872 (if (and (derived-mode-p 'message-mode)
22873 (or (not (message-in-body-p))
22874 (save-excursion (move-beginning-of-line 1)
22875 (looking-at message-cite-prefix-regexp))))
22876 ;; First ensure filling is correct in message-mode.
22877 (let ((fill-paragraph-function
22878 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22879 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22880 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22881 (paragraph-separate
22882 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22883 (fill-paragraph nil))
22884 (with-syntax-table org-mode-transpose-word-syntax-table
22885 ;; Move to end of line in order to get the first paragraph
22886 ;; within a plain list or a footnote definition.
22887 (let ((element (save-excursion
22888 (end-of-line)
22889 (or (ignore-errors (org-element-at-point))
22890 (user-error "An element cannot be parsed line %d"
22891 (line-number-at-pos (point)))))))
22892 ;; First check if point is in a blank line at the beginning of
22893 ;; the buffer. In that case, ignore filling.
22894 (case (org-element-type element)
22895 ;; Use major mode filling function is src blocks.
22896 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22897 ;; Align Org tables, leave table.el tables as-is.
22898 (table-row (org-table-align) t)
22899 (table
22900 (when (eq (org-element-property :type element) 'org)
22901 (save-excursion
22902 (goto-char (org-element-property :post-affiliated element))
22903 (org-table-align)))
22905 (paragraph
22906 ;; Paragraphs may contain `line-break' type objects.
22907 (let ((beg (max (point-min)
22908 (org-element-property :contents-begin element)))
22909 (end (min (point-max)
22910 (org-element-property :contents-end element))))
22911 ;; Do nothing if point is at an affiliated keyword.
22912 (if (< (line-end-position) beg) t
22913 (when (derived-mode-p 'message-mode)
22914 ;; In `message-mode', do not fill following citation
22915 ;; in current paragraph nor text before message body.
22916 (let ((body-start (save-excursion (message-goto-body))))
22917 (when body-start (setq beg (max body-start beg))))
22918 (when (save-excursion
22919 (re-search-forward
22920 (concat "^" message-cite-prefix-regexp) end t))
22921 (setq end (match-beginning 0))))
22922 ;; Fill paragraph, taking line breaks into account.
22923 (save-excursion
22924 (goto-char beg)
22925 (let ((cuts (list beg)))
22926 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22927 (when (eq 'line-break
22928 (org-element-type
22929 (save-excursion (backward-char)
22930 (org-element-context))))
22931 (push (point) cuts)))
22932 (dolist (c (delq end cuts))
22933 (fill-region-as-paragraph c end justify)
22934 (setq end c))))
22935 t)))
22936 ;; Contents of `comment-block' type elements should be
22937 ;; filled as plain text, but only if point is within block
22938 ;; markers.
22939 (comment-block
22940 (let* ((case-fold-search t)
22941 (beg (save-excursion
22942 (goto-char (org-element-property :begin element))
22943 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22944 (forward-line)
22945 (point)))
22946 (end (save-excursion
22947 (goto-char (org-element-property :end element))
22948 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22949 (line-beginning-position))))
22950 (if (or (< (point) beg) (> (point) end)) t
22951 (fill-region-as-paragraph
22952 (save-excursion (end-of-line)
22953 (re-search-backward "^[ \t]*$" beg 'move)
22954 (line-beginning-position))
22955 (save-excursion (beginning-of-line)
22956 (re-search-forward "^[ \t]*$" end 'move)
22957 (line-beginning-position))
22958 justify))))
22959 ;; Fill comments.
22960 (comment
22961 (let ((begin (org-element-property :post-affiliated element))
22962 (end (org-element-property :end element)))
22963 (when (and (>= (point) begin) (<= (point) end))
22964 (let ((begin (save-excursion
22965 (end-of-line)
22966 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22967 (progn (forward-line) (point))
22968 begin)))
22969 (end (save-excursion
22970 (end-of-line)
22971 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22972 (1- (line-beginning-position))
22973 (skip-chars-backward " \r\t\n")
22974 (line-end-position)))))
22975 ;; Do not fill comments when at a blank line.
22976 (when (> end begin)
22977 (let ((fill-prefix
22978 (save-excursion
22979 (beginning-of-line)
22980 (looking-at "[ \t]*#")
22981 (let ((comment-prefix (match-string 0)))
22982 (goto-char (match-end 0))
22983 (if (looking-at adaptive-fill-regexp)
22984 (concat comment-prefix (match-string 0))
22985 (concat comment-prefix " "))))))
22986 (save-excursion
22987 (fill-region-as-paragraph begin end justify))))))
22989 ;; Ignore every other element.
22990 (otherwise t))))))
22992 (defun org-auto-fill-function ()
22993 "Auto-fill function."
22994 ;; Check if auto-filling is meaningful.
22995 (let ((fc (current-fill-column)))
22996 (when (and fc (> (current-column) fc))
22997 (let* ((fill-prefix (org-adaptive-fill-function))
22998 ;; Enforce empty fill prefix, if required. Otherwise, it
22999 ;; will be computed again.
23000 (adaptive-fill-mode (not (equal fill-prefix ""))))
23001 (when fill-prefix (do-auto-fill))))))
23003 (defun org-comment-line-break-function (&optional soft)
23004 "Break line at point and indent, continuing comment if within one.
23005 The inserted newline is marked hard if variable
23006 `use-hard-newlines' is true, unless optional argument SOFT is
23007 non-nil."
23008 (if soft (insert-and-inherit ?\n) (newline 1))
23009 (save-excursion (forward-char -1) (delete-horizontal-space))
23010 (delete-horizontal-space)
23011 (indent-to-left-margin)
23012 (insert-before-markers-and-inherit fill-prefix))
23015 ;;; Fixed Width Areas
23017 (defun org-toggle-fixed-width ()
23018 "Toggle fixed-width markup.
23020 Add or remove fixed-width markup on current line, whenever it
23021 makes sense. Return an error otherwise.
23023 If a region is active and if it contains only fixed-width areas
23024 or blank lines, remove all fixed-width markup in it. If the
23025 region contains anything else, convert all non-fixed-width lines
23026 to fixed-width ones.
23028 Blank lines at the end of the region are ignored unless the
23029 region only contains such lines."
23030 (interactive)
23031 (if (not (org-region-active-p))
23032 ;; No region:
23034 ;; Remove fixed width marker only in a fixed-with element.
23036 ;; Add fixed width maker in paragraphs, in blank lines after
23037 ;; elements or at the beginning of a headline or an inlinetask,
23038 ;; and before any one-line elements (e.g., a clock).
23039 (progn
23040 (beginning-of-line)
23041 (let* ((element (org-element-at-point))
23042 (type (org-element-type element)))
23043 (cond
23044 ((and (eq type 'fixed-width)
23045 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23046 (replace-match
23047 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23048 ((and (memq type '(babel-call clock comment diary-sexp headline
23049 horizontal-rule keyword paragraph
23050 planning))
23051 (<= (org-element-property :post-affiliated element) (point)))
23052 (skip-chars-forward " \t")
23053 (insert ": "))
23054 ((and (org-looking-at-p "[ \t]*$")
23055 (or (eq type 'inlinetask)
23056 (save-excursion
23057 (skip-chars-forward " \r\t\n")
23058 (<= (org-element-property :end element) (point)))))
23059 (delete-region (point) (line-end-position))
23060 (org-indent-line)
23061 (insert ": "))
23062 (t (user-error "Cannot insert a fixed-width line here")))))
23063 ;; Region active.
23064 (let* ((begin (save-excursion
23065 (goto-char (region-beginning))
23066 (line-beginning-position)))
23067 (end (copy-marker
23068 (save-excursion
23069 (goto-char (region-end))
23070 (unless (eolp) (beginning-of-line))
23071 (if (save-excursion (re-search-backward "\\S-" begin t))
23072 (progn (skip-chars-backward " \r\t\n") (point))
23073 (point)))))
23074 (all-fixed-width-p
23075 (catch 'not-all-p
23076 (save-excursion
23077 (goto-char begin)
23078 (skip-chars-forward " \r\t\n")
23079 (when (eobp) (throw 'not-all-p nil))
23080 (while (< (point) end)
23081 (let ((element (org-element-at-point)))
23082 (if (eq (org-element-type element) 'fixed-width)
23083 (goto-char (org-element-property :end element))
23084 (throw 'not-all-p nil))))
23085 t))))
23086 (if all-fixed-width-p
23087 (save-excursion
23088 (goto-char begin)
23089 (while (< (point) end)
23090 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23091 (replace-match
23092 "" nil nil nil
23093 (if (= (line-end-position) (match-end 0)) 0 1)))
23094 (forward-line)))
23095 (let ((min-ind (point-max)))
23096 ;; Find minimum indentation across all lines.
23097 (save-excursion
23098 (goto-char begin)
23099 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23100 (setq min-ind 0)
23101 (catch 'zerop
23102 (while (< (point) end)
23103 (unless (org-looking-at-p "[ \t]*$")
23104 (let ((ind (org-get-indentation)))
23105 (setq min-ind (min min-ind ind))
23106 (when (zerop ind) (throw 'zerop t))))
23107 (forward-line)))))
23108 ;; Loop over all lines and add fixed-width markup everywhere
23109 ;; but in fixed-width lines.
23110 (save-excursion
23111 (goto-char begin)
23112 (while (< (point) end)
23113 (cond
23114 ((org-at-heading-p)
23115 (insert ": ")
23116 (forward-line)
23117 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23118 (insert ":")
23119 (forward-line)))
23120 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23121 (let* ((element (org-element-at-point))
23122 (element-end (org-element-property :end element)))
23123 (if (eq (org-element-type element) 'fixed-width)
23124 (progn (goto-char element-end)
23125 (skip-chars-backward " \r\t\n")
23126 (forward-line))
23127 (let ((limit (min end element-end)))
23128 (while (< (point) limit)
23129 (org-move-to-column min-ind t)
23130 (insert ": ")
23131 (forward-line))))))
23133 (org-move-to-column min-ind t)
23134 (insert ": ")
23135 (forward-line)))))))
23136 (set-marker end nil))))
23139 ;;; Comments
23141 ;; Org comments syntax is quite complex. It requires the entire line
23142 ;; to be just a comment. Also, even with the right syntax at the
23143 ;; beginning of line, some some elements (i.e. verse-block or
23144 ;; example-block) don't accept comments. Usual Emacs comment commands
23145 ;; cannot cope with those requirements. Therefore, Org replaces them.
23147 ;; Org still relies on `comment-dwim', but cannot trust
23148 ;; `comment-only-p'. So, `comment-region-function' and
23149 ;; `uncomment-region-function' both point
23150 ;; to`org-comment-or-uncomment-region'. Eventually,
23151 ;; `org-insert-comment' takes care of insertion of comments at the
23152 ;; beginning of line.
23154 ;; `org-setup-comments-handling' install comments related variables
23155 ;; during `org-mode' initialization.
23157 (defun org-setup-comments-handling ()
23158 (interactive)
23159 (org-set-local 'comment-use-syntax nil)
23160 (org-set-local 'comment-start "# ")
23161 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23162 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23163 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23164 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23166 (defun org-insert-comment ()
23167 "Insert an empty comment above current line.
23168 If the line is empty, insert comment at its beginning. When
23169 point is within a source block, comment according to the related
23170 major mode."
23171 (if (let ((element (org-element-at-point)))
23172 (and (eq (org-element-type element) 'src-block)
23173 (< (save-excursion
23174 (goto-char (org-element-property :post-affiliated element))
23175 (line-end-position))
23176 (point))
23177 (> (save-excursion
23178 (goto-char (org-element-property :end element))
23179 (skip-chars-backward " \r\t\n")
23180 (line-beginning-position))
23181 (point))))
23182 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23183 (beginning-of-line)
23184 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23185 (open-line 1))
23186 (org-indent-line)
23187 (insert "# ")))
23189 (defvar comment-empty-lines) ; From newcomment.el.
23190 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23191 "Comment or uncomment each non-blank line in the region.
23192 Uncomment each non-blank line between BEG and END if it only
23193 contains commented lines. Otherwise, comment them. If region is
23194 strictly within a source block, use appropriate comment syntax."
23195 (if (let ((element (org-element-at-point)))
23196 (and (eq (org-element-type element) 'src-block)
23197 (< (save-excursion
23198 (goto-char (org-element-property :post-affiliated element))
23199 (line-end-position))
23200 beg)
23201 (>= (save-excursion
23202 (goto-char (org-element-property :end element))
23203 (skip-chars-backward " \r\t\n")
23204 (line-beginning-position))
23205 end)))
23206 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23207 (save-restriction
23208 ;; Restrict region
23209 (narrow-to-region (save-excursion (goto-char beg)
23210 (skip-chars-forward " \r\t\n" end)
23211 (line-beginning-position))
23212 (save-excursion (goto-char end)
23213 (skip-chars-backward " \r\t\n" beg)
23214 (line-end-position)))
23215 (let ((uncommentp
23216 ;; UNCOMMENTP is non-nil when every non blank line between
23217 ;; BEG and END is a comment.
23218 (save-excursion
23219 (goto-char (point-min))
23220 (while (and (not (eobp))
23221 (let ((element (org-element-at-point)))
23222 (and (eq (org-element-type element) 'comment)
23223 (goto-char (min (point-max)
23224 (org-element-property
23225 :end element)))))))
23226 (eobp))))
23227 (if uncommentp
23228 ;; Only blank lines and comments in region: uncomment it.
23229 (save-excursion
23230 (goto-char (point-min))
23231 (while (not (eobp))
23232 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23233 (replace-match "" nil nil nil 1))
23234 (forward-line)))
23235 ;; Comment each line in region.
23236 (let ((min-indent (point-max)))
23237 ;; First find the minimum indentation across all lines.
23238 (save-excursion
23239 (goto-char (point-min))
23240 (while (and (not (eobp)) (not (zerop min-indent)))
23241 (unless (looking-at "[ \t]*$")
23242 (setq min-indent (min min-indent (current-indentation))))
23243 (forward-line)))
23244 ;; Then loop over all lines.
23245 (save-excursion
23246 (goto-char (point-min))
23247 (while (not (eobp))
23248 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23249 ;; Don't get fooled by invisible text (e.g. link path)
23250 ;; when moving to column MIN-INDENT.
23251 (let ((buffer-invisibility-spec nil))
23252 (org-move-to-column min-indent t))
23253 (insert comment-start))
23254 (forward-line)))))))))
23256 (defun org-comment-dwim (arg)
23257 "Call `comment-dwim' within a source edit buffer if needed."
23258 (interactive "*P")
23259 (if (org-in-src-block-p)
23260 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23261 (call-interactively 'comment-dwim)))
23264 ;;; Planning
23266 ;; This section contains tools to operate on timestamp objects, as
23267 ;; returned by, e.g. `org-element-context'.
23269 (defun org-timestamp-has-time-p (timestamp)
23270 "Non-nil when TIMESTAMP has a time specified."
23271 (org-element-property :hour-start timestamp))
23273 (defun org-timestamp-format (timestamp format &optional end utc)
23274 "Format a TIMESTAMP element into a string.
23276 FORMAT is a format specifier to be passed to
23277 `format-time-string'.
23279 When optional argument END is non-nil, use end of date-range or
23280 time-range, if possible.
23282 When optional argument UTC is non-nil, time will be expressed as
23283 Universal Time."
23284 (format-time-string
23285 format
23286 (apply 'encode-time
23287 (cons 0
23288 (mapcar
23289 (lambda (prop) (or (org-element-property prop timestamp) 0))
23290 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23291 '(:minute-start :hour-start :day-start :month-start
23292 :year-start)))))
23293 utc))
23295 (defun org-timestamp-split-range (timestamp &optional end)
23296 "Extract a timestamp object from a date or time range.
23298 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23299 the end of the range. Otherwise, extract its start.
23301 Return a new timestamp object sharing the same parent as
23302 TIMESTAMP."
23303 (let ((type (org-element-property :type timestamp)))
23304 (if (memq type '(active inactive diary)) timestamp
23305 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23306 ;; Set new type.
23307 (org-element-put-property
23308 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23309 ;; Copy start properties over end properties if END is
23310 ;; non-nil. Otherwise, copy end properties over `start' ones.
23311 (let ((p-alist '((:minute-start . :minute-end)
23312 (:hour-start . :hour-end)
23313 (:day-start . :day-end)
23314 (:month-start . :month-end)
23315 (:year-start . :year-end))))
23316 (dolist (p-cell p-alist)
23317 (org-element-put-property
23318 split-ts
23319 (funcall (if end 'car 'cdr) p-cell)
23320 (org-element-property
23321 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23322 ;; Eventually refresh `:raw-value'.
23323 (org-element-put-property split-ts :raw-value nil)
23324 (org-element-put-property
23325 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23327 (defun org-timestamp-translate (timestamp &optional boundary)
23328 "Apply `org-translate-time' on a TIMESTAMP object.
23329 When optional argument BOUNDARY is non-nil, it is either the
23330 symbol `start' or `end'. In this case, only translate the
23331 starting or ending part of TIMESTAMP if it is a date or time
23332 range. Otherwise, translate both parts."
23333 (if (and (not boundary)
23334 (memq (org-element-property :type timestamp)
23335 '(active-range inactive-range)))
23336 (concat
23337 (org-translate-time
23338 (org-element-property :raw-value
23339 (org-timestamp-split-range timestamp)))
23340 "--"
23341 (org-translate-time
23342 (org-element-property :raw-value
23343 (org-timestamp-split-range timestamp t))))
23344 (org-translate-time
23345 (org-element-property
23346 :raw-value
23347 (if (not boundary) timestamp
23348 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23352 ;;; Other stuff.
23354 (defun org-reftex-citation ()
23355 "Use reftex-citation to insert a citation into the buffer.
23356 This looks for a line like
23358 #+BIBLIOGRAPHY: foo plain option:-d
23360 and derives from it that foo.bib is the bibliography file relevant
23361 for this document. It then installs the necessary environment for RefTeX
23362 to work in this buffer and calls `reftex-citation' to insert a citation
23363 into the buffer.
23365 Export of such citations to both LaTeX and HTML is handled by the contributed
23366 package ox-bibtex by Taru Karttunen."
23367 (interactive)
23368 (let ((reftex-docstruct-symbol 'rds)
23369 (reftex-cite-format "\\cite{%l}")
23370 rds bib)
23371 (save-excursion
23372 (save-restriction
23373 (widen)
23374 (let ((case-fold-search t)
23375 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23376 (if (not (save-excursion
23377 (or (re-search-forward re nil t)
23378 (re-search-backward re nil t))))
23379 (user-error "No bibliography defined in file")
23380 (setq bib (concat (match-string 1) ".bib")
23381 rds (list (list 'bib bib)))))))
23382 (call-interactively 'reftex-citation)))
23384 ;;;; Functions extending outline functionality
23386 (defun org-beginning-of-line (&optional arg)
23387 "Go to the beginning of the current line. If that is invisible, continue
23388 to a visible line beginning. This makes the function of C-a more intuitive.
23389 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23390 first attempt, and only move to after the tags when the cursor is already
23391 beyond the end of the headline."
23392 (interactive "P")
23393 (let ((pos (point))
23394 (special (if (consp org-special-ctrl-a/e)
23395 (car org-special-ctrl-a/e)
23396 org-special-ctrl-a/e))
23397 deactivate-mark refpos)
23398 (if (org-bound-and-true-p visual-line-mode)
23399 (beginning-of-visual-line 1)
23400 (beginning-of-line 1))
23401 (if (and arg (fboundp 'move-beginning-of-line))
23402 (call-interactively 'move-beginning-of-line)
23403 (if (bobp)
23405 (backward-char 1)
23406 (if (org-truely-invisible-p)
23407 (while (and (not (bobp)) (org-truely-invisible-p))
23408 (backward-char 1)
23409 (beginning-of-line 1))
23410 (forward-char 1))))
23411 (when special
23412 (cond
23413 ((and (looking-at org-complex-heading-regexp)
23414 (= (char-after (match-end 1)) ?\ ))
23415 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23416 (point-at-eol)))
23417 (goto-char
23418 (if (eq special t)
23419 (cond ((> pos refpos) refpos)
23420 ((= pos (point)) refpos)
23421 (t (point)))
23422 (cond ((> pos (point)) (point))
23423 ((not (eq last-command this-command)) (point))
23424 (t refpos)))))
23425 ((org-at-item-p)
23426 ;; Being at an item and not looking at an the item means point
23427 ;; was previously moved to beginning of a visual line, which
23428 ;; doesn't contain the item. Therefore, do nothing special,
23429 ;; just stay here.
23430 (when (looking-at org-list-full-item-re)
23431 ;; Set special position at first white space character after
23432 ;; bullet, and check-box, if any.
23433 (let ((after-bullet
23434 (let ((box (match-end 3)))
23435 (if (not box) (match-end 1)
23436 (let ((after (char-after box)))
23437 (if (and after (= after ? )) (1+ box) box))))))
23438 ;; Special case: Move point to special position when
23439 ;; currently after it or at beginning of line.
23440 (if (eq special t)
23441 (when (or (> pos after-bullet) (= (point) pos))
23442 (goto-char after-bullet))
23443 ;; Reversed case: Move point to special position when
23444 ;; point was already at beginning of line and command is
23445 ;; repeated.
23446 (when (and (= (point) pos) (eq last-command this-command))
23447 (goto-char after-bullet))))))))
23448 (org-no-warnings
23449 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23450 (setq disable-point-adjustment
23451 (or (not (invisible-p (point)))
23452 (not (invisible-p (max (point-min) (1- (point))))))))
23454 (defun org-end-of-line (&optional arg)
23455 "Go to the end of the line.
23456 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23457 tags on the first attempt, and only move to after the tags when
23458 the cursor is already beyond the end of the headline."
23459 (interactive "P")
23460 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23461 org-special-ctrl-a/e))
23462 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23463 'end-of-visual-line)
23464 ((fboundp 'move-end-of-line) 'move-end-of-line)
23465 (t 'end-of-line)))
23466 deactivate-mark)
23467 (if (or (not special) arg) (call-interactively move-fun)
23468 (let* ((element (save-excursion (beginning-of-line)
23469 (org-element-at-point)))
23470 (type (org-element-type element)))
23471 (cond
23472 ((memq type '(headline inlinetask))
23473 (let ((pos (point)))
23474 (beginning-of-line 1)
23475 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23476 (if (eq special t)
23477 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23478 (goto-char (match-beginning 1))
23479 (goto-char (match-end 0)))
23480 (if (or (< pos (match-end 0))
23481 (not (eq this-command last-command)))
23482 (goto-char (match-end 0))
23483 (goto-char (match-beginning 1))))
23484 (call-interactively move-fun))))
23485 ((outline-invisible-p (line-end-position))
23486 ;; If element is hidden, `move-end-of-line' would put point
23487 ;; after it. Use `end-of-line' to stay on current line.
23488 (call-interactively 'end-of-line))
23489 (t (call-interactively move-fun)))))
23490 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23491 (setq disable-point-adjustment
23492 (or (not (invisible-p (point)))
23493 (not (invisible-p (max (point-min) (1- (point))))))))
23495 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23496 (define-key org-mode-map "\C-e" 'org-end-of-line)
23498 (defun org-backward-sentence (&optional arg)
23499 "Go to beginning of sentence, or beginning of table field.
23500 This will call `backward-sentence' or `org-table-beginning-of-field',
23501 depending on context."
23502 (interactive "P")
23503 (cond
23504 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23505 (t (call-interactively 'backward-sentence))))
23507 (defun org-forward-sentence (&optional arg)
23508 "Go to end of sentence, or end of table field.
23509 This will call `forward-sentence' or `org-table-end-of-field',
23510 depending on context."
23511 (interactive "P")
23512 (cond
23513 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23514 (t (call-interactively 'forward-sentence))))
23516 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23517 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23519 (defun org-kill-line (&optional arg)
23520 "Kill line, to tags or end of line."
23521 (interactive "P")
23522 (cond
23523 ((or (not org-special-ctrl-k)
23524 (bolp)
23525 (not (org-at-heading-p)))
23526 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23527 org-ctrl-k-protect-subtree)
23528 (if (or (eq org-ctrl-k-protect-subtree 'error)
23529 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23530 (user-error "C-k aborted as it would kill a hidden subtree")))
23531 (call-interactively
23532 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23533 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23534 (kill-region (point) (match-beginning 1))
23535 (org-set-tags nil t))
23536 (t (kill-region (point) (point-at-eol)))))
23538 (define-key org-mode-map "\C-k" 'org-kill-line)
23540 (defun org-yank (&optional arg)
23541 "Yank. If the kill is a subtree, treat it specially.
23542 This command will look at the current kill and check if is a single
23543 subtree, or a series of subtrees[1]. If it passes the test, and if the
23544 cursor is at the beginning of a line or after the stars of a currently
23545 empty headline, then the yank is handled specially. How exactly depends
23546 on the value of the following variables, both set by default.
23548 `org-yank-folded-subtrees'
23549 When set, the subtree(s) will be folded after insertion, but only
23550 if doing so would now swallow text after the yanked text.
23552 `org-yank-adjusted-subtrees'
23553 When set, the subtree will be promoted or demoted in order to
23554 fit into the local outline tree structure, which means that the
23555 level will be adjusted so that it becomes the smaller one of the
23556 two *visible* surrounding headings.
23558 Any prefix to this command will cause `yank' to be called directly with
23559 no special treatment. In particular, a simple \\[universal-argument] prefix \
23560 will just
23561 plainly yank the text as it is.
23563 \[1] The test checks if the first non-white line is a heading
23564 and if there are no other headings with fewer stars."
23565 (interactive "P")
23566 (org-yank-generic 'yank arg))
23568 (defun org-yank-generic (command arg)
23569 "Perform some yank-like command.
23571 This function implements the behavior described in the `org-yank'
23572 documentation. However, it has been generalized to work for any
23573 interactive command with similar behavior."
23575 ;; pretend to be command COMMAND
23576 (setq this-command command)
23578 (if arg
23579 (call-interactively command)
23581 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23582 (and (org-kill-is-subtree-p)
23583 (or (bolp)
23584 (and (looking-at "[ \t]*$")
23585 (string-match
23586 "\\`\\*+\\'"
23587 (buffer-substring (point-at-bol) (point)))))))
23588 swallowp)
23589 (cond
23590 ((and subtreep org-yank-folded-subtrees)
23591 (let ((beg (point))
23592 end)
23593 (if (and subtreep org-yank-adjusted-subtrees)
23594 (org-paste-subtree nil nil 'for-yank)
23595 (call-interactively command))
23597 (setq end (point))
23598 (goto-char beg)
23599 (when (and (bolp) subtreep
23600 (not (setq swallowp
23601 (org-yank-folding-would-swallow-text beg end))))
23602 (org-with-limited-levels
23603 (or (looking-at org-outline-regexp)
23604 (re-search-forward org-outline-regexp-bol end t))
23605 (while (and (< (point) end) (looking-at org-outline-regexp))
23606 (hide-subtree)
23607 (org-cycle-show-empty-lines 'folded)
23608 (condition-case nil
23609 (outline-forward-same-level 1)
23610 (error (goto-char end))))))
23611 (when swallowp
23612 (message
23613 "Inserted text not folded because that would swallow text"))
23615 (goto-char end)
23616 (skip-chars-forward " \t\n\r")
23617 (beginning-of-line 1)
23618 (push-mark beg 'nomsg)))
23619 ((and subtreep org-yank-adjusted-subtrees)
23620 (let ((beg (point-at-bol)))
23621 (org-paste-subtree nil nil 'for-yank)
23622 (push-mark beg 'nomsg)))
23624 (call-interactively command))))))
23626 (defun org-yank-folding-would-swallow-text (beg end)
23627 "Would hide-subtree at BEG swallow any text after END?"
23628 (let (level)
23629 (org-with-limited-levels
23630 (save-excursion
23631 (goto-char beg)
23632 (when (or (looking-at org-outline-regexp)
23633 (re-search-forward org-outline-regexp-bol end t))
23634 (setq level (org-outline-level)))
23635 (goto-char end)
23636 (skip-chars-forward " \t\r\n\v\f")
23637 (if (or (eobp)
23638 (and (bolp) (looking-at org-outline-regexp)
23639 (<= (org-outline-level) level)))
23640 nil ; Nothing would be swallowed
23641 t))))) ; something would swallow
23643 (define-key org-mode-map "\C-y" 'org-yank)
23645 (defun org-truely-invisible-p ()
23646 "Check if point is at a character currently not visible.
23647 This version does not only check the character property, but also
23648 `visible-mode'."
23649 ;; Early versions of noutline don't have `outline-invisible-p'.
23650 (if (org-bound-and-true-p visible-mode)
23652 (outline-invisible-p)))
23654 (defun org-invisible-p2 ()
23655 "Check if point is at a character currently not visible."
23656 (save-excursion
23657 (if (and (eolp) (not (bobp))) (backward-char 1))
23658 ;; Early versions of noutline don't have `outline-invisible-p'.
23659 (outline-invisible-p)))
23661 (defun org-back-to-heading (&optional invisible-ok)
23662 "Call `outline-back-to-heading', but provide a better error message."
23663 (condition-case nil
23664 (outline-back-to-heading invisible-ok)
23665 (error (error "Before first headline at position %d in buffer %s"
23666 (point) (current-buffer)))))
23668 (defun org-before-first-heading-p ()
23669 "Before first heading?"
23670 (save-excursion
23671 (end-of-line)
23672 (null (re-search-backward org-outline-regexp-bol nil t))))
23674 (defun org-at-heading-p (&optional ignored)
23675 (outline-on-heading-p t))
23676 ;; Compatibility alias with Org versions < 7.8.03
23677 (defalias 'org-on-heading-p 'org-at-heading-p)
23679 (defun org-in-commented-heading-p (&optional no-inheritance)
23680 "Non-nil if point is under a commented heading.
23681 This function also checks ancestors of the current headline,
23682 unless optional argument NO-INHERITANCE is non-nil."
23683 (cond
23684 ((org-before-first-heading-p) nil)
23685 ((let ((headline (nth 4 (org-heading-components))))
23686 (and headline
23687 (let ((case-fold-search nil))
23688 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23689 headline)))))
23690 (no-inheritance nil)
23692 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23694 (defun org-at-comment-p nil
23695 "Is cursor in a commented line?"
23696 (save-excursion
23697 (save-match-data
23698 (beginning-of-line)
23699 (looking-at "^[ \t]*# "))))
23701 (defun org-at-drawer-p nil
23702 "Is cursor at a drawer keyword?"
23703 (save-excursion
23704 (move-beginning-of-line 1)
23705 (looking-at org-drawer-regexp)))
23707 (defun org-at-block-p nil
23708 "Is cursor at a block keyword?"
23709 (save-excursion
23710 (move-beginning-of-line 1)
23711 (looking-at org-block-regexp)))
23713 (defun org-point-at-end-of-empty-headline ()
23714 "If point is at the end of an empty headline, return t, else nil.
23715 If the heading only contains a TODO keyword, it is still still considered
23716 empty."
23717 (and (looking-at "[ \t]*$")
23718 (when org-todo-line-regexp
23719 (save-excursion
23720 (beginning-of-line 1)
23721 (let ((case-fold-search nil))
23722 (looking-at org-todo-line-regexp)
23723 (string= (match-string 3) ""))))))
23725 (defun org-at-heading-or-item-p ()
23726 (or (org-at-heading-p) (org-at-item-p)))
23728 (defun org-at-target-p ()
23729 (or (org-in-regexp org-radio-target-regexp)
23730 (org-in-regexp org-target-regexp)))
23731 ;; Compatibility alias with Org versions < 7.8.03
23732 (defalias 'org-on-target-p 'org-at-target-p)
23734 (defun org-up-heading-all (arg)
23735 "Move to the heading line of which the present line is a subheading.
23736 This function considers both visible and invisible heading lines.
23737 With argument, move up ARG levels."
23738 (if (fboundp 'outline-up-heading-all)
23739 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23740 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23742 (defun org-up-heading-safe ()
23743 "Move to the heading line of which the present line is a subheading.
23744 This version will not throw an error. It will return the level of the
23745 headline found, or nil if no higher level is found.
23747 Also, this function will be a lot faster than `outline-up-heading',
23748 because it relies on stars being the outline starters. This can really
23749 make a significant difference in outlines with very many siblings."
23750 (when (ignore-errors (org-back-to-heading t))
23751 (let ((level-up (1- (funcall outline-level))))
23752 (and (> level-up 0)
23753 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23754 (funcall outline-level)))))
23756 (defun org-first-sibling-p ()
23757 "Is this heading the first child of its parents?"
23758 (interactive)
23759 (let ((re org-outline-regexp-bol)
23760 level l)
23761 (unless (org-at-heading-p t)
23762 (user-error "Not at a heading"))
23763 (setq level (funcall outline-level))
23764 (save-excursion
23765 (if (not (re-search-backward re nil t))
23767 (setq l (funcall outline-level))
23768 (< l level)))))
23770 (defun org-goto-sibling (&optional previous)
23771 "Goto the next sibling, even if it is invisible.
23772 When PREVIOUS is set, go to the previous sibling instead. Returns t
23773 when a sibling was found. When none is found, return nil and don't
23774 move point."
23775 (let ((fun (if previous 're-search-backward 're-search-forward))
23776 (pos (point))
23777 (re org-outline-regexp-bol)
23778 level l)
23779 (when (ignore-errors (org-back-to-heading t))
23780 (setq level (funcall outline-level))
23781 (catch 'exit
23782 (or previous (forward-char 1))
23783 (while (funcall fun re nil t)
23784 (setq l (funcall outline-level))
23785 (when (< l level) (goto-char pos) (throw 'exit nil))
23786 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23787 (goto-char pos)
23788 nil))))
23790 (defun org-show-siblings ()
23791 "Show all siblings of the current headline."
23792 (save-excursion
23793 (while (org-goto-sibling) (org-flag-heading nil)))
23794 (save-excursion
23795 (while (org-goto-sibling 'previous)
23796 (org-flag-heading nil))))
23798 (defun org-goto-first-child ()
23799 "Goto the first child, even if it is invisible.
23800 Return t when a child was found. Otherwise don't move point and
23801 return nil."
23802 (let (level (pos (point)) (re org-outline-regexp-bol))
23803 (when (ignore-errors (org-back-to-heading t))
23804 (setq level (outline-level))
23805 (forward-char 1)
23806 (if (and (re-search-forward re nil t) (> (outline-level) level))
23807 (progn (goto-char (match-beginning 0)) t)
23808 (goto-char pos) nil))))
23810 (defun org-show-hidden-entry ()
23811 "Show an entry where even the heading is hidden."
23812 (save-excursion
23813 (org-show-entry)))
23815 (defun org-flag-heading (flag &optional entry)
23816 "Flag the current heading. FLAG non-nil means make invisible.
23817 When ENTRY is non-nil, show the entire entry."
23818 (save-excursion
23819 (org-back-to-heading t)
23820 ;; Check if we should show the entire entry
23821 (if entry
23822 (progn
23823 (org-show-entry)
23824 (save-excursion
23825 (and (outline-next-heading)
23826 (org-flag-heading nil))))
23827 (outline-flag-region (max (point-min) (1- (point)))
23828 (save-excursion (outline-end-of-heading) (point))
23829 flag))))
23831 (defun org-get-next-sibling ()
23832 "Move to next heading of the same level, and return point.
23833 If there is no such heading, return nil.
23834 This is like outline-next-sibling, but invisible headings are ok."
23835 (let ((level (funcall outline-level)))
23836 (outline-next-heading)
23837 (while (and (not (eobp)) (> (funcall outline-level) level))
23838 (outline-next-heading))
23839 (if (or (eobp) (< (funcall outline-level) level))
23841 (point))))
23843 (defun org-get-last-sibling ()
23844 "Move to previous heading of the same level, and return point.
23845 If there is no such heading, return nil."
23846 (let ((opoint (point))
23847 (level (funcall outline-level)))
23848 (outline-previous-heading)
23849 (when (and (/= (point) opoint) (outline-on-heading-p t))
23850 (while (and (> (funcall outline-level) level)
23851 (not (bobp)))
23852 (outline-previous-heading))
23853 (if (< (funcall outline-level) level)
23855 (point)))))
23857 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23858 "Goto to the end of a subtree."
23859 ;; This contains an exact copy of the original function, but it uses
23860 ;; `org-back-to-heading', to make it work also in invisible
23861 ;; trees. And is uses an invisible-ok argument.
23862 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23863 ;; Furthermore, when used inside Org, finding the end of a large subtree
23864 ;; with many children and grandchildren etc, this can be much faster
23865 ;; than the outline version.
23866 (org-back-to-heading invisible-ok)
23867 (let ((first t)
23868 (level (funcall outline-level)))
23869 (if (and (derived-mode-p 'org-mode) (< level 1000))
23870 ;; A true heading (not a plain list item), in Org-mode
23871 ;; This means we can easily find the end by looking
23872 ;; only for the right number of stars. Using a regexp to do
23873 ;; this is so much faster than using a Lisp loop.
23874 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23875 (forward-char 1)
23876 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23877 ;; something else, do it the slow way
23878 (while (and (not (eobp))
23879 (or first (> (funcall outline-level) level)))
23880 (setq first nil)
23881 (outline-next-heading)))
23882 (unless to-heading
23883 (if (memq (preceding-char) '(?\n ?\^M))
23884 (progn
23885 ;; Go to end of line before heading
23886 (forward-char -1)
23887 (if (memq (preceding-char) '(?\n ?\^M))
23888 ;; leave blank line before heading
23889 (forward-char -1))))))
23890 (point))
23892 (defun org-end-of-meta-data-and-drawers ()
23893 "Jump to the first text after meta data and drawers in the current entry.
23894 This will move over empty lines, lines with planning time stamps,
23895 clocking lines, and drawers."
23896 (org-back-to-heading t)
23897 (let ((end (save-excursion (outline-next-heading) (point)))
23898 (re (concat "\\(" org-drawer-regexp "\\)"
23899 "\\|" "[ \t]*" org-keyword-time-regexp)))
23900 (forward-line 1)
23901 (while (re-search-forward re end t)
23902 (if (not (match-end 1))
23903 ;; empty or planning line
23904 (forward-line 1)
23905 ;; a drawer, find the end
23906 (re-search-forward "^[ \t]*:END:" end 'move)
23907 (forward-line 1)))
23908 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23909 (point)))
23911 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23912 "Move forward to the ARG'th subheading at same level as this one.
23913 Stop at the first and last subheadings of a superior heading.
23914 Normally this only looks at visible headings, but when INVISIBLE-OK is
23915 non-nil it will also look at invisible ones."
23916 (interactive "p")
23917 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23918 (if (and arg (< arg 0))
23919 (goto-char (point-min))
23920 (outline-next-heading))
23921 (org-at-heading-p)
23922 (let ((level (- (match-end 0) (match-beginning 0) 1))
23923 (f (if (and arg (< arg 0))
23924 're-search-backward
23925 're-search-forward))
23926 (count (if arg (abs arg) 1))
23927 (result (point)))
23928 (while (and (prog1 (> count 0)
23929 (forward-char (if (and arg (< arg 0)) -1 1)))
23930 (funcall f org-outline-regexp-bol nil 'move))
23931 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23932 (cond ((< l level) (setq count 0))
23933 ((and (= l level)
23934 (or invisible-ok
23935 (progn
23936 (goto-char (line-beginning-position))
23937 (not (outline-invisible-p)))))
23938 (setq count (1- count))
23939 (when (eq l level)
23940 (setq result (point)))))))
23941 (goto-char result))
23942 (beginning-of-line 1)))
23944 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23945 "Move backward to the ARG'th subheading at same level as this one.
23946 Stop at the first and last subheadings of a superior heading."
23947 (interactive "p")
23948 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23950 (defun org-next-block (arg &optional backward block-regexp)
23951 "Jump to the next block.
23952 With a prefix argument ARG, jump forward ARG many source blocks.
23953 When BACKWARD is non-nil, jump to the previous block.
23954 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23955 (interactive "p")
23956 (let ((re (or block-regexp org-block-regexp))
23957 (re-search-fn (or (and backward 're-search-backward)
23958 're-search-forward)))
23959 (if (looking-at re) (forward-char 1))
23960 (condition-case nil
23961 (funcall re-search-fn re nil nil arg)
23962 (error (user-error "No %s code blocks"
23963 (if backward "previous" "further" ))))
23964 (goto-char (match-beginning 0)) (org-show-context)))
23966 (defun org-previous-block (arg &optional block-regexp)
23967 "Jump to the previous block.
23968 With a prefix argument ARG, jump backward ARG many source blocks.
23969 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23970 (interactive "p")
23971 (org-next-block arg t block-regexp))
23973 (defun org-forward-paragraph ()
23974 "Move forward to beginning of next paragraph or equivalent.
23976 The function moves point to the beginning of the next visible
23977 structural element, which can be a paragraph, a table, a list
23978 item, etc. It also provides some special moves for convenience:
23980 - On an affiliated keyword, jump to the beginning of the
23981 relative element.
23982 - On an item or a footnote definition, move to the second
23983 element inside, if any.
23984 - On a table or a property drawer, jump after it.
23985 - On a verse or source block, stop after blank lines."
23986 (interactive)
23987 (when (eobp) (user-error "Cannot move further down"))
23988 (let* ((deactivate-mark nil)
23989 (element (org-element-at-point))
23990 (type (org-element-type element))
23991 (post-affiliated (org-element-property :post-affiliated element))
23992 (contents-begin (org-element-property :contents-begin element))
23993 (contents-end (org-element-property :contents-end element))
23994 (end (let ((end (org-element-property :end element)) (parent element))
23995 (while (and (setq parent (org-element-property :parent parent))
23996 (= (org-element-property :contents-end parent) end))
23997 (setq end (org-element-property :end parent)))
23998 end)))
23999 (cond ((not element)
24000 (skip-chars-forward " \r\t\n")
24001 (or (eobp) (beginning-of-line)))
24002 ;; On affiliated keywords, move to element's beginning.
24003 ((< (point) post-affiliated)
24004 (goto-char post-affiliated))
24005 ;; At a table row, move to the end of the table. Similarly,
24006 ;; at a node property, move to the end of the property
24007 ;; drawer.
24008 ((memq type '(node-property table-row))
24009 (goto-char (org-element-property
24010 :end (org-element-property :parent element))))
24011 ((memq type '(property-drawer table)) (goto-char end))
24012 ;; Consider blank lines as separators in verse and source
24013 ;; blocks to ease editing.
24014 ((memq type '(src-block verse-block))
24015 (when (eq type 'src-block)
24016 (setq contents-end
24017 (save-excursion (goto-char end)
24018 (skip-chars-backward " \r\t\n")
24019 (line-beginning-position))))
24020 (beginning-of-line)
24021 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24022 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24023 (goto-char end)
24024 (skip-chars-forward " \r\t\n")
24025 (if (= (point) contents-end) (goto-char end)
24026 (beginning-of-line))))
24027 ;; With no contents, just skip element.
24028 ((not contents-begin) (goto-char end))
24029 ;; If contents are invisible, skip the element altogether.
24030 ((outline-invisible-p (line-end-position))
24031 (case type
24032 (headline
24033 (org-with-limited-levels (outline-next-visible-heading 1)))
24034 ;; At a plain list, make sure we move to the next item
24035 ;; instead of skipping the whole list.
24036 (plain-list (forward-char)
24037 (org-forward-paragraph))
24038 (otherwise (goto-char end))))
24039 ((>= (point) contents-end) (goto-char end))
24040 ((>= (point) contents-begin)
24041 ;; This can only happen on paragraphs and plain lists.
24042 (case type
24043 (paragraph (goto-char end))
24044 ;; At a plain list, try to move to second element in
24045 ;; first item, if possible.
24046 (plain-list (end-of-line)
24047 (org-forward-paragraph))))
24048 ;; When contents start on the middle of a line (e.g. in
24049 ;; items and footnote definitions), try to reach first
24050 ;; element starting after current line.
24051 ((> (line-end-position) contents-begin)
24052 (end-of-line)
24053 (org-forward-paragraph))
24054 (t (goto-char contents-begin)))))
24056 (defun org-backward-paragraph ()
24057 "Move backward to start of previous paragraph or equivalent.
24059 The function moves point to the beginning of the current
24060 structural element, which can be a paragraph, a table, a list
24061 item, etc., or to the beginning of the previous visible one if
24062 point is already there. It also provides some special moves for
24063 convenience:
24065 - On an affiliated keyword, jump to the first one.
24066 - On a table or a property drawer, move to its beginning.
24067 - On a verse or source block, stop before blank lines."
24068 (interactive)
24069 (when (bobp) (user-error "Cannot move further up"))
24070 (let* ((deactivate-mark nil)
24071 (element (org-element-at-point))
24072 (type (org-element-type element))
24073 (contents-begin (org-element-property :contents-begin element))
24074 (contents-end (org-element-property :contents-end element))
24075 (post-affiliated (org-element-property :post-affiliated element))
24076 (begin (org-element-property :begin element)))
24077 (cond
24078 ((not element) (goto-char (point-min)))
24079 ((= (point) begin)
24080 (backward-char)
24081 (org-backward-paragraph))
24082 ((<= (point) post-affiliated) (goto-char begin))
24083 ((memq type '(node-property table-row))
24084 (goto-char (org-element-property
24085 :post-affiliated (org-element-property :parent element))))
24086 ((memq type '(property-drawer table)) (goto-char begin))
24087 ((memq type '(src-block verse-block))
24088 (when (eq type 'src-block)
24089 (setq contents-begin
24090 (save-excursion (goto-char begin) (forward-line) (point))))
24091 (if (= (point) contents-begin) (goto-char post-affiliated)
24092 ;; Inside a verse block, see blank lines as paragraph
24093 ;; separators.
24094 (let ((origin (point)))
24095 (skip-chars-backward " \r\t\n" contents-begin)
24096 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24097 (skip-chars-forward " \r\t\n" origin)
24098 (if (= (point) origin) (goto-char contents-begin)
24099 (beginning-of-line))))))
24100 ((not contents-begin) (goto-char (or post-affiliated begin)))
24101 ((eq type 'paragraph)
24102 (goto-char contents-begin)
24103 ;; When at first paragraph in an item or a footnote definition,
24104 ;; move directly to beginning of line.
24105 (let ((parent-contents
24106 (org-element-property
24107 :contents-begin (org-element-property :parent element))))
24108 (when (and parent-contents (= parent-contents contents-begin))
24109 (beginning-of-line))))
24110 ;; At the end of a greater element, move to the beginning of the
24111 ;; last element within.
24112 ((>= (point) contents-end)
24113 (goto-char (1- contents-end))
24114 (org-backward-paragraph))
24115 (t (goto-char (or post-affiliated begin))))
24116 ;; Ensure we never leave point invisible.
24117 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24119 (defun org-forward-element ()
24120 "Move forward by one element.
24121 Move to the next element at the same level, when possible."
24122 (interactive)
24123 (cond ((eobp) (user-error "Cannot move further down"))
24124 ((org-with-limited-levels (org-at-heading-p))
24125 (let ((origin (point)))
24126 (goto-char (org-end-of-subtree nil t))
24127 (unless (org-with-limited-levels (org-at-heading-p))
24128 (goto-char origin)
24129 (user-error "Cannot move further down"))))
24131 (let* ((elem (org-element-at-point))
24132 (end (org-element-property :end elem))
24133 (parent (org-element-property :parent elem)))
24134 (cond ((and parent (= (org-element-property :contents-end parent) end))
24135 (goto-char (org-element-property :end parent)))
24136 ((integer-or-marker-p end) (goto-char end))
24137 (t (message "No element at point")))))))
24139 (defun org-backward-element ()
24140 "Move backward by one element.
24141 Move to the previous element at the same level, when possible."
24142 (interactive)
24143 (cond ((bobp) (user-error "Cannot move further up"))
24144 ((org-with-limited-levels (org-at-heading-p))
24145 ;; At a headline, move to the previous one, if any, or stay
24146 ;; here.
24147 (let ((origin (point)))
24148 (org-with-limited-levels (org-backward-heading-same-level 1))
24149 ;; When current headline has no sibling above, move to its
24150 ;; parent.
24151 (when (= (point) origin)
24152 (or (org-with-limited-levels (org-up-heading-safe))
24153 (progn (goto-char origin)
24154 (user-error "Cannot move further up"))))))
24156 (let* ((elem (org-element-at-point))
24157 (beg (org-element-property :begin elem)))
24158 (cond
24159 ;; Move to beginning of current element if point isn't
24160 ;; there already.
24161 ((null beg) (message "No element at point"))
24162 ((/= (point) beg) (goto-char beg))
24163 (t (goto-char beg)
24164 (skip-chars-backward " \r\t\n")
24165 (unless (bobp)
24166 (let ((prev (org-element-at-point)))
24167 (goto-char (org-element-property :begin prev))
24168 (while (and (setq prev (org-element-property :parent prev))
24169 (<= (org-element-property :end prev) beg))
24170 (goto-char (org-element-property :begin prev)))))))))))
24172 (defun org-up-element ()
24173 "Move to upper element."
24174 (interactive)
24175 (if (org-with-limited-levels (org-at-heading-p))
24176 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24177 (let* ((elem (org-element-at-point))
24178 (parent (org-element-property :parent elem)))
24179 (if parent (goto-char (org-element-property :begin parent))
24180 (if (org-with-limited-levels (org-before-first-heading-p))
24181 (user-error "No surrounding element")
24182 (org-with-limited-levels (org-back-to-heading)))))))
24184 (defvar org-element-greater-elements)
24185 (defun org-down-element ()
24186 "Move to inner element."
24187 (interactive)
24188 (let ((element (org-element-at-point)))
24189 (cond
24190 ((memq (org-element-type element) '(plain-list table))
24191 (goto-char (org-element-property :contents-begin element))
24192 (forward-char))
24193 ((memq (org-element-type element) org-element-greater-elements)
24194 ;; If contents are hidden, first disclose them.
24195 (when (outline-invisible-p (line-end-position)) (org-cycle))
24196 (goto-char (or (org-element-property :contents-begin element)
24197 (user-error "No content for this element"))))
24198 (t (user-error "No inner element")))))
24200 (defun org-drag-element-backward ()
24201 "Move backward element at point."
24202 (interactive)
24203 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24204 (let* ((elem (org-element-at-point))
24205 (prev-elem
24206 (save-excursion
24207 (goto-char (org-element-property :begin elem))
24208 (skip-chars-backward " \r\t\n")
24209 (unless (bobp)
24210 (let* ((beg (org-element-property :begin elem))
24211 (prev (org-element-at-point))
24212 (up prev))
24213 (while (and (setq up (org-element-property :parent up))
24214 (<= (org-element-property :end up) beg))
24215 (setq prev up))
24216 prev)))))
24217 ;; Error out if no previous element or previous element is
24218 ;; a parent of the current one.
24219 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24220 (user-error "Cannot drag element backward")
24221 (let ((pos (point)))
24222 (org-element-swap-A-B prev-elem elem)
24223 (goto-char (+ (org-element-property :begin prev-elem)
24224 (- pos (org-element-property :begin elem)))))))))
24226 (defun org-drag-element-forward ()
24227 "Move forward element at point."
24228 (interactive)
24229 (let* ((pos (point))
24230 (elem (org-element-at-point)))
24231 (when (= (point-max) (org-element-property :end elem))
24232 (user-error "Cannot drag element forward"))
24233 (goto-char (org-element-property :end elem))
24234 (let ((next-elem (org-element-at-point)))
24235 (when (or (org-element-nested-p elem next-elem)
24236 (and (eq (org-element-type next-elem) 'headline)
24237 (not (eq (org-element-type elem) 'headline))))
24238 (goto-char pos)
24239 (user-error "Cannot drag element forward"))
24240 ;; Compute new position of point: it's shifted by NEXT-ELEM
24241 ;; body's length (without final blanks) and by the length of
24242 ;; blanks between ELEM and NEXT-ELEM.
24243 (let ((size-next (- (save-excursion
24244 (goto-char (org-element-property :end next-elem))
24245 (skip-chars-backward " \r\t\n")
24246 (forward-line)
24247 ;; Small correction if buffer doesn't end
24248 ;; with a newline character.
24249 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24250 (org-element-property :begin next-elem)))
24251 (size-blank (- (org-element-property :end elem)
24252 (save-excursion
24253 (goto-char (org-element-property :end elem))
24254 (skip-chars-backward " \r\t\n")
24255 (forward-line)
24256 (point)))))
24257 (org-element-swap-A-B elem next-elem)
24258 (goto-char (+ pos size-next size-blank))))))
24260 (defun org-drag-line-forward (arg)
24261 "Drag the line at point ARG lines forward."
24262 (interactive "p")
24263 (dotimes (n (abs arg))
24264 (let ((c (current-column)))
24265 (if (< 0 arg)
24266 (progn
24267 (beginning-of-line 2)
24268 (transpose-lines 1)
24269 (beginning-of-line 0))
24270 (transpose-lines 1)
24271 (beginning-of-line -1))
24272 (org-move-to-column c))))
24274 (defun org-drag-line-backward (arg)
24275 "Drag the line at point ARG lines backward."
24276 (interactive "p")
24277 (org-drag-line-forward (- arg)))
24279 (defun org-mark-element ()
24280 "Put point at beginning of this element, mark at end.
24282 Interactively, if this command is repeated or (in Transient Mark
24283 mode) if the mark is active, it marks the next element after the
24284 ones already marked."
24285 (interactive)
24286 (let (deactivate-mark)
24287 (if (and (org-called-interactively-p 'any)
24288 (or (and (eq last-command this-command) (mark t))
24289 (and transient-mark-mode mark-active)))
24290 (set-mark
24291 (save-excursion
24292 (goto-char (mark))
24293 (goto-char (org-element-property :end (org-element-at-point)))))
24294 (let ((element (org-element-at-point)))
24295 (end-of-line)
24296 (push-mark (org-element-property :end element) t t)
24297 (goto-char (org-element-property :begin element))))))
24299 (defun org-narrow-to-element ()
24300 "Narrow buffer to current element."
24301 (interactive)
24302 (let ((elem (org-element-at-point)))
24303 (cond
24304 ((eq (car elem) 'headline)
24305 (narrow-to-region
24306 (org-element-property :begin elem)
24307 (org-element-property :end elem)))
24308 ((memq (car elem) org-element-greater-elements)
24309 (narrow-to-region
24310 (org-element-property :contents-begin elem)
24311 (org-element-property :contents-end elem)))
24313 (narrow-to-region
24314 (org-element-property :begin elem)
24315 (org-element-property :end elem))))))
24317 (defun org-transpose-element ()
24318 "Transpose current and previous elements, keeping blank lines between.
24319 Point is moved after both elements."
24320 (interactive)
24321 (org-skip-whitespace)
24322 (let ((end (org-element-property :end (org-element-at-point))))
24323 (org-drag-element-backward)
24324 (goto-char end)))
24326 (defun org-unindent-buffer ()
24327 "Un-indent the visible part of the buffer.
24328 Relative indentation (between items, inside blocks, etc.) isn't
24329 modified."
24330 (interactive)
24331 (unless (eq major-mode 'org-mode)
24332 (user-error "Cannot un-indent a buffer not in Org mode"))
24333 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24334 unindent-tree ; For byte-compiler.
24335 (unindent-tree
24336 (function
24337 (lambda (contents)
24338 (mapc
24339 (lambda (element)
24340 (if (memq (org-element-type element) '(headline section))
24341 (funcall unindent-tree (org-element-contents element))
24342 (save-excursion
24343 (save-restriction
24344 (narrow-to-region
24345 (org-element-property :begin element)
24346 (org-element-property :end element))
24347 (org-do-remove-indentation)))))
24348 (reverse contents))))))
24349 (funcall unindent-tree (org-element-contents parse-tree))))
24351 (defun org-show-subtree ()
24352 "Show everything after this heading at deeper levels."
24353 (interactive)
24354 (outline-flag-region
24355 (point)
24356 (save-excursion
24357 (org-end-of-subtree t t))
24358 nil))
24360 (defun org-show-entry ()
24361 "Show the body directly following this heading.
24362 Show the heading too, if it is currently invisible."
24363 (interactive)
24364 (save-excursion
24365 (ignore-errors
24366 (org-back-to-heading t)
24367 (outline-flag-region
24368 (max (point-min) (1- (point)))
24369 (save-excursion
24370 (if (re-search-forward
24371 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24372 (match-beginning 1)
24373 (point-max)))
24374 nil)
24375 (org-cycle-hide-drawers 'children))))
24377 (defun org-make-options-regexp (kwds &optional extra)
24378 "Make a regular expression for keyword lines."
24379 (concat
24380 "^[ \t]*#\\+\\("
24381 (mapconcat 'regexp-quote kwds "\\|")
24382 (if extra (concat "\\|" extra))
24383 "\\):[ \t]*\\(.*\\)"))
24385 ;; Make isearch reveal the necessary context
24386 (defun org-isearch-end ()
24387 "Reveal context after isearch exits."
24388 (when isearch-success ; only if search was successful
24389 (if (featurep 'xemacs)
24390 ;; Under XEmacs, the hook is run in the correct place,
24391 ;; we directly show the context.
24392 (org-show-context 'isearch)
24393 ;; In Emacs the hook runs *before* restoring the overlays.
24394 ;; So we have to use a one-time post-command-hook to do this.
24395 ;; (Emacs 22 has a special variable, see function `org-mode')
24396 (unless (and (boundp 'isearch-mode-end-hook-quit)
24397 isearch-mode-end-hook-quit)
24398 ;; Only when the isearch was not quitted.
24399 (org-add-hook 'post-command-hook 'org-isearch-post-command
24400 'append 'local)))))
24402 (defun org-isearch-post-command ()
24403 "Remove self from hook, and show context."
24404 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24405 (org-show-context 'isearch))
24408 ;;;; Integration with and fixes for other packages
24410 ;;; Imenu support
24412 (defvar org-imenu-markers nil
24413 "All markers currently used by Imenu.")
24414 (make-variable-buffer-local 'org-imenu-markers)
24416 (defun org-imenu-new-marker (&optional pos)
24417 "Return a new marker for use by Imenu, and remember the marker."
24418 (let ((m (make-marker)))
24419 (move-marker m (or pos (point)))
24420 (push m org-imenu-markers)
24423 (defun org-imenu-get-tree ()
24424 "Produce the index for Imenu."
24425 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24426 (setq org-imenu-markers nil)
24427 (let* ((n org-imenu-depth)
24428 (re (concat "^" (org-get-limited-outline-regexp)))
24429 (subs (make-vector (1+ n) nil))
24430 (last-level 0)
24431 m level head0 head)
24432 (save-excursion
24433 (save-restriction
24434 (widen)
24435 (goto-char (point-max))
24436 (while (re-search-backward re nil t)
24437 (setq level (org-reduced-level (funcall outline-level)))
24438 (when (and (<= level n)
24439 (looking-at org-complex-heading-regexp)
24440 (setq head0 (org-match-string-no-properties 4)))
24441 (setq head (org-link-display-format head0)
24442 m (org-imenu-new-marker))
24443 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24444 (if (>= level last-level)
24445 (push (cons head m) (aref subs level))
24446 (push (cons head (aref subs (1+ level))) (aref subs level))
24447 (loop for i from (1+ level) to n do (aset subs i nil)))
24448 (setq last-level level)))))
24449 (aref subs 1)))
24451 (eval-after-load "imenu"
24452 '(progn
24453 (add-hook 'imenu-after-jump-hook
24454 (lambda ()
24455 (if (derived-mode-p 'org-mode)
24456 (org-show-context 'org-goto))))))
24458 (defun org-link-display-format (link)
24459 "Replace a link with its the description.
24460 If there is no description, use the link target."
24461 (save-match-data
24462 (if (string-match org-bracket-link-analytic-regexp link)
24463 (replace-match (if (match-end 5)
24464 (match-string 5 link)
24465 (concat (match-string 1 link)
24466 (match-string 3 link)))
24467 nil t link)
24468 link)))
24470 (defun org-toggle-link-display ()
24471 "Toggle the literal or descriptive display of links."
24472 (interactive)
24473 (if org-descriptive-links
24474 (progn (org-remove-from-invisibility-spec '(org-link))
24475 (org-restart-font-lock)
24476 (setq org-descriptive-links nil))
24477 (progn (add-to-invisibility-spec '(org-link))
24478 (org-restart-font-lock)
24479 (setq org-descriptive-links t))))
24481 ;; Speedbar support
24483 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24484 "Overlay marking the agenda restriction line in speedbar.")
24485 (overlay-put org-speedbar-restriction-lock-overlay
24486 'face 'org-agenda-restriction-lock)
24487 (overlay-put org-speedbar-restriction-lock-overlay
24488 'help-echo "Agendas are currently limited to this item.")
24489 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24491 (defun org-speedbar-set-agenda-restriction ()
24492 "Restrict future agenda commands to the location at point in speedbar.
24493 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24494 (interactive)
24495 (require 'org-agenda)
24496 (let (p m tp np dir txt)
24497 (cond
24498 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24499 'org-imenu t))
24500 (setq m (get-text-property p 'org-imenu-marker))
24501 (with-current-buffer (marker-buffer m)
24502 (goto-char m)
24503 (org-agenda-set-restriction-lock 'subtree)))
24504 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24505 'speedbar-function 'speedbar-find-file))
24506 (setq tp (previous-single-property-change
24507 (1+ p) 'speedbar-function)
24508 np (next-single-property-change
24509 tp 'speedbar-function)
24510 dir (speedbar-line-directory)
24511 txt (buffer-substring-no-properties (or tp (point-min))
24512 (or np (point-max))))
24513 (with-current-buffer (find-file-noselect
24514 (let ((default-directory dir))
24515 (expand-file-name txt)))
24516 (unless (derived-mode-p 'org-mode)
24517 (user-error "Cannot restrict to non-Org-mode file"))
24518 (org-agenda-set-restriction-lock 'file)))
24519 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24520 (move-overlay org-speedbar-restriction-lock-overlay
24521 (point-at-bol) (point-at-eol))
24522 (setq current-prefix-arg nil)
24523 (org-agenda-maybe-redo)))
24525 (defvar speedbar-file-key-map)
24526 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24527 (eval-after-load "speedbar"
24528 '(progn
24529 (speedbar-add-supported-extension ".org")
24530 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24531 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24532 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24533 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24534 (add-hook 'speedbar-visiting-tag-hook
24535 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24537 ;;; Fixes and Hacks for problems with other packages
24539 (defun org-mode-flyspell-verify ()
24540 "Function used for `flyspell-generic-check-word-predicate'."
24541 (if (org-at-heading-p)
24542 ;; At a headline or an inlinetask, check title only. This is
24543 ;; faster than relying on `org-element-at-point'.
24544 (and (save-excursion (beginning-of-line)
24545 (and (let ((case-fold-search t))
24546 (not (looking-at "\\*+ END[ \t]*$")))
24547 (looking-at org-complex-heading-regexp)))
24548 (match-beginning 4)
24549 (>= (point) (match-beginning 4))
24550 (or (not (match-beginning 5))
24551 (< (point) (match-beginning 5))))
24552 (let* ((element (org-element-at-point))
24553 (post-affiliated (org-element-property :post-affiliated element))
24554 (object-check
24555 (function
24556 ;; Non-nil if checks can be done for object at point.
24557 (lambda ()
24558 (let ((object (save-excursion
24559 (when (org-looking-at-p "\\>") (backward-char))
24560 (org-element-context element))))
24561 (case (org-element-type object)
24562 ;; Prevent checks in links due to keybinding conflict
24563 ;; with Flyspell.
24564 ((code entity export-snippet inline-babel-call
24565 inline-src-block line-break latex-fragment link macro
24566 statistics-cookie target timestamp verbatim)
24567 nil)
24568 (footnote-reference
24569 ;; Only in inline footnotes, within the definition.
24570 (and (eq (org-element-property :type object) 'inline)
24571 (< (save-excursion
24572 (goto-char (org-element-property :begin object))
24573 (search-forward ":" nil t 2))
24574 (point))))
24575 (otherwise t)))))))
24576 (cond
24577 ;; Ignore checks in all affiliated keywords but captions.
24578 ((< (point) post-affiliated)
24579 (and (save-excursion
24580 (beginning-of-line)
24581 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24582 (> (point) (match-end 0))
24583 (funcall object-check)))
24584 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24585 ((and org-log-into-drawer
24586 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24587 (parent element))
24588 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24589 (setq parent (org-element-property :parent parent)))
24590 (and parent
24591 (eq (compare-strings
24592 log nil nil
24593 (org-element-property :drawer-name parent) nil nil t)
24594 t))))
24595 nil)
24597 (case (org-element-type element)
24598 ((comment quote-section) t)
24599 (comment-block
24600 ;; Allow checks between block markers, not on them.
24601 (and (> (line-beginning-position) post-affiliated)
24602 (save-excursion
24603 (end-of-line)
24604 (skip-chars-forward " \r\t\n")
24605 (< (point) (org-element-property :end element)))))
24606 ;; Arbitrary list of keywords where checks are meaningful.
24607 ;; Make sure point is on the value part of the element.
24608 (keyword
24609 (and (member (org-element-property :key element)
24610 '("DESCRIPTION" "TITLE"))
24611 (< (save-excursion
24612 (beginning-of-line) (search-forward ":") (point))
24613 (point))))
24614 ;; Check is globally allowed in paragraphs verse blocks and
24615 ;; table rows (after affiliated keywords) but some objects
24616 ;; must not be affected.
24617 ((paragraph table-row verse-block)
24618 (and (>= (point) (org-element-property :contents-begin element))
24619 (< (point) (org-element-property :contents-end element))
24620 (funcall object-check)))))))))
24621 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24623 (defun org-remove-flyspell-overlays-in (beg end)
24624 "Remove flyspell overlays in region."
24625 (and (org-bound-and-true-p flyspell-mode)
24626 (fboundp 'flyspell-delete-region-overlays)
24627 (flyspell-delete-region-overlays beg end)))
24629 (defvar flyspell-delayed-commands)
24630 (eval-after-load "flyspell"
24631 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24633 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24634 (eval-after-load "bookmark"
24635 '(if (boundp 'bookmark-after-jump-hook)
24636 ;; We can use the hook
24637 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24638 ;; Hook not available, use advice
24639 (defadvice bookmark-jump (after org-make-visible activate)
24640 "Make the position visible."
24641 (org-bookmark-jump-unhide))))
24643 ;; Make sure saveplace shows the location if it was hidden
24644 (eval-after-load "saveplace"
24645 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24646 "Make the position visible."
24647 (org-bookmark-jump-unhide)))
24649 ;; Make sure ecb shows the location if it was hidden
24650 (eval-after-load "ecb"
24651 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24652 "Make hierarchy visible when jumping into location from ECB tree buffer."
24653 (if (derived-mode-p 'org-mode)
24654 (org-show-context))))
24656 (defun org-bookmark-jump-unhide ()
24657 "Unhide the current position, to show the bookmark location."
24658 (and (derived-mode-p 'org-mode)
24659 (or (outline-invisible-p)
24660 (save-excursion (goto-char (max (point-min) (1- (point))))
24661 (outline-invisible-p)))
24662 (org-show-context 'bookmark-jump)))
24664 (defun org-mark-jump-unhide ()
24665 "Make the point visible with `org-show-context' after jumping to the mark."
24666 (when (and (derived-mode-p 'org-mode)
24667 (outline-invisible-p))
24668 (org-show-context 'mark-goto)))
24670 (eval-after-load "simple"
24671 '(defadvice pop-to-mark-command (after org-make-visible activate)
24672 "Make the point visible with `org-show-context'."
24673 (org-mark-jump-unhide)))
24675 (eval-after-load "simple"
24676 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24677 "Make the point visible with `org-show-context'."
24678 (org-mark-jump-unhide)))
24680 (eval-after-load "simple"
24681 '(defadvice pop-global-mark (after org-make-visible activate)
24682 "Make the point visible with `org-show-context'."
24683 (org-mark-jump-unhide)))
24685 ;; Make session.el ignore our circular variable
24686 (defvar session-globals-exclude)
24687 (eval-after-load "session"
24688 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24690 ;;;; Finish up
24692 (provide 'org)
24694 (run-hooks 'org-load-hook)
24696 ;;; org.el ends here