Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob9fada3268e22af4564e3df69da9583ae8eb09267
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" ())
167 (declare-function org-element-at-point "org-element" ())
168 (declare-function org-element-cache-reset "org-element" (&optional all))
169 (declare-function org-element-cache-refresh "org-element" (pos))
170 (declare-function org-element-contents "org-element" (element))
171 (declare-function org-element-context "org-element" (&optional element))
172 (declare-function org-element-interpret-data "org-element"
173 (data &optional parent))
174 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
175 (declare-function org-element-parse-buffer "org-element"
176 (&optional granularity visible-only))
177 (declare-function org-element-property "org-element" (property element))
178 (declare-function org-element-put-property "org-element"
179 (element property value))
180 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
181 (declare-function org-element-parse-buffer "org-element"
182 (&optional granularity visible-only))
183 (declare-function org-element-type "org-element" (element))
185 (defsubst org-uniquify (list)
186 "Non-destructively remove duplicate elements from LIST."
187 (let ((res (copy-sequence list))) (delete-dups res)))
189 (defsubst org-get-at-bol (property)
190 "Get text property PROPERTY at the beginning of line."
191 (get-text-property (point-at-bol) property))
193 (defsubst org-trim (s)
194 "Remove whitespace at the beginning and the end of string S."
195 (replace-regexp-in-string
196 "\\`[ \t\n\r]+" ""
197 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
199 ;; load languages based on value of `org-babel-load-languages'
200 (defvar org-babel-load-languages)
202 ;;;###autoload
203 (defun org-babel-do-load-languages (sym value)
204 "Load the languages defined in `org-babel-load-languages'."
205 (set-default sym value)
206 (mapc (lambda (pair)
207 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
208 (if active
209 (progn
210 (require (intern (concat "ob-" lang))))
211 (progn
212 (funcall 'fmakunbound
213 (intern (concat "org-babel-execute:" lang)))
214 (funcall 'fmakunbound
215 (intern (concat "org-babel-expand-body:" lang)))))))
216 org-babel-load-languages))
218 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
219 ;;;###autoload
220 (defun org-babel-load-file (file &optional compile)
221 "Load Emacs Lisp source code blocks in the Org-mode FILE.
222 This function exports the source code using `org-babel-tangle'
223 and then loads the resulting file using `load-file'. With prefix
224 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
225 file to byte-code before it is loaded."
226 (interactive "fFile to load: \nP")
227 (let* ((age (lambda (file)
228 (float-time
229 (time-subtract (current-time)
230 (nth 5 (or (file-attributes (file-truename file))
231 (file-attributes file)))))))
232 (base-name (file-name-sans-extension file))
233 (exported-file (concat base-name ".el")))
234 ;; tangle if the org-mode file is newer than the elisp file
235 (unless (and (file-exists-p exported-file)
236 (> (funcall age file) (funcall age exported-file)))
237 (setq exported-file
238 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
239 (message "%s %s"
240 (if compile
241 (progn (byte-compile-file exported-file 'load)
242 "Compiled and loaded")
243 (progn (load-file exported-file) "Loaded"))
244 exported-file)))
246 (defcustom org-babel-load-languages '((emacs-lisp . t))
247 "Languages which can be evaluated in Org-mode buffers.
248 This list can be used to load support for any of the languages
249 below, note that each language will depend on a different set of
250 system executables and/or Emacs modes. When a language is
251 \"loaded\", then code blocks in that language can be evaluated
252 with `org-babel-execute-src-block' bound by default to C-c
253 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
254 be set to remove code block evaluation from the C-c C-c
255 keybinding. By default only Emacs Lisp (which has no
256 requirements) is loaded."
257 :group 'org-babel
258 :set 'org-babel-do-load-languages
259 :version "24.1"
260 :type '(alist :tag "Babel Languages"
261 :key-type
262 (choice
263 (const :tag "Awk" awk)
264 (const :tag "C" C)
265 (const :tag "R" R)
266 (const :tag "Asymptote" asymptote)
267 (const :tag "Calc" calc)
268 (const :tag "Clojure" clojure)
269 (const :tag "CSS" css)
270 (const :tag "Ditaa" ditaa)
271 (const :tag "Dot" dot)
272 (const :tag "Emacs Lisp" emacs-lisp)
273 (const :tag "Forth" forth)
274 (const :tag "Fortran" fortran)
275 (const :tag "Gnuplot" gnuplot)
276 (const :tag "Haskell" haskell)
277 (const :tag "IO" io)
278 (const :tag "J" J)
279 (const :tag "Java" java)
280 (const :tag "Javascript" js)
281 (const :tag "LaTeX" latex)
282 (const :tag "Ledger" ledger)
283 (const :tag "Lilypond" lilypond)
284 (const :tag "Lisp" lisp)
285 (const :tag "Makefile" makefile)
286 (const :tag "Maxima" maxima)
287 (const :tag "Matlab" matlab)
288 (const :tag "Mscgen" mscgen)
289 (const :tag "Ocaml" ocaml)
290 (const :tag "Octave" octave)
291 (const :tag "Org" org)
292 (const :tag "Perl" perl)
293 (const :tag "Pico Lisp" picolisp)
294 (const :tag "PlantUML" plantuml)
295 (const :tag "Python" python)
296 (const :tag "Ruby" ruby)
297 (const :tag "Sass" sass)
298 (const :tag "Scala" scala)
299 (const :tag "Scheme" scheme)
300 (const :tag "Screen" screen)
301 (const :tag "Shell Script" shell)
302 (const :tag "Shen" shen)
303 (const :tag "Sql" sql)
304 (const :tag "Sqlite" sqlite)
305 (const :tag "ebnf2ps" ebnf2ps))
306 :value-type (boolean :tag "Activate" :value t)))
308 ;;;; Customization variables
309 (defcustom org-clone-delete-id nil
310 "Remove ID property of clones of a subtree.
311 When non-nil, clones of a subtree don't inherit the ID property.
312 Otherwise they inherit the ID property with a new unique
313 identifier."
314 :type 'boolean
315 :version "24.1"
316 :group 'org-id)
318 ;;; Version
319 (org-check-version)
321 ;;;###autoload
322 (defun org-version (&optional here full message)
323 "Show the org-mode version.
324 Interactively, or when MESSAGE is non-nil, show it in echo area.
325 With prefix argument, or when HERE is non-nil, insert it at point.
326 In non-interactive uses, a reduced version string is output unless
327 FULL is given."
328 (interactive (list current-prefix-arg t (not current-prefix-arg)))
329 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
330 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
331 (load-suffixes (list ".el"))
332 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
333 (org-trash (or
334 (and (fboundp 'org-release) (fboundp 'org-git-version))
335 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
336 (load-suffixes save-load-suffixes)
337 (org-version (org-release))
338 (git-version (org-git-version))
339 (version (format "Org-mode version %s (%s @ %s)"
340 org-version
341 git-version
342 (if org-install-dir
343 (if (string= org-dir org-install-dir)
344 org-install-dir
345 (concat "mixed installation! " org-install-dir " and " org-dir))
346 "org-loaddefs.el can not be found!")))
347 (version1 (if full version org-version)))
348 (when here (insert version1))
349 (when message (message "%s" version1))
350 version1))
352 (defconst org-version (org-version))
355 ;;; Syntax Constants
357 ;;;; Block
359 (defconst org-block-regexp
360 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
361 "Regular expression for hiding blocks.")
363 (defconst org-dblock-start-re
364 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
365 "Matches the start line of a dynamic block, with parameters.")
367 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
368 "Matches the end of a dynamic block.")
370 ;;;; Clock and Planning
372 (defconst org-clock-string "CLOCK:"
373 "String used as prefix for timestamps clocking work hours on an item.")
375 (defconst org-closed-string "CLOSED:"
376 "String used as the prefix for timestamps logging closing a TODO entry.")
378 (defconst org-deadline-string "DEADLINE:"
379 "String to mark deadline entries.
380 A deadline is this string, followed by a time stamp. Should be a word,
381 terminated by a colon. You can insert a schedule keyword and
382 a timestamp with \\[org-deadline].")
384 (defconst org-scheduled-string "SCHEDULED:"
385 "String to mark scheduled TODO entries.
386 A schedule is this string, followed by a time stamp. Should be a word,
387 terminated by a colon. You can insert a schedule keyword and
388 a timestamp with \\[org-schedule].")
390 (defconst org-planning-or-clock-line-re
391 (concat "^[ \t]*"
392 (regexp-opt
393 (list org-clock-string org-closed-string org-deadline-string
394 org-scheduled-string)
396 "Matches a line with planning or clock info.
397 Matched keyword is in group 1.")
399 (defconst org-clock-line-re
400 (concat "^[ \t]*" org-clock-string)
401 "Matches a line with clock info.")
403 ;;;; Drawer
405 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
406 "Matches first or last line of a hidden block.
407 Group 1 contains drawer's name or \"END\".")
409 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
410 "Regular expression matching the first line of a property drawer.")
412 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
413 "Regular expression matching the last line of a property drawer.")
415 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
416 "Regular expression matching the first line of a clock drawer.")
418 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
419 "Regular expression matching the last line of a clock drawer.")
421 (defconst org-property-drawer-re
422 (concat "\\(" org-property-start-re "\\)[^\000]*?\\("
423 org-property-end-re "\\)\n?")
424 "Matches an entire property drawer.")
426 (defconst org-clock-drawer-re
427 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
428 org-clock-drawer-end-re "\\)\n?")
429 "Matches an entire clock drawer.")
431 ;;;; Headline
433 (defconst org-heading-keyword-regexp-format
434 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
435 "Printf format for a regexp matching a headline with some keyword.
436 This regexp will match the headline of any node which has the
437 exact keyword that is put into the format. The keyword isn't in
438 any group by default, but the stars and the body are.")
440 (defconst org-heading-keyword-maybe-regexp-format
441 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
442 "Printf format for a regexp matching a headline, possibly with some keyword.
443 This regexp can match any headline with the specified keyword, or
444 without a keyword. The keyword isn't in any group by default,
445 but the stars and the body are.")
447 (defconst org-archive-tag "ARCHIVE"
448 "The tag that marks a subtree as archived.
449 An archived subtree does not open during visibility cycling, and does
450 not contribute to the agenda listings.")
452 (defconst org-comment-string "COMMENT"
453 "Entries starting with this keyword will never be exported.
454 An entry can be toggled between COMMENT and normal with
455 \\[org-toggle-comment].")
458 ;;;; LaTeX Environments and Fragments
460 (defconst org-latex-regexps
461 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
462 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
463 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
464 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
465 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
466 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
467 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
468 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
469 "Regular expressions for matching embedded LaTeX.")
471 ;;;; Node Property
473 (defconst org-effort-property "Effort"
474 "The property that is being used to keep track of effort estimates.
475 Effort estimates given in this property need to have the format H:MM.")
477 ;;;; Table
479 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
480 "Detect an org-type or table-type table.")
482 (defconst org-table-line-regexp "^[ \t]*|"
483 "Detect an org-type table line.")
485 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
486 "Detect an org-type table line.")
488 (defconst org-table-hline-regexp "^[ \t]*|-"
489 "Detect an org-type table hline.")
491 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
492 "Detect a table-type table hline.")
494 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
495 "Detect the first line outside a table when searching from within it.
496 This works for both table types.")
498 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
499 "Detect a #+TBLFM line.")
501 ;;;; Timestamp
503 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
504 "Regular expression for fast time stamp matching.")
506 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
507 "Regular expression for fast time stamp matching.")
509 (defconst org-ts-regexp0
510 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
511 "Regular expression matching time strings for analysis.
512 This one does not require the space after the date, so it can be used
513 on a string that terminates immediately after the date.")
515 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
516 "Regular expression matching time strings for analysis.")
518 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
519 "Regular expression matching time stamps, with groups.")
521 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
522 "Regular expression matching time stamps (also [..]), with groups.")
524 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
525 "Regular expression matching a time stamp range.")
527 (defconst org-tr-regexp-both
528 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
529 "Regular expression matching a time stamp range.")
531 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
532 org-ts-regexp "\\)?")
533 "Regular expression matching a time stamp or time stamp range.")
535 (defconst org-tsr-regexp-both
536 (concat org-ts-regexp-both "\\(--?-?"
537 org-ts-regexp-both "\\)?")
538 "Regular expression matching a time stamp or time stamp range.
539 The time stamps may be either active or inactive.")
541 (defconst org-repeat-re
542 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
543 "Regular expression for specifying repeated events.
544 After a match, group 1 contains the repeat expression.")
546 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
547 "Formats for `format-time-string' which are used for time stamps.")
550 ;;; The custom variables
552 (defgroup org nil
553 "Outline-based notes management and organizer."
554 :tag "Org"
555 :group 'outlines
556 :group 'calendar)
558 (defcustom org-mode-hook nil
559 "Mode hook for Org-mode, run after the mode was turned on."
560 :group 'org
561 :type 'hook)
563 (defcustom org-load-hook nil
564 "Hook that is run after org.el has been loaded."
565 :group 'org
566 :type 'hook)
568 (defcustom org-log-buffer-setup-hook nil
569 "Hook that is run after an Org log buffer is created."
570 :group 'org
571 :version "24.1"
572 :type 'hook)
574 (defvar org-modules) ; defined below
575 (defvar org-modules-loaded nil
576 "Have the modules been loaded already?")
578 (defun org-load-modules-maybe (&optional force)
579 "Load all extensions listed in `org-modules'."
580 (when (or force (not org-modules-loaded))
581 (mapc (lambda (ext)
582 (condition-case nil (require ext)
583 (error (message "Problems while trying to load feature `%s'" ext))))
584 org-modules)
585 (setq org-modules-loaded t)))
587 (defun org-set-modules (var value)
588 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
589 (set var value)
590 (when (featurep 'org)
591 (org-load-modules-maybe 'force)
592 (org-element-cache-reset 'all)))
594 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
595 "Modules that should always be loaded together with org.el.
597 If a description starts with <C>, the file is not part of Emacs
598 and loading it will require that you have downloaded and properly
599 installed the Org mode distribution.
601 You can also use this system to load external packages (i.e. neither Org
602 core modules, nor modules from the CONTRIB directory). Just add symbols
603 to the end of the list. If the package is called org-xyz.el, then you need
604 to add the symbol `xyz', and the package must have a call to:
606 \(provide 'org-xyz)
608 For export specific modules, see also `org-export-backends'."
609 :group 'org
610 :set 'org-set-modules
611 :version "24.4"
612 :package-version '(Org . "8.0")
613 :type
614 '(set :greedy t
615 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
616 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
617 (const :tag " crypt: Encryption of subtrees" org-crypt)
618 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
619 (const :tag " docview: Links to doc-view buffers" org-docview)
620 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
621 (const :tag " habit: Track your consistency with habits" org-habit)
622 (const :tag " id: Global IDs for identifying entries" org-id)
623 (const :tag " info: Links to Info nodes" org-info)
624 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
625 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
626 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
627 (const :tag " mouse: Additional mouse support" org-mouse)
628 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
629 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
630 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
632 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
633 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
634 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
635 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
636 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
637 (const :tag "C collector: Collect properties into tables" org-collector)
638 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
639 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
640 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
641 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
642 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
643 (const :tag "C eval: Include command output as text" org-eval)
644 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
645 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
646 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
647 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
648 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
649 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
650 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
651 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
652 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
653 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
654 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
655 (const :tag "C mew: Links to Mew folders/messages" org-mew)
656 (const :tag "C mtags: Support for muse-like tags" org-mtags)
657 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
658 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
659 (const :tag "C registry: A registry for Org-mode links" org-registry)
660 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
661 (const :tag "C secretary: Team management with org-mode" org-secretary)
662 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
663 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
664 (const :tag "C track: Keep up with Org-mode development" org-track)
665 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
666 (const :tag "C vm: Links to VM folders/messages" org-vm)
667 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
668 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
669 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
671 (defvar org-export--registered-backends) ; From ox.el.
672 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
673 (declare-function org-export-backend-name "ox" (backend))
674 (defcustom org-export-backends '(ascii html icalendar latex)
675 "List of export back-ends that should be always available.
677 If a description starts with <C>, the file is not part of Emacs
678 and loading it will require that you have downloaded and properly
679 installed the Org mode distribution.
681 Unlike to `org-modules', libraries in this list will not be
682 loaded along with Org, but only once the export framework is
683 needed.
685 This variable needs to be set before org.el is loaded. If you
686 need to make a change while Emacs is running, use the customize
687 interface or run the following code, where VAL stands for the new
688 value of the variable, after updating it:
690 \(progn
691 \(setq org-export--registered-backends
692 \(org-remove-if-not
693 \(lambda (backend)
694 \(let ((name (org-export-backend-name backend)))
695 \(or (memq name val)
696 \(catch 'parentp
697 \(dolist (b val)
698 \(and (org-export-derived-backend-p b name)
699 \(throw 'parentp t)))))))
700 org-export--registered-backends))
701 \(let ((new-list (mapcar 'org-export-backend-name
702 org-export--registered-backends)))
703 \(dolist (backend val)
704 \(cond
705 \((not (load (format \"ox-%s\" backend) t t))
706 \(message \"Problems while trying to load export back-end `%s'\"
707 backend))
708 \((not (memq backend new-list)) (push backend new-list))))
709 \(set-default 'org-export-backends new-list)))
711 Adding a back-end to this list will also pull the back-end it
712 depends on, if any."
713 :group 'org
714 :group 'org-export
715 :version "24.4"
716 :package-version '(Org . "8.0")
717 :initialize 'custom-initialize-set
718 :set (lambda (var val)
719 (if (not (featurep 'ox)) (set-default var val)
720 ;; Any back-end not required anymore (not present in VAL and not
721 ;; a parent of any back-end in the new value) is removed from the
722 ;; list of registered back-ends.
723 (setq org-export--registered-backends
724 (org-remove-if-not
725 (lambda (backend)
726 (let ((name (org-export-backend-name backend)))
727 (or (memq name val)
728 (catch 'parentp
729 (dolist (b val)
730 (and (org-export-derived-backend-p b name)
731 (throw 'parentp t)))))))
732 org-export--registered-backends))
733 ;; Now build NEW-LIST of both new back-ends and required
734 ;; parents.
735 (let ((new-list (mapcar 'org-export-backend-name
736 org-export--registered-backends)))
737 (dolist (backend val)
738 (cond
739 ((not (load (format "ox-%s" backend) t t))
740 (message "Problems while trying to load export back-end `%s'"
741 backend))
742 ((not (memq backend new-list)) (push backend new-list))))
743 ;; Set VAR to that list with fixed dependencies.
744 (set-default var new-list))))
745 :type '(set :greedy t
746 (const :tag " ascii Export buffer to ASCII format" ascii)
747 (const :tag " beamer Export buffer to Beamer presentation" beamer)
748 (const :tag " html Export buffer to HTML format" html)
749 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
750 (const :tag " latex Export buffer to LaTeX format" latex)
751 (const :tag " man Export buffer to MAN format" man)
752 (const :tag " md Export buffer to Markdown format" md)
753 (const :tag " odt Export buffer to ODT format" odt)
754 (const :tag " org Export buffer to Org format" org)
755 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
756 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
757 (const :tag "C deck Export buffer to deck.js presentations" deck)
758 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
759 (const :tag "C groff Export buffer to Groff format" groff)
760 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
761 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
762 (const :tag "C s5 Export buffer to s5 presentations" s5)
763 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
765 (eval-after-load 'ox
766 '(mapc
767 (lambda (backend)
768 (condition-case nil (require (intern (format "ox-%s" backend)))
769 (error (message "Problems while trying to load export back-end `%s'"
770 backend))))
771 org-export-backends))
773 (defcustom org-support-shift-select nil
774 "Non-nil means make shift-cursor commands select text when possible.
776 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
777 start selecting a region, or enlarge regions started in this way.
778 In Org-mode, in special contexts, these same keys are used for
779 other purposes, important enough to compete with shift selection.
780 Org tries to balance these needs by supporting `shift-select-mode'
781 outside these special contexts, under control of this variable.
783 The default of this variable is nil, to avoid confusing behavior. Shifted
784 cursor keys will then execute Org commands in the following contexts:
785 - on a headline, changing TODO state (left/right) and priority (up/down)
786 - on a time stamp, changing the time
787 - in a plain list item, changing the bullet type
788 - in a property definition line, switching between allowed values
789 - in the BEGIN line of a clock table (changing the time block).
790 Outside these contexts, the commands will throw an error.
792 When this variable is t and the cursor is not in a special
793 context, Org-mode will support shift-selection for making and
794 enlarging regions. To make this more effective, the bullet
795 cycling will no longer happen anywhere in an item line, but only
796 if the cursor is exactly on the bullet.
798 If you set this variable to the symbol `always', then the keys
799 will not be special in headlines, property lines, and item lines,
800 to make shift selection work there as well. If this is what you
801 want, you can use the following alternative commands: `C-c C-t'
802 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
803 can be used to switch TODO sets, `C-c -' to cycle item bullet
804 types, and properties can be edited by hand or in column view.
806 However, when the cursor is on a timestamp, shift-cursor commands
807 will still edit the time stamp - this is just too good to give up.
809 XEmacs user should have this variable set to nil, because
810 `shift-select-mode' is in Emacs 23 or later only."
811 :group 'org
812 :type '(choice
813 (const :tag "Never" nil)
814 (const :tag "When outside special context" t)
815 (const :tag "Everywhere except timestamps" always)))
817 (defcustom org-loop-over-headlines-in-active-region nil
818 "Shall some commands act upon headlines in the active region?
820 When set to `t', some commands will be performed in all headlines
821 within the active region.
823 When set to `start-level', some commands will be performed in all
824 headlines within the active region, provided that these headlines
825 are of the same level than the first one.
827 When set to a string, those commands will be performed on the
828 matching headlines within the active region. Such string must be
829 a tags/property/todo match as it is used in the agenda tags view.
831 The list of commands is: `org-schedule', `org-deadline',
832 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
833 `org-archive-to-archive-sibling'. The archiving commands skip
834 already archived entries."
835 :type '(choice (const :tag "Don't loop" nil)
836 (const :tag "All headlines in active region" t)
837 (const :tag "In active region, headlines at the same level than the first one" start-level)
838 (string :tag "Tags/Property/Todo matcher"))
839 :version "24.1"
840 :group 'org-todo
841 :group 'org-archive)
843 (defgroup org-startup nil
844 "Options concerning startup of Org-mode."
845 :tag "Org Startup"
846 :group 'org)
848 (defcustom org-startup-folded t
849 "Non-nil means entering Org-mode will switch to OVERVIEW.
850 This can also be configured on a per-file basis by adding one of
851 the following lines anywhere in the buffer:
853 #+STARTUP: fold (or `overview', this is equivalent)
854 #+STARTUP: nofold (or `showall', this is equivalent)
855 #+STARTUP: content
856 #+STARTUP: showeverything
858 By default, this option is ignored when Org opens agenda files
859 for the first time. If you want the agenda to honor the startup
860 option, set `org-agenda-inhibit-startup' to nil."
861 :group 'org-startup
862 :type '(choice
863 (const :tag "nofold: show all" nil)
864 (const :tag "fold: overview" t)
865 (const :tag "content: all headlines" content)
866 (const :tag "show everything, even drawers" showeverything)))
868 (defcustom org-startup-truncated t
869 "Non-nil means entering Org-mode will set `truncate-lines'.
870 This is useful since some lines containing links can be very long and
871 uninteresting. Also tables look terrible when wrapped."
872 :group 'org-startup
873 :type 'boolean)
875 (defcustom org-startup-indented nil
876 "Non-nil means turn on `org-indent-mode' on startup.
877 This can also be configured on a per-file basis by adding one of
878 the following lines anywhere in the buffer:
880 #+STARTUP: indent
881 #+STARTUP: noindent"
882 :group 'org-structure
883 :type '(choice
884 (const :tag "Not" nil)
885 (const :tag "Globally (slow on startup in large files)" t)))
887 (defcustom org-use-sub-superscripts t
888 "Non-nil means interpret \"_\" and \"^\" for display.
890 If you want to control how Org exports those characters, see
891 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
892 used to be an alias for `org-export-with-sub-superscripts' in
893 Org <8.0, it is not anymore.
895 When this option is turned on, you can use TeX-like syntax for
896 sub- and superscripts within the buffer. Several characters after
897 \"_\" or \"^\" will be considered as a single item - so grouping
898 with {} is normally not needed. For example, the following things
899 will be parsed as single sub- or superscripts:
901 10^24 or 10^tau several digits will be considered 1 item.
902 10^-12 or 10^-tau a leading sign with digits or a word
903 x^2-y^3 will be read as x^2 - y^3, because items are
904 terminated by almost any nonword/nondigit char.
905 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
907 Still, ambiguity is possible. So when in doubt, use {} to enclose
908 the sub/superscript. If you set this variable to the symbol `{}',
909 the braces are *required* in order to trigger interpretations as
910 sub/superscript. This can be helpful in documents that need \"_\"
911 frequently in plain text."
912 :group 'org-startup
913 :version "24.4"
914 :package-version '(Org . "8.0")
915 :type '(choice
916 (const :tag "Always interpret" t)
917 (const :tag "Only with braces" {})
918 (const :tag "Never interpret" nil)))
920 (defcustom org-startup-with-beamer-mode nil
921 "Non-nil means turn on `org-beamer-mode' on startup.
922 This can also be configured on a per-file basis by adding one of
923 the following lines anywhere in the buffer:
925 #+STARTUP: beamer"
926 :group 'org-startup
927 :version "24.1"
928 :type 'boolean)
930 (defcustom org-startup-align-all-tables nil
931 "Non-nil means align all tables when visiting a file.
932 This is useful when the column width in tables is forced with <N> cookies
933 in table fields. Such tables will look correct only after the first re-align.
934 This can also be configured on a per-file basis by adding one of
935 the following lines anywhere in the buffer:
936 #+STARTUP: align
937 #+STARTUP: noalign"
938 :group 'org-startup
939 :type 'boolean)
941 (defcustom org-startup-with-inline-images nil
942 "Non-nil means show inline images when loading a new Org file.
943 This can also be configured on a per-file basis by adding one of
944 the following lines anywhere in the buffer:
945 #+STARTUP: inlineimages
946 #+STARTUP: noinlineimages"
947 :group 'org-startup
948 :version "24.1"
949 :type 'boolean)
951 (defcustom org-startup-with-latex-preview nil
952 "Non-nil means preview LaTeX fragments when loading a new Org file.
954 This can also be configured on a per-file basis by adding one of
955 the following lines anywhere in the buffer:
956 #+STARTUP: latexpreview
957 #+STARTUP: nolatexpreview"
958 :group 'org-startup
959 :version "24.4"
960 :package-version '(Org . "8.0")
961 :type 'boolean)
963 (defcustom org-insert-mode-line-in-empty-file nil
964 "Non-nil means insert the first line setting Org-mode in empty files.
965 When the function `org-mode' is called interactively in an empty file, this
966 normally means that the file name does not automatically trigger Org-mode.
967 To ensure that the file will always be in Org-mode in the future, a
968 line enforcing Org-mode will be inserted into the buffer, if this option
969 has been set."
970 :group 'org-startup
971 :type 'boolean)
973 (defcustom org-replace-disputed-keys nil
974 "Non-nil means use alternative key bindings for some keys.
975 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
976 These keys are also used by other packages like shift-selection-mode'
977 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
978 If you want to use Org-mode together with one of these other modes,
979 or more generally if you would like to move some Org-mode commands to
980 other keys, set this variable and configure the keys with the variable
981 `org-disputed-keys'.
983 This option is only relevant at load-time of Org-mode, and must be set
984 *before* org.el is loaded. Changing it requires a restart of Emacs to
985 become effective."
986 :group 'org-startup
987 :type 'boolean)
989 (defcustom org-use-extra-keys nil
990 "Non-nil means use extra key sequence definitions for certain commands.
991 This happens automatically if you run XEmacs or if `window-system'
992 is nil. This variable lets you do the same manually. You must
993 set it before loading org.
995 Example: on Carbon Emacs 22 running graphically, with an external
996 keyboard on a Powerbook, the default way of setting M-left might
997 not work for either Alt or ESC. Setting this variable will make
998 it work for ESC."
999 :group 'org-startup
1000 :type 'boolean)
1002 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1004 (defcustom org-disputed-keys
1005 '(([(shift up)] . [(meta p)])
1006 ([(shift down)] . [(meta n)])
1007 ([(shift left)] . [(meta -)])
1008 ([(shift right)] . [(meta +)])
1009 ([(control shift right)] . [(meta shift +)])
1010 ([(control shift left)] . [(meta shift -)]))
1011 "Keys for which Org-mode and other modes compete.
1012 This is an alist, cars are the default keys, second element specifies
1013 the alternative to use when `org-replace-disputed-keys' is t.
1015 Keys can be specified in any syntax supported by `define-key'.
1016 The value of this option takes effect only at Org-mode's startup,
1017 therefore you'll have to restart Emacs to apply it after changing."
1018 :group 'org-startup
1019 :type 'alist)
1021 (defun org-key (key)
1022 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1023 Or return the original if not disputed.
1024 Also apply the translations defined in `org-xemacs-key-equivalents'."
1025 (when org-replace-disputed-keys
1026 (let* ((nkey (key-description key))
1027 (x (org-find-if (lambda (x)
1028 (equal (key-description (car x)) nkey))
1029 org-disputed-keys)))
1030 (setq key (if x (cdr x) key))))
1031 (when (featurep 'xemacs)
1032 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1033 key)
1035 (defun org-find-if (predicate seq)
1036 (catch 'exit
1037 (while seq
1038 (if (funcall predicate (car seq))
1039 (throw 'exit (car seq))
1040 (pop seq)))))
1042 (defun org-defkey (keymap key def)
1043 "Define a key, possibly translated, as returned by `org-key'."
1044 (define-key keymap (org-key key) def))
1046 (defcustom org-ellipsis nil
1047 "The ellipsis to use in the Org-mode outline.
1048 When nil, just use the standard three dots.
1049 When a string, use that string instead.
1050 When a face, use the standard 3 dots, but with the specified face.
1051 The change affects only Org-mode (which will then use its own display table).
1052 Changing this requires executing \\[org-mode] in a buffer to become
1053 effective."
1054 :group 'org-startup
1055 :type '(choice (const :tag "Default" nil)
1056 (face :tag "Face" :value org-warning)
1057 (string :tag "String" :value "...#")))
1059 (defvar org-display-table nil
1060 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1062 (defgroup org-keywords nil
1063 "Keywords in Org-mode."
1064 :tag "Org Keywords"
1065 :group 'org)
1067 (defcustom org-closed-keep-when-no-todo nil
1068 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1069 :group 'org-todo
1070 :group 'org-keywords
1071 :version "24.4"
1072 :package-version '(Org . "8.0")
1073 :type 'boolean)
1075 (defgroup org-structure nil
1076 "Options concerning the general structure of Org-mode files."
1077 :tag "Org Structure"
1078 :group 'org)
1080 (defgroup org-reveal-location nil
1081 "Options about how to make context of a location visible."
1082 :tag "Org Reveal Location"
1083 :group 'org-structure)
1085 (defconst org-context-choice
1086 '(choice
1087 (const :tag "Always" t)
1088 (const :tag "Never" nil)
1089 (repeat :greedy t :tag "Individual contexts"
1090 (cons
1091 (choice :tag "Context"
1092 (const agenda)
1093 (const org-goto)
1094 (const occur-tree)
1095 (const tags-tree)
1096 (const link-search)
1097 (const mark-goto)
1098 (const bookmark-jump)
1099 (const isearch)
1100 (const default))
1101 (boolean))))
1102 "Contexts for the reveal options.")
1104 (defcustom org-show-hierarchy-above '((default . t))
1105 "Non-nil means show full hierarchy when revealing a location.
1106 Org-mode often shows locations in an org-mode file which might have
1107 been invisible before. When this is set, the hierarchy of headings
1108 above the exposed location is shown.
1109 Turning this off for example for sparse trees makes them very compact.
1110 Instead of t, this can also be an alist specifying this option for different
1111 contexts. Valid contexts are
1112 agenda when exposing an entry from the agenda
1113 org-goto when using the command `org-goto' on key C-c C-j
1114 occur-tree when using the command `org-occur' on key C-c /
1115 tags-tree when constructing a sparse tree based on tags matches
1116 link-search when exposing search matches associated with a link
1117 mark-goto when exposing the jump goal of a mark
1118 bookmark-jump when exposing a bookmark location
1119 isearch when exiting from an incremental search
1120 default default for all contexts not set explicitly"
1121 :group 'org-reveal-location
1122 :type org-context-choice)
1124 (defcustom org-show-following-heading '((default . nil))
1125 "Non-nil means show following heading when revealing a location.
1126 Org-mode often shows locations in an org-mode file which might have
1127 been invisible before. When this is set, the heading following the
1128 match is shown.
1129 Turning this off for example for sparse trees makes them very compact,
1130 but makes it harder to edit the location of the match. In such a case,
1131 use the command \\[org-reveal] to show more context.
1132 Instead of t, this can also be an alist specifying this option for different
1133 contexts. See `org-show-hierarchy-above' for valid contexts."
1134 :group 'org-reveal-location
1135 :type org-context-choice)
1137 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
1138 "Non-nil means show all sibling heading when revealing a location.
1139 Org-mode often shows locations in an org-mode file which might have
1140 been invisible before. When this is set, the sibling of the current entry
1141 heading are all made visible. If `org-show-hierarchy-above' is t,
1142 the same happens on each level of the hierarchy above the current entry.
1144 By default this is on for the isearch context, off for all other contexts.
1145 Turning this off for example for sparse trees makes them very compact,
1146 but makes it harder to edit the location of the match. In such a case,
1147 use the command \\[org-reveal] to show more context.
1148 Instead of t, this can also be an alist specifying this option for different
1149 contexts. See `org-show-hierarchy-above' for valid contexts."
1150 :group 'org-reveal-location
1151 :type org-context-choice
1152 :version "24.4"
1153 :package-version '(Org . "8.0"))
1155 (defcustom org-show-entry-below '((default . nil))
1156 "Non-nil means show the entry below a headline when revealing a location.
1157 Org-mode often shows locations in an org-mode file which might have
1158 been invisible before. When this is set, the text below the headline that is
1159 exposed is also shown.
1161 By default this is off for all contexts.
1162 Instead of t, this can also be an alist specifying this option for different
1163 contexts. See `org-show-hierarchy-above' for valid contexts."
1164 :group 'org-reveal-location
1165 :type org-context-choice)
1167 (defcustom org-indirect-buffer-display 'other-window
1168 "How should indirect tree buffers be displayed?
1169 This applies to indirect buffers created with the commands
1170 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1171 Valid values are:
1172 current-window Display in the current window
1173 other-window Just display in another window.
1174 dedicated-frame Create one new frame, and re-use it each time.
1175 new-frame Make a new frame each time. Note that in this case
1176 previously-made indirect buffers are kept, and you need to
1177 kill these buffers yourself."
1178 :group 'org-structure
1179 :group 'org-agenda-windows
1180 :type '(choice
1181 (const :tag "In current window" current-window)
1182 (const :tag "In current frame, other window" other-window)
1183 (const :tag "Each time a new frame" new-frame)
1184 (const :tag "One dedicated frame" dedicated-frame)))
1186 (defcustom org-use-speed-commands nil
1187 "Non-nil means activate single letter commands at beginning of a headline.
1188 This may also be a function to test for appropriate locations where speed
1189 commands should be active.
1191 For example, to activate speed commands when the point is on any
1192 star at the beginning of the headline, you can do this:
1194 (setq org-use-speed-commands
1195 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1196 :group 'org-structure
1197 :type '(choice
1198 (const :tag "Never" nil)
1199 (const :tag "At beginning of headline stars" t)
1200 (function)))
1202 (defcustom org-speed-commands-user nil
1203 "Alist of additional speed commands.
1204 This list will be checked before `org-speed-commands-default'
1205 when the variable `org-use-speed-commands' is non-nil
1206 and when the cursor is at the beginning of a headline.
1207 The car if each entry is a string with a single letter, which must
1208 be assigned to `self-insert-command' in the global map.
1209 The cdr is either a command to be called interactively, a function
1210 to be called, or a form to be evaluated.
1211 An entry that is just a list with a single string will be interpreted
1212 as a descriptive headline that will be added when listing the speed
1213 commands in the Help buffer using the `?' speed command."
1214 :group 'org-structure
1215 :type '(repeat :value ("k" . ignore)
1216 (choice :value ("k" . ignore)
1217 (list :tag "Descriptive Headline" (string :tag "Headline"))
1218 (cons :tag "Letter and Command"
1219 (string :tag "Command letter")
1220 (choice
1221 (function)
1222 (sexp))))))
1224 (defcustom org-bookmark-names-plist
1225 '(:last-capture "org-capture-last-stored"
1226 :last-refile "org-refile-last-stored"
1227 :last-capture-marker "org-capture-last-stored-marker")
1228 "Names for bookmarks automatically set by some Org commands.
1229 This can provide strings as names for a number of bookmarks Org sets
1230 automatically. The following keys are currently implemented:
1231 :last-capture
1232 :last-capture-marker
1233 :last-refile
1234 When a key does not show up in the property list, the corresponding bookmark
1235 is not set."
1236 :group 'org-structure
1237 :type 'plist)
1239 (defgroup org-cycle nil
1240 "Options concerning visibility cycling in Org-mode."
1241 :tag "Org Cycle"
1242 :group 'org-structure)
1244 (defcustom org-cycle-skip-children-state-if-no-children t
1245 "Non-nil means skip CHILDREN state in entries that don't have any."
1246 :group 'org-cycle
1247 :type 'boolean)
1249 (defcustom org-cycle-max-level nil
1250 "Maximum level which should still be subject to visibility cycling.
1251 Levels higher than this will, for cycling, be treated as text, not a headline.
1252 When `org-odd-levels-only' is set, a value of N in this variable actually
1253 means 2N-1 stars as the limiting headline.
1254 When nil, cycle all levels.
1255 Note that the limiting level of cycling is also influenced by
1256 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1257 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1258 than its value."
1259 :group 'org-cycle
1260 :type '(choice
1261 (const :tag "No limit" nil)
1262 (integer :tag "Maximum level")))
1264 (defcustom org-hide-block-startup nil
1265 "Non-nil means entering Org-mode will fold all blocks.
1266 This can also be set in on a per-file basis with
1268 #+STARTUP: hideblocks
1269 #+STARTUP: showblocks"
1270 :group 'org-startup
1271 :group 'org-cycle
1272 :type 'boolean)
1274 (defcustom org-cycle-global-at-bob nil
1275 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1276 This makes it possible to do global cycling without having to use S-TAB or
1277 \\[universal-argument] TAB. For this special case to work, the first line
1278 of the buffer must not be a headline -- it may be empty or some other text.
1279 When used in this way, `org-cycle-hook' is disabled temporarily to make
1280 sure the cursor stays at the beginning of the buffer. When this option is
1281 nil, don't do anything special at the beginning of the buffer."
1282 :group 'org-cycle
1283 :type 'boolean)
1285 (defcustom org-cycle-level-after-item/entry-creation t
1286 "Non-nil means cycle entry level or item indentation in new empty entries.
1288 When the cursor is at the end of an empty headline, i.e., with only stars
1289 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1290 and then all possible ancestor states, before returning to the original state.
1291 This makes data entry extremely fast: M-RET to create a new headline,
1292 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1294 When the cursor is at the end of an empty plain list item, one TAB will
1295 make it a subitem, two or more tabs will back up to make this an item
1296 higher up in the item hierarchy."
1297 :group 'org-cycle
1298 :type 'boolean)
1300 (defcustom org-cycle-emulate-tab t
1301 "Where should `org-cycle' emulate TAB.
1302 nil Never
1303 white Only in completely white lines
1304 whitestart Only at the beginning of lines, before the first non-white char
1305 t Everywhere except in headlines
1306 exc-hl-bol Everywhere except at the start of a headline
1307 If TAB is used in a place where it does not emulate TAB, the current subtree
1308 visibility is cycled."
1309 :group 'org-cycle
1310 :type '(choice (const :tag "Never" nil)
1311 (const :tag "Only in completely white lines" white)
1312 (const :tag "Before first char in a line" whitestart)
1313 (const :tag "Everywhere except in headlines" t)
1314 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1316 (defcustom org-cycle-separator-lines 2
1317 "Number of empty lines needed to keep an empty line between collapsed trees.
1318 If you leave an empty line between the end of a subtree and the following
1319 headline, this empty line is hidden when the subtree is folded.
1320 Org-mode will leave (exactly) one empty line visible if the number of
1321 empty lines is equal or larger to the number given in this variable.
1322 So the default 2 means at least 2 empty lines after the end of a subtree
1323 are needed to produce free space between a collapsed subtree and the
1324 following headline.
1326 If the number is negative, and the number of empty lines is at least -N,
1327 all empty lines are shown.
1329 Special case: when 0, never leave empty lines in collapsed view."
1330 :group 'org-cycle
1331 :type 'integer)
1332 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1334 (defcustom org-pre-cycle-hook nil
1335 "Hook that is run before visibility cycling is happening.
1336 The function(s) in this hook must accept a single argument which indicates
1337 the new state that will be set right after running this hook. The
1338 argument is a symbol. Before a global state change, it can have the values
1339 `overview', `content', or `all'. Before a local state change, it can have
1340 the values `folded', `children', or `subtree'."
1341 :group 'org-cycle
1342 :type 'hook)
1344 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1345 org-cycle-hide-drawers
1346 org-cycle-hide-inline-tasks
1347 org-cycle-show-empty-lines
1348 org-optimize-window-after-visibility-change)
1349 "Hook that is run after `org-cycle' has changed the buffer visibility.
1350 The function(s) in this hook must accept a single argument which indicates
1351 the new state that was set by the most recent `org-cycle' command. The
1352 argument is a symbol. After a global state change, it can have the values
1353 `overview', `contents', or `all'. After a local state change, it can have
1354 the values `folded', `children', or `subtree'."
1355 :group 'org-cycle
1356 :type 'hook)
1358 (defgroup org-edit-structure nil
1359 "Options concerning structure editing in Org-mode."
1360 :tag "Org Edit Structure"
1361 :group 'org-structure)
1363 (defcustom org-odd-levels-only nil
1364 "Non-nil means skip even levels and only use odd levels for the outline.
1365 This has the effect that two stars are being added/taken away in
1366 promotion/demotion commands. It also influences how levels are
1367 handled by the exporters.
1368 Changing it requires restart of `font-lock-mode' to become effective
1369 for fontification also in regions already fontified.
1370 You may also set this on a per-file basis by adding one of the following
1371 lines to the buffer:
1373 #+STARTUP: odd
1374 #+STARTUP: oddeven"
1375 :group 'org-edit-structure
1376 :group 'org-appearance
1377 :type 'boolean)
1379 (defcustom org-adapt-indentation t
1380 "Non-nil means adapt indentation to outline node level.
1382 When this variable is set, Org assumes that you write outlines by
1383 indenting text in each node to align with the headline (after the stars).
1384 The following issues are influenced by this variable:
1386 - When this is set and the *entire* text in an entry is indented, the
1387 indentation is increased by one space in a demotion command, and
1388 decreased by one in a promotion command. If any line in the entry
1389 body starts with text at column 0, indentation is not changed at all.
1391 - Property drawers and planning information is inserted indented when
1392 this variable s set. When nil, they will not be indented.
1394 - TAB indents a line relative to context. The lines below a headline
1395 will be indented when this variable is set.
1397 Note that this is all about true indentation, by adding and removing
1398 space characters. See also `org-indent.el' which does level-dependent
1399 indentation in a virtual way, i.e. at display time in Emacs."
1400 :group 'org-edit-structure
1401 :type 'boolean)
1403 (defcustom org-special-ctrl-a/e nil
1404 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1406 When t, `C-a' will bring back the cursor to the beginning of the
1407 headline text, i.e. after the stars and after a possible TODO
1408 keyword. In an item, this will be the position after bullet and
1409 check-box, if any. When the cursor is already at that position,
1410 another `C-a' will bring it to the beginning of the line.
1412 `C-e' will jump to the end of the headline, ignoring the presence
1413 of tags in the headline. A second `C-e' will then jump to the
1414 true end of the line, after any tags. This also means that, when
1415 this variable is non-nil, `C-e' also will never jump beyond the
1416 end of the heading of a folded section, i.e. not after the
1417 ellipses.
1419 When set to the symbol `reversed', the first `C-a' or `C-e' works
1420 normally, going to the true line boundary first. Only a directly
1421 following, identical keypress will bring the cursor to the
1422 special positions.
1424 This may also be a cons cell where the behavior for `C-a' and
1425 `C-e' is set separately."
1426 :group 'org-edit-structure
1427 :type '(choice
1428 (const :tag "off" nil)
1429 (const :tag "on: after stars/bullet and before tags first" t)
1430 (const :tag "reversed: true line boundary first" reversed)
1431 (cons :tag "Set C-a and C-e separately"
1432 (choice :tag "Special C-a"
1433 (const :tag "off" nil)
1434 (const :tag "on: after stars/bullet first" t)
1435 (const :tag "reversed: before stars/bullet first" reversed))
1436 (choice :tag "Special C-e"
1437 (const :tag "off" nil)
1438 (const :tag "on: before tags first" t)
1439 (const :tag "reversed: after tags first" reversed)))))
1440 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1442 (defcustom org-special-ctrl-k nil
1443 "Non-nil means `C-k' will behave specially in headlines.
1444 When nil, `C-k' will call the default `kill-line' command.
1445 When t, the following will happen while the cursor is in the headline:
1447 - When the cursor is at the beginning of a headline, kill the entire
1448 line and possible the folded subtree below the line.
1449 - When in the middle of the headline text, kill the headline up to the tags.
1450 - When after the headline text, kill the tags."
1451 :group 'org-edit-structure
1452 :type 'boolean)
1454 (defcustom org-ctrl-k-protect-subtree nil
1455 "Non-nil means, do not delete a hidden subtree with C-k.
1456 When set to the symbol `error', simply throw an error when C-k is
1457 used to kill (part-of) a headline that has hidden text behind it.
1458 Any other non-nil value will result in a query to the user, if it is
1459 OK to kill that hidden subtree. When nil, kill without remorse."
1460 :group 'org-edit-structure
1461 :version "24.1"
1462 :type '(choice
1463 (const :tag "Do not protect hidden subtrees" nil)
1464 (const :tag "Protect hidden subtrees with a security query" t)
1465 (const :tag "Never kill a hidden subtree with C-k" error)))
1467 (defcustom org-special-ctrl-o t
1468 "Non-nil means, make `C-o' insert a row in tables."
1469 :group 'org-edit-structure
1470 :type 'boolean)
1472 (defcustom org-catch-invisible-edits nil
1473 "Check if in invisible region before inserting or deleting a character.
1474 Valid values are:
1476 nil Do not check, so just do invisible edits.
1477 error Throw an error and do nothing.
1478 show Make point visible, and do the requested edit.
1479 show-and-error Make point visible, then throw an error and abort the edit.
1480 smart Make point visible, and do insertion/deletion if it is
1481 adjacent to visible text and the change feels predictable.
1482 Never delete a previously invisible character or add in the
1483 middle or right after an invisible region. Basically, this
1484 allows insertion and backward-delete right before ellipses.
1485 FIXME: maybe in this case we should not even show?"
1486 :group 'org-edit-structure
1487 :version "24.1"
1488 :type '(choice
1489 (const :tag "Do not check" nil)
1490 (const :tag "Throw error when trying to edit" error)
1491 (const :tag "Unhide, but do not do the edit" show-and-error)
1492 (const :tag "Show invisible part and do the edit" show)
1493 (const :tag "Be smart and do the right thing" smart)))
1495 (defcustom org-yank-folded-subtrees t
1496 "Non-nil means when yanking subtrees, fold them.
1497 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1498 it starts with a heading and all other headings in it are either children
1499 or siblings, then fold all the subtrees. However, do this only if no
1500 text after the yank would be swallowed into a folded tree by this action."
1501 :group 'org-edit-structure
1502 :type 'boolean)
1504 (defcustom org-yank-adjusted-subtrees nil
1505 "Non-nil means when yanking subtrees, adjust the level.
1506 With this setting, `org-paste-subtree' is used to insert the subtree, see
1507 this function for details."
1508 :group 'org-edit-structure
1509 :type 'boolean)
1511 (defcustom org-M-RET-may-split-line '((default . t))
1512 "Non-nil means M-RET will split the line at the cursor position.
1513 When nil, it will go to the end of the line before making a
1514 new line.
1515 You may also set this option in a different way for different
1516 contexts. Valid contexts are:
1518 headline when creating a new headline
1519 item when creating a new item
1520 table in a table field
1521 default the value to be used for all contexts not explicitly
1522 customized"
1523 :group 'org-structure
1524 :group 'org-table
1525 :type '(choice
1526 (const :tag "Always" t)
1527 (const :tag "Never" nil)
1528 (repeat :greedy t :tag "Individual contexts"
1529 (cons
1530 (choice :tag "Context"
1531 (const headline)
1532 (const item)
1533 (const table)
1534 (const default))
1535 (boolean)))))
1538 (defcustom org-insert-heading-respect-content nil
1539 "Non-nil means insert new headings after the current subtree.
1540 When nil, the new heading is created directly after the current line.
1541 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1542 this variable on for the duration of the command."
1543 :group 'org-structure
1544 :type 'boolean)
1546 (defcustom org-blank-before-new-entry '((heading . auto)
1547 (plain-list-item . auto))
1548 "Should `org-insert-heading' leave a blank line before new heading/item?
1549 The value is an alist, with `heading' and `plain-list-item' as CAR,
1550 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1551 which case Org will look at the surrounding headings/items and try to
1552 make an intelligent decision whether to insert a blank line or not.
1554 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1555 the setting here is ignored and no empty line is inserted to avoid breaking
1556 the list structure."
1557 :group 'org-edit-structure
1558 :type '(list
1559 (cons (const heading)
1560 (choice (const :tag "Never" nil)
1561 (const :tag "Always" t)
1562 (const :tag "Auto" auto)))
1563 (cons (const plain-list-item)
1564 (choice (const :tag "Never" nil)
1565 (const :tag "Always" t)
1566 (const :tag "Auto" auto)))))
1568 (defcustom org-insert-heading-hook nil
1569 "Hook being run after inserting a new heading."
1570 :group 'org-edit-structure
1571 :type 'hook)
1573 (defcustom org-enable-fixed-width-editor t
1574 "Non-nil means lines starting with \":\" are treated as fixed-width.
1575 This currently only means they are never auto-wrapped.
1576 When nil, such lines will be treated like ordinary lines."
1577 :group 'org-edit-structure
1578 :type 'boolean)
1580 (defcustom org-goto-auto-isearch t
1581 "Non-nil means typing characters in `org-goto' starts incremental search.
1582 When nil, you can use these keybindings to navigate the buffer:
1584 q Quit the org-goto interface
1585 n Go to the next visible heading
1586 p Go to the previous visible heading
1587 f Go one heading forward on same level
1588 b Go one heading backward on same level
1589 u Go one heading up"
1590 :group 'org-edit-structure
1591 :type 'boolean)
1593 (defgroup org-sparse-trees nil
1594 "Options concerning sparse trees in Org-mode."
1595 :tag "Org Sparse Trees"
1596 :group 'org-structure)
1598 (defcustom org-highlight-sparse-tree-matches t
1599 "Non-nil means highlight all matches that define a sparse tree.
1600 The highlights will automatically disappear the next time the buffer is
1601 changed by an edit command."
1602 :group 'org-sparse-trees
1603 :type 'boolean)
1605 (defcustom org-remove-highlights-with-change t
1606 "Non-nil means any change to the buffer will remove temporary highlights.
1607 Such highlights are created by `org-occur' and `org-clock-display'.
1608 When nil, `C-c C-c' needs to be used to get rid of the highlights.
1609 The highlights created by `org-toggle-latex-fragment' always need
1610 `C-c C-x C-l' to be removed."
1611 :group 'org-sparse-trees
1612 :group 'org-time
1613 :type 'boolean)
1616 (defcustom org-occur-hook '(org-first-headline-recenter)
1617 "Hook that is run after `org-occur' has constructed a sparse tree.
1618 This can be used to recenter the window to show as much of the structure
1619 as possible."
1620 :group 'org-sparse-trees
1621 :type 'hook)
1623 (defgroup org-imenu-and-speedbar nil
1624 "Options concerning imenu and speedbar in Org-mode."
1625 :tag "Org Imenu and Speedbar"
1626 :group 'org-structure)
1628 (defcustom org-imenu-depth 2
1629 "The maximum level for Imenu access to Org-mode headlines.
1630 This also applied for speedbar access."
1631 :group 'org-imenu-and-speedbar
1632 :type 'integer)
1634 (defgroup org-table nil
1635 "Options concerning tables in Org-mode."
1636 :tag "Org Table"
1637 :group 'org)
1639 (defcustom org-enable-table-editor 'optimized
1640 "Non-nil means lines starting with \"|\" are handled by the table editor.
1641 When nil, such lines will be treated like ordinary lines.
1643 When equal to the symbol `optimized', the table editor will be optimized to
1644 do the following:
1645 - Automatic overwrite mode in front of whitespace in table fields.
1646 This makes the structure of the table stay in tact as long as the edited
1647 field does not exceed the column width.
1648 - Minimize the number of realigns. Normally, the table is aligned each time
1649 TAB or RET are pressed to move to another field. With optimization this
1650 happens only if changes to a field might have changed the column width.
1651 Optimization requires replacing the functions `self-insert-command',
1652 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1653 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1654 very good at guessing when a re-align will be necessary, but you can always
1655 force one with \\[org-ctrl-c-ctrl-c].
1657 If you would like to use the optimized version in Org-mode, but the
1658 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1660 This variable can be used to turn on and off the table editor during a session,
1661 but in order to toggle optimization, a restart is required.
1663 See also the variable `org-table-auto-blank-field'."
1664 :group 'org-table
1665 :type '(choice
1666 (const :tag "off" nil)
1667 (const :tag "on" t)
1668 (const :tag "on, optimized" optimized)))
1670 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1671 (version<= emacs-version "24.1"))
1672 "Non-nil means cluster self-insert commands for undo when possible.
1673 If this is set, then, like in the Emacs command loop, 20 consecutive
1674 characters will be undone together.
1675 This is configurable, because there is some impact on typing performance."
1676 :group 'org-table
1677 :type 'boolean)
1679 (defcustom org-table-tab-recognizes-table.el t
1680 "Non-nil means TAB will automatically notice a table.el table.
1681 When it sees such a table, it moves point into it and - if necessary -
1682 calls `table-recognize-table'."
1683 :group 'org-table-editing
1684 :type 'boolean)
1686 (defgroup org-link nil
1687 "Options concerning links in Org-mode."
1688 :tag "Org Link"
1689 :group 'org)
1691 (defvar org-link-abbrev-alist-local nil
1692 "Buffer-local version of `org-link-abbrev-alist', which see.
1693 The value of this is taken from the #+LINK lines.")
1694 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1696 (defcustom org-link-abbrev-alist nil
1697 "Alist of link abbreviations.
1698 The car of each element is a string, to be replaced at the start of a link.
1699 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1700 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1702 [[linkkey:tag][description]]
1704 The 'linkkey' must be a word word, starting with a letter, followed
1705 by letters, numbers, '-' or '_'.
1707 If REPLACE is a string, the tag will simply be appended to create the link.
1708 If the string contains \"%s\", the tag will be inserted there. If the string
1709 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1710 at that point (see the function `url-hexify-string'). If the string contains
1711 the specifier \"%(my-function)\", then the custom function `my-function' will
1712 be invoked: this function takes the tag as its only argument and must return
1713 a string.
1715 REPLACE may also be a function that will be called with the tag as the
1716 only argument to create the link, which should be returned as a string.
1718 See the manual for examples."
1719 :group 'org-link
1720 :type '(repeat
1721 (cons
1722 (string :tag "Protocol")
1723 (choice
1724 (string :tag "Format")
1725 (function)))))
1727 (defcustom org-descriptive-links t
1728 "Non-nil means Org will display descriptive links.
1729 E.g. [[http://orgmode.org][Org website]] will be displayed as
1730 \"Org Website\", hiding the link itself and just displaying its
1731 description. When set to `nil', Org will display the full links
1732 literally.
1734 You can interactively set the value of this variable by calling
1735 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1736 :group 'org-link
1737 :type 'boolean)
1739 (defcustom org-link-file-path-type 'adaptive
1740 "How the path name in file links should be stored.
1741 Valid values are:
1743 relative Relative to the current directory, i.e. the directory of the file
1744 into which the link is being inserted.
1745 absolute Absolute path, if possible with ~ for home directory.
1746 noabbrev Absolute path, no abbreviation of home directory.
1747 adaptive Use relative path for files in the current directory and sub-
1748 directories of it. For other files, use an absolute path."
1749 :group 'org-link
1750 :type '(choice
1751 (const relative)
1752 (const absolute)
1753 (const noabbrev)
1754 (const adaptive)))
1756 (defvaralias 'org-activate-links 'org-highlight-links)
1757 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1758 "Types of links that should be highlighted in Org-mode files.
1760 This is a list of symbols, each one of them leading to the
1761 highlighting of a certain link type.
1763 You can still open links that are not highlighted.
1765 In principle, it does not hurt to turn on highlighting for all
1766 link types. There may be a small gain when turning off unused
1767 link types. The types are:
1769 bracket The recommended [[link][description]] or [[link]] links with hiding.
1770 angle Links in angular brackets that may contain whitespace like
1771 <bbdb:Carsten Dominik>.
1772 plain Plain links in normal text, no whitespace, like http://google.com.
1773 radio Text that is matched by a radio target, see manual for details.
1774 tag Tag settings in a headline (link to tag search).
1775 date Time stamps (link to calendar).
1776 footnote Footnote labels.
1778 If you set this variable during an Emacs session, use `org-mode-restart'
1779 in the Org buffer so that the change takes effect."
1780 :group 'org-link
1781 :group 'org-appearance
1782 :type '(set :greedy t
1783 (const :tag "Double bracket links" bracket)
1784 (const :tag "Angular bracket links" angle)
1785 (const :tag "Plain text links" plain)
1786 (const :tag "Radio target matches" radio)
1787 (const :tag "Tags" tag)
1788 (const :tag "Timestamps" date)
1789 (const :tag "Footnotes" footnote)))
1791 (defcustom org-make-link-description-function nil
1792 "Function to use for generating link descriptions from links.
1793 When nil, the link location will be used. This function must take
1794 two parameters: the first one is the link, the second one is the
1795 description generated by `org-insert-link'. The function should
1796 return the description to use."
1797 :group 'org-link
1798 :type '(choice (const nil) (function)))
1800 (defgroup org-link-store nil
1801 "Options concerning storing links in Org-mode."
1802 :tag "Org Store Link"
1803 :group 'org-link)
1805 (defcustom org-url-hexify-p t
1806 "When non-nil, hexify URL when creating a link."
1807 :type 'boolean
1808 :version "24.3"
1809 :group 'org-link-store)
1811 (defcustom org-email-link-description-format "Email %c: %.30s"
1812 "Format of the description part of a link to an email or usenet message.
1813 The following %-escapes will be replaced by corresponding information:
1815 %F full \"From\" field
1816 %f name, taken from \"From\" field, address if no name
1817 %T full \"To\" field
1818 %t first name in \"To\" field, address if no name
1819 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1820 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1821 %s subject
1822 %d date
1823 %m message-id.
1825 You may use normal field width specification between the % and the letter.
1826 This is for example useful to limit the length of the subject.
1828 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1829 :group 'org-link-store
1830 :type 'string)
1832 (defcustom org-from-is-user-regexp
1833 (let (r1 r2)
1834 (when (and user-mail-address (not (string= user-mail-address "")))
1835 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1836 (when (and user-full-name (not (string= user-full-name "")))
1837 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1838 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1839 "Regexp matched against the \"From:\" header of an email or usenet message.
1840 It should match if the message is from the user him/herself."
1841 :group 'org-link-store
1842 :type 'regexp)
1844 (defcustom org-context-in-file-links t
1845 "Non-nil means file links from `org-store-link' contain context.
1846 A search string will be added to the file name with :: as separator and
1847 used to find the context when the link is activated by the command
1848 `org-open-at-point'. When this option is t, the entire active region
1849 will be placed in the search string of the file link. If set to a
1850 positive integer, only the first n lines of context will be stored.
1852 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1853 negates this setting for the duration of the command."
1854 :group 'org-link-store
1855 :type '(choice boolean integer))
1857 (defcustom org-keep-stored-link-after-insertion nil
1858 "Non-nil means keep link in list for entire session.
1860 The command `org-store-link' adds a link pointing to the current
1861 location to an internal list. These links accumulate during a session.
1862 The command `org-insert-link' can be used to insert links into any
1863 Org-mode file (offering completion for all stored links). When this
1864 option is nil, every link which has been inserted once using \\[org-insert-link]
1865 will be removed from the list, to make completing the unused links
1866 more efficient."
1867 :group 'org-link-store
1868 :type 'boolean)
1870 (defgroup org-link-follow nil
1871 "Options concerning following links in Org-mode."
1872 :tag "Org Follow Link"
1873 :group 'org-link)
1875 (defcustom org-link-translation-function nil
1876 "Function to translate links with different syntax to Org syntax.
1877 This can be used to translate links created for example by the Planner
1878 or emacs-wiki packages to Org syntax.
1879 The function must accept two parameters, a TYPE containing the link
1880 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1881 which is everything after the link protocol. It should return a cons
1882 with possibly modified values of type and path.
1883 Org contains a function for this, so if you set this variable to
1884 `org-translate-link-from-planner', you should be able follow many
1885 links created by planner."
1886 :group 'org-link-follow
1887 :type '(choice (const nil) (function)))
1889 (defcustom org-follow-link-hook nil
1890 "Hook that is run after a link has been followed."
1891 :group 'org-link-follow
1892 :type 'hook)
1894 (defcustom org-tab-follows-link nil
1895 "Non-nil means on links TAB will follow the link.
1896 Needs to be set before org.el is loaded.
1897 This really should not be used, it does not make sense, and the
1898 implementation is bad."
1899 :group 'org-link-follow
1900 :type 'boolean)
1902 (defcustom org-return-follows-link nil
1903 "Non-nil means on links RET will follow the link.
1904 In tables, the special behavior of RET has precedence."
1905 :group 'org-link-follow
1906 :type 'boolean)
1908 (defcustom org-mouse-1-follows-link
1909 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1910 "Non-nil means mouse-1 on a link will follow the link.
1911 A longer mouse click will still set point. Does not work on XEmacs.
1912 Needs to be set before org.el is loaded."
1913 :group 'org-link-follow
1914 :version "24.4"
1915 :package-version '(Org . "8.3")
1916 :type '(choice
1917 (const :tag "A double click follows the link" double)
1918 (const :tag "Unconditionally follow the link with mouse-1" t)
1919 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1921 (defcustom org-mark-ring-length 4
1922 "Number of different positions to be recorded in the ring.
1923 Changing this requires a restart of Emacs to work correctly."
1924 :group 'org-link-follow
1925 :type 'integer)
1927 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1928 "Non-nil means internal links in Org files must exactly match a headline.
1929 When nil, the link search tries to match a phrase with all words
1930 in the search text."
1931 :group 'org-link-follow
1932 :version "24.1"
1933 :type '(choice
1934 (const :tag "Use fuzzy text search" nil)
1935 (const :tag "Match only exact headline" t)
1936 (const :tag "Match exact headline or query to create it"
1937 query-to-create)))
1939 (defcustom org-link-frame-setup
1940 '((vm . vm-visit-folder-other-frame)
1941 (vm-imap . vm-visit-imap-folder-other-frame)
1942 (gnus . org-gnus-no-new-news)
1943 (file . find-file-other-window)
1944 (wl . wl-other-frame))
1945 "Setup the frame configuration for following links.
1946 When following a link with Emacs, it may often be useful to display
1947 this link in another window or frame. This variable can be used to
1948 set this up for the different types of links.
1949 For VM, use any of
1950 `vm-visit-folder'
1951 `vm-visit-folder-other-window'
1952 `vm-visit-folder-other-frame'
1953 For Gnus, use any of
1954 `gnus'
1955 `gnus-other-frame'
1956 `org-gnus-no-new-news'
1957 For FILE, use any of
1958 `find-file'
1959 `find-file-other-window'
1960 `find-file-other-frame'
1961 For Wanderlust use any of
1962 `wl'
1963 `wl-other-frame'
1964 For the calendar, use the variable `calendar-setup'.
1965 For BBDB, it is currently only possible to display the matches in
1966 another window."
1967 :group 'org-link-follow
1968 :type '(list
1969 (cons (const vm)
1970 (choice
1971 (const vm-visit-folder)
1972 (const vm-visit-folder-other-window)
1973 (const vm-visit-folder-other-frame)))
1974 (cons (const vm-imap)
1975 (choice
1976 (const vm-visit-imap-folder)
1977 (const vm-visit-imap-folder-other-window)
1978 (const vm-visit-imap-folder-other-frame)))
1979 (cons (const gnus)
1980 (choice
1981 (const gnus)
1982 (const gnus-other-frame)
1983 (const org-gnus-no-new-news)))
1984 (cons (const file)
1985 (choice
1986 (const find-file)
1987 (const find-file-other-window)
1988 (const find-file-other-frame)))
1989 (cons (const wl)
1990 (choice
1991 (const wl)
1992 (const wl-other-frame)))))
1994 (defcustom org-display-internal-link-with-indirect-buffer nil
1995 "Non-nil means use indirect buffer to display infile links.
1996 Activating internal links (from one location in a file to another location
1997 in the same file) normally just jumps to the location. When the link is
1998 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1999 is displayed in
2000 another window. When this option is set, the other window actually displays
2001 an indirect buffer clone of the current buffer, to avoid any visibility
2002 changes to the current buffer."
2003 :group 'org-link-follow
2004 :type 'boolean)
2006 (defcustom org-open-non-existing-files nil
2007 "Non-nil means `org-open-file' will open non-existing files.
2008 When nil, an error will be generated.
2009 This variable applies only to external applications because they
2010 might choke on non-existing files. If the link is to a file that
2011 will be opened in Emacs, the variable is ignored."
2012 :group 'org-link-follow
2013 :type 'boolean)
2015 (defcustom org-open-directory-means-index-dot-org nil
2016 "Non-nil means a link to a directory really means to index.org.
2017 When nil, following a directory link will run dired or open a finder/explorer
2018 window on that directory."
2019 :group 'org-link-follow
2020 :type 'boolean)
2022 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2023 "Non-nil means ask for confirmation before executing shell links.
2024 Shell links can be dangerous: just think about a link
2026 [[shell:rm -rf ~/*][Google Search]]
2028 This link would show up in your Org-mode document as \"Google Search\",
2029 but really it would remove your entire home directory.
2030 Therefore we advise against setting this variable to nil.
2031 Just change it to `y-or-n-p' if you want to confirm with a
2032 single keystroke rather than having to type \"yes\"."
2033 :group 'org-link-follow
2034 :type '(choice
2035 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2036 (const :tag "with y-or-n (faster)" y-or-n-p)
2037 (const :tag "no confirmation (dangerous)" nil)))
2038 (put 'org-confirm-shell-link-function
2039 'safe-local-variable
2040 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2042 (defcustom org-confirm-shell-link-not-regexp ""
2043 "A regexp to skip confirmation for shell links."
2044 :group 'org-link-follow
2045 :version "24.1"
2046 :type 'regexp)
2048 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2049 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2050 Elisp links can be dangerous: just think about a link
2052 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2054 This link would show up in your Org-mode document as \"Google Search\",
2055 but really it would remove your entire home directory.
2056 Therefore we advise against setting this variable to nil.
2057 Just change it to `y-or-n-p' if you want to confirm with a
2058 single keystroke rather than having to type \"yes\"."
2059 :group 'org-link-follow
2060 :type '(choice
2061 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2062 (const :tag "with y-or-n (faster)" y-or-n-p)
2063 (const :tag "no confirmation (dangerous)" nil)))
2064 (put 'org-confirm-shell-link-function
2065 'safe-local-variable
2066 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2068 (defcustom org-confirm-elisp-link-not-regexp ""
2069 "A regexp to skip confirmation for Elisp links."
2070 :group 'org-link-follow
2071 :version "24.1"
2072 :type 'regexp)
2074 (defconst org-file-apps-defaults-gnu
2075 '((remote . emacs)
2076 (system . mailcap)
2077 (t . mailcap))
2078 "Default file applications on a UNIX or GNU/Linux system.
2079 See `org-file-apps'.")
2081 (defconst org-file-apps-defaults-macosx
2082 '((remote . emacs)
2083 (t . "open %s")
2084 (system . "open %s")
2085 ("ps.gz" . "gv %s")
2086 ("eps.gz" . "gv %s")
2087 ("dvi" . "xdvi %s")
2088 ("fig" . "xfig %s"))
2089 "Default file applications on a MacOS X system.
2090 The system \"open\" is known as a default, but we use X11 applications
2091 for some files for which the OS does not have a good default.
2092 See `org-file-apps'.")
2094 (defconst org-file-apps-defaults-windowsnt
2095 (list
2096 '(remote . emacs)
2097 (cons t
2098 (list (if (featurep 'xemacs)
2099 'mswindows-shell-execute
2100 'w32-shell-execute)
2101 "open" 'file))
2102 (cons 'system
2103 (list (if (featurep 'xemacs)
2104 'mswindows-shell-execute
2105 'w32-shell-execute)
2106 "open" 'file)))
2107 "Default file applications on a Windows NT system.
2108 The system \"open\" is used for most files.
2109 See `org-file-apps'.")
2111 (defcustom org-file-apps
2112 '((auto-mode . emacs)
2113 ("\\.mm\\'" . default)
2114 ("\\.x?html?\\'" . default)
2115 ("\\.pdf\\'" . default))
2116 "External applications for opening `file:path' items in a document.
2117 Org-mode uses system defaults for different file types, but
2118 you can use this variable to set the application for a given file
2119 extension. The entries in this list are cons cells where the car identifies
2120 files and the cdr the corresponding command. Possible values for the
2121 file identifier are
2122 \"string\" A string as a file identifier can be interpreted in different
2123 ways, depending on its contents:
2125 - Alphanumeric characters only:
2126 Match links with this file extension.
2127 Example: (\"pdf\" . \"evince %s\")
2128 to open PDFs with evince.
2130 - Regular expression: Match links where the
2131 filename matches the regexp. If you want to
2132 use groups here, use shy groups.
2134 Example: (\"\\.x?html\\'\" . \"firefox %s\")
2135 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2136 to open *.html and *.xhtml with firefox.
2138 - Regular expression which contains (non-shy) groups:
2139 Match links where the whole link, including \"::\", and
2140 anything after that, matches the regexp.
2141 In a custom command string, %1, %2, etc. are replaced with
2142 the parts of the link that were matched by the groups.
2143 For backwards compatibility, if a command string is given
2144 that does not use any of the group matches, this case is
2145 handled identically to the second one (i.e. match against
2146 file name only).
2147 In a custom lisp form, you can access the group matches with
2148 (match-string n link).
2150 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
2151 to open [[file:document.pdf::5]] with evince at page 5.
2153 `directory' Matches a directory
2154 `remote' Matches a remote file, accessible through tramp or efs.
2155 Remote files most likely should be visited through Emacs
2156 because external applications cannot handle such paths.
2157 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2158 so all files Emacs knows how to handle. Using this with
2159 command `emacs' will open most files in Emacs. Beware that this
2160 will also open html files inside Emacs, unless you add
2161 (\"html\" . default) to the list as well.
2162 t Default for files not matched by any of the other options.
2163 `system' The system command to open files, like `open' on Windows
2164 and Mac OS X, and mailcap under GNU/Linux. This is the command
2165 that will be selected if you call `C-c C-o' with a double
2166 \\[universal-argument] \\[universal-argument] prefix.
2168 Possible values for the command are:
2169 `emacs' The file will be visited by the current Emacs process.
2170 `default' Use the default application for this file type, which is the
2171 association for t in the list, most likely in the system-specific
2172 part.
2173 This can be used to overrule an unwanted setting in the
2174 system-specific variable.
2175 `system' Use the system command for opening files, like \"open\".
2176 This command is specified by the entry whose car is `system'.
2177 Most likely, the system-specific version of this variable
2178 does define this command, but you can overrule/replace it
2179 here.
2180 string A command to be executed by a shell; %s will be replaced
2181 by the path to the file.
2182 sexp A Lisp form which will be evaluated. The file path will
2183 be available in the Lisp variable `file'.
2184 For more examples, see the system specific constants
2185 `org-file-apps-defaults-macosx'
2186 `org-file-apps-defaults-windowsnt'
2187 `org-file-apps-defaults-gnu'."
2188 :group 'org-link-follow
2189 :type '(repeat
2190 (cons (choice :value ""
2191 (string :tag "Extension")
2192 (const :tag "System command to open files" system)
2193 (const :tag "Default for unrecognized files" t)
2194 (const :tag "Remote file" remote)
2195 (const :tag "Links to a directory" directory)
2196 (const :tag "Any files that have Emacs modes"
2197 auto-mode))
2198 (choice :value ""
2199 (const :tag "Visit with Emacs" emacs)
2200 (const :tag "Use default" default)
2201 (const :tag "Use the system command" system)
2202 (string :tag "Command")
2203 (sexp :tag "Lisp form")))))
2205 (defcustom org-doi-server-url "http://dx.doi.org/"
2206 "The URL of the DOI server."
2207 :type 'string
2208 :version "24.3"
2209 :group 'org-link-follow)
2211 (defgroup org-refile nil
2212 "Options concerning refiling entries in Org-mode."
2213 :tag "Org Refile"
2214 :group 'org)
2216 (defcustom org-directory "~/org"
2217 "Directory with org files.
2218 This is just a default location to look for Org files. There is no need
2219 at all to put your files into this directory. It is only used in the
2220 following situations:
2222 1. When a capture template specifies a target file that is not an
2223 absolute path. The path will then be interpreted relative to
2224 `org-directory'
2225 2. When a capture note is filed away in an interactive way (when exiting the
2226 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2227 with `org-directory' as the default path."
2228 :group 'org-refile
2229 :group 'org-capture
2230 :type 'directory)
2232 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2233 "Default target for storing notes.
2234 Used as a fall back file for org-capture.el, for templates that
2235 do not specify a target file."
2236 :group 'org-refile
2237 :group 'org-capture
2238 :type '(choice
2239 (const :tag "Default from remember-data-file" nil)
2240 file))
2242 (defcustom org-goto-interface 'outline
2243 "The default interface to be used for `org-goto'.
2244 Allowed values are:
2245 outline The interface shows an outline of the relevant file
2246 and the correct heading is found by moving through
2247 the outline or by searching with incremental search.
2248 outline-path-completion Headlines in the current buffer are offered via
2249 completion. This is the interface also used by
2250 the refile command."
2251 :group 'org-refile
2252 :type '(choice
2253 (const :tag "Outline" outline)
2254 (const :tag "Outline-path-completion" outline-path-completion)))
2256 (defcustom org-goto-max-level 5
2257 "Maximum target level when running `org-goto' with refile interface."
2258 :group 'org-refile
2259 :type 'integer)
2261 (defcustom org-reverse-note-order nil
2262 "Non-nil means store new notes at the beginning of a file or entry.
2263 When nil, new notes will be filed to the end of a file or entry.
2264 This can also be a list with cons cells of regular expressions that
2265 are matched against file names, and values."
2266 :group 'org-capture
2267 :group 'org-refile
2268 :type '(choice
2269 (const :tag "Reverse always" t)
2270 (const :tag "Reverse never" nil)
2271 (repeat :tag "By file name regexp"
2272 (cons regexp boolean))))
2274 (defcustom org-log-refile nil
2275 "Information to record when a task is refiled.
2277 Possible values are:
2279 nil Don't add anything
2280 time Add a time stamp to the task
2281 note Prompt for a note and add it with template `org-log-note-headings'
2283 This option can also be set with on a per-file-basis with
2285 #+STARTUP: nologrefile
2286 #+STARTUP: logrefile
2287 #+STARTUP: lognoterefile
2289 You can have local logging settings for a subtree by setting the LOGGING
2290 property to one or more of these keywords.
2292 When bulk-refiling from the agenda, the value `note' is forbidden and
2293 will temporarily be changed to `time'."
2294 :group 'org-refile
2295 :group 'org-progress
2296 :version "24.1"
2297 :type '(choice
2298 (const :tag "No logging" nil)
2299 (const :tag "Record timestamp" time)
2300 (const :tag "Record timestamp with note." note)))
2302 (defcustom org-refile-targets nil
2303 "Targets for refiling entries with \\[org-refile].
2304 This is a list of cons cells. Each cell contains:
2305 - a specification of the files to be considered, either a list of files,
2306 or a symbol whose function or variable value will be used to retrieve
2307 a file name or a list of file names. If you use `org-agenda-files' for
2308 that, all agenda files will be scanned for targets. Nil means consider
2309 headings in the current buffer.
2310 - A specification of how to find candidate refile targets. This may be
2311 any of:
2312 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2313 This tag has to be present in all target headlines, inheritance will
2314 not be considered.
2315 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2316 todo keyword.
2317 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2318 headlines that are refiling targets.
2319 - a cons cell (:level . N). Any headline of level N is considered a target.
2320 Note that, when `org-odd-levels-only' is set, level corresponds to
2321 order in hierarchy, not to the number of stars.
2322 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2323 Note that, when `org-odd-levels-only' is set, level corresponds to
2324 order in hierarchy, not to the number of stars.
2326 Each element of this list generates a set of possible targets.
2327 The union of these sets is presented (with completion) to
2328 the user by `org-refile'.
2330 You can set the variable `org-refile-target-verify-function' to a function
2331 to verify each headline found by the simple criteria above.
2333 When this variable is nil, all top-level headlines in the current buffer
2334 are used, equivalent to the value `((nil . (:level . 1))'."
2335 :group 'org-refile
2336 :type '(repeat
2337 (cons
2338 (choice :value org-agenda-files
2339 (const :tag "All agenda files" org-agenda-files)
2340 (const :tag "Current buffer" nil)
2341 (function) (variable) (file))
2342 (choice :tag "Identify target headline by"
2343 (cons :tag "Specific tag" (const :value :tag) (string))
2344 (cons :tag "TODO keyword" (const :value :todo) (string))
2345 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2346 (cons :tag "Level number" (const :value :level) (integer))
2347 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2349 (defcustom org-refile-target-verify-function nil
2350 "Function to verify if the headline at point should be a refile target.
2351 The function will be called without arguments, with point at the
2352 beginning of the headline. It should return t and leave point
2353 where it is if the headline is a valid target for refiling.
2355 If the target should not be selected, the function must return nil.
2356 In addition to this, it may move point to a place from where the search
2357 should be continued. For example, the function may decide that the entire
2358 subtree of the current entry should be excluded and move point to the end
2359 of the subtree."
2360 :group 'org-refile
2361 :type '(choice
2362 (const nil)
2363 (function)))
2365 (defcustom org-refile-use-cache nil
2366 "Non-nil means cache refile targets to speed up the process.
2367 The cache for a particular file will be updated automatically when
2368 the buffer has been killed, or when any of the marker used for flagging
2369 refile targets no longer points at a live buffer.
2370 If you have added new entries to a buffer that might themselves be targets,
2371 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2372 find that easier, `C-u C-u C-u C-c C-w'."
2373 :group 'org-refile
2374 :version "24.1"
2375 :type 'boolean)
2377 (defcustom org-refile-use-outline-path nil
2378 "Non-nil means provide refile targets as paths.
2379 So a level 3 headline will be available as level1/level2/level3.
2381 When the value is `file', also include the file name (without directory)
2382 into the path. In this case, you can also stop the completion after
2383 the file name, to get entries inserted as top level in the file.
2385 When `full-file-path', include the full file path."
2386 :group 'org-refile
2387 :type '(choice
2388 (const :tag "Not" nil)
2389 (const :tag "Yes" t)
2390 (const :tag "Start with file name" file)
2391 (const :tag "Start with full file path" full-file-path)))
2393 (defcustom org-outline-path-complete-in-steps t
2394 "Non-nil means complete the outline path in hierarchical steps.
2395 When Org-mode uses the refile interface to select an outline path
2396 \(see variable `org-refile-use-outline-path'), the completion of
2397 the path can be done is a single go, or if can be done in steps down
2398 the headline hierarchy. Going in steps is probably the best if you
2399 do not use a special completion package like `ido' or `icicles'.
2400 However, when using these packages, going in one step can be very
2401 fast, while still showing the whole path to the entry."
2402 :group 'org-refile
2403 :type 'boolean)
2405 (defcustom org-refile-allow-creating-parent-nodes nil
2406 "Non-nil means allow to create new nodes as refile targets.
2407 New nodes are then created by adding \"/new node name\" to the completion
2408 of an existing node. When the value of this variable is `confirm',
2409 new node creation must be confirmed by the user (recommended).
2410 When nil, the completion must match an existing entry.
2412 Note that, if the new heading is not seen by the criteria
2413 listed in `org-refile-targets', multiple instances of the same
2414 heading would be created by trying again to file under the new
2415 heading."
2416 :group 'org-refile
2417 :type '(choice
2418 (const :tag "Never" nil)
2419 (const :tag "Always" t)
2420 (const :tag "Prompt for confirmation" confirm)))
2422 (defcustom org-refile-active-region-within-subtree nil
2423 "Non-nil means also refile active region within a subtree.
2425 By default `org-refile' doesn't allow refiling regions if they
2426 don't contain a set of subtrees, but it might be convenient to
2427 do so sometimes: in that case, the first line of the region is
2428 converted to a headline before refiling."
2429 :group 'org-refile
2430 :version "24.1"
2431 :type 'boolean)
2433 (defgroup org-todo nil
2434 "Options concerning TODO items in Org-mode."
2435 :tag "Org TODO"
2436 :group 'org)
2438 (defgroup org-progress nil
2439 "Options concerning Progress logging in Org-mode."
2440 :tag "Org Progress"
2441 :group 'org-time)
2443 (defvar org-todo-interpretation-widgets
2444 '((:tag "Sequence (cycling hits every state)" sequence)
2445 (:tag "Type (cycling directly to DONE)" type))
2446 "The available interpretation symbols for customizing `org-todo-keywords'.
2447 Interested libraries should add to this list.")
2449 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2450 "List of TODO entry keyword sequences and their interpretation.
2451 \\<org-mode-map>This is a list of sequences.
2453 Each sequence starts with a symbol, either `sequence' or `type',
2454 indicating if the keywords should be interpreted as a sequence of
2455 action steps, or as different types of TODO items. The first
2456 keywords are states requiring action - these states will select a headline
2457 for inclusion into the global TODO list Org-mode produces. If one of
2458 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2459 signify that no further action is necessary. If \"|\" is not found,
2460 the last keyword is treated as the only DONE state of the sequence.
2462 The command \\[org-todo] cycles an entry through these states, and one
2463 additional state where no keyword is present. For details about this
2464 cycling, see the manual.
2466 TODO keywords and interpretation can also be set on a per-file basis with
2467 the special #+SEQ_TODO and #+TYP_TODO lines.
2469 Each keyword can optionally specify a character for fast state selection
2470 \(in combination with the variable `org-use-fast-todo-selection')
2471 and specifiers for state change logging, using the same syntax that
2472 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2473 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2474 indicates to record a time stamp each time this state is selected.
2476 Each keyword may also specify if a timestamp or a note should be
2477 recorded when entering or leaving the state, by adding additional
2478 characters in the parenthesis after the keyword. This looks like this:
2479 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2480 record only the time of the state change. With X and Y being either
2481 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2482 Y when leaving the state if and only if the *target* state does not
2483 define X. You may omit any of the fast-selection key or X or /Y,
2484 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2486 For backward compatibility, this variable may also be just a list
2487 of keywords. In this case the interpretation (sequence or type) will be
2488 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2489 :group 'org-todo
2490 :group 'org-keywords
2491 :type '(choice
2492 (repeat :tag "Old syntax, just keywords"
2493 (string :tag "Keyword"))
2494 (repeat :tag "New syntax"
2495 (cons
2496 (choice
2497 :tag "Interpretation"
2498 ;;Quick and dirty way to see
2499 ;;`org-todo-interpretations'. This takes the
2500 ;;place of item arguments
2501 :convert-widget
2502 (lambda (widget)
2503 (widget-put widget
2504 :args (mapcar
2505 (lambda (x)
2506 (widget-convert
2507 (cons 'const x)))
2508 org-todo-interpretation-widgets))
2509 widget))
2510 (repeat
2511 (string :tag "Keyword"))))))
2513 (defvar org-todo-keywords-1 nil
2514 "All TODO and DONE keywords active in a buffer.")
2515 (make-variable-buffer-local 'org-todo-keywords-1)
2516 (defvar org-todo-keywords-for-agenda nil)
2517 (defvar org-done-keywords-for-agenda nil)
2518 (defvar org-todo-keyword-alist-for-agenda nil)
2519 (defvar org-tag-alist-for-agenda nil
2520 "Alist of all tags from all agenda files.")
2521 (defvar org-tag-groups-alist-for-agenda nil
2522 "Alist of all groups tags from all current agenda files.")
2523 (defvar org-tag-groups-alist nil)
2524 (make-variable-buffer-local 'org-tag-groups-alist)
2525 (defvar org-agenda-contributing-files nil)
2526 (defvar org-not-done-keywords nil)
2527 (make-variable-buffer-local 'org-not-done-keywords)
2528 (defvar org-done-keywords nil)
2529 (make-variable-buffer-local 'org-done-keywords)
2530 (defvar org-todo-heads nil)
2531 (make-variable-buffer-local 'org-todo-heads)
2532 (defvar org-todo-sets nil)
2533 (make-variable-buffer-local 'org-todo-sets)
2534 (defvar org-todo-log-states nil)
2535 (make-variable-buffer-local 'org-todo-log-states)
2536 (defvar org-todo-kwd-alist nil)
2537 (make-variable-buffer-local 'org-todo-kwd-alist)
2538 (defvar org-todo-key-alist nil)
2539 (make-variable-buffer-local 'org-todo-key-alist)
2540 (defvar org-todo-key-trigger nil)
2541 (make-variable-buffer-local 'org-todo-key-trigger)
2543 (defcustom org-todo-interpretation 'sequence
2544 "Controls how TODO keywords are interpreted.
2545 This variable is in principle obsolete and is only used for
2546 backward compatibility, if the interpretation of todo keywords is
2547 not given already in `org-todo-keywords'. See that variable for
2548 more information."
2549 :group 'org-todo
2550 :group 'org-keywords
2551 :type '(choice (const sequence)
2552 (const type)))
2554 (defcustom org-use-fast-todo-selection t
2555 "Non-nil means use the fast todo selection scheme with C-c C-t.
2556 This variable describes if and under what circumstances the cycling
2557 mechanism for TODO keywords will be replaced by a single-key, direct
2558 selection scheme.
2560 When nil, fast selection is never used.
2562 When the symbol `prefix', it will be used when `org-todo' is called
2563 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2564 `C-u t' in an agenda buffer.
2566 When t, fast selection is used by default. In this case, the prefix
2567 argument forces cycling instead.
2569 In all cases, the special interface is only used if access keys have
2570 actually been assigned by the user, i.e. if keywords in the configuration
2571 are followed by a letter in parenthesis, like TODO(t)."
2572 :group 'org-todo
2573 :type '(choice
2574 (const :tag "Never" nil)
2575 (const :tag "By default" t)
2576 (const :tag "Only with C-u C-c C-t" prefix)))
2578 (defcustom org-provide-todo-statistics t
2579 "Non-nil means update todo statistics after insert and toggle.
2580 ALL-HEADLINES means update todo statistics by including headlines
2581 with no TODO keyword as well, counting them as not done.
2582 A list of TODO keywords means the same, but skip keywords that are
2583 not in this list.
2584 When set to a list of two lists, the first list contains keywords
2585 to consider as TODO keywords, the second list contains keywords
2586 to consider as DONE keywords.
2588 When this is set, todo statistics is updated in the parent of the
2589 current entry each time a todo state is changed."
2590 :group 'org-todo
2591 :type '(choice
2592 (const :tag "Yes, only for TODO entries" t)
2593 (const :tag "Yes, including all entries" all-headlines)
2594 (repeat :tag "Yes, for TODOs in this list"
2595 (string :tag "TODO keyword"))
2596 (list :tag "Yes, for TODOs and DONEs in these lists"
2597 (repeat (string :tag "TODO keyword"))
2598 (repeat (string :tag "DONE keyword")))
2599 (other :tag "No TODO statistics" nil)))
2601 (defcustom org-hierarchical-todo-statistics t
2602 "Non-nil means TODO statistics covers just direct children.
2603 When nil, all entries in the subtree are considered.
2604 This has only an effect if `org-provide-todo-statistics' is set.
2605 To set this to nil for only a single subtree, use a COOKIE_DATA
2606 property and include the word \"recursive\" into the value."
2607 :group 'org-todo
2608 :type 'boolean)
2610 (defcustom org-after-todo-state-change-hook nil
2611 "Hook which is run after the state of a TODO item was changed.
2612 The new state (a string with a TODO keyword, or nil) is available in the
2613 Lisp variable `org-state'."
2614 :group 'org-todo
2615 :type 'hook)
2617 (defvar org-blocker-hook nil
2618 "Hook for functions that are allowed to block a state change.
2620 Functions in this hook should not modify the buffer.
2621 Each function gets as its single argument a property list,
2622 see `org-trigger-hook' for more information about this list.
2624 If any of the functions in this hook returns nil, the state change
2625 is blocked.")
2627 (defvar org-trigger-hook nil
2628 "Hook for functions that are triggered by a state change.
2630 Each function gets as its single argument a property list with at
2631 least the following elements:
2633 (:type type-of-change :position pos-at-entry-start
2634 :from old-state :to new-state)
2636 Depending on the type, more properties may be present.
2638 This mechanism is currently implemented for:
2640 TODO state changes
2641 ------------------
2642 :type todo-state-change
2643 :from previous state (keyword as a string), or nil, or a symbol
2644 'todo' or 'done', to indicate the general type of state.
2645 :to new state, like in :from")
2647 (defcustom org-enforce-todo-dependencies nil
2648 "Non-nil means undone TODO entries will block switching the parent to DONE.
2649 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2650 be blocked if any prior sibling is not yet done.
2651 Finally, if the parent is blocked because of ordered siblings of its own,
2652 the child will also be blocked."
2653 :set (lambda (var val)
2654 (set var val)
2655 (if val
2656 (add-hook 'org-blocker-hook
2657 'org-block-todo-from-children-or-siblings-or-parent)
2658 (remove-hook 'org-blocker-hook
2659 'org-block-todo-from-children-or-siblings-or-parent)))
2660 :group 'org-todo
2661 :type 'boolean)
2663 (defcustom org-enforce-todo-checkbox-dependencies nil
2664 "Non-nil means unchecked boxes will block switching the parent to DONE.
2665 When this is nil, checkboxes have no influence on switching TODO states.
2666 When non-nil, you first need to check off all check boxes before the TODO
2667 entry can be switched to DONE.
2668 This variable needs to be set before org.el is loaded, and you need to
2669 restart Emacs after a change to make the change effective. The only way
2670 to change is while Emacs is running is through the customize interface."
2671 :set (lambda (var val)
2672 (set var val)
2673 (if val
2674 (add-hook 'org-blocker-hook
2675 'org-block-todo-from-checkboxes)
2676 (remove-hook 'org-blocker-hook
2677 'org-block-todo-from-checkboxes)))
2678 :group 'org-todo
2679 :type 'boolean)
2681 (defcustom org-treat-insert-todo-heading-as-state-change nil
2682 "Non-nil means inserting a TODO heading is treated as state change.
2683 So when the command \\[org-insert-todo-heading] is used, state change
2684 logging will apply if appropriate. When nil, the new TODO item will
2685 be inserted directly, and no logging will take place."
2686 :group 'org-todo
2687 :type 'boolean)
2689 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2690 "Non-nil means switching TODO states with S-cursor counts as state change.
2691 This is the default behavior. However, setting this to nil allows a
2692 convenient way to select a TODO state and bypass any logging associated
2693 with that."
2694 :group 'org-todo
2695 :type 'boolean)
2697 (defcustom org-todo-state-tags-triggers nil
2698 "Tag changes that should be triggered by TODO state changes.
2699 This is a list. Each entry is
2701 (state-change (tag . flag) .......)
2703 State-change can be a string with a state, and empty string to indicate the
2704 state that has no TODO keyword, or it can be one of the symbols `todo'
2705 or `done', meaning any not-done or done state, respectively."
2706 :group 'org-todo
2707 :group 'org-tags
2708 :type '(repeat
2709 (cons (choice :tag "When changing to"
2710 (const :tag "Not-done state" todo)
2711 (const :tag "Done state" done)
2712 (string :tag "State"))
2713 (repeat
2714 (cons :tag "Tag action"
2715 (string :tag "Tag")
2716 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2718 (defcustom org-log-done nil
2719 "Information to record when a task moves to the DONE state.
2721 Possible values are:
2723 nil Don't add anything, just change the keyword
2724 time Add a time stamp to the task
2725 note Prompt for a note and add it with template `org-log-note-headings'
2727 This option can also be set with on a per-file-basis with
2729 #+STARTUP: nologdone
2730 #+STARTUP: logdone
2731 #+STARTUP: lognotedone
2733 You can have local logging settings for a subtree by setting the LOGGING
2734 property to one or more of these keywords."
2735 :group 'org-todo
2736 :group 'org-progress
2737 :type '(choice
2738 (const :tag "No logging" nil)
2739 (const :tag "Record CLOSED timestamp" time)
2740 (const :tag "Record CLOSED timestamp with note." note)))
2742 ;; Normalize old uses of org-log-done.
2743 (cond
2744 ((eq org-log-done t) (setq org-log-done 'time))
2745 ((and (listp org-log-done) (memq 'done org-log-done))
2746 (setq org-log-done 'note)))
2748 (defcustom org-log-reschedule nil
2749 "Information to record when the scheduling date of a tasks is modified.
2751 Possible values are:
2753 nil Don't add anything, just change the date
2754 time Add a time stamp to the task
2755 note Prompt for a note and add it with template `org-log-note-headings'
2757 This option can also be set with on a per-file-basis with
2759 #+STARTUP: nologreschedule
2760 #+STARTUP: logreschedule
2761 #+STARTUP: lognotereschedule"
2762 :group 'org-todo
2763 :group 'org-progress
2764 :type '(choice
2765 (const :tag "No logging" nil)
2766 (const :tag "Record timestamp" time)
2767 (const :tag "Record timestamp with note." note)))
2769 (defcustom org-log-redeadline nil
2770 "Information to record when the deadline date of a tasks is modified.
2772 Possible values are:
2774 nil Don't add anything, just change the date
2775 time Add a time stamp to the task
2776 note Prompt for a note and add it with template `org-log-note-headings'
2778 This option can also be set with on a per-file-basis with
2780 #+STARTUP: nologredeadline
2781 #+STARTUP: logredeadline
2782 #+STARTUP: lognoteredeadline
2784 You can have local logging settings for a subtree by setting the LOGGING
2785 property to one or more of these keywords."
2786 :group 'org-todo
2787 :group 'org-progress
2788 :type '(choice
2789 (const :tag "No logging" nil)
2790 (const :tag "Record timestamp" time)
2791 (const :tag "Record timestamp with note." note)))
2793 (defcustom org-log-note-clock-out nil
2794 "Non-nil means record a note when clocking out of an item.
2795 This can also be configured on a per-file basis by adding one of
2796 the following lines anywhere in the buffer:
2798 #+STARTUP: lognoteclock-out
2799 #+STARTUP: nolognoteclock-out"
2800 :group 'org-todo
2801 :group 'org-progress
2802 :type 'boolean)
2804 (defcustom org-log-done-with-time t
2805 "Non-nil means the CLOSED time stamp will contain date and time.
2806 When nil, only the date will be recorded."
2807 :group 'org-progress
2808 :type 'boolean)
2810 (defcustom org-log-note-headings
2811 '((done . "CLOSING NOTE %t")
2812 (state . "State %-12s from %-12S %t")
2813 (note . "Note taken on %t")
2814 (reschedule . "Rescheduled from %S on %t")
2815 (delschedule . "Not scheduled, was %S on %t")
2816 (redeadline . "New deadline from %S on %t")
2817 (deldeadline . "Removed deadline, was %S on %t")
2818 (refile . "Refiled on %t")
2819 (clock-out . ""))
2820 "Headings for notes added to entries.
2821 The value is an alist, with the car being a symbol indicating the note
2822 context, and the cdr is the heading to be used. The heading may also be the
2823 empty string.
2824 %t in the heading will be replaced by a time stamp.
2825 %T will be an active time stamp instead the default inactive one
2826 %d will be replaced by a short-format time stamp.
2827 %D will be replaced by an active short-format time stamp.
2828 %s will be replaced by the new TODO state, in double quotes.
2829 %S will be replaced by the old TODO state, in double quotes.
2830 %u will be replaced by the user name.
2831 %U will be replaced by the full user name.
2833 In fact, it is not a good idea to change the `state' entry, because
2834 agenda log mode depends on the format of these entries."
2835 :group 'org-todo
2836 :group 'org-progress
2837 :type '(list :greedy t
2838 (cons (const :tag "Heading when closing an item" done) string)
2839 (cons (const :tag
2840 "Heading when changing todo state (todo sequence only)"
2841 state) string)
2842 (cons (const :tag "Heading when just taking a note" note) string)
2843 (cons (const :tag "Heading when rescheduling" reschedule) string)
2844 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2845 (cons (const :tag "Heading when changing deadline" redeadline) string)
2846 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2847 (cons (const :tag "Heading when refiling" refile) string)
2848 (cons (const :tag "Heading when clocking out" clock-out) string)))
2850 (unless (assq 'note org-log-note-headings)
2851 (push '(note . "%t") org-log-note-headings))
2853 (defcustom org-log-into-drawer nil
2854 "Non-nil means insert state change notes and time stamps into a drawer.
2855 When nil, state changes notes will be inserted after the headline and
2856 any scheduling and clock lines, but not inside a drawer.
2858 The value of this variable should be the name of the drawer to use.
2859 LOGBOOK is proposed as the default drawer for this purpose, you can
2860 also set this to a string to define the drawer of your choice.
2862 A value of t is also allowed, representing \"LOGBOOK\".
2864 A value of t or nil can also be set with on a per-file-basis with
2866 #+STARTUP: logdrawer
2867 #+STARTUP: nologdrawer
2869 If this variable is set, `org-log-state-notes-insert-after-drawers'
2870 will be ignored.
2872 You can set the property LOG_INTO_DRAWER to overrule this setting for
2873 a subtree."
2874 :group 'org-todo
2875 :group 'org-progress
2876 :type '(choice
2877 (const :tag "Not into a drawer" nil)
2878 (const :tag "LOGBOOK" t)
2879 (string :tag "Other")))
2881 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2883 (defun org-log-into-drawer ()
2884 "Return the value of `org-log-into-drawer', but let properties overrule.
2885 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2886 used instead of the default value."
2887 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2888 (cond
2889 ((not p) org-log-into-drawer)
2890 ((equal p "nil") nil)
2891 ((equal p "t") "LOGBOOK")
2892 (t p))))
2894 (defcustom org-log-state-notes-insert-after-drawers nil
2895 "Non-nil means insert state change notes after any drawers in entry.
2896 Only the drawers that *immediately* follow the headline and the
2897 deadline/scheduled line are skipped.
2898 When nil, insert notes right after the heading and perhaps the line
2899 with deadline/scheduling if present.
2901 This variable will have no effect if `org-log-into-drawer' is
2902 set."
2903 :group 'org-todo
2904 :group 'org-progress
2905 :type 'boolean)
2907 (defcustom org-log-states-order-reversed t
2908 "Non-nil means the latest state note will be directly after heading.
2909 When nil, the state change notes will be ordered according to time.
2911 This option can also be set with on a per-file-basis with
2913 #+STARTUP: logstatesreversed
2914 #+STARTUP: nologstatesreversed"
2915 :group 'org-todo
2916 :group 'org-progress
2917 :type 'boolean)
2919 (defcustom org-todo-repeat-to-state nil
2920 "The TODO state to which a repeater should return the repeating task.
2921 By default this is the first task in a TODO sequence, or the previous state
2922 in a TODO_TYP set. But you can specify another task here.
2923 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2924 :group 'org-todo
2925 :version "24.1"
2926 :type '(choice (const :tag "Head of sequence" nil)
2927 (string :tag "Specific state")))
2929 (defcustom org-log-repeat 'time
2930 "Non-nil means record moving through the DONE state when triggering repeat.
2931 An auto-repeating task is immediately switched back to TODO when
2932 marked DONE. If you are not logging state changes (by adding \"@\"
2933 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2934 record a closing note, there will be no record of the task moving
2935 through DONE. This variable forces taking a note anyway.
2937 nil Don't force a record
2938 time Record a time stamp
2939 note Prompt for a note and add it with template `org-log-note-headings'
2941 This option can also be set with on a per-file-basis with
2943 #+STARTUP: nologrepeat
2944 #+STARTUP: logrepeat
2945 #+STARTUP: lognoterepeat
2947 You can have local logging settings for a subtree by setting the LOGGING
2948 property to one or more of these keywords."
2949 :group 'org-todo
2950 :group 'org-progress
2951 :type '(choice
2952 (const :tag "Don't force a record" nil)
2953 (const :tag "Force recording the DONE state" time)
2954 (const :tag "Force recording a note with the DONE state" note)))
2957 (defgroup org-priorities nil
2958 "Priorities in Org-mode."
2959 :tag "Org Priorities"
2960 :group 'org-todo)
2962 (defcustom org-enable-priority-commands t
2963 "Non-nil means priority commands are active.
2964 When nil, these commands will be disabled, so that you never accidentally
2965 set a priority."
2966 :group 'org-priorities
2967 :type 'boolean)
2969 (defcustom org-highest-priority ?A
2970 "The highest priority of TODO items. A character like ?A, ?B etc.
2971 Must have a smaller ASCII number than `org-lowest-priority'."
2972 :group 'org-priorities
2973 :type 'character)
2975 (defcustom org-lowest-priority ?C
2976 "The lowest priority of TODO items. A character like ?A, ?B etc.
2977 Must have a larger ASCII number than `org-highest-priority'."
2978 :group 'org-priorities
2979 :type 'character)
2981 (defcustom org-default-priority ?B
2982 "The default priority of TODO items.
2983 This is the priority an item gets if no explicit priority is given.
2984 When starting to cycle on an empty priority the first step in the cycle
2985 depends on `org-priority-start-cycle-with-default'. The resulting first
2986 step priority must not exceed the range from `org-highest-priority' to
2987 `org-lowest-priority' which means that `org-default-priority' has to be
2988 in this range exclusive or inclusive the range boundaries. Else the
2989 first step refuses to set the default and the second will fall back
2990 to (depending on the command used) the highest or lowest priority."
2991 :group 'org-priorities
2992 :type 'character)
2994 (defcustom org-priority-start-cycle-with-default t
2995 "Non-nil means start with default priority when starting to cycle.
2996 When this is nil, the first step in the cycle will be (depending on the
2997 command used) one higher or lower than the default priority.
2998 See also `org-default-priority'."
2999 :group 'org-priorities
3000 :type 'boolean)
3002 (defcustom org-get-priority-function nil
3003 "Function to extract the priority from a string.
3004 The string is normally the headline. If this is nil Org computes the
3005 priority from the priority cookie like [#A] in the headline. It returns
3006 an integer, increasing by 1000 for each priority level.
3007 The user can set a different function here, which should take a string
3008 as an argument and return the numeric priority."
3009 :group 'org-priorities
3010 :version "24.1"
3011 :type '(choice
3012 (const nil)
3013 (function)))
3015 (defgroup org-time nil
3016 "Options concerning time stamps and deadlines in Org-mode."
3017 :tag "Org Time"
3018 :group 'org)
3020 (defcustom org-insert-labeled-timestamps-at-point nil
3021 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
3022 When nil, these labeled time stamps are forces into the second line of an
3023 entry, just after the headline. When scheduling from the global TODO list,
3024 the time stamp will always be forced into the second line."
3025 :group 'org-time
3026 :type 'boolean)
3028 (defcustom org-time-stamp-rounding-minutes '(0 5)
3029 "Number of minutes to round time stamps to.
3030 These are two values, the first applies when first creating a time stamp.
3031 The second applies when changing it with the commands `S-up' and `S-down'.
3032 When changing the time stamp, this means that it will change in steps
3033 of N minutes, as given by the second value.
3035 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3036 numbers should be factors of 60, so for example 5, 10, 15.
3038 When this is larger than 1, you can still force an exact time stamp by using
3039 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
3040 and by using a prefix arg to `S-up/down' to specify the exact number
3041 of minutes to shift."
3042 :group 'org-time
3043 :get (lambda (var) ; Make sure both elements are there
3044 (if (integerp (default-value var))
3045 (list (default-value var) 5)
3046 (default-value var)))
3047 :type '(list
3048 (integer :tag "when inserting times")
3049 (integer :tag "when modifying times")))
3051 ;; Normalize old customizations of this variable.
3052 (when (integerp org-time-stamp-rounding-minutes)
3053 (setq org-time-stamp-rounding-minutes
3054 (list org-time-stamp-rounding-minutes
3055 org-time-stamp-rounding-minutes)))
3057 (defcustom org-display-custom-times nil
3058 "Non-nil means overlay custom formats over all time stamps.
3059 The formats are defined through the variable `org-time-stamp-custom-formats'.
3060 To turn this on on a per-file basis, insert anywhere in the file:
3061 #+STARTUP: customtime"
3062 :group 'org-time
3063 :set 'set-default
3064 :type 'sexp)
3065 (make-variable-buffer-local 'org-display-custom-times)
3067 (defcustom org-time-stamp-custom-formats
3068 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3069 "Custom formats for time stamps. See `format-time-string' for the syntax.
3070 These are overlaid over the default ISO format if the variable
3071 `org-display-custom-times' is set. Time like %H:%M should be at the
3072 end of the second format. The custom formats are also honored by export
3073 commands, if custom time display is turned on at the time of export."
3074 :group 'org-time
3075 :type 'sexp)
3077 (defun org-time-stamp-format (&optional long inactive)
3078 "Get the right format for a time string."
3079 (let ((f (if long (cdr org-time-stamp-formats)
3080 (car org-time-stamp-formats))))
3081 (if inactive
3082 (concat "[" (substring f 1 -1) "]")
3083 f)))
3085 (defcustom org-time-clocksum-format
3086 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3087 "The format string used when creating CLOCKSUM lines.
3088 This is also used when Org mode generates a time duration.
3090 The value can be a single format string containing two
3091 %-sequences, which will be filled with the number of hours and
3092 minutes in that order.
3094 Alternatively, the value can be a plist associating any of the
3095 keys :years, :months, :weeks, :days, :hours or :minutes with
3096 format strings. The time duration is formatted using only the
3097 time components that are needed and concatenating the results.
3098 If a time unit in absent, it falls back to the next smallest
3099 unit.
3101 The keys :require-years, :require-months, :require-days,
3102 :require-weeks, :require-hours, :require-minutes are also
3103 meaningful. A non-nil value for these keys indicates that the
3104 corresponding time component should always be included, even if
3105 its value is 0.
3108 For example,
3110 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3111 :require-minutes t)
3113 means durations longer than a day will be expressed in days,
3114 hours and minutes, and durations less than a day will always be
3115 expressed in hours and minutes (even for durations less than an
3116 hour).
3118 The value
3120 \(:days \"%dd\" :minutes \"%dm\")
3122 means durations longer than a day will be expressed in days and
3123 minutes, and durations less than a day will be expressed entirely
3124 in minutes (even for durations longer than an hour)."
3125 :group 'org-time
3126 :group 'org-clock
3127 :version "24.4"
3128 :package-version '(Org . "8.0")
3129 :type '(choice (string :tag "Format string")
3130 (set :tag "Plist"
3131 (group :inline t (const :tag "Years" :years)
3132 (string :tag "Format string"))
3133 (group :inline t
3134 (const :tag "Always show years" :require-years)
3135 (const t))
3136 (group :inline t (const :tag "Months" :months)
3137 (string :tag "Format string"))
3138 (group :inline t
3139 (const :tag "Always show months" :require-months)
3140 (const t))
3141 (group :inline t (const :tag "Weeks" :weeks)
3142 (string :tag "Format string"))
3143 (group :inline t
3144 (const :tag "Always show weeks" :require-weeks)
3145 (const t))
3146 (group :inline t (const :tag "Days" :days)
3147 (string :tag "Format string"))
3148 (group :inline t
3149 (const :tag "Always show days" :require-days)
3150 (const t))
3151 (group :inline t (const :tag "Hours" :hours)
3152 (string :tag "Format string"))
3153 (group :inline t
3154 (const :tag "Always show hours" :require-hours)
3155 (const t))
3156 (group :inline t (const :tag "Minutes" :minutes)
3157 (string :tag "Format string"))
3158 (group :inline t
3159 (const :tag "Always show minutes" :require-minutes)
3160 (const t)))))
3162 (defcustom org-time-clocksum-use-fractional nil
3163 "When non-nil, \\[org-clock-display] uses fractional times.
3164 See `org-time-clocksum-format' for more on time clock formats."
3165 :group 'org-time
3166 :group 'org-clock
3167 :version "24.3"
3168 :type 'boolean)
3170 (defcustom org-time-clocksum-use-effort-durations nil
3171 "When non-nil, \\[org-clock-display] uses effort durations.
3172 E.g. by default, one day is considered to be a 8 hours effort,
3173 so a task that has been clocked for 16 hours will be displayed
3174 as during 2 days in the clock display or in the clocktable.
3176 See `org-effort-durations' on how to set effort durations
3177 and `org-time-clocksum-format' for more on time clock formats."
3178 :group 'org-time
3179 :group 'org-clock
3180 :version "24.4"
3181 :package-version '(Org . "8.0")
3182 :type 'boolean)
3184 (defcustom org-time-clocksum-fractional-format "%.2f"
3185 "The format string used when creating CLOCKSUM lines,
3186 or when Org mode generates a time duration, if
3187 `org-time-clocksum-use-fractional' is enabled.
3189 The value can be a single format string containing one
3190 %-sequence, which will be filled with the number of hours as
3191 a float.
3193 Alternatively, the value can be a plist associating any of the
3194 keys :years, :months, :weeks, :days, :hours or :minutes with
3195 a format string. The time duration is formatted using the
3196 largest time unit which gives a non-zero integer part. If all
3197 specified formats have zero integer part, the smallest time unit
3198 is used."
3199 :group 'org-time
3200 :type '(choice (string :tag "Format string")
3201 (set (group :inline t (const :tag "Years" :years)
3202 (string :tag "Format string"))
3203 (group :inline t (const :tag "Months" :months)
3204 (string :tag "Format string"))
3205 (group :inline t (const :tag "Weeks" :weeks)
3206 (string :tag "Format string"))
3207 (group :inline t (const :tag "Days" :days)
3208 (string :tag "Format string"))
3209 (group :inline t (const :tag "Hours" :hours)
3210 (string :tag "Format string"))
3211 (group :inline t (const :tag "Minutes" :minutes)
3212 (string :tag "Format string")))))
3214 (defcustom org-deadline-warning-days 14
3215 "Number of days before expiration during which a deadline becomes active.
3216 This variable governs the display in sparse trees and in the agenda.
3217 When 0 or negative, it means use this number (the absolute value of it)
3218 even if a deadline has a different individual lead time specified.
3220 Custom commands can set this variable in the options section."
3221 :group 'org-time
3222 :group 'org-agenda-daily/weekly
3223 :type 'integer)
3225 (defcustom org-scheduled-delay-days 0
3226 "Number of days before a scheduled item becomes active.
3227 This variable governs the display in sparse trees and in the agenda.
3228 The default value (i.e. 0) means: don't delay scheduled item.
3229 When negative, it means use this number (the absolute value of it)
3230 even if a scheduled item has a different individual delay time
3231 specified.
3233 Custom commands can set this variable in the options section."
3234 :group 'org-time
3235 :group 'org-agenda-daily/weekly
3236 :version "24.4"
3237 :package-version '(Org . "8.0")
3238 :type 'integer)
3240 (defcustom org-read-date-prefer-future t
3241 "Non-nil means assume future for incomplete date input from user.
3242 This affects the following situations:
3243 1. The user gives a month but not a year.
3244 For example, if it is April and you enter \"feb 2\", this will be read
3245 as Feb 2, *next* year. \"May 5\", however, will be this year.
3246 2. The user gives a day, but no month.
3247 For example, if today is the 15th, and you enter \"3\", Org-mode will
3248 read this as the third of *next* month. However, if you enter \"17\",
3249 it will be considered as *this* month.
3251 If you set this variable to the symbol `time', then also the following
3252 will work:
3254 3. If the user gives a time.
3255 If the time is before now, it will be interpreted as tomorrow.
3257 Currently none of this works for ISO week specifications.
3259 When this option is nil, the current day, month and year will always be
3260 used as defaults.
3262 See also `org-agenda-jump-prefer-future'."
3263 :group 'org-time
3264 :type '(choice
3265 (const :tag "Never" nil)
3266 (const :tag "Check month and day" t)
3267 (const :tag "Check month, day, and time" time)))
3269 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3270 "Should the agenda jump command prefer the future for incomplete dates?
3271 The default is to do the same as configured in `org-read-date-prefer-future'.
3272 But you can also set a deviating value here.
3273 This may t or nil, or the symbol `org-read-date-prefer-future'."
3274 :group 'org-agenda
3275 :group 'org-time
3276 :version "24.1"
3277 :type '(choice
3278 (const :tag "Use org-read-date-prefer-future"
3279 org-read-date-prefer-future)
3280 (const :tag "Never" nil)
3281 (const :tag "Always" t)))
3283 (defcustom org-read-date-force-compatible-dates t
3284 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3286 Depending on the system Emacs is running on, certain dates cannot
3287 be represented with the type used internally to represent time.
3288 Dates between 1970-1-1 and 2038-1-1 can always be represented
3289 correctly. Some systems allow for earlier dates, some for later,
3290 some for both. One way to find out it to insert any date into an
3291 Org buffer, putting the cursor on the year and hitting S-up and
3292 S-down to test the range.
3294 When this variable is set to t, the date/time prompt will not let
3295 you specify dates outside the 1970-2037 range, so it is certain that
3296 these dates will work in whatever version of Emacs you are
3297 running, and also that you can move a file from one Emacs implementation
3298 to another. WHenever Org is forcing the year for you, it will display
3299 a message and beep.
3301 When this variable is nil, Org will check if the date is
3302 representable in the specific Emacs implementation you are using.
3303 If not, it will force a year, usually the current year, and beep
3304 to remind you. Currently this setting is not recommended because
3305 the likelihood that you will open your Org files in an Emacs that
3306 has limited date range is not negligible.
3308 A workaround for this problem is to use diary sexp dates for time
3309 stamps outside of this range."
3310 :group 'org-time
3311 :version "24.1"
3312 :type 'boolean)
3314 (defcustom org-read-date-display-live t
3315 "Non-nil means display current interpretation of date prompt live.
3316 This display will be in an overlay, in the minibuffer."
3317 :group 'org-time
3318 :type 'boolean)
3320 (defcustom org-read-date-popup-calendar t
3321 "Non-nil means pop up a calendar when prompting for a date.
3322 In the calendar, the date can be selected with mouse-1. However, the
3323 minibuffer will also be active, and you can simply enter the date as well.
3324 When nil, only the minibuffer will be available."
3325 :group 'org-time
3326 :type 'boolean)
3327 (org-defvaralias 'org-popup-calendar-for-date-prompt
3328 'org-read-date-popup-calendar)
3330 (make-obsolete-variable
3331 'org-read-date-minibuffer-setup-hook
3332 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3333 (defcustom org-read-date-minibuffer-setup-hook nil
3334 "Hook to be used to set up keys for the date/time interface.
3335 Add key definitions to `minibuffer-local-map', which will be a
3336 temporary copy.
3338 WARNING: This option is obsolete, you should use
3339 `org-read-date-minibuffer-local-map' to set up keys."
3340 :group 'org-time
3341 :type 'hook)
3343 (defcustom org-extend-today-until 0
3344 "The hour when your day really ends. Must be an integer.
3345 This has influence for the following applications:
3346 - When switching the agenda to \"today\". It it is still earlier than
3347 the time given here, the day recognized as TODAY is actually yesterday.
3348 - When a date is read from the user and it is still before the time given
3349 here, the current date and time will be assumed to be yesterday, 23:59.
3350 Also, timestamps inserted in capture templates follow this rule.
3352 IMPORTANT: This is a feature whose implementation is and likely will
3353 remain incomplete. Really, it is only here because past midnight seems to
3354 be the favorite working time of John Wiegley :-)"
3355 :group 'org-time
3356 :type 'integer)
3358 (defcustom org-use-effective-time nil
3359 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3360 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3361 \"effective time\" of any timestamps between midnight and 8am will be
3362 23:59 of the previous day."
3363 :group 'org-time
3364 :version "24.1"
3365 :type 'boolean)
3367 (defcustom org-use-last-clock-out-time-as-effective-time nil
3368 "When non-nil, use the last clock out time for `org-todo'.
3369 Note that this option has precedence over the combined use of
3370 `org-use-effective-time' and `org-extend-today-until'."
3371 :group 'org-time
3372 :version "24.4"
3373 :package-version '(Org . "8.0")
3374 :type 'boolean)
3376 (defcustom org-edit-timestamp-down-means-later nil
3377 "Non-nil means S-down will increase the time in a time stamp.
3378 When nil, S-up will increase."
3379 :group 'org-time
3380 :type 'boolean)
3382 (defcustom org-calendar-follow-timestamp-change t
3383 "Non-nil means make the calendar window follow timestamp changes.
3384 When a timestamp is modified and the calendar window is visible, it will be
3385 moved to the new date."
3386 :group 'org-time
3387 :type 'boolean)
3389 (defgroup org-tags nil
3390 "Options concerning tags in Org-mode."
3391 :tag "Org Tags"
3392 :group 'org)
3394 (defcustom org-tag-alist nil
3395 "List of tags allowed in Org-mode files.
3396 When this list is nil, Org-mode will base TAG input on what is already in the
3397 buffer.
3398 The value of this variable is an alist, the car of each entry must be a
3399 keyword as a string, the cdr may be a character that is used to select
3400 that tag through the fast-tag-selection interface.
3401 See the manual for details."
3402 :group 'org-tags
3403 :type '(repeat
3404 (choice
3405 (cons (string :tag "Tag name")
3406 (character :tag "Access char"))
3407 (list :tag "Start radio group"
3408 (const :startgroup)
3409 (option (string :tag "Group description")))
3410 (list :tag "Group tags delimiter"
3411 (const :grouptags))
3412 (list :tag "End radio group"
3413 (const :endgroup)
3414 (option (string :tag "Group description")))
3415 (const :tag "New line" (:newline)))))
3417 (defcustom org-tag-persistent-alist nil
3418 "List of tags that will always appear in all Org-mode files.
3419 This is in addition to any in buffer settings or customizations
3420 of `org-tag-alist'.
3421 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3422 The value of this variable is an alist, the car of each entry must be a
3423 keyword as a string, the cdr may be a character that is used to select
3424 that tag through the fast-tag-selection interface.
3425 See the manual for details.
3426 To disable these tags on a per-file basis, insert anywhere in the file:
3427 #+STARTUP: noptag"
3428 :group 'org-tags
3429 :type '(repeat
3430 (choice
3431 (cons (string :tag "Tag name")
3432 (character :tag "Access char"))
3433 (const :tag "Start radio group" (:startgroup))
3434 (const :tag "Group tags delimiter" (:grouptags))
3435 (const :tag "End radio group" (:endgroup))
3436 (const :tag "New line" (:newline)))))
3438 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3439 "If non-nil, always offer completion for all tags of all agenda files.
3440 Instead of customizing this variable directly, you might want to
3441 set it locally for capture buffers, because there no list of
3442 tags in that file can be created dynamically (there are none).
3444 (add-hook 'org-capture-mode-hook
3445 (lambda ()
3446 (set (make-local-variable
3447 'org-complete-tags-always-offer-all-agenda-tags)
3448 t)))"
3449 :group 'org-tags
3450 :version "24.1"
3451 :type 'boolean)
3453 (defvar org-file-tags nil
3454 "List of tags that can be inherited by all entries in the file.
3455 The tags will be inherited if the variable `org-use-tag-inheritance'
3456 says they should be.
3457 This variable is populated from #+FILETAGS lines.")
3459 (defcustom org-use-fast-tag-selection 'auto
3460 "Non-nil means use fast tag selection scheme.
3461 This is a special interface to select and deselect tags with single keys.
3462 When nil, fast selection is never used.
3463 When the symbol `auto', fast selection is used if and only if selection
3464 characters for tags have been configured, either through the variable
3465 `org-tag-alist' or through a #+TAGS line in the buffer.
3466 When t, fast selection is always used and selection keys are assigned
3467 automatically if necessary."
3468 :group 'org-tags
3469 :type '(choice
3470 (const :tag "Always" t)
3471 (const :tag "Never" nil)
3472 (const :tag "When selection characters are configured" auto)))
3474 (defcustom org-fast-tag-selection-single-key nil
3475 "Non-nil means fast tag selection exits after first change.
3476 When nil, you have to press RET to exit it.
3477 During fast tag selection, you can toggle this flag with `C-c'.
3478 This variable can also have the value `expert'. In this case, the window
3479 displaying the tags menu is not even shown, until you press C-c again."
3480 :group 'org-tags
3481 :type '(choice
3482 (const :tag "No" nil)
3483 (const :tag "Yes" t)
3484 (const :tag "Expert" expert)))
3486 (defvar org-fast-tag-selection-include-todo nil
3487 "Non-nil means fast tags selection interface will also offer TODO states.
3488 This is an undocumented feature, you should not rely on it.")
3490 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3491 "The column to which tags should be indented in a headline.
3492 If this number is positive, it specifies the column. If it is negative,
3493 it means that the tags should be flushright to that column. For example,
3494 -80 works well for a normal 80 character screen.
3495 When 0, place tags directly after headline text, with only one space in
3496 between."
3497 :group 'org-tags
3498 :type 'integer)
3500 (defcustom org-auto-align-tags t
3501 "Non-nil keeps tags aligned when modifying headlines.
3502 Some operations (i.e. demoting) change the length of a headline and
3503 therefore shift the tags around. With this option turned on, after
3504 each such operation the tags are again aligned to `org-tags-column'."
3505 :group 'org-tags
3506 :type 'boolean)
3508 (defcustom org-use-tag-inheritance t
3509 "Non-nil means tags in levels apply also for sublevels.
3510 When nil, only the tags directly given in a specific line apply there.
3511 This may also be a list of tags that should be inherited, or a regexp that
3512 matches tags that should be inherited. Additional control is possible
3513 with the variable `org-tags-exclude-from-inheritance' which gives an
3514 explicit list of tags to be excluded from inheritance, even if the value of
3515 `org-use-tag-inheritance' would select it for inheritance.
3517 If this option is t, a match early-on in a tree can lead to a large
3518 number of matches in the subtree when constructing the agenda or creating
3519 a sparse tree. If you only want to see the first match in a tree during
3520 a search, check out the variable `org-tags-match-list-sublevels'."
3521 :group 'org-tags
3522 :type '(choice
3523 (const :tag "Not" nil)
3524 (const :tag "Always" t)
3525 (repeat :tag "Specific tags" (string :tag "Tag"))
3526 (regexp :tag "Tags matched by regexp")))
3528 (defcustom org-tags-exclude-from-inheritance nil
3529 "List of tags that should never be inherited.
3530 This is a way to exclude a few tags from inheritance. For way to do
3531 the opposite, to actively allow inheritance for selected tags,
3532 see the variable `org-use-tag-inheritance'."
3533 :group 'org-tags
3534 :type '(repeat (string :tag "Tag")))
3536 (defun org-tag-inherit-p (tag)
3537 "Check if TAG is one that should be inherited."
3538 (cond
3539 ((member tag org-tags-exclude-from-inheritance) nil)
3540 ((eq org-use-tag-inheritance t) t)
3541 ((not org-use-tag-inheritance) nil)
3542 ((stringp org-use-tag-inheritance)
3543 (string-match org-use-tag-inheritance tag))
3544 ((listp org-use-tag-inheritance)
3545 (member tag org-use-tag-inheritance))
3546 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3548 (defcustom org-tags-match-list-sublevels t
3549 "Non-nil means list also sublevels of headlines matching a search.
3550 This variable applies to tags/property searches, and also to stuck
3551 projects because this search is based on a tags match as well.
3553 When set to the symbol `indented', sublevels are indented with
3554 leading dots.
3556 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3557 the sublevels of a headline matching a tag search often also match
3558 the same search. Listing all of them can create very long lists.
3559 Setting this variable to nil causes subtrees of a match to be skipped.
3561 This variable is semi-obsolete and probably should always be true. It
3562 is better to limit inheritance to certain tags using the variables
3563 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3564 :group 'org-tags
3565 :type '(choice
3566 (const :tag "No, don't list them" nil)
3567 (const :tag "Yes, do list them" t)
3568 (const :tag "List them, indented with leading dots" indented)))
3570 (defcustom org-tags-sort-function nil
3571 "When set, tags are sorted using this function as a comparator."
3572 :group 'org-tags
3573 :type '(choice
3574 (const :tag "No sorting" nil)
3575 (const :tag "Alphabetical" string<)
3576 (const :tag "Reverse alphabetical" string>)
3577 (function :tag "Custom function" nil)))
3579 (defvar org-tags-history nil
3580 "History of minibuffer reads for tags.")
3581 (defvar org-last-tags-completion-table nil
3582 "The last used completion table for tags.")
3583 (defvar org-after-tags-change-hook nil
3584 "Hook that is run after the tags in a line have changed.")
3586 (defgroup org-properties nil
3587 "Options concerning properties in Org-mode."
3588 :tag "Org Properties"
3589 :group 'org)
3591 (defcustom org-property-format "%-10s %s"
3592 "How property key/value pairs should be formatted by `indent-line'.
3593 When `indent-line' hits a property definition, it will format the line
3594 according to this format, mainly to make sure that the values are
3595 lined-up with respect to each other."
3596 :group 'org-properties
3597 :type 'string)
3599 (defcustom org-properties-postprocess-alist nil
3600 "Alist of properties and functions to adjust inserted values.
3601 Elements of this alist must be of the form
3603 ([string] [function])
3605 where [string] must be a property name and [function] must be a
3606 lambda expression: this lambda expression must take one argument,
3607 the value to adjust, and return the new value as a string.
3609 For example, this element will allow the property \"Remaining\"
3610 to be updated wrt the relation between the \"Effort\" property
3611 and the clock summary:
3613 ((\"Remaining\" (lambda(value)
3614 (let ((clocksum (org-clock-sum-current-item))
3615 (effort (org-duration-string-to-minutes
3616 (org-entry-get (point) \"Effort\"))))
3617 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3618 :group 'org-properties
3619 :version "24.1"
3620 :type '(alist :key-type (string :tag "Property")
3621 :value-type (function :tag "Function")))
3623 (defcustom org-use-property-inheritance nil
3624 "Non-nil means properties apply also for sublevels.
3626 This setting is chiefly used during property searches. Turning it on can
3627 cause significant overhead when doing a search, which is why it is not
3628 on by default.
3630 When nil, only the properties directly given in the current entry count.
3631 When t, every property is inherited. The value may also be a list of
3632 properties that should have inheritance, or a regular expression matching
3633 properties that should be inherited.
3635 However, note that some special properties use inheritance under special
3636 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3637 and the properties ending in \"_ALL\" when they are used as descriptor
3638 for valid values of a property.
3640 Note for programmers:
3641 When querying an entry with `org-entry-get', you can control if inheritance
3642 should be used. By default, `org-entry-get' looks only at the local
3643 properties. You can request inheritance by setting the inherit argument
3644 to t (to force inheritance) or to `selective' (to respect the setting
3645 in this variable)."
3646 :group 'org-properties
3647 :type '(choice
3648 (const :tag "Not" nil)
3649 (const :tag "Always" t)
3650 (repeat :tag "Specific properties" (string :tag "Property"))
3651 (regexp :tag "Properties matched by regexp")))
3653 (defun org-property-inherit-p (property)
3654 "Check if PROPERTY is one that should be inherited."
3655 (cond
3656 ((eq org-use-property-inheritance t) t)
3657 ((not org-use-property-inheritance) nil)
3658 ((stringp org-use-property-inheritance)
3659 (string-match org-use-property-inheritance property))
3660 ((listp org-use-property-inheritance)
3661 (member property org-use-property-inheritance))
3662 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3664 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3665 "The default column format, if no other format has been defined.
3666 This variable can be set on the per-file basis by inserting a line
3668 #+COLUMNS: %25ITEM ....."
3669 :group 'org-properties
3670 :type 'string)
3672 (defcustom org-columns-ellipses ".."
3673 "The ellipses to be used when a field in column view is truncated.
3674 When this is the empty string, as many characters as possible are shown,
3675 but then there will be no visual indication that the field has been truncated.
3676 When this is a string of length N, the last N characters of a truncated
3677 field are replaced by this string. If the column is narrower than the
3678 ellipses string, only part of the ellipses string will be shown."
3679 :group 'org-properties
3680 :type 'string)
3682 (defcustom org-columns-modify-value-for-display-function nil
3683 "Function that modifies values for display in column view.
3684 For example, it can be used to cut out a certain part from a time stamp.
3685 The function must take 2 arguments:
3687 column-title The title of the column (*not* the property name)
3688 value The value that should be modified.
3690 The function should return the value that should be displayed,
3691 or nil if the normal value should be used."
3692 :group 'org-properties
3693 :type '(choice (const nil) (function)))
3695 (defconst org-global-properties-fixed
3696 '(("VISIBILITY_ALL" . "folded children content all")
3697 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3698 "List of property/value pairs that can be inherited by any entry.
3700 These are fixed values, for the preset properties. The user variable
3701 that can be used to add to this list is `org-global-properties'.
3703 The entries in this list are cons cells where the car is a property
3704 name and cdr is a string with the value. If the value represents
3705 multiple items like an \"_ALL\" property, separate the items by
3706 spaces.")
3708 (defcustom org-global-properties nil
3709 "List of property/value pairs that can be inherited by any entry.
3711 This list will be combined with the constant `org-global-properties-fixed'.
3713 The entries in this list are cons cells where the car is a property
3714 name and cdr is a string with the value.
3716 You can set buffer-local values for the same purpose in the variable
3717 `org-file-properties' this by adding lines like
3719 #+PROPERTY: NAME VALUE"
3720 :group 'org-properties
3721 :type '(repeat
3722 (cons (string :tag "Property")
3723 (string :tag "Value"))))
3725 (defvar org-file-properties nil
3726 "List of property/value pairs that can be inherited by any entry.
3727 Valid for the current buffer.
3728 This variable is populated from #+PROPERTY lines.")
3729 (make-variable-buffer-local 'org-file-properties)
3731 (defgroup org-agenda nil
3732 "Options concerning agenda views in Org-mode."
3733 :tag "Org Agenda"
3734 :group 'org)
3736 (defvar org-category nil
3737 "Variable used by org files to set a category for agenda display.
3738 Such files should use a file variable to set it, for example
3740 # -*- mode: org; org-category: \"ELisp\"
3742 or contain a special line
3744 #+CATEGORY: ELisp
3746 If the file does not specify a category, then file's base name
3747 is used instead.")
3748 (make-variable-buffer-local 'org-category)
3749 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3751 (defcustom org-agenda-files nil
3752 "The files to be used for agenda display.
3753 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3754 \\[org-remove-file]. You can also use customize to edit the list.
3756 If an entry is a directory, all files in that directory that are matched by
3757 `org-agenda-file-regexp' will be part of the file list.
3759 If the value of the variable is not a list but a single file name, then
3760 the list of agenda files is actually stored and maintained in that file, one
3761 agenda file per line. In this file paths can be given relative to
3762 `org-directory'. Tilde expansion and environment variable substitution
3763 are also made."
3764 :group 'org-agenda
3765 :type '(choice
3766 (repeat :tag "List of files and directories" file)
3767 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3769 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3770 "Regular expression to match files for `org-agenda-files'.
3771 If any element in the list in that variable contains a directory instead
3772 of a normal file, all files in that directory that are matched by this
3773 regular expression will be included."
3774 :group 'org-agenda
3775 :type 'regexp)
3777 (defcustom org-agenda-text-search-extra-files nil
3778 "List of extra files to be searched by text search commands.
3779 These files will be searched in addition to the agenda files by the
3780 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3781 Note that these files will only be searched for text search commands,
3782 not for the other agenda views like todo lists, tag searches or the weekly
3783 agenda. This variable is intended to list notes and possibly archive files
3784 that should also be searched by these two commands.
3785 In fact, if the first element in the list is the symbol `agenda-archives',
3786 then all archive files of all agenda files will be added to the search
3787 scope."
3788 :group 'org-agenda
3789 :type '(set :greedy t
3790 (const :tag "Agenda Archives" agenda-archives)
3791 (repeat :inline t (file))))
3793 (org-defvaralias 'org-agenda-multi-occur-extra-files
3794 'org-agenda-text-search-extra-files)
3796 (defcustom org-agenda-skip-unavailable-files nil
3797 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3798 A nil value means to remove them, after a query, from the list."
3799 :group 'org-agenda
3800 :type 'boolean)
3802 (defcustom org-calendar-to-agenda-key [?c]
3803 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3804 The command `org-calendar-goto-agenda' will be bound to this key. The
3805 default is the character `c' because then `c' can be used to switch back and
3806 forth between agenda and calendar."
3807 :group 'org-agenda
3808 :type 'sexp)
3810 (defcustom org-calendar-insert-diary-entry-key [?i]
3811 "The key to be installed in `calendar-mode-map' for adding diary entries.
3812 This option is irrelevant until `org-agenda-diary-file' has been configured
3813 to point to an Org-mode file. When that is the case, the command
3814 `org-agenda-diary-entry' will be bound to the key given here, by default
3815 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3816 if you want to continue doing this, you need to change this to a different
3817 key."
3818 :group 'org-agenda
3819 :type 'sexp)
3821 (defcustom org-agenda-diary-file 'diary-file
3822 "File to which to add new entries with the `i' key in agenda and calendar.
3823 When this is the symbol `diary-file', the functionality in the Emacs
3824 calendar will be used to add entries to the `diary-file'. But when this
3825 points to a file, `org-agenda-diary-entry' will be used instead."
3826 :group 'org-agenda
3827 :type '(choice
3828 (const :tag "The standard Emacs diary file" diary-file)
3829 (file :tag "Special Org file diary entries")))
3831 (eval-after-load "calendar"
3832 '(progn
3833 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3834 'org-calendar-goto-agenda)
3835 (add-hook 'calendar-mode-hook
3836 (lambda ()
3837 (unless (eq org-agenda-diary-file 'diary-file)
3838 (define-key calendar-mode-map
3839 org-calendar-insert-diary-entry-key
3840 'org-agenda-diary-entry))))))
3842 (defgroup org-latex nil
3843 "Options for embedding LaTeX code into Org-mode."
3844 :tag "Org LaTeX"
3845 :group 'org)
3847 (defcustom org-format-latex-options
3848 '(:foreground default :background default :scale 1.0
3849 :html-foreground "Black" :html-background "Transparent"
3850 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3851 "Options for creating images from LaTeX fragments.
3852 This is a property list with the following properties:
3853 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3854 `default' means use the foreground of the default face.
3855 `auto' means use the foreground from the text face.
3856 :background the background color, or \"Transparent\".
3857 `default' means use the background of the default face.
3858 `auto' means use the background from the text face.
3859 :scale a scaling factor for the size of the images, to get more pixels
3860 :html-foreground, :html-background, :html-scale
3861 the same numbers for HTML export.
3862 :matchers a list indicating which matchers should be used to
3863 find LaTeX fragments. Valid members of this list are:
3864 \"begin\" find environments
3865 \"$1\" find single characters surrounded by $.$
3866 \"$\" find math expressions surrounded by $...$
3867 \"$$\" find math expressions surrounded by $$....$$
3868 \"\\(\" find math expressions surrounded by \\(...\\)
3869 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3870 :group 'org-latex
3871 :type 'plist)
3873 (defcustom org-format-latex-signal-error t
3874 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3875 When nil, just push out a message."
3876 :group 'org-latex
3877 :version "24.1"
3878 :type 'boolean)
3880 (defcustom org-latex-to-mathml-jar-file nil
3881 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3882 Use this to specify additional executable file say a jar file.
3884 When using MathToWeb as the converter, specify the full-path to
3885 your mathtoweb.jar file."
3886 :group 'org-latex
3887 :version "24.1"
3888 :type '(choice
3889 (const :tag "None" nil)
3890 (file :tag "JAR file" :must-match t)))
3892 (defcustom org-latex-to-mathml-convert-command nil
3893 "Command to convert LaTeX fragments to MathML.
3894 Replace format-specifiers in the command as noted below and use
3895 `shell-command' to convert LaTeX to MathML.
3896 %j: Executable file in fully expanded form as specified by
3897 `org-latex-to-mathml-jar-file'.
3898 %I: Input LaTeX file in fully expanded form
3899 %o: Output MathML file
3900 This command is used by `org-create-math-formula'.
3902 When using MathToWeb as the converter, set this to
3903 \"java -jar %j -unicode -force -df %o %I\"."
3904 :group 'org-latex
3905 :version "24.1"
3906 :type '(choice
3907 (const :tag "None" nil)
3908 (string :tag "\nShell command")))
3910 (defcustom org-latex-create-formula-image-program 'dvipng
3911 "Program to convert LaTeX fragments with.
3913 dvipng Process the LaTeX fragments to dvi file, then convert
3914 dvi files to png files using dvipng.
3915 This will also include processing of non-math environments.
3916 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3917 to convert pdf files to png files"
3918 :group 'org-latex
3919 :version "24.1"
3920 :type '(choice
3921 (const :tag "dvipng" dvipng)
3922 (const :tag "imagemagick" imagemagick)))
3924 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3925 "Path to store latex preview images.
3926 A relative path here creates many directories relative to the
3927 processed org files paths. An absolute path puts all preview
3928 images at the same place."
3929 :group 'org-latex
3930 :version "24.3"
3931 :type 'string)
3933 (defun org-format-latex-mathml-available-p ()
3934 "Return t if `org-latex-to-mathml-convert-command' is usable."
3935 (save-match-data
3936 (when (and (boundp 'org-latex-to-mathml-convert-command)
3937 org-latex-to-mathml-convert-command)
3938 (let ((executable (car (split-string
3939 org-latex-to-mathml-convert-command))))
3940 (when (executable-find executable)
3941 (if (string-match
3942 "%j" org-latex-to-mathml-convert-command)
3943 (file-readable-p org-latex-to-mathml-jar-file)
3944 t))))))
3946 (defcustom org-format-latex-header "\\documentclass{article}
3947 \\usepackage[usenames]{color}
3948 \[PACKAGES]
3949 \[DEFAULT-PACKAGES]
3950 \\pagestyle{empty} % do not remove
3951 % The settings below are copied from fullpage.sty
3952 \\setlength{\\textwidth}{\\paperwidth}
3953 \\addtolength{\\textwidth}{-3cm}
3954 \\setlength{\\oddsidemargin}{1.5cm}
3955 \\addtolength{\\oddsidemargin}{-2.54cm}
3956 \\setlength{\\evensidemargin}{\\oddsidemargin}
3957 \\setlength{\\textheight}{\\paperheight}
3958 \\addtolength{\\textheight}{-\\headheight}
3959 \\addtolength{\\textheight}{-\\headsep}
3960 \\addtolength{\\textheight}{-\\footskip}
3961 \\addtolength{\\textheight}{-3cm}
3962 \\setlength{\\topmargin}{1.5cm}
3963 \\addtolength{\\topmargin}{-2.54cm}"
3964 "The document header used for processing LaTeX fragments.
3965 It is imperative that this header make sure that no page number
3966 appears on the page. The package defined in the variables
3967 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3968 will either replace the placeholder \"[PACKAGES]\" in this
3969 header, or they will be appended."
3970 :group 'org-latex
3971 :type 'string)
3973 (defun org-set-packages-alist (var val)
3974 "Set the packages alist and make sure it has 3 elements per entry."
3975 (set var (mapcar (lambda (x)
3976 (if (and (consp x) (= (length x) 2))
3977 (list (car x) (nth 1 x) t)
3979 val)))
3981 (defun org-get-packages-alist (var)
3982 "Get the packages alist and make sure it has 3 elements per entry."
3983 (mapcar (lambda (x)
3984 (if (and (consp x) (= (length x) 2))
3985 (list (car x) (nth 1 x) t)
3987 (default-value var)))
3989 (defcustom org-latex-default-packages-alist
3990 '(("AUTO" "inputenc" t)
3991 ("T1" "fontenc" t)
3992 ("" "fixltx2e" nil)
3993 ("" "graphicx" t)
3994 ("" "longtable" nil)
3995 ("" "float" nil)
3996 ("" "wrapfig" nil)
3997 ("" "rotating" nil)
3998 ("normalem" "ulem" t)
3999 ("" "amsmath" t)
4000 ("" "textcomp" t)
4001 ("" "marvosym" t)
4002 ("" "wasysym" t)
4003 ("" "amssymb" t)
4004 ("" "hyperref" nil)
4005 "\\tolerance=1000")
4006 "Alist of default packages to be inserted in the header.
4008 Change this only if one of the packages here causes an
4009 incompatibility with another package you are using.
4011 The packages in this list are needed by one part or another of
4012 Org mode to function properly:
4014 - inputenc, fontenc: for basic font and character selection
4015 - fixltx2e: Important patches of LaTeX itself
4016 - graphicx: for including images
4017 - longtable: For multipage tables
4018 - float, wrapfig: for figure placement
4019 - rotating: for sideways figures and tables
4020 - ulem: for underline and strike-through
4021 - amsmath: for subscript and superscript and math environments
4022 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
4023 for interpreting the entities in `org-entities'. You can skip
4024 some of these packages if you don't use any of their symbols.
4025 - hyperref: for cross references
4027 Therefore you should not modify this variable unless you know
4028 what you are doing. The one reason to change it anyway is that
4029 you might be loading some other package that conflicts with one
4030 of the default packages. Each element is either a cell or
4031 a string.
4033 A cell is of the format:
4035 \( \"options\" \"package\" SNIPPET-FLAG).
4037 If SNIPPET-FLAG is non-nil, the package also needs to be included
4038 when compiling LaTeX snippets into images for inclusion into
4039 non-LaTeX output.
4041 A string will be inserted as-is in the header of the document."
4042 :group 'org-latex
4043 :group 'org-export-latex
4044 :set 'org-set-packages-alist
4045 :get 'org-get-packages-alist
4046 :version "24.1"
4047 :type '(repeat
4048 (choice
4049 (list :tag "options/package pair"
4050 (string :tag "options")
4051 (string :tag "package")
4052 (boolean :tag "Snippet"))
4053 (string :tag "A line of LaTeX"))))
4055 (defcustom org-latex-packages-alist nil
4056 "Alist of packages to be inserted in every LaTeX header.
4058 These will be inserted after `org-latex-default-packages-alist'.
4059 Each element is either a cell or a string.
4061 A cell is of the format:
4063 \(\"options\" \"package\" SNIPPET-FLAG)
4065 SNIPPET-FLAG, when non-nil, indicates that this package is also
4066 needed when turning LaTeX snippets into images for inclusion into
4067 non-LaTeX output.
4069 A string will be inserted as-is in the header of the document.
4071 Make sure that you only list packages here which:
4073 - you want in every file;
4074 - do not conflict with the setup in `org-format-latex-header';
4075 - do not conflict with the default packages in
4076 `org-latex-default-packages-alist'."
4077 :group 'org-latex
4078 :group 'org-export-latex
4079 :set 'org-set-packages-alist
4080 :get 'org-get-packages-alist
4081 :type '(repeat
4082 (choice
4083 (list :tag "options/package pair"
4084 (string :tag "options")
4085 (string :tag "package")
4086 (boolean :tag "Snippet"))
4087 (string :tag "A line of LaTeX"))))
4089 (defgroup org-appearance nil
4090 "Settings for Org-mode appearance."
4091 :tag "Org Appearance"
4092 :group 'org)
4094 (defcustom org-level-color-stars-only nil
4095 "Non-nil means fontify only the stars in each headline.
4096 When nil, the entire headline is fontified.
4097 Changing it requires restart of `font-lock-mode' to become effective
4098 also in regions already fontified."
4099 :group 'org-appearance
4100 :type 'boolean)
4102 (defcustom org-hide-leading-stars nil
4103 "Non-nil means hide the first N-1 stars in a headline.
4104 This works by using the face `org-hide' for these stars. This
4105 face is white for a light background, and black for a dark
4106 background. You may have to customize the face `org-hide' to
4107 make this work.
4108 Changing it requires restart of `font-lock-mode' to become effective
4109 also in regions already fontified.
4110 You may also set this on a per-file basis by adding one of the following
4111 lines to the buffer:
4113 #+STARTUP: hidestars
4114 #+STARTUP: showstars"
4115 :group 'org-appearance
4116 :type 'boolean)
4118 (defcustom org-hidden-keywords nil
4119 "List of symbols corresponding to keywords to be hidden the org buffer.
4120 For example, a value '(title) for this list will make the document's title
4121 appear in the buffer without the initial #+TITLE: keyword."
4122 :group 'org-appearance
4123 :version "24.1"
4124 :type '(set (const :tag "#+AUTHOR" author)
4125 (const :tag "#+DATE" date)
4126 (const :tag "#+EMAIL" email)
4127 (const :tag "#+TITLE" title)))
4129 (defcustom org-custom-properties nil
4130 "List of properties (as strings) with a special meaning.
4131 The default use of these custom properties is to let the user
4132 hide them with `org-toggle-custom-properties-visibility'."
4133 :group 'org-properties
4134 :group 'org-appearance
4135 :version "24.3"
4136 :type '(repeat (string :tag "Property Name")))
4138 (defcustom org-fontify-done-headline nil
4139 "Non-nil means change the face of a headline if it is marked DONE.
4140 Normally, only the TODO/DONE keyword indicates the state of a headline.
4141 When this is non-nil, the headline after the keyword is set to the
4142 `org-headline-done' as an additional indication."
4143 :group 'org-appearance
4144 :type 'boolean)
4146 (defcustom org-fontify-emphasized-text t
4147 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4148 Changing this variable requires a restart of Emacs to take effect."
4149 :group 'org-appearance
4150 :type 'boolean)
4152 (defcustom org-fontify-whole-heading-line nil
4153 "Non-nil means fontify the whole line for headings.
4154 This is useful when setting a background color for the
4155 org-level-* faces."
4156 :group 'org-appearance
4157 :type 'boolean)
4159 (defcustom org-highlight-latex-and-related nil
4160 "Non-nil means highlight LaTeX related syntax in the buffer.
4161 When non nil, the value should be a list containing any of the
4162 following symbols:
4163 `latex' Highlight LaTeX snippets and environments.
4164 `script' Highlight subscript and superscript.
4165 `entities' Highlight entities."
4166 :group 'org-appearance
4167 :version "24.4"
4168 :package-version '(Org . "8.0")
4169 :type '(choice
4170 (const :tag "No highlighting" nil)
4171 (set :greedy t :tag "Highlight"
4172 (const :tag "LaTeX snippets and environments" latex)
4173 (const :tag "Subscript and superscript" script)
4174 (const :tag "Entities" entities))))
4176 (defcustom org-hide-emphasis-markers nil
4177 "Non-nil mean font-lock should hide the emphasis marker characters."
4178 :group 'org-appearance
4179 :type 'boolean)
4181 (defcustom org-hide-macro-markers nil
4182 "Non-nil mean font-lock should hide the brackets marking macro calls."
4183 :group 'org-appearance
4184 :type 'boolean)
4186 (defcustom org-pretty-entities nil
4187 "Non-nil means show entities as UTF8 characters.
4188 When nil, the \\name form remains in the buffer."
4189 :group 'org-appearance
4190 :version "24.1"
4191 :type 'boolean)
4193 (defcustom org-pretty-entities-include-sub-superscripts t
4194 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4195 :group 'org-appearance
4196 :version "24.1"
4197 :type 'boolean)
4199 (defvar org-emph-re nil
4200 "Regular expression for matching emphasis.
4201 After a match, the match groups contain these elements:
4202 0 The match of the full regular expression, including the characters
4203 before and after the proper match
4204 1 The character before the proper match, or empty at beginning of line
4205 2 The proper match, including the leading and trailing markers
4206 3 The leading marker like * or /, indicating the type of highlighting
4207 4 The text between the emphasis markers, not including the markers
4208 5 The character after the match, empty at the end of a line")
4209 (defvar org-verbatim-re nil
4210 "Regular expression for matching verbatim text.")
4211 (defvar org-emphasis-regexp-components) ; defined just below
4212 (defvar org-emphasis-alist) ; defined just below
4213 (defun org-set-emph-re (var val)
4214 "Set variable and compute the emphasis regular expression."
4215 (set var val)
4216 (when (and (boundp 'org-emphasis-alist)
4217 (boundp 'org-emphasis-regexp-components)
4218 org-emphasis-alist org-emphasis-regexp-components)
4219 (let* ((e org-emphasis-regexp-components)
4220 (pre (car e))
4221 (post (nth 1 e))
4222 (border (nth 2 e))
4223 (body (nth 3 e))
4224 (nl (nth 4 e))
4225 (body1 (concat body "*?"))
4226 (markers (mapconcat 'car org-emphasis-alist ""))
4227 (vmarkers (mapconcat
4228 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4229 org-emphasis-alist "")))
4230 ;; make sure special characters appear at the right position in the class
4231 (if (string-match "\\^" markers)
4232 (setq markers (concat (replace-match "" t t markers) "^")))
4233 (if (string-match "-" markers)
4234 (setq markers (concat (replace-match "" t t markers) "-")))
4235 (if (string-match "\\^" vmarkers)
4236 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4237 (if (string-match "-" vmarkers)
4238 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4239 (if (> nl 0)
4240 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4241 (int-to-string nl) "\\}")))
4242 ;; Make the regexp
4243 (setq org-emph-re
4244 (concat "\\([" pre "]\\|^\\)"
4245 "\\("
4246 "\\([" markers "]\\)"
4247 "\\("
4248 "[^" border "]\\|"
4249 "[^" border "]"
4250 body1
4251 "[^" border "]"
4252 "\\)"
4253 "\\3\\)"
4254 "\\([" post "]\\|$\\)"))
4255 (setq org-verbatim-re
4256 (concat "\\([" pre "]\\|^\\)"
4257 "\\("
4258 "\\([" vmarkers "]\\)"
4259 "\\("
4260 "[^" border "]\\|"
4261 "[^" border "]"
4262 body1
4263 "[^" border "]"
4264 "\\)"
4265 "\\3\\)"
4266 "\\([" post "]\\|$\\)")))))
4268 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4269 ;; set this option proved cumbersome. See this message/thread:
4270 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4271 (defvar org-emphasis-regexp-components
4272 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n,\"'" "." 1)
4273 "Components used to build the regular expression for emphasis.
4274 This is a list with five entries. Terminology: In an emphasis string
4275 like \" *strong word* \", we call the initial space PREMATCH, the final
4276 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4277 and \"trong wor\" is the body. The different components in this variable
4278 specify what is allowed/forbidden in each part:
4280 pre Chars allowed as prematch. Beginning of line will be allowed too.
4281 post Chars allowed as postmatch. End of line will be allowed too.
4282 border The chars *forbidden* as border characters.
4283 body-regexp A regexp like \".\" to match a body character. Don't use
4284 non-shy groups here, and don't allow newline here.
4285 newline The maximum number of newlines allowed in an emphasis exp.
4287 You need to reload Org or to restart Emacs after customizing this.")
4289 (defcustom org-emphasis-alist
4290 `(("*" bold)
4291 ("/" italic)
4292 ("_" underline)
4293 ("=" org-verbatim verbatim)
4294 ("~" org-code verbatim)
4295 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4296 "Alist of characters and faces to emphasize text.
4297 Text starting and ending with a special character will be emphasized,
4298 for example *bold*, _underlined_ and /italic/. This variable sets the
4299 marker characters and the face to be used by font-lock for highlighting
4300 in Org-mode Emacs buffers.
4302 You need to reload Org or to restart Emacs after customizing this."
4303 :group 'org-appearance
4304 :set 'org-set-emph-re
4305 :version "24.4"
4306 :package-version '(Org . "8.0")
4307 :type '(repeat
4308 (list
4309 (string :tag "Marker character")
4310 (choice
4311 (face :tag "Font-lock-face")
4312 (plist :tag "Face property list"))
4313 (option (const verbatim)))))
4315 (defvar org-protecting-blocks
4316 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4317 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4318 This is needed for font-lock setup.")
4320 ;;; Miscellaneous options
4322 (defgroup org-completion nil
4323 "Completion in Org-mode."
4324 :tag "Org Completion"
4325 :group 'org)
4327 (defcustom org-completion-use-ido nil
4328 "Non-nil means use ido completion wherever possible.
4329 Note that `ido-mode' must be active for this variable to be relevant.
4330 If you decide to turn this variable on, you might well want to turn off
4331 `org-outline-path-complete-in-steps'.
4332 See also `org-completion-use-iswitchb'."
4333 :group 'org-completion
4334 :type 'boolean)
4336 (defcustom org-completion-use-iswitchb nil
4337 "Non-nil means use iswitchb completion wherever possible.
4338 Note that `iswitchb-mode' must be active for this variable to be relevant.
4339 If you decide to turn this variable on, you might well want to turn off
4340 `org-outline-path-complete-in-steps'.
4341 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4342 :group 'org-completion
4343 :type 'boolean)
4345 (defcustom org-completion-fallback-command 'hippie-expand
4346 "The expansion command called by \\[pcomplete] in normal context.
4347 Normal means, no org-mode-specific context."
4348 :group 'org-completion
4349 :type 'function)
4351 ;;; Functions and variables from their packages
4352 ;; Declared here to avoid compiler warnings
4354 ;; XEmacs only
4355 (defvar outline-mode-menu-heading)
4356 (defvar outline-mode-menu-show)
4357 (defvar outline-mode-menu-hide)
4358 (defvar zmacs-regions) ; XEmacs regions
4360 ;; Emacs only
4361 (defvar mark-active)
4363 ;; Various packages
4364 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4365 (declare-function calendar-forward-day "cal-move" (arg))
4366 (declare-function calendar-goto-date "cal-move" (date))
4367 (declare-function calendar-goto-today "cal-move" ())
4368 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4369 (defvar calc-embedded-close-formula)
4370 (defvar calc-embedded-open-formula)
4371 (declare-function cdlatex-tab "ext:cdlatex" ())
4372 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4373 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4374 (defvar font-lock-unfontify-region-function)
4375 (declare-function iswitchb-read-buffer "iswitchb"
4376 (prompt &optional default require-match start matches-set))
4377 (defvar iswitchb-temp-buflist)
4378 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4379 (defvar org-agenda-tags-todo-honor-ignore-options)
4380 (declare-function org-agenda-skip "org-agenda" ())
4381 (declare-function
4382 org-agenda-format-item "org-agenda"
4383 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4384 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4385 (declare-function org-agenda-change-all-lines "org-agenda"
4386 (newhead hdmarker &optional fixface just-this))
4387 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4388 (declare-function org-agenda-maybe-redo "org-agenda" ())
4389 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4390 (beg end))
4391 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4392 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4393 "org-agenda" (&optional end))
4394 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4395 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4396 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4397 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4398 (declare-function org-indent-mode "org-indent" (&optional arg))
4399 (declare-function parse-time-string "parse-time" (string))
4400 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4401 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4402 (defvar remember-data-file)
4403 (defvar texmathp-why)
4404 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4405 (declare-function table--at-cell-p "table" (position &optional object at-column))
4406 (declare-function calc-eval "calc" (str &optional separator &rest args))
4408 ;;;###autoload
4409 (defun turn-on-orgtbl ()
4410 "Unconditionally turn on `orgtbl-mode'."
4411 (require 'org-table)
4412 (orgtbl-mode 1))
4414 (defun org-at-table-p (&optional table-type)
4415 "Return t if the cursor is inside an org-type table.
4416 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4417 (if org-enable-table-editor
4418 (save-excursion
4419 (beginning-of-line 1)
4420 (looking-at (if table-type org-table-any-line-regexp
4421 org-table-line-regexp)))
4422 nil))
4423 (defsubst org-table-p () (org-at-table-p))
4425 (defun org-at-table.el-p ()
4426 "Return t if and only if we are at a table.el table."
4427 (and (org-at-table-p 'any)
4428 (save-excursion
4429 (goto-char (org-table-begin 'any))
4430 (looking-at org-table1-hline-regexp))))
4432 (defun org-table-recognize-table.el ()
4433 "If there is a table.el table nearby, recognize it and move into it."
4434 (if org-table-tab-recognizes-table.el
4435 (if (org-at-table.el-p)
4436 (progn
4437 (beginning-of-line 1)
4438 (if (looking-at org-table-dataline-regexp)
4440 (if (looking-at org-table1-hline-regexp)
4441 (progn
4442 (beginning-of-line 2)
4443 (if (looking-at org-table-any-border-regexp)
4444 (beginning-of-line -1)))))
4445 (if (re-search-forward "|" (org-table-end t) t)
4446 (progn
4447 (require 'table)
4448 (if (table--at-cell-p (point))
4450 (message "recognizing table.el table...")
4451 (table-recognize-table)
4452 (message "recognizing table.el table...done")))
4453 (error "This should not happen"))
4455 nil)
4456 nil))
4458 (defun org-at-table-hline-p ()
4459 "Return t if the cursor is inside a hline in a table."
4460 (if org-enable-table-editor
4461 (save-excursion
4462 (beginning-of-line 1)
4463 (looking-at org-table-hline-regexp))
4464 nil))
4466 (defun org-table-map-tables (function &optional quietly)
4467 "Apply FUNCTION to the start of all tables in the buffer."
4468 (save-excursion
4469 (save-restriction
4470 (widen)
4471 (goto-char (point-min))
4472 (while (re-search-forward org-table-any-line-regexp nil t)
4473 (unless quietly
4474 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4475 (beginning-of-line 1)
4476 (when (and (looking-at org-table-line-regexp)
4477 ;; Exclude tables in src/example/verbatim/clocktable blocks
4478 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4479 (save-excursion (funcall function))
4480 (or (looking-at org-table-line-regexp)
4481 (forward-char 1)))
4482 (re-search-forward org-table-any-border-regexp nil 1))))
4483 (unless quietly (message "Mapping tables: done")))
4485 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4486 (declare-function org-clock-update-mode-line "org-clock" ())
4487 (declare-function org-resolve-clocks "org-clock"
4488 (&optional also-non-dangling-p prompt last-valid))
4490 (defun org-at-TBLFM-p (&optional pos)
4491 "Return t when point (or POS) is in #+TBLFM line."
4492 (save-excursion
4493 (let ((pos pos)))
4494 (goto-char (or pos (point)))
4495 (beginning-of-line 1)
4496 (looking-at org-TBLFM-regexp)))
4498 (defvar org-clock-start-time)
4499 (defvar org-clock-marker (make-marker)
4500 "Marker recording the last clock-in.")
4501 (defvar org-clock-hd-marker (make-marker)
4502 "Marker recording the last clock-in, but the headline position.")
4503 (defvar org-clock-heading ""
4504 "The heading of the current clock entry.")
4505 (defun org-clock-is-active ()
4506 "Return the buffer where the clock is currently running.
4507 Return nil if no clock is running."
4508 (marker-buffer org-clock-marker))
4510 (defun org-check-running-clock ()
4511 "Check if the current buffer contains the running clock.
4512 If yes, offer to stop it and to save the buffer with the changes."
4513 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4514 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4515 (buffer-name))))
4516 (org-clock-out)
4517 (when (y-or-n-p "Save changed buffer?")
4518 (save-buffer))))
4520 (defun org-clocktable-try-shift (dir n)
4521 "Check if this line starts a clock table, if yes, shift the time block."
4522 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4523 (org-clocktable-shift dir n)))
4525 ;;;###autoload
4526 (defun org-clock-persistence-insinuate ()
4527 "Set up hooks for clock persistence."
4528 (require 'org-clock)
4529 (add-hook 'org-mode-hook 'org-clock-load)
4530 (add-hook 'kill-emacs-hook 'org-clock-save))
4532 (defgroup org-archive nil
4533 "Options concerning archiving in Org-mode."
4534 :tag "Org Archive"
4535 :group 'org-structure)
4537 (defcustom org-archive-location "%s_archive::"
4538 "The location where subtrees should be archived.
4540 The value of this variable is a string, consisting of two parts,
4541 separated by a double-colon. The first part is a filename and
4542 the second part is a headline.
4544 When the filename is omitted, archiving happens in the same file.
4545 %s in the filename will be replaced by the current file
4546 name (without the directory part). Archiving to a different file
4547 is useful to keep archived entries from contributing to the
4548 Org-mode Agenda.
4550 The archived entries will be filed as subtrees of the specified
4551 headline. When the headline is omitted, the subtrees are simply
4552 filed away at the end of the file, as top-level entries. Also in
4553 the heading you can use %s to represent the file name, this can be
4554 useful when using the same archive for a number of different files.
4556 Here are a few examples:
4557 \"%s_archive::\"
4558 If the current file is Projects.org, archive in file
4559 Projects.org_archive, as top-level trees. This is the default.
4561 \"::* Archived Tasks\"
4562 Archive in the current file, under the top-level headline
4563 \"* Archived Tasks\".
4565 \"~/org/archive.org::\"
4566 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4568 \"~/org/archive.org::* From %s\"
4569 Archive in file ~/org/archive.org (absolute path), under headlines
4570 \"From FILENAME\" where file name is the current file name.
4572 \"~/org/datetree.org::datetree/* Finished Tasks\"
4573 The \"datetree/\" string is special, signifying to archive
4574 items to the datetree. Items are placed in either the CLOSED
4575 date of the item, or the current date if there is no CLOSED date.
4576 The heading will be a subentry to the current date. There doesn't
4577 need to be a heading, but there always needs to be a slash after
4578 datetree. For example, to store archived items directly in the
4579 datetree, use \"~/org/datetree.org::datetree/\".
4581 \"basement::** Finished Tasks\"
4582 Archive in file ./basement (relative path), as level 3 trees
4583 below the level 2 heading \"** Finished Tasks\".
4585 You may set this option on a per-file basis by adding to the buffer a
4586 line like
4588 #+ARCHIVE: basement::** Finished Tasks
4590 You may also define it locally for a subtree by setting an ARCHIVE property
4591 in the entry. If such a property is found in an entry, or anywhere up
4592 the hierarchy, it will be used."
4593 :group 'org-archive
4594 :type 'string)
4596 (defcustom org-agenda-skip-archived-trees t
4597 "Non-nil means the agenda will skip any items located in archived trees.
4598 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4599 variable is no longer recommended, you should leave it at the value t.
4600 Instead, use the key `v' to cycle the archives-mode in the agenda."
4601 :group 'org-archive
4602 :group 'org-agenda-skip
4603 :type 'boolean)
4605 (defcustom org-columns-skip-archived-trees t
4606 "Non-nil means ignore archived trees when creating column view."
4607 :group 'org-archive
4608 :group 'org-properties
4609 :type 'boolean)
4611 (defcustom org-cycle-open-archived-trees nil
4612 "Non-nil means `org-cycle' will open archived trees.
4613 An archived tree is a tree marked with the tag ARCHIVE.
4614 When nil, archived trees will stay folded. You can still open them with
4615 normal outline commands like `show-all', but not with the cycling commands."
4616 :group 'org-archive
4617 :group 'org-cycle
4618 :type 'boolean)
4620 (defcustom org-sparse-tree-open-archived-trees nil
4621 "Non-nil means sparse tree construction shows matches in archived trees.
4622 When nil, matches in these trees are highlighted, but the trees are kept in
4623 collapsed state."
4624 :group 'org-archive
4625 :group 'org-sparse-trees
4626 :type 'boolean)
4628 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4629 "The default date type when building a sparse tree.
4630 When this is nil, a date is a scheduled or a deadline timestamp.
4631 Otherwise, these types are allowed:
4633 all: all timestamps
4634 active: only active timestamps (<...>)
4635 inactive: only inactive timestamps (<...)
4636 scheduled: only scheduled timestamps
4637 deadline: only deadline timestamps"
4638 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4639 (const :tag "All timestamps" all)
4640 (const :tag "Only active timestamps" active)
4641 (const :tag "Only inactive timestamps" inactive)
4642 (const :tag "Only scheduled timestamps" scheduled)
4643 (const :tag "Only deadline timestamps" deadline)
4644 (const :tag "Only closed timestamps" closed))
4645 :version "24.3"
4646 :group 'org-sparse-trees)
4648 (defun org-cycle-hide-archived-subtrees (state)
4649 "Re-hide all archived subtrees after a visibility state change."
4650 (when (and (not org-cycle-open-archived-trees)
4651 (not (memq state '(overview folded))))
4652 (save-excursion
4653 (let* ((globalp (memq state '(contents all)))
4654 (beg (if globalp (point-min) (point)))
4655 (end (if globalp (point-max) (org-end-of-subtree t))))
4656 (org-hide-archived-subtrees beg end)
4657 (goto-char beg)
4658 (if (looking-at (concat ".*:" org-archive-tag ":"))
4659 (message "%s" (substitute-command-keys
4660 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4662 (defun org-force-cycle-archived ()
4663 "Cycle subtree even if it is archived."
4664 (interactive)
4665 (setq this-command 'org-cycle)
4666 (let ((org-cycle-open-archived-trees t))
4667 (call-interactively 'org-cycle)))
4669 (defun org-hide-archived-subtrees (beg end)
4670 "Re-hide all archived subtrees after a visibility state change."
4671 (save-excursion
4672 (let* ((re (concat ":" org-archive-tag ":")))
4673 (goto-char beg)
4674 (while (re-search-forward re end t)
4675 (when (org-at-heading-p)
4676 (org-flag-subtree t)
4677 (org-end-of-subtree t))))))
4679 (declare-function outline-end-of-heading "outline" ())
4680 (declare-function outline-flag-region "outline" (from to flag))
4681 (defun org-flag-subtree (flag)
4682 (save-excursion
4683 (org-back-to-heading t)
4684 (outline-end-of-heading)
4685 (outline-flag-region (point)
4686 (progn (org-end-of-subtree t) (point))
4687 flag)))
4689 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4691 ;; Declare Column View Code
4693 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4694 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4695 (declare-function org-columns-compute "org-colview" (property))
4697 ;; Declare ID code
4699 (declare-function org-id-store-link "org-id")
4700 (declare-function org-id-locations-load "org-id")
4701 (declare-function org-id-locations-save "org-id")
4702 (defvar org-id-track-globally)
4704 ;;; Variables for pre-computed regular expressions, all buffer local
4706 (defvar org-todo-regexp nil
4707 "Matches any of the TODO state keywords.")
4708 (make-variable-buffer-local 'org-todo-regexp)
4709 (defvar org-not-done-regexp nil
4710 "Matches any of the TODO state keywords except the last one.")
4711 (make-variable-buffer-local 'org-not-done-regexp)
4712 (defvar org-not-done-heading-regexp nil
4713 "Matches a TODO headline that is not done.")
4714 (make-variable-buffer-local 'org-not-done-regexp)
4715 (defvar org-todo-line-regexp nil
4716 "Matches a headline and puts TODO state into group 2 if present.")
4717 (make-variable-buffer-local 'org-todo-line-regexp)
4718 (defvar org-complex-heading-regexp nil
4719 "Matches a headline and puts everything into groups:
4720 group 1: the stars
4721 group 2: The todo keyword, maybe
4722 group 3: Priority cookie
4723 group 4: True headline
4724 group 5: Tags")
4725 (make-variable-buffer-local 'org-complex-heading-regexp)
4726 (defvar org-complex-heading-regexp-format nil
4727 "Printf format to make regexp to match an exact headline.
4728 This regexp will match the headline of any node which has the
4729 exact headline text that is put into the format, but may have any
4730 TODO state, priority and tags.")
4731 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4732 (defvar org-todo-line-tags-regexp nil
4733 "Matches a headline and puts TODO state into group 2 if present.
4734 Also put tags into group 4 if tags are present.")
4735 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4736 (defvar org-ds-keyword-length 12
4737 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4738 (make-variable-buffer-local 'org-ds-keyword-length)
4739 (defvar org-deadline-regexp nil
4740 "Matches the DEADLINE keyword.")
4741 (make-variable-buffer-local 'org-deadline-regexp)
4742 (defvar org-deadline-time-regexp nil
4743 "Matches the DEADLINE keyword together with a time stamp.")
4744 (make-variable-buffer-local 'org-deadline-time-regexp)
4745 (defvar org-deadline-time-hour-regexp nil
4746 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4747 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4748 (defvar org-deadline-line-regexp nil
4749 "Matches the DEADLINE keyword and the rest of the line.")
4750 (make-variable-buffer-local 'org-deadline-line-regexp)
4751 (defvar org-scheduled-regexp nil
4752 "Matches the SCHEDULED keyword.")
4753 (make-variable-buffer-local 'org-scheduled-regexp)
4754 (defvar org-scheduled-time-regexp nil
4755 "Matches the SCHEDULED keyword together with a time stamp.")
4756 (make-variable-buffer-local 'org-scheduled-time-regexp)
4757 (defvar org-scheduled-time-hour-regexp nil
4758 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4759 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4760 (defvar org-closed-time-regexp nil
4761 "Matches the CLOSED keyword together with a time stamp.")
4762 (make-variable-buffer-local 'org-closed-time-regexp)
4764 (defvar org-keyword-time-regexp nil
4765 "Matches any of the 4 keywords, together with the time stamp.")
4766 (make-variable-buffer-local 'org-keyword-time-regexp)
4767 (defvar org-keyword-time-not-clock-regexp nil
4768 "Matches any of the 3 keywords, together with the time stamp.")
4769 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4770 (defvar org-maybe-keyword-time-regexp nil
4771 "Matches a timestamp, possibly preceded by a keyword.")
4772 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4773 (defvar org-all-time-keywords nil
4774 "List of time keywords.")
4775 (make-variable-buffer-local 'org-all-time-keywords)
4777 (defconst org-plain-time-of-day-regexp
4778 (concat
4779 "\\(\\<[012]?[0-9]"
4780 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4781 "\\(--?"
4782 "\\(\\<[012]?[0-9]"
4783 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4784 "\\)?")
4785 "Regular expression to match a plain time or time range.
4786 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4787 groups carry important information:
4788 0 the full match
4789 1 the first time, range or not
4790 8 the second time, if it is a range.")
4792 (defconst org-plain-time-extension-regexp
4793 (concat
4794 "\\(\\<[012]?[0-9]"
4795 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4796 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4797 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4798 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4799 groups carry important information:
4800 0 the full match
4801 7 hours of duration
4802 9 minutes of duration")
4804 (defconst org-stamp-time-of-day-regexp
4805 (concat
4806 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4807 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4808 "\\(--?"
4809 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4810 "Regular expression to match a timestamp time or time range.
4811 After a match, the following groups carry important information:
4812 0 the full match
4813 1 date plus weekday, for back referencing to make sure both times are on the same day
4814 2 the first time, range or not
4815 4 the second time, if it is a range.")
4817 (defconst org-startup-options
4818 '(("fold" org-startup-folded t)
4819 ("overview" org-startup-folded t)
4820 ("nofold" org-startup-folded nil)
4821 ("showall" org-startup-folded nil)
4822 ("showeverything" org-startup-folded showeverything)
4823 ("content" org-startup-folded content)
4824 ("indent" org-startup-indented t)
4825 ("noindent" org-startup-indented nil)
4826 ("hidestars" org-hide-leading-stars t)
4827 ("showstars" org-hide-leading-stars nil)
4828 ("odd" org-odd-levels-only t)
4829 ("oddeven" org-odd-levels-only nil)
4830 ("align" org-startup-align-all-tables t)
4831 ("noalign" org-startup-align-all-tables nil)
4832 ("inlineimages" org-startup-with-inline-images t)
4833 ("noinlineimages" org-startup-with-inline-images nil)
4834 ("latexpreview" org-startup-with-latex-preview t)
4835 ("nolatexpreview" org-startup-with-latex-preview nil)
4836 ("customtime" org-display-custom-times t)
4837 ("logdone" org-log-done time)
4838 ("lognotedone" org-log-done note)
4839 ("nologdone" org-log-done nil)
4840 ("lognoteclock-out" org-log-note-clock-out t)
4841 ("nolognoteclock-out" org-log-note-clock-out nil)
4842 ("logrepeat" org-log-repeat state)
4843 ("lognoterepeat" org-log-repeat note)
4844 ("logdrawer" org-log-into-drawer t)
4845 ("nologdrawer" org-log-into-drawer nil)
4846 ("logstatesreversed" org-log-states-order-reversed t)
4847 ("nologstatesreversed" org-log-states-order-reversed nil)
4848 ("nologrepeat" org-log-repeat nil)
4849 ("logreschedule" org-log-reschedule time)
4850 ("lognotereschedule" org-log-reschedule note)
4851 ("nologreschedule" org-log-reschedule nil)
4852 ("logredeadline" org-log-redeadline time)
4853 ("lognoteredeadline" org-log-redeadline note)
4854 ("nologredeadline" org-log-redeadline nil)
4855 ("logrefile" org-log-refile time)
4856 ("lognoterefile" org-log-refile note)
4857 ("nologrefile" org-log-refile nil)
4858 ("fninline" org-footnote-define-inline t)
4859 ("nofninline" org-footnote-define-inline nil)
4860 ("fnlocal" org-footnote-section nil)
4861 ("fnauto" org-footnote-auto-label t)
4862 ("fnprompt" org-footnote-auto-label nil)
4863 ("fnconfirm" org-footnote-auto-label confirm)
4864 ("fnplain" org-footnote-auto-label plain)
4865 ("fnadjust" org-footnote-auto-adjust t)
4866 ("nofnadjust" org-footnote-auto-adjust nil)
4867 ("constcgs" constants-unit-system cgs)
4868 ("constSI" constants-unit-system SI)
4869 ("noptag" org-tag-persistent-alist nil)
4870 ("hideblocks" org-hide-block-startup t)
4871 ("nohideblocks" org-hide-block-startup nil)
4872 ("beamer" org-startup-with-beamer-mode t)
4873 ("entitiespretty" org-pretty-entities t)
4874 ("entitiesplain" org-pretty-entities nil))
4875 "Variable associated with STARTUP options for org-mode.
4876 Each element is a list of three items: the startup options (as written
4877 in the #+STARTUP line), the corresponding variable, and the value to set
4878 this variable to if the option is found. An optional forth element PUSH
4879 means to push this value onto the list in the variable.")
4881 (defun org-update-property-plist (key val props)
4882 "Update PROPS with KEY and VAL."
4883 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4884 (key (if appending (substring key 0 (- (length key) 1)) key))
4885 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4886 (previous (cdr (assoc key props))))
4887 (if appending
4888 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4889 (cons (cons key val) remainder))))
4891 (defcustom org-group-tags t
4892 "When non-nil (the default), use group tags.
4893 This can be turned on/off through `org-toggle-tags-groups'."
4894 :group 'org-tags
4895 :group 'org-startup
4896 :type 'boolean)
4898 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4900 (defun org-toggle-tags-groups ()
4901 "Toggle support for group tags.
4902 Support for group tags is controlled by the option
4903 `org-group-tags', which is non-nil by default."
4904 (interactive)
4905 (setq org-group-tags (not org-group-tags))
4906 (cond ((and (derived-mode-p 'org-agenda-mode)
4907 org-group-tags)
4908 (org-agenda-redo))
4909 ((derived-mode-p 'org-mode)
4910 (let ((org-inhibit-startup t)) (org-mode))))
4911 (message "Groups tags support has been turned %s"
4912 (if org-group-tags "on" "off")))
4914 (defun org-set-regexps-and-options-for-tags ()
4915 "Precompute variables used for tags."
4916 (when (derived-mode-p 'org-mode)
4917 (org-set-local 'org-file-tags nil)
4918 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4919 (splitre "[ \t]+")
4920 (start 0)
4921 tags ftags key value)
4922 (save-excursion
4923 (save-restriction
4924 (widen)
4925 (goto-char (point-min))
4926 (while (re-search-forward re nil t)
4927 (setq key (upcase (org-match-string-no-properties 1))
4928 value (org-match-string-no-properties 2))
4929 (if (stringp value) (setq value (org-trim value)))
4930 (cond
4931 ((equal key "TAGS")
4932 (setq tags (append tags (if tags '("\\n") nil)
4933 (org-split-string value splitre))))
4934 ((equal key "FILETAGS")
4935 (when (string-match "\\S-" value)
4936 (setq ftags
4937 (append
4938 ftags
4939 (apply 'append
4940 (mapcar (lambda (x) (org-split-string x ":"))
4941 (org-split-string value)))))))))))
4942 ;; Process the file tags.
4943 (and ftags (org-set-local 'org-file-tags
4944 (mapcar 'org-add-prop-inherited ftags)))
4945 (org-set-local 'org-tag-groups-alist nil)
4946 ;; Process the tags.
4947 (when (and (not tags) org-tag-alist)
4948 (setq tags
4949 (mapcar
4950 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4951 ((eq (car tg) :endgroup) "}")
4952 ((eq (car tg) :grouptags) ":")
4953 ((eq (car tg) :newline) "\n")
4954 (t (concat (car tg)
4955 (if (characterp (cdr tg))
4956 (format "(%s)" (char-to-string (cdr tg))) "")))))
4957 org-tag-alist)))
4958 (let (e tgs g)
4959 (while (setq e (pop tags))
4960 (cond
4961 ((equal e "{")
4962 (progn (push '(:startgroup) tgs)
4963 (when (equal (nth 1 tags) ":")
4964 (push (list (replace-regexp-in-string
4965 "(.+)$" "" (nth 0 tags)))
4966 org-tag-groups-alist)
4967 (setq g 0))))
4968 ((equal e ":") (push '(:grouptags) tgs))
4969 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4970 ((equal e "\\n") (push '(:newline) tgs))
4971 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4972 (push (cons (match-string 1 e)
4973 (string-to-char (match-string 2 e))) tgs)
4974 (if (and g (> g 0))
4975 (setcar org-tag-groups-alist
4976 (append (car org-tag-groups-alist)
4977 (list (match-string 1 e)))))
4978 (if g (setq g (1+ g))))
4979 (t (push (list e) tgs)
4980 (if (and g (> g 0))
4981 (setcar org-tag-groups-alist
4982 (append (car org-tag-groups-alist) (list e))))
4983 (if g (setq g (1+ g))))))
4984 (org-set-local 'org-tag-alist nil)
4985 (while (setq e (pop tgs))
4986 (or (and (stringp (car e))
4987 (assoc (car e) org-tag-alist))
4988 (push e org-tag-alist)))
4989 ;; Return a list with tag variables
4990 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4992 (defvar org-ota nil)
4993 (defun org-set-regexps-and-options ()
4994 "Precompute regular expressions used in the current buffer."
4995 (when (derived-mode-p 'org-mode)
4996 (org-set-local 'org-todo-kwd-alist nil)
4997 (org-set-local 'org-todo-key-alist nil)
4998 (org-set-local 'org-todo-key-trigger nil)
4999 (org-set-local 'org-todo-keywords-1 nil)
5000 (org-set-local 'org-done-keywords nil)
5001 (org-set-local 'org-todo-heads nil)
5002 (org-set-local 'org-todo-sets nil)
5003 (org-set-local 'org-todo-log-states nil)
5004 (org-set-local 'org-file-properties nil)
5005 (let ((re (org-make-options-regexp
5006 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
5007 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
5008 "SETUPFILE" "OPTIONS")
5009 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
5010 (splitre "[ \t]+")
5011 (scripts org-use-sub-superscripts)
5012 kwds kws0 kwsa key log value cat arch const links hw dws
5013 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
5014 (start 0))
5015 (save-excursion
5016 (save-restriction
5017 (widen)
5018 (goto-char (point-min))
5019 (while
5020 (or (and
5021 ext-setup-or-nil
5022 (not org-ota)
5023 (let (ret)
5024 (with-temp-buffer
5025 (insert ext-setup-or-nil)
5026 (let ((major-mode 'org-mode) org-ota)
5027 (setq ret (save-match-data
5028 (org-set-regexps-and-options-for-tags)))))
5029 ;; Append setupfile tags to existing tags
5030 (setq org-ota t)
5031 (setq org-file-tags
5032 (delq nil (append org-file-tags (nth 0 ret)))
5033 org-tag-alist
5034 (delq nil (append org-tag-alist (nth 1 ret)))
5035 org-tag-groups-alist
5036 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
5037 (and ext-setup-or-nil
5038 (string-match re ext-setup-or-nil start)
5039 (setq start (match-end 0)))
5040 (and (setq ext-setup-or-nil nil start 0)
5041 (re-search-forward re nil t)))
5042 (setq key (upcase (match-string 1 ext-setup-or-nil))
5043 value (org-match-string-no-properties 2 ext-setup-or-nil))
5044 (if (stringp value) (setq value (org-trim value)))
5045 (cond
5046 ((equal key "CATEGORY")
5047 (setq cat value))
5048 ((member key '("SEQ_TODO" "TODO"))
5049 (push (cons 'sequence (org-split-string value splitre)) kwds))
5050 ((equal key "TYP_TODO")
5051 (push (cons 'type (org-split-string value splitre)) kwds))
5052 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
5053 ;; general TODO-like setup
5054 (push (cons (intern (downcase (match-string 1 key)))
5055 (org-split-string value splitre)) kwds))
5056 ((equal key "COLUMNS")
5057 (org-set-local 'org-columns-default-format value))
5058 ((equal key "LINK")
5059 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5060 (push (cons (match-string 1 value)
5061 (org-trim (match-string 2 value)))
5062 links)))
5063 ((equal key "PRIORITIES")
5064 (setq prio (org-split-string value " +")))
5065 ((equal key "PROPERTY")
5066 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5067 (setq props (org-update-property-plist (match-string 1 value)
5068 (match-string 2 value)
5069 props))))
5070 ((equal key "CONSTANTS")
5071 (org-table-set-constants))
5072 ((equal key "STARTUP")
5073 (let ((opts (org-split-string value splitre))
5074 l var val)
5075 (while (setq l (pop opts))
5076 (when (setq l (assoc l org-startup-options))
5077 (setq var (nth 1 l) val (nth 2 l))
5078 (if (not (nth 3 l))
5079 (set (make-local-variable var) val)
5080 (if (not (listp (symbol-value var)))
5081 (set (make-local-variable var) nil))
5082 (set (make-local-variable var) (symbol-value var))
5083 (add-to-list var val))))))
5084 ((equal key "ARCHIVE")
5085 (setq arch value)
5086 (remove-text-properties 0 (length arch)
5087 '(face t fontified t) arch))
5088 ((equal key "OPTIONS")
5089 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
5090 (setq scripts (read (match-string 2 value)))))
5091 ((and (equal key "SETUPFILE")
5092 ;; Prevent checking in Gnus messages
5093 (not buffer-read-only))
5094 (setq setup-contents (org-file-contents
5095 (expand-file-name
5096 (org-remove-double-quotes value))
5097 'noerror))
5098 (if (not ext-setup-or-nil)
5099 (setq ext-setup-or-nil setup-contents start 0)
5100 (setq ext-setup-or-nil
5101 (concat (substring ext-setup-or-nil 0 start)
5102 "\n" setup-contents "\n"
5103 (substring ext-setup-or-nil start)))))))
5104 ;; search for property blocks
5105 (goto-char (point-min))
5106 (while (re-search-forward org-block-regexp nil t)
5107 (when (equal "PROPERTY" (upcase (match-string 1)))
5108 (setq value (replace-regexp-in-string
5109 "[\n\r]" " " (match-string 4)))
5110 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5111 (setq props (org-update-property-plist (match-string 1 value)
5112 (match-string 2 value)
5113 props)))))))
5114 (org-set-local 'org-use-sub-superscripts scripts)
5115 (when cat
5116 (org-set-local 'org-category (intern cat))
5117 (push (cons "CATEGORY" cat) props))
5118 (when prio
5119 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5120 (setq prio (mapcar 'string-to-char prio))
5121 (org-set-local 'org-highest-priority (nth 0 prio))
5122 (org-set-local 'org-lowest-priority (nth 1 prio))
5123 (org-set-local 'org-default-priority (nth 2 prio)))
5124 (and props (org-set-local 'org-file-properties (nreverse props)))
5125 (and arch (org-set-local 'org-archive-location arch))
5126 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5127 ;; Process the TODO keywords
5128 (unless kwds
5129 ;; Use the global values as if they had been given locally.
5130 (setq kwds (default-value 'org-todo-keywords))
5131 (if (stringp (car kwds))
5132 (setq kwds (list (cons org-todo-interpretation
5133 (default-value 'org-todo-keywords)))))
5134 (setq kwds (reverse kwds)))
5135 (setq kwds (nreverse kwds))
5136 (let (inter kws kw)
5137 (while (setq kws (pop kwds))
5138 (let ((kws (or
5139 (run-hook-with-args-until-success
5140 'org-todo-setup-filter-hook kws)
5141 kws)))
5142 (setq inter (pop kws) sep (member "|" kws)
5143 kws0 (delete "|" (copy-sequence kws))
5144 kwsa nil
5145 kws1 (mapcar
5146 (lambda (x)
5147 ;; 1 2
5148 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5149 (progn
5150 (setq kw (match-string 1 x)
5151 key (and (match-end 2) (match-string 2 x))
5152 log (org-extract-log-state-settings x))
5153 (push (cons kw (and key (string-to-char key))) kwsa)
5154 (and log (push log org-todo-log-states))
5156 (error "Invalid TODO keyword %s" x)))
5157 kws0)
5158 kwsa (if kwsa (append '((:startgroup))
5159 (nreverse kwsa)
5160 '((:endgroup))))
5161 hw (car kws1)
5162 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5163 tail (list inter hw (car dws) (org-last dws))))
5164 (add-to-list 'org-todo-heads hw 'append)
5165 (push kws1 org-todo-sets)
5166 (setq org-done-keywords (append org-done-keywords dws nil))
5167 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5168 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5169 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5170 (setq org-todo-sets (nreverse org-todo-sets)
5171 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5172 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5173 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5174 ;; Compute the regular expressions and other local variables.
5175 ;; Using `org-outline-regexp-bol' would complicate them much,
5176 ;; because of the fixed white space at the end of that string.
5177 (if (not org-done-keywords)
5178 (setq org-done-keywords (and org-todo-keywords-1
5179 (list (org-last org-todo-keywords-1)))))
5180 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5181 (length org-scheduled-string)
5182 (length org-clock-string)
5183 (length org-closed-string)))
5184 org-not-done-keywords
5185 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5186 org-todo-regexp
5187 (concat "\\("
5188 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5189 "\\)")
5190 org-not-done-regexp
5191 (concat "\\("
5192 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5193 "\\)")
5194 org-not-done-heading-regexp
5195 (format org-heading-keyword-regexp-format org-not-done-regexp)
5196 org-todo-line-regexp
5197 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5198 org-complex-heading-regexp
5199 (concat "^\\(\\*+\\)"
5200 "\\(?: +" org-todo-regexp "\\)?"
5201 "\\(?: +\\(\\[#.\\]\\)\\)?"
5202 "\\(?: +\\(.*?\\)\\)??"
5203 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5204 "[ \t]*$")
5205 org-complex-heading-regexp-format
5206 (concat "^\\(\\*+\\)"
5207 "\\(?: +" org-todo-regexp "\\)?"
5208 "\\(?: +\\(\\[#.\\]\\)\\)?"
5209 "\\(?: +"
5210 ;; Stats cookies can be stuck to body.
5211 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5212 "\\(%s\\)"
5213 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5214 "\\)"
5215 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5216 "[ \t]*$")
5217 org-todo-line-tags-regexp
5218 (concat "^\\(\\*+\\)"
5219 "\\(?: +" org-todo-regexp "\\)?"
5220 "\\(?: +\\(.*?\\)\\)??"
5221 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5222 "[ \t]*$")
5223 org-deadline-regexp (concat "\\<" org-deadline-string)
5224 org-deadline-time-regexp
5225 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5226 org-deadline-time-hour-regexp
5227 (concat "\\<" org-deadline-string
5228 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5229 org-deadline-line-regexp
5230 (concat "\\<\\(" org-deadline-string "\\).*")
5231 org-scheduled-regexp
5232 (concat "\\<" org-scheduled-string)
5233 org-scheduled-time-regexp
5234 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5235 org-scheduled-time-hour-regexp
5236 (concat "\\<" org-scheduled-string
5237 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5238 org-closed-time-regexp
5239 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5240 org-keyword-time-regexp
5241 (concat "\\<\\(" org-scheduled-string
5242 "\\|" org-deadline-string
5243 "\\|" org-closed-string
5244 "\\|" org-clock-string "\\)"
5245 " *[[<]\\([^]>]+\\)[]>]")
5246 org-keyword-time-not-clock-regexp
5247 (concat "\\<\\(" org-scheduled-string
5248 "\\|" org-deadline-string
5249 "\\|" org-closed-string
5250 "\\)"
5251 " *[[<]\\([^]>]+\\)[]>]")
5252 org-maybe-keyword-time-regexp
5253 (concat "\\(\\<\\(" org-scheduled-string
5254 "\\|" org-deadline-string
5255 "\\|" org-closed-string
5256 "\\|" org-clock-string "\\)\\)?"
5257 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5258 org-all-time-keywords
5259 (mapcar (lambda (w) (substring w 0 -1))
5260 (list org-scheduled-string org-deadline-string
5261 org-clock-string org-closed-string)))
5262 (setq org-ota nil)
5263 (org-compute-latex-and-related-regexp))))
5265 (defun org-file-contents (file &optional noerror)
5266 "Return the contents of FILE, as a string."
5267 (if (and file (file-readable-p file))
5268 (with-temp-buffer
5269 (insert-file-contents file)
5270 (buffer-string))
5271 (funcall (if noerror 'message 'error)
5272 "Cannot read file \"%s\"%s"
5273 file
5274 (let ((from (buffer-file-name (buffer-base-buffer))))
5275 (if from (concat " (referenced in file \"" from "\")") "")))))
5277 (defun org-extract-log-state-settings (x)
5278 "Extract the log state setting from a TODO keyword string.
5279 This will extract info from a string like \"WAIT(w@/!)\"."
5280 (let (kw key log1 log2)
5281 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5282 (setq kw (match-string 1 x)
5283 key (and (match-end 2) (match-string 2 x))
5284 log1 (and (match-end 3) (match-string 3 x))
5285 log2 (and (match-end 4) (match-string 4 x)))
5286 (and (or log1 log2)
5287 (list kw
5288 (and log1 (if (equal log1 "!") 'time 'note))
5289 (and log2 (if (equal log2 "!") 'time 'note)))))))
5291 (defun org-remove-keyword-keys (list)
5292 "Remove a pair of parenthesis at the end of each string in LIST."
5293 (mapcar (lambda (x)
5294 (if (string-match "(.*)$" x)
5295 (substring x 0 (match-beginning 0))
5297 list))
5299 (defun org-assign-fast-keys (alist)
5300 "Assign fast keys to a keyword-key alist.
5301 Respect keys that are already there."
5302 (let (new e (alt ?0))
5303 (while (setq e (pop alist))
5304 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5305 (cdr e)) ;; Key already assigned.
5306 (push e new)
5307 (let ((clist (string-to-list (downcase (car e))))
5308 (used (append new alist)))
5309 (when (= (car clist) ?@)
5310 (pop clist))
5311 (while (and clist (rassoc (car clist) used))
5312 (pop clist))
5313 (unless clist
5314 (while (rassoc alt used)
5315 (incf alt)))
5316 (push (cons (car e) (or (car clist) alt)) new))))
5317 (nreverse new)))
5319 ;;; Some variables used in various places
5321 (defvar org-window-configuration nil
5322 "Used in various places to store a window configuration.")
5323 (defvar org-selected-window nil
5324 "Used in various places to store a window configuration.")
5325 (defvar org-finish-function nil
5326 "Function to be called when `C-c C-c' is used.
5327 This is for getting out of special buffers like capture.")
5330 ;; FIXME: Occasionally check by commenting these, to make sure
5331 ;; no other functions uses these, forgetting to let-bind them.
5332 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5333 (defvar org-last-state)
5334 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5336 ;; Defined somewhere in this file, but used before definition.
5337 (defvar org-entities) ;; defined in org-entities.el
5338 (defvar org-struct-menu)
5339 (defvar org-org-menu)
5340 (defvar org-tbl-menu)
5342 ;;;; Define the Org-mode
5344 ;; We use a before-change function to check if a table might need
5345 ;; an update.
5346 (defvar org-table-may-need-update t
5347 "Indicates that a table might need an update.
5348 This variable is set by `org-before-change-function'.
5349 `org-table-align' sets it back to nil.")
5350 (defun org-before-change-function (beg end)
5351 "Every change indicates that a table might need an update."
5352 (setq org-table-may-need-update t))
5353 (defvar org-mode-map)
5354 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5355 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5356 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5357 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5358 (defvar org-table-buffer-is-an nil)
5360 (defvar bidi-paragraph-direction)
5361 (defvar buffer-face-mode-face)
5363 (require 'outline)
5364 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5365 (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"))
5366 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5368 ;; Other stuff we need.
5369 (require 'time-date)
5370 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5371 (require 'easymenu)
5372 (require 'overlay)
5374 ;; (require 'org-macs) moved higher up in the file before it is first used
5375 (require 'org-entities)
5376 ;; (require 'org-compat) moved higher up in the file before it is first used
5377 (require 'org-faces)
5378 (require 'org-list)
5379 (require 'org-pcomplete)
5380 (require 'org-src)
5381 (require 'org-footnote)
5382 (require 'org-macro)
5384 ;; babel
5385 (require 'ob)
5387 ;;;###autoload
5388 (define-derived-mode org-mode outline-mode "Org"
5389 "Outline-based notes management and organizer, alias
5390 \"Carsten's outline-mode for keeping track of everything.\"
5392 Org-mode develops organizational tasks around a NOTES file which
5393 contains information about projects as plain text. Org-mode is
5394 implemented on top of outline-mode, which is ideal to keep the content
5395 of large files well structured. It supports ToDo items, deadlines and
5396 time stamps, which magically appear in the diary listing of the Emacs
5397 calendar. Tables are easily created with a built-in table editor.
5398 Plain text URL-like links connect to websites, emails (VM), Usenet
5399 messages (Gnus), BBDB entries, and any files related to the project.
5400 For printing and sharing of notes, an Org-mode file (or a part of it)
5401 can be exported as a structured ASCII or HTML file.
5403 The following commands are available:
5405 \\{org-mode-map}"
5407 ;; Get rid of Outline menus, they are not needed
5408 ;; Need to do this here because define-derived-mode sets up
5409 ;; the keymap so late. Still, it is a waste to call this each time
5410 ;; we switch another buffer into org-mode.
5411 (if (featurep 'xemacs)
5412 (when (boundp 'outline-mode-menu-heading)
5413 ;; Assume this is Greg's port, it uses easymenu
5414 (easy-menu-remove outline-mode-menu-heading)
5415 (easy-menu-remove outline-mode-menu-show)
5416 (easy-menu-remove outline-mode-menu-hide))
5417 (define-key org-mode-map [menu-bar headings] 'undefined)
5418 (define-key org-mode-map [menu-bar hide] 'undefined)
5419 (define-key org-mode-map [menu-bar show] 'undefined))
5421 (org-load-modules-maybe)
5422 (easy-menu-add org-org-menu)
5423 (easy-menu-add org-tbl-menu)
5424 (org-install-agenda-files-menu)
5425 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5426 (add-to-invisibility-spec '(org-cwidth))
5427 (add-to-invisibility-spec '(org-hide-block . t))
5428 (when (featurep 'xemacs)
5429 (org-set-local 'line-move-ignore-invisible t))
5430 (org-set-local 'outline-regexp org-outline-regexp)
5431 (org-set-local 'outline-level 'org-outline-level)
5432 (setq bidi-paragraph-direction 'left-to-right)
5433 (when (and org-ellipsis
5434 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5435 (fboundp 'make-glyph-code))
5436 (unless org-display-table
5437 (setq org-display-table (make-display-table)))
5438 (set-display-table-slot
5439 org-display-table 4
5440 (vconcat (mapcar
5441 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5442 org-ellipsis)))
5443 (if (stringp org-ellipsis) org-ellipsis "..."))))
5444 (setq buffer-display-table org-display-table))
5445 (org-set-regexps-and-options-for-tags)
5446 (org-set-regexps-and-options)
5447 (org-set-font-lock-defaults)
5448 (when (and org-tag-faces (not org-tags-special-faces-re))
5449 ;; tag faces set outside customize.... force initialization.
5450 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5451 ;; Calc embedded
5452 (org-set-local 'calc-embedded-open-mode "# ")
5453 ;; Modify a few syntax entries
5454 (modify-syntax-entry ?@ "w")
5455 (modify-syntax-entry ?\" "\"")
5456 (modify-syntax-entry ?\\ "_")
5457 (modify-syntax-entry ?~ "_")
5458 (if org-startup-truncated (setq truncate-lines t))
5459 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5460 (org-set-local 'font-lock-unfontify-region-function
5461 'org-unfontify-region)
5462 ;; Activate before-change-function
5463 (org-set-local 'org-table-may-need-update t)
5464 (org-add-hook 'before-change-functions 'org-before-change-function nil
5465 'local)
5466 ;; Check for running clock before killing a buffer
5467 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5468 ;; Initialize macros templates.
5469 (org-macro-initialize-templates)
5470 ;; Initialize radio targets.
5471 (org-update-radio-target-regexp)
5472 ;; Indentation.
5473 (org-set-local 'indent-line-function 'org-indent-line)
5474 (org-set-local 'indent-region-function 'org-indent-region)
5475 ;; Filling and auto-filling.
5476 (org-setup-filling)
5477 ;; Comments.
5478 (org-setup-comments-handling)
5479 ;; Initialize cache.
5480 (org-element-cache-reset)
5481 ;; Beginning/end of defun
5482 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5483 (org-set-local 'end-of-defun-function
5484 (lambda ()
5485 (if (not (org-at-heading-p))
5486 (org-forward-element)
5487 (org-forward-element)
5488 (forward-char -1))))
5489 ;; Next error for sparse trees
5490 (org-set-local 'next-error-function 'org-occur-next-match)
5491 ;; Make sure dependence stuff works reliably, even for users who set it
5492 ;; too late :-(
5493 (if org-enforce-todo-dependencies
5494 (add-hook 'org-blocker-hook
5495 'org-block-todo-from-children-or-siblings-or-parent)
5496 (remove-hook 'org-blocker-hook
5497 'org-block-todo-from-children-or-siblings-or-parent))
5498 (if org-enforce-todo-checkbox-dependencies
5499 (add-hook 'org-blocker-hook
5500 'org-block-todo-from-checkboxes)
5501 (remove-hook 'org-blocker-hook
5502 'org-block-todo-from-checkboxes))
5504 ;; Align options lines
5505 (org-set-local
5506 'align-mode-rules-list
5507 '((org-in-buffer-settings
5508 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5509 (modes . '(org-mode)))))
5511 ;; Imenu
5512 (org-set-local 'imenu-create-index-function
5513 'org-imenu-get-tree)
5515 ;; Make isearch reveal context
5516 (if (or (featurep 'xemacs)
5517 (not (boundp 'outline-isearch-open-invisible-function)))
5518 ;; Emacs 21 and XEmacs make use of the hook
5519 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5520 ;; Emacs 22 deals with this through a special variable
5521 (org-set-local 'outline-isearch-open-invisible-function
5522 (lambda (&rest ignore) (org-show-context 'isearch))))
5524 ;; Setup the pcomplete hooks
5525 (set (make-local-variable 'pcomplete-command-completion-function)
5526 'org-pcomplete-initial)
5527 (set (make-local-variable 'pcomplete-command-name-function)
5528 'org-command-at-point)
5529 (set (make-local-variable 'pcomplete-default-completion-function)
5530 'ignore)
5531 (set (make-local-variable 'pcomplete-parse-arguments-function)
5532 'org-parse-arguments)
5533 (set (make-local-variable 'pcomplete-termination-string) "")
5534 (when (>= emacs-major-version 23)
5535 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5537 ;; If empty file that did not turn on org-mode automatically, make it to.
5538 (if (and org-insert-mode-line-in-empty-file
5539 (org-called-interactively-p 'any)
5540 (= (point-min) (point-max)))
5541 (insert "# -*- mode: org -*-\n\n"))
5542 (unless org-inhibit-startup
5543 (org-unmodified
5544 (and org-startup-with-beamer-mode (org-beamer-mode))
5545 (when org-startup-align-all-tables
5546 (org-table-map-tables 'org-table-align 'quietly))
5547 (when org-startup-with-inline-images
5548 (org-display-inline-images))
5549 (when org-startup-with-latex-preview
5550 (org-toggle-latex-fragment))
5551 (unless org-inhibit-startup-visibility-stuff
5552 (org-set-startup-visibility))
5553 (org-refresh-effort-properties)))
5554 ;; Try to set org-hide correctly
5555 (let ((foreground (org-find-invisible-foreground)))
5556 (if foreground
5557 (set-face-foreground 'org-hide foreground))))
5559 ;; Update `customize-package-emacs-version-alist'
5560 (add-to-list 'customize-package-emacs-version-alist
5561 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5562 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5563 ("8.2.6" . "24.4")))
5565 (defvar org-mode-transpose-word-syntax-table
5566 (let ((st (make-syntax-table)))
5567 (mapc (lambda(c) (modify-syntax-entry
5568 (string-to-char (car c)) "w p" st))
5569 org-emphasis-alist)
5570 st))
5572 (when (fboundp 'abbrev-table-put)
5573 (abbrev-table-put org-mode-abbrev-table
5574 :parents (list text-mode-abbrev-table)))
5576 (defun org-find-invisible-foreground ()
5577 (let ((candidates (remove
5578 "unspecified-bg"
5579 (nconc
5580 (list (face-background 'default)
5581 (face-background 'org-default))
5582 (mapcar
5583 (lambda (alist)
5584 (when (boundp alist)
5585 (cdr (assoc 'background-color (symbol-value alist)))))
5586 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5587 (list (face-foreground 'org-hide))))))
5588 (car (remove nil candidates))))
5590 (defun org-current-time (&optional rounding-minutes past)
5591 "Current time, possibly rounded to ROUNDING-MINUTES.
5592 When ROUNDING-MINUTES is not an integer, fall back on the car of
5593 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5594 the rounding returns a past time."
5595 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5596 (car org-time-stamp-rounding-minutes)))
5597 (time (decode-time)) res)
5598 (if (< r 1)
5599 (current-time)
5600 (setq res
5601 (apply 'encode-time
5602 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5603 (nthcdr 2 time))))
5604 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5605 (seconds-to-time (- (org-float-time res) (* r 60)))
5606 res))))
5608 (defun org-today ()
5609 "Return today date, considering `org-extend-today-until'."
5610 (time-to-days
5611 (time-subtract (current-time)
5612 (list 0 (* 3600 org-extend-today-until) 0))))
5614 ;;;; Font-Lock stuff, including the activators
5616 (defvar org-mouse-map (make-sparse-keymap))
5617 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5618 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5619 (when org-mouse-1-follows-link
5620 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5621 (when org-tab-follows-link
5622 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5623 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5625 (require 'font-lock)
5627 (defconst org-non-link-chars "]\t\n\r<>")
5628 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5629 "file+sys" "news" "shell" "elisp" "doi" "message"
5630 "help"))
5631 (defvar org-link-types-re nil
5632 "Matches a link that has a url-like prefix like \"http:\"")
5633 (defvar org-link-re-with-space nil
5634 "Matches a link with spaces, optional angular brackets around it.")
5635 (defvar org-link-re-with-space2 nil
5636 "Matches a link with spaces, optional angular brackets around it.")
5637 (defvar org-link-re-with-space3 nil
5638 "Matches a link with spaces, only for internal part in bracket links.")
5639 (defvar org-angle-link-re nil
5640 "Matches link with angular brackets, spaces are allowed.")
5641 (defvar org-plain-link-re nil
5642 "Matches plain link, without spaces.")
5643 (defvar org-bracket-link-regexp nil
5644 "Matches a link in double brackets.")
5645 (defvar org-bracket-link-analytic-regexp nil
5646 "Regular expression used to analyze links.
5647 Here is what the match groups contain after a match:
5648 1: http:
5649 2: http
5650 3: path
5651 4: [desc]
5652 5: desc")
5653 (defvar org-bracket-link-analytic-regexp++ nil
5654 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5655 (defvar org-any-link-re nil
5656 "Regular expression matching any link.")
5658 (defconst org-match-sexp-depth 3
5659 "Number of stacked braces for sub/superscript matching.")
5661 (defun org-create-multibrace-regexp (left right n)
5662 "Create a regular expression which will match a balanced sexp.
5663 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5664 as single character strings.
5665 The regexp returned will match the entire expression including the
5666 delimiters. It will also define a single group which contains the
5667 match except for the outermost delimiters. The maximum depth of
5668 stacked delimiters is N. Escaping delimiters is not possible."
5669 (let* ((nothing (concat "[^" left right "]*?"))
5670 (or "\\|")
5671 (re nothing)
5672 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5673 (while (> n 1)
5674 (setq n (1- n)
5675 re (concat re or next)
5676 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5677 (concat left "\\(" re "\\)" right)))
5679 (defconst org-match-substring-regexp
5680 (concat
5681 "\\(\\S-\\)\\([_^]\\)\\("
5682 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5683 "\\|"
5684 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5685 "\\|"
5686 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5687 "The regular expression matching a sub- or superscript.")
5689 (defconst org-match-substring-with-braces-regexp
5690 (concat
5691 "\\(\\S-\\)\\([_^]\\)"
5692 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5693 "The regular expression matching a sub- or superscript, forcing braces.")
5695 (defun org-make-link-regexps ()
5696 "Update the link regular expressions.
5697 This should be called after the variable `org-link-types' has changed."
5698 (let ((types-re (regexp-opt org-link-types t)))
5699 (setq org-link-types-re
5700 (concat "\\`" types-re ":")
5701 org-link-re-with-space
5702 (concat "<?" types-re ":"
5703 "\\([^" org-non-link-chars " ]"
5704 "[^" org-non-link-chars "]*"
5705 "[^" org-non-link-chars " ]\\)>?")
5706 org-link-re-with-space2
5707 (concat "<?" types-re ":"
5708 "\\([^" org-non-link-chars " ]"
5709 "[^\t\n\r]*"
5710 "[^" org-non-link-chars " ]\\)>?")
5711 org-link-re-with-space3
5712 (concat "<?" types-re ":"
5713 "\\([^" org-non-link-chars " ]"
5714 "[^\t\n\r]*\\)")
5715 org-angle-link-re
5716 (concat "<" types-re ":"
5717 "\\([^" org-non-link-chars " ]"
5718 "[^" org-non-link-chars "]*"
5719 "\\)>")
5720 org-plain-link-re
5721 (concat
5722 "\\<" types-re ":"
5723 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5724 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5725 org-bracket-link-regexp
5726 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5727 org-bracket-link-analytic-regexp
5728 (concat
5729 "\\[\\["
5730 "\\(" types-re ":\\)?"
5731 "\\([^]]+\\)"
5732 "\\]"
5733 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5734 "\\]")
5735 org-bracket-link-analytic-regexp++
5736 (concat
5737 "\\[\\["
5738 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5739 "\\([^]]+\\)"
5740 "\\]"
5741 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5742 "\\]")
5743 org-any-link-re
5744 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5745 org-angle-link-re "\\)\\|\\("
5746 org-plain-link-re "\\)"))))
5748 (org-make-link-regexps)
5750 (defvar org-emph-face nil)
5752 (defun org-do-emphasis-faces (limit)
5753 "Run through the buffer and emphasize strings."
5754 (let (rtn a)
5755 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5756 (let* ((border (char-after (match-beginning 3)))
5757 (bre (regexp-quote (char-to-string border))))
5758 (if (and (not (= border (char-after (match-beginning 4))))
5759 (not (save-match-data
5760 (string-match (concat bre ".*" bre)
5761 (replace-regexp-in-string
5762 "\n" " "
5763 (substring (match-string 2) 1 -1))))))
5764 (progn
5765 (setq rtn t)
5766 (setq a (assoc (match-string 3) org-emphasis-alist))
5767 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5768 'face
5769 (nth 1 a))
5770 (and (nth 2 a)
5771 (org-remove-flyspell-overlays-in
5772 (match-beginning 0) (match-end 0)))
5773 (add-text-properties (match-beginning 2) (match-end 2)
5774 '(font-lock-multiline t org-emphasis t))
5775 (when org-hide-emphasis-markers
5776 (add-text-properties (match-end 4) (match-beginning 5)
5777 '(invisible org-link))
5778 (add-text-properties (match-beginning 3) (match-end 3)
5779 '(invisible org-link))))))
5780 (goto-char (1+ (match-beginning 0))))
5781 rtn))
5783 (defun org-emphasize (&optional char)
5784 "Insert or change an emphasis, i.e. a font like bold or italic.
5785 If there is an active region, change that region to a new emphasis.
5786 If there is no region, just insert the marker characters and position
5787 the cursor between them.
5788 CHAR should be the marker character. If it is a space, it means to
5789 remove the emphasis of the selected region.
5790 If CHAR is not given (for example in an interactive call) it will be
5791 prompted for."
5792 (interactive)
5793 (let ((erc org-emphasis-regexp-components)
5794 (prompt "")
5795 (string "") beg end move c s)
5796 (if (org-region-active-p)
5797 (setq beg (region-beginning) end (region-end)
5798 string (buffer-substring beg end))
5799 (setq move t))
5801 (unless char
5802 (message "Emphasis marker or tag: [%s]"
5803 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5804 (setq char (read-char-exclusive)))
5805 (if (equal char ?\ )
5806 (setq s "" move nil)
5807 (unless (assoc (char-to-string char) org-emphasis-alist)
5808 (user-error "No such emphasis marker: \"%c\"" char))
5809 (setq s (char-to-string char)))
5810 (while (and (> (length string) 1)
5811 (equal (substring string 0 1) (substring string -1))
5812 (assoc (substring string 0 1) org-emphasis-alist))
5813 (setq string (substring string 1 -1)))
5814 (setq string (concat s string s))
5815 (if beg (delete-region beg end))
5816 (unless (or (bolp)
5817 (string-match (concat "[" (nth 0 erc) "\n]")
5818 (char-to-string (char-before (point)))))
5819 (insert " "))
5820 (unless (or (eobp)
5821 (string-match (concat "[" (nth 1 erc) "\n]")
5822 (char-to-string (char-after (point)))))
5823 (insert " ") (backward-char 1))
5824 (insert string)
5825 (and move (backward-char 1))))
5827 (defconst org-nonsticky-props
5828 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5830 (defsubst org-rear-nonsticky-at (pos)
5831 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5833 (defun org-activate-plain-links (limit)
5834 "Add link properties for plain links."
5835 (let (f hl)
5836 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5837 (not (member 'org-tag
5838 (get-text-property (1- (match-beginning 0)) 'face)))
5839 (not (org-in-src-block-p)))
5840 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5841 (setq f (get-text-property (match-beginning 0) 'face))
5842 (setq hl (org-match-string-no-properties 0))
5843 (if (or (eq f 'org-tag)
5844 (and (listp f) (memq 'org-tag f)))
5846 (add-text-properties (match-beginning 0) (match-end 0)
5847 (list 'mouse-face 'highlight
5848 'face 'org-link
5849 'htmlize-link `(:uri ,hl)
5850 'keymap org-mouse-map))
5851 (org-rear-nonsticky-at (match-end 0)))
5852 t)))
5854 (defun org-activate-code (limit)
5855 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5856 (progn
5857 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5858 (remove-text-properties (match-beginning 0) (match-end 0)
5859 '(display t invisible t intangible t))
5860 t)))
5862 (defcustom org-src-fontify-natively t
5863 "When non-nil, fontify code in code blocks."
5864 :type 'boolean
5865 :version "24.4"
5866 :package-version '(Org . "8.3")
5867 :group 'org-appearance
5868 :group 'org-babel)
5870 (defcustom org-allow-promoting-top-level-subtree nil
5871 "When non-nil, allow promoting a top level subtree.
5872 The leading star of the top level headline will be replaced
5873 by a #."
5874 :type 'boolean
5875 :version "24.1"
5876 :group 'org-appearance)
5878 (defun org-fontify-meta-lines-and-blocks (limit)
5879 (condition-case nil
5880 (org-fontify-meta-lines-and-blocks-1 limit)
5881 (error (message "org-mode fontification error"))))
5883 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5884 "Fontify #+ lines and blocks."
5885 (let ((case-fold-search t))
5886 (if (re-search-forward
5887 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5888 limit t)
5889 (let ((beg (match-beginning 0))
5890 (block-start (match-end 0))
5891 (block-end nil)
5892 (lang (match-string 7))
5893 (beg1 (line-beginning-position 2))
5894 (dc1 (downcase (match-string 2)))
5895 (dc3 (downcase (match-string 3)))
5896 end end1 quoting block-type ovl)
5897 (cond
5898 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5899 ;; a single line of backend-specific content
5900 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5901 (remove-text-properties (match-beginning 0) (match-end 0)
5902 '(display t invisible t intangible t))
5903 (add-text-properties (match-beginning 1) (match-end 3)
5904 '(font-lock-fontified t face org-meta-line))
5905 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5906 '(font-lock-fontified t face org-block))
5907 ; for backend-specific code
5909 ((and (match-end 4) (equal dc3 "+begin"))
5910 ;; Truly a block
5911 (setq block-type (downcase (match-string 5))
5912 quoting (member block-type org-protecting-blocks))
5913 (when (re-search-forward
5914 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5915 nil t) ;; on purpose, we look further than LIMIT
5916 (setq end (min (point-max) (match-end 0))
5917 end1 (min (point-max) (1- (match-beginning 0))))
5918 (setq block-end (match-beginning 0))
5919 (when quoting
5920 (org-remove-flyspell-overlays-in beg1 end1)
5921 (remove-text-properties beg end
5922 '(display t invisible t intangible t)))
5923 (add-text-properties
5924 beg end '(font-lock-fontified t font-lock-multiline t))
5925 (add-text-properties beg beg1 '(face org-meta-line))
5926 (org-remove-flyspell-overlays-in beg beg1)
5927 (add-text-properties ; For end_src
5928 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5929 (org-remove-flyspell-overlays-in end1 end)
5930 (cond
5931 ((and lang (not (string= lang "")) org-src-fontify-natively)
5932 (org-src-font-lock-fontify-block lang block-start block-end)
5933 (add-text-properties beg1 block-end '(src-block t)))
5934 (quoting
5935 (add-text-properties beg1 (min (point-max) (1+ end1))
5936 '(face org-block))) ; end of source block
5937 ((not org-fontify-quote-and-verse-blocks))
5938 ((string= block-type "quote")
5939 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5940 ((string= block-type "verse")
5941 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5942 (add-text-properties beg beg1 '(face org-block-begin-line))
5943 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5944 '(face org-block-end-line))
5946 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5947 (org-remove-flyspell-overlays-in
5948 (match-beginning 0)
5949 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5950 (add-text-properties
5951 beg (match-end 3)
5952 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5953 '(font-lock-fontified t invisible t)
5954 '(font-lock-fontified t face org-document-info-keyword)))
5955 (add-text-properties
5956 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5957 (if (string-equal dc1 "+title:")
5958 '(font-lock-fontified t face org-document-title)
5959 '(font-lock-fontified t face org-document-info))))
5960 ((or (equal dc1 "+results")
5961 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5962 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5963 "+call:" "+header:" "+headers:" "+name:"))
5964 (and (match-end 4) (equal dc3 "+attr")))
5965 (org-remove-flyspell-overlays-in
5966 (match-beginning 0)
5967 (if (equal "+caption:" dc1) (match-end 2) (match-end 0)))
5968 (add-text-properties
5969 beg (match-end 0)
5970 '(font-lock-fontified t face org-meta-line))
5972 ((member dc3 '(" " ""))
5973 (org-remove-flyspell-overlays-in beg (match-end 0))
5974 (add-text-properties
5975 beg (match-end 0)
5976 '(font-lock-fontified t face font-lock-comment-face)))
5977 (t ;; just any other in-buffer setting, but not indented
5978 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5979 (add-text-properties
5980 beg (match-end 0)
5981 '(font-lock-fontified t face org-meta-line))
5982 t))))))
5984 (defun org-fontify-drawers (limit)
5985 "Fontify drawers."
5986 (when (re-search-forward org-drawer-regexp limit t)
5987 (add-text-properties
5988 (match-beginning 0) (match-end 0)
5989 '(font-lock-fontified t face org-special-keyword))
5990 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5993 (defun org-fontify-macros (limit)
5994 "Fontify macros."
5995 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5996 (add-text-properties
5997 (match-beginning 0) (match-end 0)
5998 '(font-lock-fontified t face org-macro))
5999 (when org-hide-macro-markers
6000 (add-text-properties (match-end 2) (match-beginning 2)
6001 '(invisible t))
6002 (add-text-properties (match-beginning 1) (match-end 1)
6003 '(invisible t)))
6004 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6007 (defun org-activate-angle-links (limit)
6008 "Add text properties for angle links."
6009 (if (and (re-search-forward org-angle-link-re limit t)
6010 (not (org-in-src-block-p)))
6011 (progn
6012 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6013 (add-text-properties (match-beginning 0) (match-end 0)
6014 (list 'mouse-face 'highlight
6015 'keymap org-mouse-map))
6016 (org-rear-nonsticky-at (match-end 0))
6017 t)))
6019 (defun org-activate-footnote-links (limit)
6020 "Add text properties for footnotes."
6021 (let ((fn (org-footnote-next-reference-or-definition limit)))
6022 (when fn
6023 (let* ((beg (nth 1 fn))
6024 (end (nth 2 fn))
6025 (label (car fn))
6026 (referencep (/= (line-beginning-position) beg)))
6027 (when (and referencep (nth 3 fn))
6028 (save-excursion
6029 (goto-char beg)
6030 (search-forward (or label "fn:"))
6031 (org-remove-flyspell-overlays-in beg (match-end 0))))
6032 (add-text-properties beg end
6033 (list 'mouse-face 'highlight
6034 'keymap org-mouse-map
6035 'help-echo
6036 (if referencep "Footnote reference"
6037 "Footnote definition")
6038 'font-lock-fontified t
6039 'font-lock-multiline t
6040 'face 'org-footnote))))))
6042 (defun org-activate-bracket-links (limit)
6043 "Add text properties for bracketed links."
6044 (if (and (re-search-forward org-bracket-link-regexp limit t)
6045 (not (org-in-src-block-p)))
6046 (let* ((hl (org-match-string-no-properties 1))
6047 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6048 (ip (org-maybe-intangible
6049 (list 'invisible 'org-link
6050 'keymap org-mouse-map 'mouse-face 'highlight
6051 'font-lock-multiline t 'help-echo help
6052 'htmlize-link `(:uri ,hl))))
6053 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6054 'font-lock-multiline t 'help-echo help
6055 'htmlize-link `(:uri ,hl))))
6056 ;; We need to remove the invisible property here. Table narrowing
6057 ;; may have made some of this invisible.
6058 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6059 (remove-text-properties (match-beginning 0) (match-end 0)
6060 '(invisible nil))
6061 (if (match-end 3)
6062 (progn
6063 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6064 (org-rear-nonsticky-at (match-beginning 3))
6065 (add-text-properties (match-beginning 3) (match-end 3) vp)
6066 (org-rear-nonsticky-at (match-end 3))
6067 (add-text-properties (match-end 3) (match-end 0) ip)
6068 (org-rear-nonsticky-at (match-end 0)))
6069 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6070 (org-rear-nonsticky-at (match-beginning 1))
6071 (add-text-properties (match-beginning 1) (match-end 1) vp)
6072 (org-rear-nonsticky-at (match-end 1))
6073 (add-text-properties (match-end 1) (match-end 0) ip)
6074 (org-rear-nonsticky-at (match-end 0)))
6075 t)))
6077 (defun org-activate-dates (limit)
6078 "Add text properties for dates."
6079 (if (and (re-search-forward org-tsr-regexp-both limit t)
6080 (not (equal (char-before (match-beginning 0)) 91)))
6081 (progn
6082 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6083 (add-text-properties (match-beginning 0) (match-end 0)
6084 (list 'mouse-face 'highlight
6085 'keymap org-mouse-map))
6086 (org-rear-nonsticky-at (match-end 0))
6087 (when org-display-custom-times
6088 (if (match-end 3)
6089 (org-display-custom-time (match-beginning 3) (match-end 3)))
6090 (org-display-custom-time (match-beginning 1) (match-end 1)))
6091 t)))
6093 (defvar org-target-link-regexp nil
6094 "Regular expression matching radio targets in plain text.")
6095 (make-variable-buffer-local 'org-target-link-regexp)
6097 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6098 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6099 border border border))
6100 "Regular expression matching a link target.")
6102 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6103 "Regular expression matching a radio target.")
6105 (defconst org-any-target-regexp
6106 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6107 "Regular expression matching any target.")
6109 (defun org-activate-target-links (limit)
6110 "Add text properties for target matches."
6111 (when org-target-link-regexp
6112 (let ((case-fold-search t))
6113 (if (re-search-forward org-target-link-regexp limit t)
6114 (progn
6115 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6116 (add-text-properties (match-beginning 1) (match-end 1)
6117 (list 'mouse-face 'highlight
6118 'keymap org-mouse-map
6119 'help-echo "Radio target link"
6120 'org-linked-text t))
6121 (org-rear-nonsticky-at (match-end 1))
6122 t)))))
6124 (defun org-update-radio-target-regexp ()
6125 "Find all radio targets in this file and update the regular expression.
6126 Also refresh fontification if needed."
6127 (interactive)
6128 (let ((old-regexp org-target-link-regexp)
6129 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6130 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6131 (targets
6132 (org-with-wide-buffer
6133 (goto-char (point-min))
6134 (let (rtn)
6135 (while (re-search-forward org-radio-target-regexp nil t)
6136 ;; Make sure point is really within the object.
6137 (backward-char)
6138 (let ((obj (org-element-context)))
6139 (when (eq (org-element-type obj) 'radio-target)
6140 (add-to-list 'rtn (org-element-property :value obj)))))
6141 rtn))))
6142 (setq org-target-link-regexp
6143 (and targets
6144 (concat before-re
6145 (mapconcat
6146 (lambda (x)
6147 (replace-regexp-in-string
6148 " +" "\\s-+" (regexp-quote x) t t))
6149 targets
6150 "\\|")
6151 after-re)))
6152 (unless (equal old-regexp org-target-link-regexp)
6153 ;; Clean-up cache.
6154 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6155 ((not org-target-link-regexp) old-regexp)
6157 (concat before-re
6158 (mapconcat
6159 (lambda (re)
6160 (substring re (length before-re)
6161 (- (length after-re))))
6162 (list old-regexp org-target-link-regexp)
6163 "\\|")
6164 after-re)))))
6165 (org-with-wide-buffer
6166 (goto-char (point-min))
6167 (while (re-search-forward regexp nil t)
6168 (org-element-cache-refresh (match-beginning 1)))))
6169 ;; Re fontify buffer.
6170 (when (memq 'radio org-highlight-links)
6171 (org-restart-font-lock)))))
6173 (defun org-hide-wide-columns (limit)
6174 (let (s e)
6175 (setq s (text-property-any (point) (or limit (point-max))
6176 'org-cwidth t))
6177 (when s
6178 (setq e (next-single-property-change s 'org-cwidth))
6179 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6180 (goto-char e)
6181 t)))
6183 (defvar org-latex-and-related-regexp nil
6184 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6186 (defun org-compute-latex-and-related-regexp ()
6187 "Compute regular expression for LaTeX, entities and sub/superscript.
6188 Result depends on variable `org-highlight-latex-and-related'."
6189 (org-set-local
6190 'org-latex-and-related-regexp
6191 (let* ((re-sub
6192 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6193 ((eq org-use-sub-superscripts '{})
6194 (list org-match-substring-with-braces-regexp))
6195 (org-use-sub-superscripts (list org-match-substring-regexp))))
6196 (re-latex
6197 (when (memq 'latex org-highlight-latex-and-related)
6198 (let ((matchers (plist-get org-format-latex-options :matchers)))
6199 (delq nil
6200 (mapcar (lambda (x)
6201 (and (member (car x) matchers) (nth 1 x)))
6202 org-latex-regexps)))))
6203 (re-entities
6204 (when (memq 'entities org-highlight-latex-and-related)
6205 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6206 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6208 (defun org-do-latex-and-related (limit)
6209 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6210 LIMIT bounds the search for syntax to highlight. Stop at first
6211 highlighted object, if any. Return t if some highlighting was
6212 done, nil otherwise."
6213 (when (org-string-nw-p org-latex-and-related-regexp)
6214 (catch 'found
6215 (while (re-search-forward org-latex-and-related-regexp limit t)
6216 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6217 'face))
6218 '(org-code org-verbatim underline))
6219 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6220 '(?_ ?^))
6222 0)))
6223 (font-lock-prepend-text-property
6224 (+ offset (match-beginning 0)) (match-end 0)
6225 'face 'org-latex-and-related)
6226 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6227 '(font-lock-multiline t)))
6228 (throw 'found t)))
6229 nil)))
6231 (defun org-restart-font-lock ()
6232 "Restart `font-lock-mode', to force refontification."
6233 (when (and (boundp 'font-lock-mode) font-lock-mode)
6234 (font-lock-mode -1)
6235 (font-lock-mode 1)))
6237 (defun org-activate-tags (limit)
6238 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6239 (progn
6240 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6241 (add-text-properties (match-beginning 1) (match-end 1)
6242 (list 'mouse-face 'highlight
6243 'keymap org-mouse-map))
6244 (org-rear-nonsticky-at (match-end 1))
6245 t)))
6247 (defun org-outline-level ()
6248 "Compute the outline level of the heading at point.
6249 If this is called at a normal headline, the level is the number of stars.
6250 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6251 (save-excursion
6252 (if (not (ignore-errors (org-back-to-heading t)))
6254 (looking-at org-outline-regexp)
6255 (1- (- (match-end 0) (match-beginning 0))))))
6257 (defvar org-font-lock-keywords nil)
6259 (defsubst org-re-property (property &optional literal allow-null)
6260 "Return a regexp matching a PROPERTY line.
6261 Match group 3 will be set to the value if it exists."
6262 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6263 (if literal property (regexp-quote property))
6264 "\\):\\)[ \t]+\\(?3:[^ \t\r\n]"
6265 (if allow-null "*")
6266 ".*?\\)\\(?5:[ \t]*\\)$"))
6268 (defconst org-property-re
6269 (org-re-property ".*?" 'literal t)
6270 "Regular expression matching a property line.
6271 There are four matching groups:
6272 1: :PROPKEY: including the leading and trailing colon,
6273 2: PROPKEY without the leading and trailing colon,
6274 3: PROPVAL without leading or trailing spaces,
6275 4: the indentation of the current line,
6276 5: trailing whitespace.")
6278 (defvar org-font-lock-hook nil
6279 "Functions to be called for special font lock stuff.")
6281 (defvar org-font-lock-set-keywords-hook nil
6282 "Functions that can manipulate `org-font-lock-extra-keywords'.
6283 This is called after `org-font-lock-extra-keywords' is defined, but before
6284 it is installed to be used by font lock. This can be useful if something
6285 needs to be inserted at a specific position in the font-lock sequence.")
6287 (defun org-font-lock-hook (limit)
6288 "Run `org-font-lock-hook' within LIMIT."
6289 (run-hook-with-args 'org-font-lock-hook limit))
6291 (defun org-set-font-lock-defaults ()
6292 "Set font lock defaults for the current buffer."
6293 (let* ((em org-fontify-emphasized-text)
6294 (lk org-highlight-links)
6295 (org-font-lock-extra-keywords
6296 (list
6297 ;; Call the hook
6298 '(org-font-lock-hook)
6299 ;; Headlines
6300 `(,(if org-fontify-whole-heading-line
6301 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6302 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6303 (1 (org-get-level-face 1))
6304 (2 (org-get-level-face 2))
6305 (3 (org-get-level-face 3)))
6306 ;; Table lines
6307 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6308 (1 'org-table t))
6309 ;; Table internals
6310 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6311 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6312 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6313 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6314 ;; Drawers
6315 '(org-fontify-drawers)
6316 ;; Properties
6317 (list org-property-re
6318 '(1 'org-special-keyword t)
6319 '(3 'org-property-value t))
6320 ;; Links
6321 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6322 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6323 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6324 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6325 (if (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6326 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6327 (if (memq 'footnote lk) '(org-activate-footnote-links))
6328 ;; Targets.
6329 (list org-any-target-regexp '(0 'org-target t))
6330 ;; Diary sexps.
6331 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6332 ;; Macro
6333 '(org-fontify-macros)
6334 '(org-hide-wide-columns (0 nil append))
6335 ;; TODO keyword
6336 (list (format org-heading-keyword-regexp-format
6337 org-todo-regexp)
6338 '(2 (org-get-todo-face 2) t))
6339 ;; DONE
6340 (if org-fontify-done-headline
6341 (list (format org-heading-keyword-regexp-format
6342 (concat
6343 "\\(?:"
6344 (mapconcat 'regexp-quote org-done-keywords "\\|")
6345 "\\)"))
6346 '(2 'org-headline-done t))
6347 nil)
6348 ;; Priorities
6349 '(org-font-lock-add-priority-faces)
6350 ;; Tags
6351 '(org-font-lock-add-tag-faces)
6352 ;; Tags groups
6353 (if (and org-group-tags org-tag-groups-alist)
6354 (list (concat org-outline-regexp-bol ".+\\(:"
6355 (regexp-opt (mapcar 'car org-tag-groups-alist))
6356 ":\\).*$")
6357 '(1 'org-tag-group prepend)))
6358 ;; Special keywords
6359 (list (concat "\\<" org-comment-string) '(0 'org-special-keyword t))
6360 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6361 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6362 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6363 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6364 ;; Emphasis
6365 (if em
6366 (if (featurep 'xemacs)
6367 '(org-do-emphasis-faces (0 nil append))
6368 '(org-do-emphasis-faces)))
6369 ;; Checkboxes
6370 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6371 1 'org-checkbox prepend)
6372 (if (cdr (assq 'checkbox org-list-automatic-rules))
6373 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6374 (0 (org-get-checkbox-statistics-face) t)))
6375 ;; Description list items
6376 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6377 1 'org-list-dt prepend)
6378 ;; ARCHIVEd headings
6379 (list (concat
6380 org-outline-regexp-bol
6381 "\\(.*:" org-archive-tag ":.*\\)")
6382 '(1 'org-archived prepend))
6383 ;; Specials
6384 '(org-do-latex-and-related)
6385 '(org-fontify-entities)
6386 '(org-raise-scripts)
6387 ;; Code
6388 '(org-activate-code (1 'org-code t))
6389 ;; COMMENT
6390 (list (format
6391 "^\\*\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6392 org-todo-regexp
6393 org-comment-string)
6394 '(9 'org-special-keyword t))
6395 ;; Blocks and meta lines
6396 '(org-fontify-meta-lines-and-blocks))))
6397 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6398 (run-hooks 'org-font-lock-set-keywords-hook)
6399 ;; Now set the full font-lock-keywords
6400 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6401 (org-set-local 'font-lock-defaults
6402 '(org-font-lock-keywords t nil nil backward-paragraph))
6403 (kill-local-variable 'font-lock-keywords) nil))
6405 (defun org-toggle-pretty-entities ()
6406 "Toggle the composition display of entities as UTF8 characters."
6407 (interactive)
6408 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6409 (org-restart-font-lock)
6410 (if org-pretty-entities
6411 (message "Entities are now displayed as UTF8 characters")
6412 (save-restriction
6413 (widen)
6414 (org-decompose-region (point-min) (point-max))
6415 (message "Entities are now displayed as plain text"))))
6417 (defvar org-custom-properties-overlays nil
6418 "List of overlays used for custom properties.")
6419 (make-variable-buffer-local 'org-custom-properties-overlays)
6421 (defun org-toggle-custom-properties-visibility ()
6422 "Display or hide properties in `org-custom-properties'."
6423 (interactive)
6424 (if org-custom-properties-overlays
6425 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6426 (setq org-custom-properties-overlays nil))
6427 (unless (not org-custom-properties)
6428 (save-excursion
6429 (save-restriction
6430 (widen)
6431 (goto-char (point-min))
6432 (while (re-search-forward org-property-re nil t)
6433 (mapc (lambda(p)
6434 (when (equal p (substring (match-string 1) 1 -1))
6435 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6436 (overlay-put o 'invisible t)
6437 (overlay-put o 'org-custom-property t)
6438 (push o org-custom-properties-overlays))))
6439 org-custom-properties)))))))
6441 (defun org-fontify-entities (limit)
6442 "Find an entity to fontify."
6443 (let (ee)
6444 (when org-pretty-entities
6445 (catch 'match
6446 (while (re-search-forward
6447 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6448 limit t)
6449 (if (and (not (org-at-comment-p))
6450 (setq ee (org-entity-get (match-string 1)))
6451 (= (length (nth 6 ee)) 1))
6452 (let*
6453 ((end (if (equal (match-string 2) "{}")
6454 (match-end 2)
6455 (match-end 1))))
6456 (add-text-properties
6457 (match-beginning 0) end
6458 (list 'font-lock-fontified t))
6459 (compose-region (match-beginning 0) end
6460 (nth 6 ee) nil)
6461 (backward-char 1)
6462 (throw 'match t))))
6463 nil))))
6465 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6466 "Fontify string S like in Org-mode."
6467 (with-temp-buffer
6468 (insert s)
6469 (let ((org-odd-levels-only odd-levels))
6470 (org-mode)
6471 (font-lock-ensure)
6472 (buffer-string))))
6474 (defvar org-m nil)
6475 (defvar org-l nil)
6476 (defvar org-f nil)
6477 (defun org-get-level-face (n)
6478 "Get the right face for match N in font-lock matching of headlines."
6479 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6480 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6481 (if org-cycle-level-faces
6482 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6483 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6484 (cond
6485 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6486 ((eq n 2) org-f)
6487 (t (if org-level-color-stars-only nil org-f))))
6490 (defun org-get-todo-face (kwd)
6491 "Get the right face for a TODO keyword KWD.
6492 If KWD is a number, get the corresponding match group."
6493 (if (numberp kwd) (setq kwd (match-string kwd)))
6494 (or (org-face-from-face-or-color
6495 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6496 (and (member kwd org-done-keywords) 'org-done)
6497 'org-todo))
6499 (defun org-face-from-face-or-color (context inherit face-or-color)
6500 "Create a face list that inherits INHERIT, but sets the foreground color.
6501 When FACE-OR-COLOR is not a string, just return it."
6502 (if (stringp face-or-color)
6503 (list :inherit inherit
6504 (cdr (assoc context org-faces-easy-properties))
6505 face-or-color)
6506 face-or-color))
6508 (defun org-font-lock-add-tag-faces (limit)
6509 "Add the special tag faces."
6510 (when (and org-tag-faces org-tags-special-faces-re)
6511 (while (re-search-forward org-tags-special-faces-re limit t)
6512 (add-text-properties (match-beginning 1) (match-end 1)
6513 (list 'face (org-get-tag-face 1)
6514 'font-lock-fontified t))
6515 (backward-char 1))))
6517 (defun org-font-lock-add-priority-faces (limit)
6518 "Add the special priority faces."
6519 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6520 (when (save-match-data (org-at-heading-p))
6521 (add-text-properties
6522 (match-beginning 0) (match-end 0)
6523 (list 'face (or (org-face-from-face-or-color
6524 'priority 'org-priority
6525 (cdr (assoc (char-after (match-beginning 1))
6526 org-priority-faces)))
6527 'org-priority)
6528 'font-lock-fontified t)))))
6530 (defun org-get-tag-face (kwd)
6531 "Get the right face for a TODO keyword KWD.
6532 If KWD is a number, get the corresponding match group."
6533 (if (numberp kwd) (setq kwd (match-string kwd)))
6534 (or (org-face-from-face-or-color
6535 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6536 'org-tag))
6538 (defun org-unfontify-region (beg end &optional maybe_loudly)
6539 "Remove fontification and activation overlays from links."
6540 (font-lock-default-unfontify-region beg end)
6541 (let* ((buffer-undo-list t)
6542 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6543 (inhibit-modification-hooks t)
6544 deactivate-mark buffer-file-name buffer-file-truename)
6545 (org-decompose-region beg end)
6546 (remove-text-properties beg end
6547 '(mouse-face t keymap t org-linked-text t
6548 invisible t intangible t
6549 org-emphasis t))
6550 (org-remove-font-lock-display-properties beg end)))
6552 (defconst org-script-display '(((raise -0.3) (height 0.7))
6553 ((raise 0.3) (height 0.7))
6554 ((raise -0.5))
6555 ((raise 0.5)))
6556 "Display properties for showing superscripts and subscripts.")
6558 (defun org-remove-font-lock-display-properties (beg end)
6559 "Remove specific display properties that have been added by font lock.
6560 The will remove the raise properties that are used to show superscripts
6561 and subscripts."
6562 (let (next prop)
6563 (while (< beg end)
6564 (setq next (next-single-property-change beg 'display nil end)
6565 prop (get-text-property beg 'display))
6566 (if (member prop org-script-display)
6567 (put-text-property beg next 'display nil))
6568 (setq beg next))))
6570 (defun org-raise-scripts (limit)
6571 "Add raise properties to sub/superscripts."
6572 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6573 (if (re-search-forward
6574 (if (eq org-use-sub-superscripts t)
6575 org-match-substring-regexp
6576 org-match-substring-with-braces-regexp)
6577 limit t)
6578 (let* ((pos (point)) table-p comment-p
6579 (mpos (match-beginning 3))
6580 (emph-p (get-text-property mpos 'org-emphasis))
6581 (link-p (get-text-property mpos 'mouse-face))
6582 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6583 (goto-char (point-at-bol))
6584 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6585 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6586 (goto-char pos)
6587 ;; Handle a_b^c
6588 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6589 (if (or comment-p emph-p link-p keyw-p)
6591 (put-text-property (match-beginning 3) (match-end 0)
6592 'display
6593 (if (equal (char-after (match-beginning 2)) ?^)
6594 (nth (if table-p 3 1) org-script-display)
6595 (nth (if table-p 2 0) org-script-display)))
6596 (add-text-properties (match-beginning 2) (match-end 2)
6597 (list 'invisible t
6598 'org-dwidth t 'org-dwidth-n 1))
6599 (if (and (eq (char-after (match-beginning 3)) ?{)
6600 (eq (char-before (match-end 3)) ?}))
6601 (progn
6602 (add-text-properties
6603 (match-beginning 3) (1+ (match-beginning 3))
6604 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6605 (add-text-properties
6606 (1- (match-end 3)) (match-end 3)
6607 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6608 t)))))
6610 ;;;; Visibility cycling, including org-goto and indirect buffer
6612 ;;; Cycling
6614 (defvar org-cycle-global-status nil)
6615 (make-variable-buffer-local 'org-cycle-global-status)
6616 (put 'org-cycle-global-status 'org-state t)
6617 (defvar org-cycle-subtree-status nil)
6618 (make-variable-buffer-local 'org-cycle-subtree-status)
6619 (put 'org-cycle-subtree-status 'org-state t)
6621 (defvar org-inlinetask-min-level)
6623 (defun org-unlogged-message (&rest args)
6624 "Display a message, but avoid logging it in the *Messages* buffer."
6625 (let ((message-log-max nil))
6626 (apply 'message args)))
6628 ;;;###autoload
6629 (defun org-cycle (&optional arg)
6630 "TAB-action and visibility cycling for Org-mode.
6632 This is the command invoked in Org-mode by the TAB key. Its main purpose
6633 is outline visibility cycling, but it also invokes other actions
6634 in special contexts.
6636 - When this function is called with a prefix argument, rotate the entire
6637 buffer through 3 states (global cycling)
6638 1. OVERVIEW: Show only top-level headlines.
6639 2. CONTENTS: Show all headlines of all levels, but no body text.
6640 3. SHOW ALL: Show everything.
6641 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6642 determined by the variable `org-startup-folded', and by any VISIBILITY
6643 properties in the buffer.
6644 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6645 including any drawers.
6647 - When inside a table, re-align the table and move to the next field.
6649 - When point is at the beginning of a headline, rotate the subtree started
6650 by this line through 3 different states (local cycling)
6651 1. FOLDED: Only the main headline is shown.
6652 2. CHILDREN: The main headline and the direct children are shown.
6653 From this state, you can move to one of the children
6654 and zoom in further.
6655 3. SUBTREE: Show the entire subtree, including body text.
6656 If there is no subtree, switch directly from CHILDREN to FOLDED.
6658 - When point is at the beginning of an empty headline and the variable
6659 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6660 of the headline by demoting and promoting it to likely levels. This
6661 speeds up creation document structure by pressing TAB once or several
6662 times right after creating a new headline.
6664 - When there is a numeric prefix, go up to a heading with level ARG, do
6665 a `show-subtree' and return to the previous cursor position. If ARG
6666 is negative, go up that many levels.
6668 - When point is not at the beginning of a headline, execute the global
6669 binding for TAB, which is re-indenting the line. See the option
6670 `org-cycle-emulate-tab' for details.
6672 - Special case: if point is at the beginning of the buffer and there is
6673 no headline in line 1, this function will act as if called with prefix arg
6674 (C-u TAB, same as S-TAB) also when called without prefix arg.
6675 But only if also the variable `org-cycle-global-at-bob' is t."
6676 (interactive "P")
6677 (org-load-modules-maybe)
6678 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6679 (and org-cycle-level-after-item/entry-creation
6680 (or (org-cycle-level)
6681 (org-cycle-item-indentation))))
6682 (let* ((limit-level
6683 (or org-cycle-max-level
6684 (and (boundp 'org-inlinetask-min-level)
6685 org-inlinetask-min-level
6686 (1- org-inlinetask-min-level))))
6687 (nstars (and limit-level
6688 (if org-odd-levels-only
6689 (and limit-level (1- (* limit-level 2)))
6690 limit-level)))
6691 (org-outline-regexp
6692 (if (not (derived-mode-p 'org-mode))
6693 outline-regexp
6694 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6695 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6696 (not (looking-at org-outline-regexp))))
6697 (org-cycle-hook
6698 (if bob-special
6699 (delq 'org-optimize-window-after-visibility-change
6700 (copy-sequence org-cycle-hook))
6701 org-cycle-hook))
6702 (pos (point)))
6704 (if (or bob-special (equal arg '(4)))
6705 ;; special case: use global cycling
6706 (setq arg t))
6708 (cond
6710 ((equal arg '(16))
6711 (setq last-command 'dummy)
6712 (org-set-startup-visibility)
6713 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6715 ((equal arg '(64))
6716 (show-all)
6717 (org-unlogged-message "Entire buffer visible, including drawers"))
6719 ;; Try cdlatex TAB completion
6720 ((org-try-cdlatex-tab))
6722 ;; Table: enter it or move to the next field.
6723 ((org-at-table-p 'any)
6724 (if (org-at-table.el-p)
6725 (message "Use C-c ' to edit table.el tables")
6726 (if arg (org-table-edit-field t)
6727 (org-table-justify-field-maybe)
6728 (call-interactively 'org-table-next-field))))
6730 ((run-hook-with-args-until-success
6731 'org-tab-after-check-for-table-hook))
6733 ;; Global cycling: delegate to `org-cycle-internal-global'.
6734 ((eq arg t) (org-cycle-internal-global))
6736 ;; Drawers: delegate to `org-flag-drawer'.
6737 ((save-excursion
6738 (beginning-of-line 1)
6739 (looking-at org-drawer-regexp))
6740 (org-flag-drawer ; toggle block visibility
6741 (not (get-char-property (match-end 0) 'invisible))))
6743 ;; Show-subtree, ARG levels up from here.
6744 ((integerp arg)
6745 (save-excursion
6746 (org-back-to-heading)
6747 (outline-up-heading (if (< arg 0) (- arg)
6748 (- (funcall outline-level) arg)))
6749 (org-show-subtree)))
6751 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6752 ((and (featurep 'org-inlinetask)
6753 (org-inlinetask-at-task-p)
6754 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6755 (org-inlinetask-toggle-visibility))
6757 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6758 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6759 (save-excursion (beginning-of-line 1)
6760 (looking-at org-outline-regexp)))
6761 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6762 (org-cycle-internal-local))
6764 ;; From there: TAB emulation and template completion.
6765 (buffer-read-only (org-back-to-heading))
6767 ((run-hook-with-args-until-success
6768 'org-tab-after-check-for-cycling-hook))
6770 ((org-try-structure-completion))
6772 ((run-hook-with-args-until-success
6773 'org-tab-before-tab-emulation-hook))
6775 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6776 (or (not (bolp))
6777 (not (looking-at org-outline-regexp))))
6778 (call-interactively (global-key-binding "\t")))
6780 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6781 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6782 (or (and (eq org-cycle-emulate-tab 'white)
6783 (= (match-end 0) (point-at-eol)))
6784 (and (eq org-cycle-emulate-tab 'whitestart)
6785 (>= (match-end 0) pos))))
6787 (eq org-cycle-emulate-tab t))
6788 (call-interactively (global-key-binding "\t")))
6790 (t (save-excursion
6791 (org-back-to-heading)
6792 (org-cycle)))))))
6794 (defun org-cycle-internal-global ()
6795 "Do the global cycling action."
6796 ;; Hack to avoid display of messages for .org attachments in Gnus
6797 (let ((ga (string-match "\\*fontification" (buffer-name))))
6798 (cond
6799 ((and (eq last-command this-command)
6800 (eq org-cycle-global-status 'overview))
6801 ;; We just created the overview - now do table of contents
6802 ;; This can be slow in very large buffers, so indicate action
6803 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6804 (unless ga (org-unlogged-message "CONTENTS..."))
6805 (org-content)
6806 (unless ga (org-unlogged-message "CONTENTS...done"))
6807 (setq org-cycle-global-status 'contents)
6808 (run-hook-with-args 'org-cycle-hook 'contents))
6810 ((and (eq last-command this-command)
6811 (eq org-cycle-global-status 'contents))
6812 ;; We just showed the table of contents - now show everything
6813 (run-hook-with-args 'org-pre-cycle-hook 'all)
6814 (show-all)
6815 (unless ga (org-unlogged-message "SHOW ALL"))
6816 (setq org-cycle-global-status 'all)
6817 (run-hook-with-args 'org-cycle-hook 'all))
6820 ;; Default action: go to overview
6821 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6822 (org-overview)
6823 (unless ga (org-unlogged-message "OVERVIEW"))
6824 (setq org-cycle-global-status 'overview)
6825 (run-hook-with-args 'org-cycle-hook 'overview)))))
6827 (defvar org-called-with-limited-levels nil
6828 "Non-nil when `org-with-limited-levels' is currently active.")
6830 (defun org-cycle-internal-local ()
6831 "Do the local cycling action."
6832 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6833 ;; First, determine end of headline (EOH), end of subtree or item
6834 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6835 (save-excursion
6836 (if (org-at-item-p)
6837 (progn
6838 (beginning-of-line)
6839 (setq struct (org-list-struct))
6840 (setq eoh (point-at-eol))
6841 (setq eos (org-list-get-item-end-before-blank (point) struct))
6842 (setq has-children (org-list-has-child-p (point) struct)))
6843 (org-back-to-heading)
6844 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6845 (setq eos (save-excursion (org-end-of-subtree t t)
6846 (when (bolp) (backward-char)) (point)))
6847 (setq has-children
6848 (or (save-excursion
6849 (let ((level (funcall outline-level)))
6850 (outline-next-heading)
6851 (and (org-at-heading-p t)
6852 (> (funcall outline-level) level))))
6853 (save-excursion
6854 (org-list-search-forward (org-item-beginning-re) eos t)))))
6855 ;; Determine end invisible part of buffer (EOL)
6856 (beginning-of-line 2)
6857 ;; XEmacs doesn't have `next-single-char-property-change'
6858 (if (featurep 'xemacs)
6859 (while (and (not (eobp)) ;; this is like `next-line'
6860 (get-char-property (1- (point)) 'invisible))
6861 (beginning-of-line 2))
6862 (while (and (not (eobp)) ;; this is like `next-line'
6863 (get-char-property (1- (point)) 'invisible))
6864 (goto-char (next-single-char-property-change (point) 'invisible))
6865 (and (eolp) (beginning-of-line 2))))
6866 (setq eol (point)))
6867 ;; Find out what to do next and set `this-command'
6868 (cond
6869 ((= eos eoh)
6870 ;; Nothing is hidden behind this heading
6871 (unless (org-before-first-heading-p)
6872 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6873 (org-unlogged-message "EMPTY ENTRY")
6874 (setq org-cycle-subtree-status nil)
6875 (save-excursion
6876 (goto-char eos)
6877 (outline-next-heading)
6878 (if (outline-invisible-p) (org-flag-heading nil))))
6879 ((and (or (>= eol eos)
6880 (not (string-match "\\S-" (buffer-substring eol eos))))
6881 (or has-children
6882 (not (setq children-skipped
6883 org-cycle-skip-children-state-if-no-children))))
6884 ;; Entire subtree is hidden in one line: children view
6885 (unless (org-before-first-heading-p)
6886 (run-hook-with-args 'org-pre-cycle-hook 'children))
6887 (if (org-at-item-p)
6888 (org-list-set-item-visibility (point-at-bol) struct 'children)
6889 (org-show-entry)
6890 (org-with-limited-levels (show-children))
6891 ;; FIXME: This slows down the func way too much.
6892 ;; How keep drawers hidden in subtree anyway?
6893 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6894 ;; (org-cycle-hide-drawers 'subtree))
6896 ;; Fold every list in subtree to top-level items.
6897 (when (eq org-cycle-include-plain-lists 'integrate)
6898 (save-excursion
6899 (org-back-to-heading)
6900 (while (org-list-search-forward (org-item-beginning-re) eos t)
6901 (beginning-of-line 1)
6902 (let* ((struct (org-list-struct))
6903 (prevs (org-list-prevs-alist struct))
6904 (end (org-list-get-bottom-point struct)))
6905 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6906 (org-list-get-all-items (point) struct prevs))
6907 (goto-char (if (< end eos) end eos)))))))
6908 (org-unlogged-message "CHILDREN")
6909 (save-excursion
6910 (goto-char eos)
6911 (outline-next-heading)
6912 (if (outline-invisible-p) (org-flag-heading nil)))
6913 (setq org-cycle-subtree-status 'children)
6914 (unless (org-before-first-heading-p)
6915 (run-hook-with-args 'org-cycle-hook 'children)))
6916 ((or children-skipped
6917 (and (eq last-command this-command)
6918 (eq org-cycle-subtree-status 'children)))
6919 ;; We just showed the children, or no children are there,
6920 ;; now show everything.
6921 (unless (org-before-first-heading-p)
6922 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6923 (outline-flag-region eoh eos nil)
6924 (org-unlogged-message
6925 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6926 (setq org-cycle-subtree-status 'subtree)
6927 (unless (org-before-first-heading-p)
6928 (run-hook-with-args 'org-cycle-hook 'subtree)))
6930 ;; Default action: hide the subtree.
6931 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6932 (outline-flag-region eoh eos t)
6933 (org-unlogged-message "FOLDED")
6934 (setq org-cycle-subtree-status 'folded)
6935 (unless (org-before-first-heading-p)
6936 (run-hook-with-args 'org-cycle-hook 'folded))))))
6938 ;;;###autoload
6939 (defun org-global-cycle (&optional arg)
6940 "Cycle the global visibility. For details see `org-cycle'.
6941 With \\[universal-argument] prefix arg, switch to startup visibility.
6942 With a numeric prefix, show all headlines up to that level."
6943 (interactive "P")
6944 (let ((org-cycle-include-plain-lists
6945 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6946 (cond
6947 ((integerp arg)
6948 (show-all)
6949 (hide-sublevels arg)
6950 (setq org-cycle-global-status 'contents))
6951 ((equal arg '(4))
6952 (org-set-startup-visibility)
6953 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6955 (org-cycle '(4))))))
6957 (defun org-set-startup-visibility ()
6958 "Set the visibility required by startup options and properties."
6959 (cond
6960 ((eq org-startup-folded t)
6961 (org-overview))
6962 ((eq org-startup-folded 'content)
6963 (org-content))
6964 ((or (eq org-startup-folded 'showeverything)
6965 (eq org-startup-folded nil))
6966 (show-all)))
6967 (unless (eq org-startup-folded 'showeverything)
6968 (if org-hide-block-startup (org-hide-block-all))
6969 (org-set-visibility-according-to-property 'no-cleanup)
6970 (org-cycle-hide-archived-subtrees 'all)
6971 (org-cycle-hide-drawers 'all)
6972 (org-cycle-show-empty-lines t)))
6974 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6975 "Switch subtree visibilities according to :VISIBILITY: property."
6976 (interactive)
6977 (let (org-show-entry-below state)
6978 (save-excursion
6979 (goto-char (point-min))
6980 (while (re-search-forward
6981 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6982 nil t)
6983 (setq state (match-string 1))
6984 (save-excursion
6985 (org-back-to-heading t)
6986 (hide-subtree)
6987 (org-reveal)
6988 (cond
6989 ((equal state '("fold" "folded"))
6990 (hide-subtree))
6991 ((equal state "children")
6992 (org-show-hidden-entry)
6993 (show-children))
6994 ((equal state "content")
6995 (save-excursion
6996 (save-restriction
6997 (org-narrow-to-subtree)
6998 (org-content))))
6999 ((member state '("all" "showall"))
7000 (show-subtree)))))
7001 (unless no-cleanup
7002 (org-cycle-hide-archived-subtrees 'all)
7003 (org-cycle-hide-drawers 'all)
7004 (org-cycle-show-empty-lines 'all)))))
7006 ;; This function uses outline-regexp instead of the more fundamental
7007 ;; org-outline-regexp so that org-cycle-global works outside of Org
7008 ;; buffers, where outline-regexp is needed.
7009 (defun org-overview ()
7010 "Switch to overview mode, showing only top-level headlines.
7011 This shows all headlines with a level equal or greater than the level
7012 of the first headline in the buffer. This is important, because if the
7013 first headline is not level one, then (hide-sublevels 1) gives confusing
7014 results."
7015 (interactive)
7016 (save-excursion
7017 (let ((level
7018 (save-excursion
7019 (goto-char (point-min))
7020 (if (re-search-forward (concat "^" outline-regexp) nil t)
7021 (progn
7022 (goto-char (match-beginning 0))
7023 (funcall outline-level))))))
7024 (and level (hide-sublevels level)))))
7026 (defun org-content (&optional arg)
7027 "Show all headlines in the buffer, like a table of contents.
7028 With numerical argument N, show content up to level N."
7029 (interactive "P")
7030 (org-overview)
7031 (save-excursion
7032 ;; Visit all headings and show their offspring
7033 (and (integerp arg) (org-overview))
7034 (goto-char (point-max))
7035 (catch 'exit
7036 (while (and (progn (condition-case nil
7037 (outline-previous-visible-heading 1)
7038 (error (goto-char (point-min))))
7040 (looking-at org-outline-regexp))
7041 (if (integerp arg)
7042 (show-children (1- arg))
7043 (show-branches))
7044 (if (bobp) (throw 'exit nil))))))
7046 (defun org-optimize-window-after-visibility-change (state)
7047 "Adjust the window after a change in outline visibility.
7048 This function is the default value of the hook `org-cycle-hook'."
7049 (when (get-buffer-window (current-buffer))
7050 (cond
7051 ((eq state 'content) nil)
7052 ((eq state 'all) nil)
7053 ((eq state 'folded) nil)
7054 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7055 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7057 (defun org-remove-empty-overlays-at (pos)
7058 "Remove outline overlays that do not contain non-white stuff."
7059 (mapc
7060 (lambda (o)
7061 (and (eq 'outline (overlay-get o 'invisible))
7062 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7063 (overlay-end o))))
7064 (delete-overlay o)))
7065 (overlays-at pos)))
7067 (defun org-clean-visibility-after-subtree-move ()
7068 "Fix visibility issues after moving a subtree."
7069 ;; First, find a reasonable region to look at:
7070 ;; Start two siblings above, end three below
7071 (let* ((beg (save-excursion
7072 (and (org-get-last-sibling)
7073 (org-get-last-sibling))
7074 (point)))
7075 (end (save-excursion
7076 (and (org-get-next-sibling)
7077 (org-get-next-sibling)
7078 (org-get-next-sibling))
7079 (if (org-at-heading-p)
7080 (point-at-eol)
7081 (point))))
7082 (level (looking-at "\\*+"))
7083 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
7084 (save-excursion
7085 (save-restriction
7086 (narrow-to-region beg end)
7087 (when re
7088 ;; Properly fold already folded siblings
7089 (goto-char (point-min))
7090 (while (re-search-forward re nil t)
7091 (if (and (not (outline-invisible-p))
7092 (save-excursion
7093 (goto-char (point-at-eol)) (outline-invisible-p)))
7094 (hide-entry))))
7095 (org-cycle-show-empty-lines 'overview)
7096 (org-cycle-hide-drawers 'overview)))))
7098 (defun org-cycle-show-empty-lines (state)
7099 "Show empty lines above all visible headlines.
7100 The region to be covered depends on STATE when called through
7101 `org-cycle-hook'. Lisp program can use t for STATE to get the
7102 entire buffer covered. Note that an empty line is only shown if there
7103 are at least `org-cycle-separator-lines' empty lines before the headline."
7104 (when (not (= org-cycle-separator-lines 0))
7105 (save-excursion
7106 (let* ((n (abs org-cycle-separator-lines))
7107 (re (cond
7108 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7109 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7110 (t (let ((ns (number-to-string (- n 2))))
7111 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7112 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7113 beg end b e)
7114 (cond
7115 ((memq state '(overview contents t))
7116 (setq beg (point-min) end (point-max)))
7117 ((memq state '(children folded))
7118 (setq beg (point) end (progn (org-end-of-subtree t t)
7119 (beginning-of-line 2)
7120 (point)))))
7121 (when beg
7122 (goto-char beg)
7123 (while (re-search-forward re end t)
7124 (unless (get-char-property (match-end 1) 'invisible)
7125 (setq e (match-end 1))
7126 (if (< org-cycle-separator-lines 0)
7127 (setq b (save-excursion
7128 (goto-char (match-beginning 0))
7129 (org-back-over-empty-lines)
7130 (if (save-excursion
7131 (goto-char (max (point-min) (1- (point))))
7132 (org-at-heading-p))
7133 (1- (point))
7134 (point))))
7135 (setq b (match-beginning 1)))
7136 (outline-flag-region b e nil)))))))
7137 ;; Never hide empty lines at the end of the file.
7138 (save-excursion
7139 (goto-char (point-max))
7140 (outline-previous-heading)
7141 (outline-end-of-heading)
7142 (if (and (looking-at "[ \t\n]+")
7143 (= (match-end 0) (point-max)))
7144 (outline-flag-region (point) (match-end 0) nil))))
7146 (defun org-show-empty-lines-in-parent ()
7147 "Move to the parent and re-show empty lines before visible headlines."
7148 (save-excursion
7149 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7150 (org-cycle-show-empty-lines context))))
7152 (defun org-files-list ()
7153 "Return `org-agenda-files' list, plus all open org-mode files.
7154 This is useful for operations that need to scan all of a user's
7155 open and agenda-wise Org files."
7156 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7157 (dolist (buf (buffer-list))
7158 (with-current-buffer buf
7159 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7160 (let ((file (expand-file-name (buffer-file-name))))
7161 (unless (member file files)
7162 (push file files))))))
7163 files))
7165 (defsubst org-entry-beginning-position ()
7166 "Return the beginning position of the current entry."
7167 (save-excursion (outline-back-to-heading t) (point)))
7169 (defsubst org-entry-end-position ()
7170 "Return the end position of the current entry."
7171 (save-excursion (outline-next-heading) (point)))
7173 (defun org-cycle-hide-drawers (state &optional exceptions)
7174 "Re-hide all drawers after a visibility state change.
7175 When non-nil, optional argument EXCEPTIONS is a list of strings
7176 specifying which drawers should not be hidden."
7177 (when (and (derived-mode-p 'org-mode)
7178 (not (memq state '(overview folded contents))))
7179 (save-excursion
7180 (let* ((globalp (memq state '(contents all)))
7181 (beg (if globalp (point-min) (point)))
7182 (end (if globalp (point-max)
7183 (if (eq state 'children)
7184 (save-excursion (outline-next-heading) (point))
7185 (org-end-of-subtree t)))))
7186 (goto-char beg)
7187 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7188 (unless (member-ignore-case (match-string 1) exceptions)
7189 (let ((drawer (org-element-at-point)))
7190 (when (memq (org-element-type drawer) '(drawer property-drawer))
7191 (org-flag-drawer t drawer)
7192 ;; Make sure to skip drawer entirely or we might flag
7193 ;; it another time when matching its ending line with
7194 ;; `org-drawer-regexp'.
7195 (goto-char (org-element-property :end drawer))))))))))
7197 (defun org-cycle-hide-inline-tasks (state)
7198 "Re-hide inline tasks when switching to 'contents or 'children
7199 visibility state."
7200 (case state
7201 (contents
7202 (when (org-bound-and-true-p org-inlinetask-min-level)
7203 (hide-sublevels (1- org-inlinetask-min-level))))
7204 (children
7205 (when (featurep 'org-inlinetask)
7206 (save-excursion
7207 (while (and (outline-next-heading)
7208 (org-inlinetask-at-task-p))
7209 (org-inlinetask-toggle-visibility)
7210 (org-inlinetask-goto-end)))))))
7212 (defun org-flag-drawer (flag &optional element)
7213 "When FLAG is non-nil, hide the drawer we are at.
7214 Otherwise make it visible. When optional argument ELEMENT is
7215 a parsed drawer, as returned by `org-element-at-point', hide or
7216 show that drawer instead."
7217 (when (save-excursion
7218 (beginning-of-line)
7219 (org-looking-at-p org-drawer-regexp))
7220 (let ((drawer (or element (org-element-at-point))))
7221 (when (memq (org-element-type drawer) '(drawer property-drawer))
7222 (let ((post (org-element-property :post-affiliated drawer)))
7223 (save-excursion
7224 (outline-flag-region
7225 (progn (goto-char post) (line-end-position))
7226 (progn (goto-char (org-element-property :end drawer))
7227 (skip-chars-backward " \r\t\n")
7228 (line-end-position))
7229 flag))
7230 ;; When the drawer is hidden away, make sure point lies in
7231 ;; a visible part of the buffer.
7232 (when (and flag (> (line-beginning-position) post))
7233 (goto-char post)))))))
7235 (defun org-subtree-end-visible-p ()
7236 "Is the end of the current subtree visible?"
7237 (pos-visible-in-window-p
7238 (save-excursion (org-end-of-subtree t) (point))))
7240 (defun org-first-headline-recenter ()
7241 "Move cursor to the first headline and recenter the headline."
7242 (goto-char (point-min))
7243 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7244 (set-window-start (selected-window) (point-at-bol))))
7246 ;;; Saving and restoring visibility
7248 (defun org-outline-overlay-data (&optional use-markers)
7249 "Return a list of the locations of all outline overlays.
7250 These are overlays with the `invisible' property value `outline'.
7251 The return value is a list of cons cells, with start and stop
7252 positions for each overlay.
7253 If USE-MARKERS is set, return the positions as markers."
7254 (let (beg end)
7255 (save-excursion
7256 (save-restriction
7257 (widen)
7258 (delq nil
7259 (mapcar (lambda (o)
7260 (when (eq (overlay-get o 'invisible) 'outline)
7261 (setq beg (overlay-start o)
7262 end (overlay-end o))
7263 (and beg end (> end beg)
7264 (if use-markers
7265 (cons (copy-marker beg)
7266 (copy-marker end t))
7267 (cons beg end)))))
7268 (overlays-in (point-min) (point-max))))))))
7270 (defun org-set-outline-overlay-data (data)
7271 "Create visibility overlays for all positions in DATA.
7272 DATA should have been made by `org-outline-overlay-data'."
7273 (let (o)
7274 (save-excursion
7275 (save-restriction
7276 (widen)
7277 (show-all)
7278 (mapc (lambda (c)
7279 (outline-flag-region (car c) (cdr c) t))
7280 data)))))
7282 ;;; Folding of blocks
7284 (defvar org-hide-block-overlays nil
7285 "Overlays hiding blocks.")
7286 (make-variable-buffer-local 'org-hide-block-overlays)
7288 (defun org-block-map (function &optional start end)
7289 "Call FUNCTION at the head of all source blocks in the current buffer.
7290 Optional arguments START and END can be used to limit the range."
7291 (let ((start (or start (point-min)))
7292 (end (or end (point-max))))
7293 (save-excursion
7294 (goto-char start)
7295 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7296 (save-excursion
7297 (save-match-data
7298 (goto-char (match-beginning 0))
7299 (funcall function)))))))
7301 (defun org-hide-block-toggle-all ()
7302 "Toggle the visibility of all blocks in the current buffer."
7303 (org-block-map 'org-hide-block-toggle))
7305 (defun org-hide-block-all ()
7306 "Fold all blocks in the current buffer."
7307 (interactive)
7308 (org-show-block-all)
7309 (org-block-map 'org-hide-block-toggle-maybe))
7311 (defun org-show-block-all ()
7312 "Unfold all blocks in the current buffer."
7313 (interactive)
7314 (mapc 'delete-overlay org-hide-block-overlays)
7315 (setq org-hide-block-overlays nil))
7317 (defun org-hide-block-toggle-maybe ()
7318 "Toggle visibility of block at point."
7319 (interactive)
7320 (let ((case-fold-search t))
7321 (if (save-excursion
7322 (beginning-of-line 1)
7323 (looking-at org-block-regexp))
7324 (progn (org-hide-block-toggle)
7325 t) ;; to signal that we took action
7326 nil))) ;; to signal that we did not
7328 (defun org-hide-block-toggle (&optional force)
7329 "Toggle the visibility of the current block.
7330 When optional argument FORCE is `off', make block visible. If it
7331 is non-nil, hide it unconditionally."
7332 (interactive)
7333 (let ((element (org-element-at-point)))
7334 (unless (memq (org-element-type element)
7335 '(center-block comment-block example-block quote-block
7336 src-block verse-block))
7337 (user-error "Not at a block"))
7338 (let* ((start (save-excursion
7339 (goto-char (org-element-property :post-affiliated element))
7340 (line-end-position)))
7341 (end (save-excursion
7342 (goto-char (org-element-property :end element))
7343 (skip-chars-backward " \r\t\n")
7344 (line-end-position)))
7345 (overlays (overlays-at start)))
7346 (cond
7347 ;; Do nothing when not before or at the block opening line or
7348 ;; at the block closing line.
7349 ((let ((eol (line-end-position)))
7350 (and (> eol start) (/= eol end))))
7351 ((and (not (eq force 'off))
7352 (not (memq t (mapcar
7353 (lambda (o)
7354 (eq (overlay-get o 'invisible) 'org-hide-block))
7355 overlays))))
7356 (let ((ov (make-overlay start end)))
7357 (overlay-put ov 'invisible 'org-hide-block)
7358 ;; Make the block accessible to `isearch'.
7359 (overlay-put
7360 ov 'isearch-open-invisible
7361 (lambda (ov)
7362 (when (memq ov org-hide-block-overlays)
7363 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7364 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7365 (delete-overlay ov))))
7366 (push ov org-hide-block-overlays)
7367 ;; When the block is hidden away, make sure point is left in
7368 ;; a visible part of the buffer.
7369 (when (> (line-beginning-position) start)
7370 (goto-char start)
7371 (beginning-of-line))))
7372 ((or (not force) (eq force 'off))
7373 (dolist (ov overlays)
7374 (when (memq ov org-hide-block-overlays)
7375 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7376 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7377 (delete-overlay ov))))))))
7379 ;; org-tab-after-check-for-cycling-hook
7380 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7381 ;; Remove overlays when changing major mode
7382 (add-hook 'org-mode-hook
7383 (lambda () (org-add-hook 'change-major-mode-hook
7384 'org-show-block-all 'append 'local)))
7386 ;;; Org-goto
7388 (defvar org-goto-window-configuration nil)
7389 (defvar org-goto-marker nil)
7390 (defvar org-goto-map)
7391 (defun org-goto-map ()
7392 "Set the keymap `org-goto'."
7393 (setq org-goto-map
7394 (let ((map (make-sparse-keymap)))
7395 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7396 mouse-drag-region universal-argument org-occur))
7397 cmd)
7398 (while (setq cmd (pop cmds))
7399 (substitute-key-definition cmd cmd map global-map)))
7400 (suppress-keymap map)
7401 (org-defkey map "\C-m" 'org-goto-ret)
7402 (org-defkey map [(return)] 'org-goto-ret)
7403 (org-defkey map [(left)] 'org-goto-left)
7404 (org-defkey map [(right)] 'org-goto-right)
7405 (org-defkey map [(control ?g)] 'org-goto-quit)
7406 (org-defkey map "\C-i" 'org-cycle)
7407 (org-defkey map [(tab)] 'org-cycle)
7408 (org-defkey map [(down)] 'outline-next-visible-heading)
7409 (org-defkey map [(up)] 'outline-previous-visible-heading)
7410 (if org-goto-auto-isearch
7411 (if (fboundp 'define-key-after)
7412 (define-key-after map [t] 'org-goto-local-auto-isearch)
7413 nil)
7414 (org-defkey map "q" 'org-goto-quit)
7415 (org-defkey map "n" 'outline-next-visible-heading)
7416 (org-defkey map "p" 'outline-previous-visible-heading)
7417 (org-defkey map "f" 'outline-forward-same-level)
7418 (org-defkey map "b" 'outline-backward-same-level)
7419 (org-defkey map "u" 'outline-up-heading))
7420 (org-defkey map "/" 'org-occur)
7421 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7422 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7423 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7424 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7425 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7426 map)))
7428 (defconst org-goto-help
7429 "Browse buffer copy, to find location or copy text.%s
7430 RET=jump to location C-g=quit and return to previous location
7431 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7433 (defvar org-goto-start-pos) ; dynamically scoped parameter
7435 (defun org-goto (&optional alternative-interface)
7436 "Look up a different location in the current file, keeping current visibility.
7438 When you want look-up or go to a different location in a
7439 document, the fastest way is often to fold the entire buffer and
7440 then dive into the tree. This method has the disadvantage, that
7441 the previous location will be folded, which may not be what you
7442 want.
7444 This command works around this by showing a copy of the current
7445 buffer in an indirect buffer, in overview mode. You can dive
7446 into the tree in that copy, use org-occur and incremental search
7447 to find a location. When pressing RET or `Q', the command
7448 returns to the original buffer in which the visibility is still
7449 unchanged. After RET it will also jump to the location selected
7450 in the indirect buffer and expose the headline hierarchy above.
7452 With a prefix argument, use the alternative interface: e.g. if
7453 `org-goto-interface' is 'outline use 'outline-path-completion."
7454 (interactive "P")
7455 (org-goto-map)
7456 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7457 (org-refile-use-outline-path t)
7458 (org-refile-target-verify-function nil)
7459 (interface
7460 (if (not alternative-interface)
7461 org-goto-interface
7462 (if (eq org-goto-interface 'outline)
7463 'outline-path-completion
7464 'outline)))
7465 (org-goto-start-pos (point))
7466 (selected-point
7467 (if (eq interface 'outline)
7468 (car (org-get-location (current-buffer) org-goto-help))
7469 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7470 (org-refile-check-position pa)
7471 (nth 3 pa)))))
7472 (if selected-point
7473 (progn
7474 (org-mark-ring-push org-goto-start-pos)
7475 (goto-char selected-point)
7476 (if (or (outline-invisible-p) (org-invisible-p2))
7477 (org-show-context 'org-goto)))
7478 (message "Quit"))))
7480 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7481 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7482 (defvar org-goto-local-auto-isearch-map) ; defined below
7484 (defun org-get-location (buf help)
7485 "Let the user select a location in the Org-mode buffer BUF.
7486 This function uses a recursive edit. It returns the selected position
7487 or nil."
7488 (org-no-popups
7489 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7490 (isearch-hide-immediately nil)
7491 (isearch-search-fun-function
7492 (lambda () 'org-goto-local-search-headings))
7493 (org-goto-selected-point org-goto-exit-command))
7494 (save-excursion
7495 (save-window-excursion
7496 (delete-other-windows)
7497 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7498 (org-pop-to-buffer-same-window
7499 (condition-case nil
7500 (make-indirect-buffer (current-buffer) "*org-goto*")
7501 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7502 (with-output-to-temp-buffer "*Org Help*"
7503 (princ (format help (if org-goto-auto-isearch
7504 " Just type for auto-isearch."
7505 " n/p/f/b/u to navigate, q to quit."))))
7506 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7507 (setq buffer-read-only nil)
7508 (let ((org-startup-truncated t)
7509 (org-startup-folded nil)
7510 (org-startup-align-all-tables nil))
7511 (org-mode)
7512 (org-overview))
7513 (setq buffer-read-only t)
7514 (if (and (boundp 'org-goto-start-pos)
7515 (integer-or-marker-p org-goto-start-pos))
7516 (let ((org-show-hierarchy-above t)
7517 (org-show-siblings t)
7518 (org-show-following-heading t))
7519 (goto-char org-goto-start-pos)
7520 (and (outline-invisible-p) (org-show-context)))
7521 (goto-char (point-min)))
7522 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7523 (message "Select location and press RET")
7524 (use-local-map org-goto-map)
7525 (recursive-edit)))
7526 (kill-buffer "*org-goto*")
7527 (cons org-goto-selected-point org-goto-exit-command))))
7529 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7530 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7531 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7532 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7534 (defun org-goto-local-search-headings (string bound noerror)
7535 "Search and make sure that any matches are in headlines."
7536 (catch 'return
7537 (while (if isearch-forward
7538 (search-forward string bound noerror)
7539 (search-backward string bound noerror))
7540 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7541 (and (member :headline context)
7542 (not (member :tags context))))
7543 (throw 'return (point))))))
7545 (defun org-goto-local-auto-isearch ()
7546 "Start isearch."
7547 (interactive)
7548 (goto-char (point-min))
7549 (let ((keys (this-command-keys)))
7550 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7551 (isearch-mode t)
7552 (isearch-process-search-char (string-to-char keys)))))
7554 (defun org-goto-ret (&optional arg)
7555 "Finish `org-goto' by going to the new location."
7556 (interactive "P")
7557 (setq org-goto-selected-point (point)
7558 org-goto-exit-command 'return)
7559 (throw 'exit nil))
7561 (defun org-goto-left ()
7562 "Finish `org-goto' by going to the new location."
7563 (interactive)
7564 (if (org-at-heading-p)
7565 (progn
7566 (beginning-of-line 1)
7567 (setq org-goto-selected-point (point)
7568 org-goto-exit-command 'left)
7569 (throw 'exit nil))
7570 (user-error "Not on a heading")))
7572 (defun org-goto-right ()
7573 "Finish `org-goto' by going to the new location."
7574 (interactive)
7575 (if (org-at-heading-p)
7576 (progn
7577 (setq org-goto-selected-point (point)
7578 org-goto-exit-command 'right)
7579 (throw 'exit nil))
7580 (user-error "Not on a heading")))
7582 (defun org-goto-quit ()
7583 "Finish `org-goto' without cursor motion."
7584 (interactive)
7585 (setq org-goto-selected-point nil)
7586 (setq org-goto-exit-command 'quit)
7587 (throw 'exit nil))
7589 ;;; Indirect buffer display of subtrees
7591 (defvar org-indirect-dedicated-frame nil
7592 "This is the frame being used for indirect tree display.")
7593 (defvar org-last-indirect-buffer nil)
7595 (defun org-tree-to-indirect-buffer (&optional arg)
7596 "Create indirect buffer and narrow it to current subtree.
7597 With a numerical prefix ARG, go up to this level and then take that tree.
7598 If ARG is negative, go up that many levels.
7600 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7601 indirect buffer previously made with this command, to avoid proliferation of
7602 indirect buffers. However, when you call the command with a \
7603 \\[universal-argument] prefix, or
7604 when `org-indirect-buffer-display' is `new-frame', the last buffer
7605 is kept so that you can work with several indirect buffers at the same time.
7606 If `org-indirect-buffer-display' is `dedicated-frame', the \
7607 \\[universal-argument] prefix also
7608 requests that a new frame be made for the new buffer, so that the dedicated
7609 frame is not changed."
7610 (interactive "P")
7611 (let ((cbuf (current-buffer))
7612 (cwin (selected-window))
7613 (pos (point))
7614 beg end level heading ibuf)
7615 (save-excursion
7616 (org-back-to-heading t)
7617 (when (numberp arg)
7618 (setq level (org-outline-level))
7619 (if (< arg 0) (setq arg (+ level arg)))
7620 (while (> (setq level (org-outline-level)) arg)
7621 (org-up-heading-safe)))
7622 (setq beg (point)
7623 heading (org-get-heading))
7624 (org-end-of-subtree t t)
7625 (if (org-at-heading-p) (backward-char 1))
7626 (setq end (point)))
7627 (if (and (buffer-live-p org-last-indirect-buffer)
7628 (not (eq org-indirect-buffer-display 'new-frame))
7629 (not arg))
7630 (kill-buffer org-last-indirect-buffer))
7631 (setq ibuf (org-get-indirect-buffer cbuf heading)
7632 org-last-indirect-buffer ibuf)
7633 (cond
7634 ((or (eq org-indirect-buffer-display 'new-frame)
7635 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7636 (select-frame (make-frame))
7637 (delete-other-windows)
7638 (org-pop-to-buffer-same-window ibuf)
7639 (org-set-frame-title heading))
7640 ((eq org-indirect-buffer-display 'dedicated-frame)
7641 (raise-frame
7642 (select-frame (or (and org-indirect-dedicated-frame
7643 (frame-live-p org-indirect-dedicated-frame)
7644 org-indirect-dedicated-frame)
7645 (setq org-indirect-dedicated-frame (make-frame)))))
7646 (delete-other-windows)
7647 (org-pop-to-buffer-same-window ibuf)
7648 (org-set-frame-title (concat "Indirect: " heading)))
7649 ((eq org-indirect-buffer-display 'current-window)
7650 (org-pop-to-buffer-same-window ibuf))
7651 ((eq org-indirect-buffer-display 'other-window)
7652 (pop-to-buffer ibuf))
7653 (t (error "Invalid value")))
7654 (if (featurep 'xemacs)
7655 (save-excursion (org-mode) (turn-on-font-lock)))
7656 (narrow-to-region beg end)
7657 (show-all)
7658 (goto-char pos)
7659 (run-hook-with-args 'org-cycle-hook 'all)
7660 (and (window-live-p cwin) (select-window cwin))))
7662 (defun org-get-indirect-buffer (&optional buffer heading)
7663 (setq buffer (or buffer (current-buffer)))
7664 (let ((n 1) (base (buffer-name buffer)) bname)
7665 (while (buffer-live-p
7666 (get-buffer
7667 (setq bname
7668 (concat base "-"
7669 (if heading (concat heading "-" (number-to-string n))
7670 (number-to-string n))))))
7671 (setq n (1+ n)))
7672 (condition-case nil
7673 (make-indirect-buffer buffer bname 'clone)
7674 (error (make-indirect-buffer buffer bname)))))
7676 (defun org-set-frame-title (title)
7677 "Set the title of the current frame to the string TITLE."
7678 ;; FIXME: how to name a single frame in XEmacs???
7679 (unless (featurep 'xemacs)
7680 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7682 ;;;; Structure editing
7684 ;;; Inserting headlines
7686 (defun org-previous-line-empty-p (&optional next)
7687 "Is the previous line a blank line?
7688 When NEXT is non-nil, check the next line instead."
7689 (save-excursion
7690 (and (not (bobp))
7691 (or (beginning-of-line (if next 2 0)) t)
7692 (save-match-data
7693 (looking-at "[ \t]*$")))))
7695 (defun org-insert-heading (&optional arg invisible-ok)
7696 "Insert a new heading or an item with the same depth at point.
7698 If point is at the beginning of a heading or a list item, insert
7699 a new heading or a new item above the current one. If point is
7700 at the beginning of a normal line, turn the line into a heading.
7702 If point is in the middle of a headline or a list item, split the
7703 headline or the item and create a new headline/item with the text
7704 in the current line after point \(see `org-M-RET-may-split-line'
7705 on how to modify this behavior).
7707 With one universal prefix argument, set the user option
7708 `org-insert-heading-respect-content' to t for the duration of
7709 the command. This modifies the behavior described above in this
7710 ways: on list items and at the beginning of normal lines, force
7711 the insertion of a heading after the current subtree.
7713 With two universal prefix arguments, insert the heading at the
7714 end of the grandparent subtree. For example, if point is within
7715 a 2nd-level heading, then it will insert a 2nd-level heading at
7716 the end of the 1st-level parent heading.
7718 If point is at the beginning of a headline, insert a sibling
7719 before the current headline. If point is not at the beginning,
7720 split the line and create a new headline with the text in the
7721 current line after point \(see `org-M-RET-may-split-line' on how
7722 to modify this behavior).
7724 If point is at the beginning of a normal line, turn this line
7725 into a heading.
7727 When INVISIBLE-OK is set, stop at invisible headlines when going
7728 back. This is important for non-interactive uses of the
7729 command."
7730 (interactive "P")
7731 (if (org-called-interactively-p 'any) (org-reveal))
7732 (let ((itemp (org-in-item-p))
7733 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7734 (respect-content (or org-insert-heading-respect-content
7735 (equal arg '(4))))
7736 (initial-content "")
7737 (adjust-empty-lines t))
7739 (cond
7741 ((or (= (buffer-size) 0)
7742 (and (not (save-excursion
7743 (and (ignore-errors (org-back-to-heading invisible-ok))
7744 (org-at-heading-p))))
7745 (or arg (not itemp))))
7746 ;; At beginning of buffer or so high up that only a heading
7747 ;; makes sense.
7748 (cond ((and (bolp) (not respect-content)) (insert "* "))
7749 ((not respect-content)
7750 (unless may-split (end-of-line))
7751 (insert "\n* "))
7752 ((re-search-forward org-outline-regexp-bol nil t)
7753 (beginning-of-line)
7754 (insert "* \n")
7755 (backward-char))
7756 (t (goto-char (point-max))
7757 (insert "\n* ")))
7758 (run-hooks 'org-insert-heading-hook))
7760 ((and itemp (not (member arg '((4) (16)))))
7761 ;; Insert an item
7762 (org-insert-item))
7765 ;; Maybe move at the end of the subtree
7766 (when (equal arg '(16))
7767 (org-up-heading-safe)
7768 (org-end-of-subtree t))
7769 ;; Insert a heading
7770 (save-restriction
7771 (widen)
7772 (let* ((level nil)
7773 (on-heading (org-at-heading-p))
7774 (empty-line-p (if on-heading
7775 (org-previous-line-empty-p)
7776 ;; We will decide later
7777 nil))
7778 ;; Get a level string to fall back on
7779 (fix-level
7780 (if (org-before-first-heading-p) "*"
7781 (save-excursion
7782 (org-back-to-heading t)
7783 (if (org-previous-line-empty-p) (setq empty-line-p t))
7784 (looking-at org-outline-regexp)
7785 (make-string (1- (length (match-string 0))) ?*))))
7786 (stars
7787 (save-excursion
7788 (condition-case nil
7789 (progn
7790 (org-back-to-heading invisible-ok)
7791 (when (and (not on-heading)
7792 (featurep 'org-inlinetask)
7793 (integerp org-inlinetask-min-level)
7794 (>= (length (match-string 0))
7795 org-inlinetask-min-level))
7796 ;; Find a heading level before the inline task
7797 (while (and (setq level (org-up-heading-safe))
7798 (>= level org-inlinetask-min-level)))
7799 (if (org-at-heading-p)
7800 (org-back-to-heading invisible-ok)
7801 (error "This should not happen")))
7802 (unless (and (save-excursion
7803 (save-match-data
7804 (org-backward-heading-same-level
7805 1 invisible-ok))
7806 (= (point) (match-beginning 0)))
7807 (not (org-previous-line-empty-p t)))
7808 (setq empty-line-p (or empty-line-p
7809 (org-previous-line-empty-p))))
7810 (match-string 0))
7811 (error (or fix-level "* ")))))
7812 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7813 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7814 pos hide-previous previous-pos)
7816 ;; If we insert after content, move there and clean up whitespace
7817 (when (and respect-content
7818 (not (org-looking-at-p org-outline-regexp-bol)))
7819 (if (not (org-before-first-heading-p))
7820 (org-end-of-subtree nil t)
7821 (re-search-forward org-outline-regexp-bol)
7822 (beginning-of-line 0))
7823 (skip-chars-backward " \r\n")
7824 (and (not (looking-back "^\\*+"))
7825 (looking-at "[ \t]+") (replace-match ""))
7826 (unless (eobp) (forward-char 1))
7827 (when (looking-at "^\\*")
7828 (unless (bobp) (backward-char 1))
7829 (insert "\n")))
7831 ;; If we are splitting, grab the text that should be moved to the new headline
7832 (when may-split
7833 (if (org-on-heading-p)
7834 ;; This is a heading, we split intelligently (keeping tags)
7835 (let ((pos (point)))
7836 (goto-char (point-at-bol))
7837 (unless (looking-at org-complex-heading-regexp)
7838 (error "This should not happen"))
7839 (when (and (match-beginning 4)
7840 (> pos (match-beginning 4))
7841 (< pos (match-end 4)))
7842 (setq initial-content (buffer-substring pos (match-end 4)))
7843 (goto-char pos)
7844 (delete-region (point) (match-end 4))
7845 (if (looking-at "[ \t]*$")
7846 (replace-match "")
7847 (insert (make-string (length initial-content) ?\ )))
7848 (setq initial-content (org-trim initial-content)))
7849 (goto-char pos))
7850 ;; a normal line
7851 (setq initial-content
7852 (org-trim (buffer-substring (point) (point-at-eol))))
7853 (delete-region (point) (point-at-eol))))
7855 ;; If we are at the beginning of the line, insert before it. Else after
7856 (cond
7857 ((and (bolp) (looking-at "[ \t]*$")))
7858 ((and (bolp) (not (looking-at "[ \t]*$")))
7859 (open-line 1))
7861 (goto-char (point-at-eol))
7862 (insert "\n")))
7864 ;; Insert the new heading
7865 (insert stars)
7866 (just-one-space)
7867 (insert initial-content)
7868 (when adjust-empty-lines
7869 (if (or (not blank)
7870 (and blank (not (org-previous-line-empty-p))))
7871 (org-N-empty-lines-before-current (if blank 1 0))))
7872 (run-hooks 'org-insert-heading-hook)))))))
7874 (defun org-N-empty-lines-before-current (N)
7875 "Make the number of empty lines before current exactly N.
7876 So this will delete or add empty lines."
7877 (save-excursion
7878 (goto-char (point-at-bol))
7879 (if (looking-back "\\s-+" nil 'greedy)
7880 (replace-match ""))
7881 (or (bobp) (insert "\n"))
7882 (while (> N 0)
7883 (insert "\n")
7884 (setq N (1- N)))))
7886 (defun org-get-heading (&optional no-tags no-todo)
7887 "Return the heading of the current entry, without the stars.
7888 When NO-TAGS is non-nil, don't include tags.
7889 When NO-TODO is non-nil, don't include TODO keywords."
7890 (save-excursion
7891 (org-back-to-heading t)
7892 (cond
7893 ((and no-tags no-todo)
7894 (looking-at org-complex-heading-regexp)
7895 (match-string 4))
7896 (no-tags
7897 (looking-at (concat org-outline-regexp
7898 "\\(.*?\\)"
7899 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7900 (match-string 1))
7901 (no-todo
7902 (looking-at org-todo-line-regexp)
7903 (match-string 3))
7904 (t (looking-at org-heading-regexp)
7905 (match-string 2)))))
7907 (defvar orgstruct-mode) ; defined below
7909 (defun org-heading-components ()
7910 "Return the components of the current heading.
7911 This is a list with the following elements:
7912 - the level as an integer
7913 - the reduced level, different if `org-odd-levels-only' is set.
7914 - the TODO keyword, or nil
7915 - the priority character, like ?A, or nil if no priority is given
7916 - the headline text itself, or the tags string if no headline text
7917 - the tags string, or nil."
7918 (save-excursion
7919 (org-back-to-heading t)
7920 (if (let (case-fold-search)
7921 (looking-at
7922 (if orgstruct-mode
7923 org-heading-regexp
7924 org-complex-heading-regexp)))
7925 (if orgstruct-mode
7926 (list (length (match-string 1))
7927 (org-reduced-level (length (match-string 1)))
7930 (match-string 2)
7931 nil)
7932 (list (length (match-string 1))
7933 (org-reduced-level (length (match-string 1)))
7934 (org-match-string-no-properties 2)
7935 (and (match-end 3) (aref (match-string 3) 2))
7936 (org-match-string-no-properties 4)
7937 (org-match-string-no-properties 5))))))
7939 (defun org-get-entry ()
7940 "Get the entry text, after heading, entire subtree."
7941 (save-excursion
7942 (org-back-to-heading t)
7943 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7945 (defun org-insert-heading-after-current ()
7946 "Insert a new heading with same level as current, after current subtree."
7947 (interactive)
7948 (org-back-to-heading)
7949 (org-insert-heading)
7950 (org-move-subtree-down)
7951 (end-of-line 1))
7953 (defun org-insert-heading-respect-content (&optional invisible-ok)
7954 "Insert heading with `org-insert-heading-respect-content' set to t."
7955 (interactive)
7956 (org-insert-heading '(4) invisible-ok))
7958 (defun org-insert-todo-heading-respect-content (&optional force-state)
7959 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7960 (interactive)
7961 (org-insert-todo-heading force-state '(4)))
7963 (defun org-insert-todo-heading (arg &optional force-heading)
7964 "Insert a new heading with the same level and TODO state as current heading.
7965 If the heading has no TODO state, or if the state is DONE, use the first
7966 state (TODO by default). Also with one prefix arg, force first state. With
7967 two prefix args, force inserting at the end of the parent subtree."
7968 (interactive "P")
7969 (when (or force-heading (not (org-insert-item 'checkbox)))
7970 (org-insert-heading (or (and (equal arg '(16)) '(16))
7971 force-heading))
7972 (save-excursion
7973 (org-back-to-heading)
7974 (outline-previous-heading)
7975 (looking-at org-todo-line-regexp))
7976 (let*
7977 ((new-mark-x
7978 (if (or (equal arg '(4))
7979 (not (match-beginning 2))
7980 (member (match-string 2) org-done-keywords))
7981 (car org-todo-keywords-1)
7982 (match-string 2)))
7983 (new-mark
7985 (run-hook-with-args-until-success
7986 'org-todo-get-default-hook new-mark-x nil)
7987 new-mark-x)))
7988 (beginning-of-line 1)
7989 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7990 (if org-treat-insert-todo-heading-as-state-change
7991 (org-todo new-mark)
7992 (insert new-mark " "))))
7993 (when org-provide-todo-statistics
7994 (org-update-parent-todo-statistics))))
7996 (defun org-insert-subheading (arg)
7997 "Insert a new subheading and demote it.
7998 Works for outline headings and for plain lists alike."
7999 (interactive "P")
8000 (org-insert-heading arg)
8001 (cond
8002 ((org-at-heading-p) (org-do-demote))
8003 ((org-at-item-p) (org-indent-item))))
8005 (defun org-insert-todo-subheading (arg)
8006 "Insert a new subheading with TODO keyword or checkbox and demote it.
8007 Works for outline headings and for plain lists alike."
8008 (interactive "P")
8009 (org-insert-todo-heading arg)
8010 (cond
8011 ((org-at-heading-p) (org-do-demote))
8012 ((org-at-item-p) (org-indent-item))))
8014 ;;; Promotion and Demotion
8016 (defvar org-after-demote-entry-hook nil
8017 "Hook run after an entry has been demoted.
8018 The cursor will be at the beginning of the entry.
8019 When a subtree is being demoted, the hook will be called for each node.")
8021 (defvar org-after-promote-entry-hook nil
8022 "Hook run after an entry has been promoted.
8023 The cursor will be at the beginning of the entry.
8024 When a subtree is being promoted, the hook will be called for each node.")
8026 (defun org-promote-subtree ()
8027 "Promote the entire subtree.
8028 See also `org-promote'."
8029 (interactive)
8030 (save-excursion
8031 (org-with-limited-levels (org-map-tree 'org-promote)))
8032 (org-fix-position-after-promote))
8034 (defun org-demote-subtree ()
8035 "Demote the entire subtree. See `org-demote'.
8036 See also `org-promote'."
8037 (interactive)
8038 (save-excursion
8039 (org-with-limited-levels (org-map-tree 'org-demote)))
8040 (org-fix-position-after-promote))
8043 (defun org-do-promote ()
8044 "Promote the current heading higher up the tree.
8045 If the region is active in `transient-mark-mode', promote all headings
8046 in the region."
8047 (interactive)
8048 (save-excursion
8049 (if (org-region-active-p)
8050 (org-map-region 'org-promote (region-beginning) (region-end))
8051 (org-promote)))
8052 (org-fix-position-after-promote))
8054 (defun org-do-demote ()
8055 "Demote the current heading lower down the tree.
8056 If the region is active in `transient-mark-mode', demote all headings
8057 in the region."
8058 (interactive)
8059 (save-excursion
8060 (if (org-region-active-p)
8061 (org-map-region 'org-demote (region-beginning) (region-end))
8062 (org-demote)))
8063 (org-fix-position-after-promote))
8065 (defun org-fix-position-after-promote ()
8066 "Make sure that after pro/demotion cursor position is right."
8067 (let ((pos (point)))
8068 (when (save-excursion
8069 (beginning-of-line 1)
8070 (looking-at org-todo-line-regexp)
8071 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8072 (cond ((eobp) (insert " "))
8073 ((eolp) (insert " "))
8074 ((equal (char-after) ?\ ) (forward-char 1))))))
8076 (defun org-current-level ()
8077 "Return the level of the current entry, or nil if before the first headline.
8078 The level is the number of stars at the beginning of the headline."
8079 (save-excursion
8080 (org-with-limited-levels
8081 (if (ignore-errors (org-back-to-heading t))
8082 (funcall outline-level)))))
8084 (defun org-get-previous-line-level ()
8085 "Return the outline depth of the last headline before the current line.
8086 Returns 0 for the first headline in the buffer, and nil if before the
8087 first headline."
8088 (and (org-current-level)
8089 (or (and (/= (line-beginning-position) (point-min))
8090 (save-excursion (beginning-of-line 0) (org-current-level)))
8091 0)))
8093 (defun org-reduced-level (l)
8094 "Compute the effective level of a heading.
8095 This takes into account the setting of `org-odd-levels-only'."
8096 (cond
8097 ((zerop l) 0)
8098 (org-odd-levels-only (1+ (floor (/ l 2))))
8099 (t l)))
8101 (defun org-level-increment ()
8102 "Return the number of stars that will be added or removed at a
8103 time to headlines when structure editing, based on the value of
8104 `org-odd-levels-only'."
8105 (if org-odd-levels-only 2 1))
8107 (defun org-get-valid-level (level &optional change)
8108 "Rectify a level change under the influence of `org-odd-levels-only'
8109 LEVEL is a current level, CHANGE is by how much the level should be
8110 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8111 even level numbers will become the next higher odd number."
8112 (if org-odd-levels-only
8113 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8114 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8115 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8116 (max 1 (+ level (or change 0)))))
8118 (if (boundp 'define-obsolete-function-alias)
8119 (if (or (featurep 'xemacs) (< emacs-major-version 23))
8120 (define-obsolete-function-alias 'org-get-legal-level
8121 'org-get-valid-level)
8122 (define-obsolete-function-alias 'org-get-legal-level
8123 'org-get-valid-level "23.1")))
8125 (defun org-promote ()
8126 "Promote the current heading higher up the tree.
8127 If the region is active in `transient-mark-mode', promote all headings
8128 in the region."
8129 (org-back-to-heading t)
8130 (let* ((level (save-match-data (funcall outline-level)))
8131 (after-change-functions (remove 'flyspell-after-change-function
8132 after-change-functions))
8133 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8134 (diff (abs (- level (length up-head) -1))))
8135 (cond ((and (= level 1) org-called-with-limited-levels
8136 org-allow-promoting-top-level-subtree)
8137 (replace-match "# " nil t))
8138 ((= level 1)
8139 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8140 (t (replace-match up-head nil t)))
8141 ;; Fixup tag positioning
8142 (unless (= level 1)
8143 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8144 (if org-adapt-indentation (org-fixup-indentation (- diff))))
8145 (run-hooks 'org-after-promote-entry-hook)))
8147 (defun org-demote ()
8148 "Demote the current heading lower down the tree.
8149 If the region is active in `transient-mark-mode', demote all headings
8150 in the region."
8151 (org-back-to-heading t)
8152 (let* ((level (save-match-data (funcall outline-level)))
8153 (after-change-functions (remove 'flyspell-after-change-function
8154 after-change-functions))
8155 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8156 (diff (abs (- level (length down-head) -1))))
8157 (replace-match down-head nil t)
8158 ;; Fixup tag positioning
8159 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
8160 (if org-adapt-indentation (org-fixup-indentation diff))
8161 (run-hooks 'org-after-demote-entry-hook)))
8163 (defun org-cycle-level ()
8164 "Cycle the level of an empty headline through possible states.
8165 This goes first to child, then to parent, level, then up the hierarchy.
8166 After top level, it switches back to sibling level."
8167 (interactive)
8168 (let ((org-adapt-indentation nil))
8169 (when (org-point-at-end-of-empty-headline)
8170 (setq this-command 'org-cycle-level) ; Only needed for caching
8171 (let ((cur-level (org-current-level))
8172 (prev-level (org-get-previous-line-level)))
8173 (cond
8174 ;; If first headline in file, promote to top-level.
8175 ((= prev-level 0)
8176 (loop repeat (/ (- cur-level 1) (org-level-increment))
8177 do (org-do-promote)))
8178 ;; If same level as prev, demote one.
8179 ((= prev-level cur-level)
8180 (org-do-demote))
8181 ;; If parent is top-level, promote to top level if not already.
8182 ((= prev-level 1)
8183 (loop repeat (/ (- cur-level 1) (org-level-increment))
8184 do (org-do-promote)))
8185 ;; If top-level, return to prev-level.
8186 ((= cur-level 1)
8187 (loop repeat (/ (- prev-level 1) (org-level-increment))
8188 do (org-do-demote)))
8189 ;; If less than prev-level, promote one.
8190 ((< cur-level prev-level)
8191 (org-do-promote))
8192 ;; If deeper than prev-level, promote until higher than
8193 ;; prev-level.
8194 ((> cur-level prev-level)
8195 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8196 do (org-do-promote))))
8197 t))))
8199 (defun org-map-tree (fun)
8200 "Call FUN for every heading underneath the current one."
8201 (org-back-to-heading)
8202 (let ((level (funcall outline-level)))
8203 (save-excursion
8204 (funcall fun)
8205 (while (and (progn
8206 (outline-next-heading)
8207 (> (funcall outline-level) level))
8208 (not (eobp)))
8209 (funcall fun)))))
8211 (defun org-map-region (fun beg end)
8212 "Call FUN for every heading between BEG and END."
8213 (let ((org-ignore-region t))
8214 (save-excursion
8215 (setq end (copy-marker end))
8216 (goto-char beg)
8217 (if (and (re-search-forward org-outline-regexp-bol nil t)
8218 (< (point) end))
8219 (funcall fun))
8220 (while (and (progn
8221 (outline-next-heading)
8222 (< (point) end))
8223 (not (eobp)))
8224 (funcall fun)))))
8226 (defvar org-property-end-re) ; silence byte-compiler
8227 (defun org-fixup-indentation (diff)
8228 "Change the indentation in the current entry by DIFF.
8229 However, if any line in the current entry has no indentation, or if it
8230 would end up with no indentation after the change, nothing at all is done."
8231 (save-excursion
8232 (let ((end (save-excursion (outline-next-heading)
8233 (point-marker)))
8234 (prohibit (if (> diff 0)
8235 "^\\S-"
8236 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8237 col)
8238 (unless (save-excursion (end-of-line 1)
8239 (re-search-forward prohibit end t))
8240 (while (and (< (point) end)
8241 (re-search-forward "^[ \t]+" end t))
8242 (goto-char (match-end 0))
8243 (setq col (current-column))
8244 (if (< diff 0) (replace-match ""))
8245 (org-indent-to-column (+ diff col))))
8246 (move-marker end nil))))
8248 (defun org-convert-to-odd-levels ()
8249 "Convert an org-mode file with all levels allowed to one with odd levels.
8250 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8251 level 5 etc."
8252 (interactive)
8253 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8254 (let ((outline-level 'org-outline-level)
8255 (org-odd-levels-only nil) n)
8256 (save-excursion
8257 (goto-char (point-min))
8258 (while (re-search-forward "^\\*\\*+ " nil t)
8259 (setq n (- (length (match-string 0)) 2))
8260 (while (>= (setq n (1- n)) 0)
8261 (org-demote))
8262 (end-of-line 1))))))
8264 (defun org-convert-to-oddeven-levels ()
8265 "Convert an org-mode file with only odd levels to one with odd/even levels.
8266 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8267 file contains a section with an even level, conversion would
8268 destroy the structure of the file. An error is signaled in this
8269 case."
8270 (interactive)
8271 (goto-char (point-min))
8272 ;; First check if there are no even levels
8273 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8274 (org-show-context t)
8275 (error "Not all levels are odd in this file. Conversion not possible"))
8276 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8277 (let ((outline-regexp org-outline-regexp)
8278 (outline-level 'org-outline-level)
8279 (org-odd-levels-only nil) n)
8280 (save-excursion
8281 (goto-char (point-min))
8282 (while (re-search-forward "^\\*\\*+ " nil t)
8283 (setq n (/ (1- (length (match-string 0))) 2))
8284 (while (>= (setq n (1- n)) 0)
8285 (org-promote))
8286 (end-of-line 1))))))
8288 (defun org-tr-level (n)
8289 "Make N odd if required."
8290 (if org-odd-levels-only (1+ (/ n 2)) n))
8292 ;;; Vertical tree motion, cutting and pasting of subtrees
8294 (defun org-move-subtree-up (&optional arg)
8295 "Move the current subtree up past ARG headlines of the same level."
8296 (interactive "p")
8297 (org-move-subtree-down (- (prefix-numeric-value arg))))
8299 (defun org-move-subtree-down (&optional arg)
8300 "Move the current subtree down past ARG headlines of the same level."
8301 (interactive "p")
8302 (setq arg (prefix-numeric-value arg))
8303 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8304 'org-get-last-sibling))
8305 (ins-point (make-marker))
8306 (cnt (abs arg))
8307 (col (current-column))
8308 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8309 ;; Select the tree
8310 (org-back-to-heading)
8311 (setq beg0 (point))
8312 (save-excursion
8313 (setq ne-beg (org-back-over-empty-lines))
8314 (setq beg (point)))
8315 (save-match-data
8316 (save-excursion (outline-end-of-heading)
8317 (setq folded (outline-invisible-p)))
8318 (progn (org-end-of-subtree nil t)
8319 (unless (eobp) (backward-char))))
8320 (outline-next-heading)
8321 (setq ne-end (org-back-over-empty-lines))
8322 (setq end (point))
8323 (goto-char beg0)
8324 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8325 ;; include less whitespace
8326 (save-excursion
8327 (goto-char beg)
8328 (forward-line (- ne-beg ne-end))
8329 (setq beg (point))))
8330 ;; Find insertion point, with error handling
8331 (while (> cnt 0)
8332 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8333 (progn (goto-char beg0)
8334 (user-error "Cannot move past superior level or buffer limit")))
8335 (setq cnt (1- cnt)))
8336 (if (> arg 0)
8337 ;; Moving forward - still need to move over subtree
8338 (progn (org-end-of-subtree t t)
8339 (save-excursion
8340 (org-back-over-empty-lines)
8341 (or (bolp) (newline)))))
8342 (setq ne-ins (org-back-over-empty-lines))
8343 (move-marker ins-point (point))
8344 (setq txt (buffer-substring beg end))
8345 (org-save-markers-in-region beg end)
8346 (delete-region beg end)
8347 (org-remove-empty-overlays-at beg)
8348 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8349 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8350 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8351 (let ((bbb (point)))
8352 (insert-before-markers txt)
8353 (org-reinstall-markers-in-region bbb)
8354 (move-marker ins-point bbb))
8355 (or (bolp) (insert "\n"))
8356 (setq ins-end (point))
8357 (goto-char ins-point)
8358 (org-skip-whitespace)
8359 (when (and (< arg 0)
8360 (org-first-sibling-p)
8361 (> ne-ins ne-beg))
8362 ;; Move whitespace back to beginning
8363 (save-excursion
8364 (goto-char ins-end)
8365 (let ((kill-whole-line t))
8366 (kill-line (- ne-ins ne-beg)) (point)))
8367 (insert (make-string (- ne-ins ne-beg) ?\n)))
8368 (move-marker ins-point nil)
8369 (if folded
8370 (hide-subtree)
8371 (org-show-entry)
8372 (show-children)
8373 (org-cycle-hide-drawers 'children))
8374 (org-clean-visibility-after-subtree-move)
8375 ;; move back to the initial column we were at
8376 (move-to-column col)))
8378 (defvar org-subtree-clip ""
8379 "Clipboard for cut and paste of subtrees.
8380 This is actually only a copy of the kill, because we use the normal kill
8381 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8383 (defvar org-subtree-clip-folded nil
8384 "Was the last copied subtree folded?
8385 This is used to fold the tree back after pasting.")
8387 (defun org-cut-subtree (&optional n)
8388 "Cut the current subtree into the clipboard.
8389 With prefix arg N, cut this many sequential subtrees.
8390 This is a short-hand for marking the subtree and then cutting it."
8391 (interactive "p")
8392 (org-copy-subtree n 'cut))
8394 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8395 "Copy the current subtree it in the clipboard.
8396 With prefix arg N, copy this many sequential subtrees.
8397 This is a short-hand for marking the subtree and then copying it.
8398 If CUT is non-nil, actually cut the subtree.
8399 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8400 of some markers in the region, even if CUT is non-nil. This is
8401 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8402 (interactive "p")
8403 (let (beg end folded (beg0 (point)))
8404 (if (org-called-interactively-p 'any)
8405 (org-back-to-heading nil) ; take what looks like a subtree
8406 (org-back-to-heading t)) ; take what is really there
8407 (setq beg (point))
8408 (skip-chars-forward " \t\r\n")
8409 (save-match-data
8410 (if nosubtrees
8411 (outline-next-heading)
8412 (save-excursion (outline-end-of-heading)
8413 (setq folded (outline-invisible-p)))
8414 (ignore-errors (org-forward-heading-same-level (1- n) t))
8415 (org-end-of-subtree t t)))
8416 (setq end (point))
8417 (goto-char beg0)
8418 (when (> end beg)
8419 (setq org-subtree-clip-folded folded)
8420 (when (or cut force-store-markers)
8421 (org-save-markers-in-region beg end))
8422 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8423 (setq org-subtree-clip (current-kill 0))
8424 (message "%s: Subtree(s) with %d characters"
8425 (if cut "Cut" "Copied")
8426 (length org-subtree-clip)))))
8428 (defun org-paste-subtree (&optional level tree for-yank remove)
8429 "Paste the clipboard as a subtree, with modification of headline level.
8430 The entire subtree is promoted or demoted in order to match a new headline
8431 level.
8433 If the cursor is at the beginning of a headline, the same level as
8434 that headline is used to paste the tree.
8436 If not, the new level is derived from the *visible* headings
8437 before and after the insertion point, and taken to be the inferior headline
8438 level of the two. So if the previous visible heading is level 3 and the
8439 next is level 4 (or vice versa), level 4 will be used for insertion.
8440 This makes sure that the subtree remains an independent subtree and does
8441 not swallow low level entries.
8443 You can also force a different level, either by using a numeric prefix
8444 argument, or by inserting the heading marker by hand. For example, if the
8445 cursor is after \"*****\", then the tree will be shifted to level 5.
8447 If optional TREE is given, use this text instead of the kill ring.
8449 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8450 move back over whitespace before inserting, and move point to the end of
8451 the inserted text when done.
8453 When REMOVE is non-nil, remove the subtree from the clipboard."
8454 (interactive "P")
8455 (setq tree (or tree (and kill-ring (current-kill 0))))
8456 (unless (org-kill-is-subtree-p tree)
8457 (user-error "%s"
8458 (substitute-command-keys
8459 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8460 (org-with-limited-levels
8461 (let* ((visp (not (outline-invisible-p)))
8462 (txt tree)
8463 (^re_ "\\(\\*+\\)[ \t]*")
8464 (old-level (if (string-match org-outline-regexp-bol txt)
8465 (- (match-end 0) (match-beginning 0) 1)
8466 -1))
8467 (force-level (cond (level (prefix-numeric-value level))
8468 ((and (looking-at "[ \t]*$")
8469 (string-match
8470 "^\\*+$" (buffer-substring
8471 (point-at-bol) (point))))
8472 (- (match-end 0) (match-beginning 0)))
8473 ((and (bolp)
8474 (looking-at org-outline-regexp))
8475 (- (match-end 0) (point) 1))))
8476 (previous-level (save-excursion
8477 (condition-case nil
8478 (progn
8479 (outline-previous-visible-heading 1)
8480 (if (looking-at ^re_)
8481 (- (match-end 0) (match-beginning 0) 1)
8483 (error 1))))
8484 (next-level (save-excursion
8485 (condition-case nil
8486 (progn
8487 (or (looking-at org-outline-regexp)
8488 (outline-next-visible-heading 1))
8489 (if (looking-at ^re_)
8490 (- (match-end 0) (match-beginning 0) 1)
8492 (error 1))))
8493 (new-level (or force-level (max previous-level next-level)))
8494 (shift (if (or (= old-level -1)
8495 (= new-level -1)
8496 (= old-level new-level))
8498 (- new-level old-level)))
8499 (delta (if (> shift 0) -1 1))
8500 (func (if (> shift 0) 'org-demote 'org-promote))
8501 (org-odd-levels-only nil)
8502 beg end newend)
8503 ;; Remove the forced level indicator
8504 (if force-level
8505 (delete-region (point-at-bol) (point)))
8506 ;; Paste
8507 (beginning-of-line (if (bolp) 1 2))
8508 (setq beg (point))
8509 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8510 (insert-before-markers txt)
8511 (unless (string-match "\n\\'" txt) (insert "\n"))
8512 (setq newend (point))
8513 (org-reinstall-markers-in-region beg)
8514 (setq end (point))
8515 (goto-char beg)
8516 (skip-chars-forward " \t\n\r")
8517 (setq beg (point))
8518 (if (and (outline-invisible-p) visp)
8519 (save-excursion (outline-show-heading)))
8520 ;; Shift if necessary
8521 (unless (= shift 0)
8522 (save-restriction
8523 (narrow-to-region beg end)
8524 (while (not (= shift 0))
8525 (org-map-region func (point-min) (point-max))
8526 (setq shift (+ delta shift)))
8527 (goto-char (point-min))
8528 (setq newend (point-max))))
8529 (when (or (org-called-interactively-p 'interactive) for-yank)
8530 (message "Clipboard pasted as level %d subtree" new-level))
8531 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8532 kill-ring
8533 (eq org-subtree-clip (current-kill 0))
8534 org-subtree-clip-folded)
8535 ;; The tree was folded before it was killed/copied
8536 (hide-subtree))
8537 (and for-yank (goto-char newend))
8538 (and remove (setq kill-ring (cdr kill-ring))))))
8540 (defun org-kill-is-subtree-p (&optional txt)
8541 "Check if the current kill is an outline subtree, or a set of trees.
8542 Returns nil if kill does not start with a headline, or if the first
8543 headline level is not the largest headline level in the tree.
8544 So this will actually accept several entries of equal levels as well,
8545 which is OK for `org-paste-subtree'.
8546 If optional TXT is given, check this string instead of the current kill."
8547 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8548 (re (org-get-limited-outline-regexp))
8549 (^re (concat "^" re))
8550 (start-level (and kill
8551 (string-match
8552 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8553 kill)
8554 (- (match-end 2) (match-beginning 2) 1)))
8555 (start (1+ (or (match-beginning 2) -1))))
8556 (if (not start-level)
8557 (progn
8558 nil) ;; does not even start with a heading
8559 (catch 'exit
8560 (while (setq start (string-match ^re kill (1+ start)))
8561 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8562 (throw 'exit nil)))
8563 t))))
8565 (defvar org-markers-to-move nil
8566 "Markers that should be moved with a cut-and-paste operation.
8567 Those markers are stored together with their positions relative to
8568 the start of the region.")
8570 (defun org-save-markers-in-region (beg end)
8571 "Check markers in region.
8572 If these markers are between BEG and END, record their position relative
8573 to BEG, so that after moving the block of text, we can put the markers back
8574 into place.
8575 This function gets called just before an entry or tree gets cut from the
8576 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8577 called immediately, to move the markers with the entries."
8578 (setq org-markers-to-move nil)
8579 (when (featurep 'org-clock)
8580 (org-clock-save-markers-for-cut-and-paste beg end))
8581 (when (featurep 'org-agenda)
8582 (org-agenda-save-markers-for-cut-and-paste beg end)))
8584 (defun org-check-and-save-marker (marker beg end)
8585 "Check if MARKER is between BEG and END.
8586 If yes, remember the marker and the distance to BEG."
8587 (when (and (marker-buffer marker)
8588 (equal (marker-buffer marker) (current-buffer)))
8589 (if (and (>= marker beg) (< marker end))
8590 (push (cons marker (- marker beg)) org-markers-to-move))))
8592 (defun org-reinstall-markers-in-region (beg)
8593 "Move all remembered markers to their position relative to BEG."
8594 (mapc (lambda (x)
8595 (move-marker (car x) (+ beg (cdr x))))
8596 org-markers-to-move)
8597 (setq org-markers-to-move nil))
8599 (defun org-narrow-to-subtree ()
8600 "Narrow buffer to the current subtree."
8601 (interactive)
8602 (save-excursion
8603 (save-match-data
8604 (org-with-limited-levels
8605 (narrow-to-region
8606 (progn (org-back-to-heading t) (point))
8607 (progn (org-end-of-subtree t t)
8608 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8609 (point)))))))
8611 (defun org-narrow-to-block ()
8612 "Narrow buffer to the current block."
8613 (interactive)
8614 (let* ((case-fold-search t)
8615 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8616 "^[ \t]*#\\+end_.*")))
8617 (if blockp
8618 (narrow-to-region (car blockp) (cdr blockp))
8619 (user-error "Not in a block"))))
8621 (eval-when-compile
8622 (defvar org-property-drawer-re))
8624 (defvar org-property-start-re) ;; defined below
8625 (defun org-clone-subtree-with-time-shift (n &optional shift)
8626 "Clone the task (subtree) at point N times.
8627 The clones will be inserted as siblings.
8629 In interactive use, the user will be prompted for the number of
8630 clones to be produced. If the entry has a timestamp, the user
8631 will also be prompted for a time shift, which may be a repeater
8632 as used in time stamps, for example `+3d'. To disable this,
8633 you can call the function with a universal prefix argument.
8635 When a valid repeater is given and the entry contains any time
8636 stamps, the clones will become a sequence in time, with time
8637 stamps in the subtree shifted for each clone produced. If SHIFT
8638 is nil or the empty string, time stamps will be left alone. The
8639 ID property of the original subtree is removed.
8641 If the original subtree did contain time stamps with a repeater,
8642 the following will happen:
8643 - the repeater will be removed in each clone
8644 - an additional clone will be produced, with the current, unshifted
8645 date(s) in the entry.
8646 - the original entry will be placed *after* all the clones, with
8647 repeater intact.
8648 - the start days in the repeater in the original entry will be shifted
8649 to past the last clone.
8650 In this way you can spell out a number of instances of a repeating task,
8651 and still retain the repeater to cover future instances of the task."
8652 (interactive "nNumber of clones to produce: ")
8653 (let ((shift
8654 (or shift
8655 (if (and (not (equal current-prefix-arg '(4)))
8656 (save-excursion
8657 (re-search-forward org-ts-regexp-both
8658 (save-excursion
8659 (org-end-of-subtree t)
8660 (point)) t)))
8661 (read-from-minibuffer
8662 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8663 ""))) ;; No time shift
8664 (n-no-remove -1)
8665 (drawer-re org-drawer-regexp)
8666 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8667 beg end template task idprop
8668 shift-n shift-what doshift nmin nmax)
8669 (if (not (and (integerp n) (> n 0)))
8670 (user-error "Invalid number of replications %s" n))
8671 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8672 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8673 shift)))
8674 (user-error "Invalid shift specification %s" shift))
8675 (when doshift
8676 (setq shift-n (string-to-number (match-string 1 shift))
8677 shift-what (cdr (assoc (match-string 2 shift)
8678 '(("d" . day) ("w" . week)
8679 ("m" . month) ("y" . year))))))
8680 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8681 (setq nmin 1 nmax n)
8682 (org-back-to-heading t)
8683 (setq beg (point))
8684 (setq idprop (org-entry-get nil "ID"))
8685 (org-end-of-subtree t t)
8686 (or (bolp) (insert "\n"))
8687 (setq end (point))
8688 (setq template (buffer-substring beg end))
8689 (when (and doshift
8690 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8691 (delete-region beg end)
8692 (setq end beg)
8693 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8694 (goto-char end)
8695 (loop for n from nmin to nmax do
8696 ;; prepare clone
8697 (with-temp-buffer
8698 (insert template)
8699 (org-mode)
8700 (goto-char (point-min))
8701 (org-show-subtree)
8702 (and idprop (if org-clone-delete-id
8703 (org-entry-delete nil "ID")
8704 (org-id-get-create t)))
8705 (unless (= n 0)
8706 (while (re-search-forward org-clock-re nil t)
8707 (kill-whole-line))
8708 (goto-char (point-min))
8709 (while (re-search-forward drawer-re nil t)
8710 (org-remove-empty-drawer-at (point))))
8711 (goto-char (point-min))
8712 (when doshift
8713 (while (re-search-forward org-ts-regexp-both nil t)
8714 (org-timestamp-change (* n shift-n) shift-what))
8715 (unless (= n n-no-remove)
8716 (goto-char (point-min))
8717 (while (re-search-forward org-ts-regexp nil t)
8718 (save-excursion
8719 (goto-char (match-beginning 0))
8720 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8721 (delete-region (match-beginning 1) (match-end 1)))))))
8722 (setq task (buffer-string)))
8723 (insert task))
8724 (goto-char beg)))
8726 ;;; Outline Sorting
8728 (defun org-sort (with-case)
8729 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8730 Optional argument WITH-CASE means sort case-sensitively."
8731 (interactive "P")
8732 (cond
8733 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8734 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8736 (org-call-with-arg 'org-sort-entries with-case))))
8738 (defun org-sort-remove-invisible (s)
8739 "Remove invisible links from string S."
8740 (remove-text-properties 0 (length s) org-rm-props s)
8741 (while (string-match org-bracket-link-regexp s)
8742 (setq s (replace-match (if (match-end 2)
8743 (match-string 3 s)
8744 (match-string 1 s)) t t s)))
8745 (let ((st (format " %s " s)))
8746 (while (string-match org-emph-re st)
8747 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8748 (setq s (substring st 1 -1)))
8751 (defvar org-priority-regexp) ; defined later in the file
8753 (defvar org-after-sorting-entries-or-items-hook nil
8754 "Hook that is run after a bunch of entries or items have been sorted.
8755 When children are sorted, the cursor is in the parent line when this
8756 hook gets called. When a region or a plain list is sorted, the cursor
8757 will be in the first entry of the sorted region/list.")
8759 (defun org-sort-entries
8760 (&optional with-case sorting-type getkey-func compare-func property)
8761 "Sort entries on a certain level of an outline tree.
8762 If there is an active region, the entries in the region are sorted.
8763 Else, if the cursor is before the first entry, sort the top-level items.
8764 Else, the children of the entry at point are sorted.
8766 Sorting can be alphabetically, numerically, by date/time as given by
8767 a time stamp, by a property, by priority order, or by a custom function.
8769 The command prompts for the sorting type unless it has been given to the
8770 function through the SORTING-TYPE argument, which needs to be a character,
8771 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8772 the precise meaning of each character:
8774 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8775 c By creation time, which is assumed to be the first inactive time stamp
8776 at the beginning of a line.
8777 d By deadline date/time.
8778 k By clocking time.
8779 n Numerically, by converting the beginning of the entry/item to a number.
8780 o By order of TODO keywords.
8781 p By priority according to the cookie.
8782 r By the value of a property.
8783 s By scheduled date/time.
8784 t By date/time, either the first active time stamp in the entry, or, if
8785 none exist, by the first inactive one.
8787 Capital letters will reverse the sort order.
8789 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8790 called with point at the beginning of the record. It must return either
8791 a string or a number that should serve as the sorting key for that record.
8793 Comparing entries ignores case by default. However, with an optional argument
8794 WITH-CASE, the sorting considers case as well.
8796 Sorting is done against the visible part of the headlines, it ignores hidden
8797 links.
8799 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8800 (interactive "P")
8801 (let ((case-func (if with-case 'identity 'downcase))
8802 (cmstr
8803 ;; The clock marker is lost when using `sort-subr', let's
8804 ;; store the clocking string.
8805 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8806 (save-excursion
8807 (goto-char org-clock-marker)
8808 (looking-back "^.*") (match-string-no-properties 0))))
8809 start beg end stars re re2
8810 txt what tmp)
8811 ;; Find beginning and end of region to sort
8812 (cond
8813 ((org-region-active-p)
8814 ;; we will sort the region
8815 (setq end (region-end)
8816 what "region")
8817 (goto-char (region-beginning))
8818 (if (not (org-at-heading-p)) (outline-next-heading))
8819 (setq start (point)))
8820 ((or (org-at-heading-p)
8821 (ignore-errors (progn (org-back-to-heading) t)))
8822 ;; we will sort the children of the current headline
8823 (org-back-to-heading)
8824 (setq start (point)
8825 end (progn (org-end-of-subtree t t)
8826 (or (bolp) (insert "\n"))
8827 (when (>= (org-back-over-empty-lines) 1)
8828 (forward-line 1))
8829 (point))
8830 what "children")
8831 (goto-char start)
8832 (show-subtree)
8833 (outline-next-heading))
8835 ;; we will sort the top-level entries in this file
8836 (goto-char (point-min))
8837 (or (org-at-heading-p) (outline-next-heading))
8838 (setq start (point))
8839 (goto-char (point-max))
8840 (beginning-of-line 1)
8841 (when (looking-at ".*?\\S-")
8842 ;; File ends in a non-white line
8843 (end-of-line 1)
8844 (insert "\n"))
8845 (setq end (point-max))
8846 (setq what "top-level")
8847 (goto-char start)
8848 (show-all)))
8850 (setq beg (point))
8851 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8853 (looking-at "\\(\\*+\\)")
8854 (setq stars (match-string 1)
8855 re (concat "^" (regexp-quote stars) " +")
8856 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8857 txt (buffer-substring beg end))
8858 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8859 (if (and (not (equal stars "*")) (string-match re2 txt))
8860 (user-error "Region to sort contains a level above the first entry"))
8862 (unless sorting-type
8863 (message
8864 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8865 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8866 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8867 what)
8868 (setq sorting-type (read-char-exclusive))
8870 (unless getkey-func
8871 (and (= (downcase sorting-type) ?f)
8872 (setq getkey-func
8873 (org-icompleting-read "Sort using function: "
8874 obarray 'fboundp t nil nil))
8875 (setq getkey-func (intern getkey-func))))
8877 (and (= (downcase sorting-type) ?r)
8878 (not property)
8879 (setq property
8880 (org-icompleting-read "Property: "
8881 (mapcar 'list (org-buffer-property-keys t))
8882 nil t))))
8884 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8885 (message "Sorting entries...")
8887 (save-restriction
8888 (narrow-to-region start end)
8889 (let ((dcst (downcase sorting-type))
8890 (case-fold-search nil)
8891 (now (current-time)))
8892 (sort-subr
8893 (/= dcst sorting-type)
8894 ;; This function moves to the beginning character of the "record" to
8895 ;; be sorted.
8896 (lambda nil
8897 (if (re-search-forward re nil t)
8898 (goto-char (match-beginning 0))
8899 (goto-char (point-max))))
8900 ;; This function moves to the last character of the "record" being
8901 ;; sorted.
8902 (lambda nil
8903 (save-match-data
8904 (condition-case nil
8905 (outline-forward-same-level 1)
8906 (error
8907 (goto-char (point-max))))))
8908 ;; This function returns the value that gets sorted against.
8909 (lambda nil
8910 (cond
8911 ((= dcst ?n)
8912 (if (looking-at org-complex-heading-regexp)
8913 (string-to-number (org-sort-remove-invisible (match-string 4)))
8914 nil))
8915 ((= dcst ?a)
8916 (if (looking-at org-complex-heading-regexp)
8917 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8918 nil))
8919 ((= dcst ?k)
8920 (or (get-text-property (point) :org-clock-minutes) 0))
8921 ((= dcst ?t)
8922 (let ((end (save-excursion (outline-next-heading) (point))))
8923 (if (or (re-search-forward org-ts-regexp end t)
8924 (re-search-forward org-ts-regexp-both end t))
8925 (org-time-string-to-seconds (match-string 0))
8926 (org-float-time now))))
8927 ((= dcst ?c)
8928 (let ((end (save-excursion (outline-next-heading) (point))))
8929 (if (re-search-forward
8930 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8931 end t)
8932 (org-time-string-to-seconds (match-string 0))
8933 (org-float-time now))))
8934 ((= dcst ?s)
8935 (let ((end (save-excursion (outline-next-heading) (point))))
8936 (if (re-search-forward org-scheduled-time-regexp end t)
8937 (org-time-string-to-seconds (match-string 1))
8938 (org-float-time now))))
8939 ((= dcst ?d)
8940 (let ((end (save-excursion (outline-next-heading) (point))))
8941 (if (re-search-forward org-deadline-time-regexp end t)
8942 (org-time-string-to-seconds (match-string 1))
8943 (org-float-time now))))
8944 ((= dcst ?p)
8945 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8946 (string-to-char (match-string 2))
8947 org-default-priority))
8948 ((= dcst ?r)
8949 (or (org-entry-get nil property) ""))
8950 ((= dcst ?o)
8951 (if (looking-at org-complex-heading-regexp)
8952 (let* ((m (match-string 2))
8953 (s (if (member m org-done-keywords) '- '+)))
8954 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8955 ((= dcst ?f)
8956 (if getkey-func
8957 (progn
8958 (setq tmp (funcall getkey-func))
8959 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8960 tmp)
8961 (error "Invalid key function `%s'" getkey-func)))
8962 (t (error "Invalid sorting type `%c'" sorting-type))))
8964 (cond
8965 ((= dcst ?a) 'string<)
8966 ((= dcst ?f) compare-func)
8967 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8968 (run-hooks 'org-after-sorting-entries-or-items-hook)
8969 ;; Reset the clock marker if needed
8970 (when cmstr
8971 (save-excursion
8972 (goto-char start)
8973 (search-forward cmstr nil t)
8974 (move-marker org-clock-marker (point))))
8975 (message "Sorting entries...done")))
8977 (defun org-do-sort (table what &optional with-case sorting-type)
8978 "Sort TABLE of WHAT according to SORTING-TYPE.
8979 The user will be prompted for the SORTING-TYPE if the call to this
8980 function does not specify it.
8981 WHAT is only for the prompt, to indicate what is being sorted.
8982 The sorting key will be extracted from the car of the elements of
8983 the table.
8984 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8985 (unless sorting-type
8986 (message
8987 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8988 what)
8989 (setq sorting-type (read-char-exclusive)))
8990 (let ((dcst (downcase sorting-type))
8991 extractfun comparefun)
8992 ;; Define the appropriate functions
8993 (cond
8994 ((= dcst ?n)
8995 (setq extractfun 'string-to-number
8996 comparefun (if (= dcst sorting-type) '< '>)))
8997 ((= dcst ?a)
8998 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8999 (lambda(x) (downcase (org-sort-remove-invisible x))))
9000 comparefun (if (= dcst sorting-type)
9001 'string<
9002 (lambda (a b) (and (not (string< a b))
9003 (not (string= a b)))))))
9004 ((= dcst ?t)
9005 (setq extractfun
9006 (lambda (x)
9007 (cond ((or (string-match org-ts-regexp x)
9008 (string-match org-ts-regexp-both x))
9009 (org-float-time
9010 (org-time-string-to-time (match-string 0 x))))
9011 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x)
9012 (org-hh:mm-string-to-minutes x))
9013 (t 0)))
9014 comparefun (if (= dcst sorting-type) '< '>)))
9015 (t (error "Invalid sorting type `%c'" sorting-type)))
9017 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
9018 table)
9019 (lambda (a b) (funcall comparefun (car a) (car b))))))
9022 ;;; The orgstruct minor mode
9024 ;; Define a minor mode which can be used in other modes in order to
9025 ;; integrate the org-mode structure editing commands.
9027 ;; This is really a hack, because the org-mode structure commands use
9028 ;; keys which normally belong to the major mode. Here is how it
9029 ;; works: The minor mode defines all the keys necessary to operate the
9030 ;; structure commands, but wraps the commands into a function which
9031 ;; tests if the cursor is currently at a headline or a plain list
9032 ;; item. If that is the case, the structure command is used,
9033 ;; temporarily setting many Org-mode variables like regular
9034 ;; expressions for filling etc. However, when any of those keys is
9035 ;; used at a different location, function uses `key-binding' to look
9036 ;; up if the key has an associated command in another currently active
9037 ;; keymap (minor modes, major mode, global), and executes that
9038 ;; command. There might be problems if any of the keys is otherwise
9039 ;; used as a prefix key.
9041 (defcustom orgstruct-heading-prefix-regexp ""
9042 "Regexp that matches the custom prefix of Org headlines in
9043 orgstruct(++)-mode."
9044 :group 'org
9045 :version "24.4"
9046 :package-version '(Org . "8.3")
9047 :type 'regexp)
9048 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9050 (defcustom orgstruct-setup-hook nil
9051 "Hook run after orgstruct-mode-map is filled."
9052 :group 'org
9053 :version "24.4"
9054 :package-version '(Org . "8.0")
9055 :type 'hook)
9057 (defvar orgstruct-initialized nil)
9059 (defvar org-local-vars nil
9060 "List of local variables, for use by `orgstruct-mode'.")
9062 ;;;###autoload
9063 (define-minor-mode orgstruct-mode
9064 "Toggle the minor mode `orgstruct-mode'.
9065 This mode is for using Org-mode structure commands in other
9066 modes. The following keys behave as if Org-mode were active, if
9067 the cursor is on a headline, or on a plain list item (both as
9068 defined by Org-mode)."
9069 nil " OrgStruct" (make-sparse-keymap)
9070 (funcall (if orgstruct-mode
9071 'add-to-invisibility-spec
9072 'remove-from-invisibility-spec)
9073 '(outline . t))
9074 (when orgstruct-mode
9075 (org-load-modules-maybe)
9076 (unless orgstruct-initialized
9077 (orgstruct-setup)
9078 (setq orgstruct-initialized t))))
9080 ;;;###autoload
9081 (defun turn-on-orgstruct ()
9082 "Unconditionally turn on `orgstruct-mode'."
9083 (orgstruct-mode 1))
9085 (defvar org-fb-vars nil)
9086 (make-variable-buffer-local 'org-fb-vars)
9087 (defun orgstruct++-mode (&optional arg)
9088 "Toggle `orgstruct-mode', the enhanced version of it.
9089 In addition to setting orgstruct-mode, this also exports all
9090 indentation and autofilling variables from org-mode into the
9091 buffer. It will also recognize item context in multiline items."
9092 (interactive "P")
9093 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9094 (if (< arg 1)
9095 (progn (orgstruct-mode -1)
9096 (mapc (lambda(v)
9097 (org-set-local (car v)
9098 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
9099 org-fb-vars))
9100 (orgstruct-mode 1)
9101 (setq org-fb-vars nil)
9102 (unless org-local-vars
9103 (setq org-local-vars (org-get-local-variables)))
9104 (let (var val)
9105 (mapc
9106 (lambda (x)
9107 (when (string-match
9108 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
9109 (symbol-name (car x)))
9110 (setq var (car x) val (nth 1 x))
9111 (push (list var `(quote ,(eval var))) org-fb-vars)
9112 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9113 org-local-vars)
9114 (org-set-local 'orgstruct-is-++ t))))
9116 (defvar orgstruct-is-++ nil
9117 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9118 (make-variable-buffer-local 'orgstruct-is-++)
9120 ;;;###autoload
9121 (defun turn-on-orgstruct++ ()
9122 "Unconditionally turn on `orgstruct++-mode'."
9123 (orgstruct++-mode 1))
9125 (defun orgstruct-error ()
9126 "Error when there is no default binding for a structure key."
9127 (interactive)
9128 (funcall (if (fboundp 'user-error)
9129 'user-error
9130 'error)
9131 "This key has no function outside structure elements"))
9133 (defun orgstruct-setup ()
9134 "Setup orgstruct keymap."
9135 (dolist (cell '((org-demote . t)
9136 (org-metaleft . t)
9137 (org-metaright . t)
9138 (org-promote . t)
9139 (org-shiftmetaleft . t)
9140 (org-shiftmetaright . t)
9141 org-backward-element
9142 org-backward-heading-same-level
9143 org-ctrl-c-ret
9144 org-ctrl-c-minus
9145 org-ctrl-c-star
9146 org-cycle
9147 org-forward-heading-same-level
9148 org-insert-heading
9149 org-insert-heading-respect-content
9150 org-kill-note-or-show-branches
9151 org-mark-subtree
9152 org-meta-return
9153 org-metadown
9154 org-metaup
9155 org-narrow-to-subtree
9156 org-promote-subtree
9157 org-reveal
9158 org-shiftdown
9159 org-shiftleft
9160 org-shiftmetadown
9161 org-shiftmetaup
9162 org-shiftright
9163 org-shifttab
9164 org-shifttab
9165 org-shiftup
9166 org-show-subtree
9167 org-sort
9168 org-up-element
9169 outline-demote
9170 outline-next-visible-heading
9171 outline-previous-visible-heading
9172 outline-promote
9173 outline-up-heading
9174 show-children))
9175 (let ((f (or (car-safe cell) cell))
9176 (disable-when-heading-prefix (cdr-safe cell)))
9177 (when (fboundp f)
9178 (let ((new-bindings))
9179 (dolist (binding (nconc (where-is-internal f org-mode-map)
9180 (where-is-internal f outline-mode-map)))
9181 (push binding new-bindings)
9182 ;; TODO use local-function-key-map
9183 (dolist (rep '(("<tab>" . "TAB")
9184 ("<return>" . "RET")
9185 ("<escape>" . "ESC")
9186 ("<delete>" . "DEL")))
9187 (setq binding (read-kbd-macro
9188 (let ((case-fold-search))
9189 (replace-regexp-in-string
9190 (regexp-quote (cdr rep))
9191 (car rep)
9192 (key-description binding)))))
9193 (pushnew binding new-bindings :test 'equal)))
9194 (dolist (binding new-bindings)
9195 (let ((key (lookup-key orgstruct-mode-map binding)))
9196 (when (or (not key) (numberp key))
9197 (ignore-errors
9198 (org-defkey orgstruct-mode-map
9199 binding
9200 (orgstruct-make-binding
9201 f binding disable-when-heading-prefix))))))))))
9202 (run-hooks 'orgstruct-setup-hook))
9204 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9205 "Create a function for binding in the structure minor mode.
9206 FUN is the command to call inside a table. KEY is the key that
9207 should be checked in for a command to execute outside of tables.
9208 Non-nil `disable-when-heading-prefix' means to disable the command
9209 if `orgstruct-heading-prefix-regexp' is not empty."
9210 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9211 (let ((nname name)
9212 (i 0))
9213 (while (fboundp (intern nname))
9214 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9215 (setq name (intern nname)))
9216 (eval
9217 (let ((bindings '((org-heading-regexp
9218 (concat "^"
9219 orgstruct-heading-prefix-regexp
9220 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9221 (org-outline-regexp
9222 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9223 (org-outline-regexp-bol
9224 (concat "^" org-outline-regexp))
9225 (outline-regexp org-outline-regexp)
9226 (outline-heading-end-regexp "\n")
9227 (outline-level 'org-outline-level)
9228 (outline-heading-alist))))
9229 `(defun ,name (arg)
9230 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9231 "Outside of structure, run the binding of `"
9232 (key-description key) "'."
9233 (when disable-when-heading-prefix
9234 (concat
9235 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9236 "back to the default binding due to limitations of Org's implementation of\n"
9237 "`" (symbol-name fun) "'.")))
9238 (interactive "p")
9239 (let* ((disable
9240 ,(and disable-when-heading-prefix
9241 '(not (string= orgstruct-heading-prefix-regexp ""))))
9242 (fallback
9243 (or disable
9244 (not
9245 (let* ,bindings
9246 (org-context-p 'headline 'item
9247 ,(when (memq fun
9248 '(org-insert-heading
9249 org-insert-heading-respect-content
9250 org-meta-return))
9251 '(when orgstruct-is-++
9252 'item-body))))))))
9253 (if fallback
9254 (let* ((orgstruct-mode)
9255 (binding
9256 (loop with key = ,key
9257 for rep in
9258 '(nil
9259 ("<\\([^>]*\\)tab>" . "\\1TAB")
9260 ("<\\([^>]*\\)return>" . "\\1RET")
9261 ("<\\([^>]*\\)escape>" . "\\1ESC")
9262 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9264 (when rep
9265 (setq key (read-kbd-macro
9266 (let ((case-fold-search))
9267 (replace-regexp-in-string
9268 (car rep)
9269 (cdr rep)
9270 (key-description key))))))
9271 thereis (key-binding key))))
9272 (if (keymapp binding)
9273 (org-set-transient-map binding)
9274 (let ((func (or binding
9275 (unless disable
9276 'orgstruct-error))))
9277 (when func
9278 (call-interactively func)))))
9279 (org-run-like-in-org-mode
9280 (lambda ()
9281 (interactive)
9282 (let* ,bindings
9283 (call-interactively ',fun)))))))))
9284 name))
9286 (defun org-contextualize-keys (alist contexts)
9287 "Return valid elements in ALIST depending on CONTEXTS.
9289 `org-agenda-custom-commands' or `org-capture-templates' are the
9290 values used for ALIST, and `org-agenda-custom-commands-contexts'
9291 or `org-capture-templates-contexts' are the associated contexts
9292 definitions."
9293 (let ((contexts
9294 ;; normalize contexts
9295 (mapcar
9296 (lambda(c) (cond ((listp (cadr c))
9297 (list (car c) (car c) (cadr c)))
9298 ((string= "" (cadr c))
9299 (list (car c) (car c) (caddr c)))
9300 (t c))) contexts))
9301 (a alist) c r s)
9302 ;; loop over all commands or templates
9303 (while (setq c (pop a))
9304 (let (vrules repl)
9305 (cond
9306 ((not (assoc (car c) contexts))
9307 (push c r))
9308 ((and (assoc (car c) contexts)
9309 (setq vrules (org-contextualize-validate-key
9310 (car c) contexts)))
9311 (mapc (lambda (vr)
9312 (when (not (equal (car vr) (cadr vr)))
9313 (setq repl vr))) vrules)
9314 (if (not repl) (push c r)
9315 (push (cadr repl) s)
9316 (push
9317 (cons (car c)
9318 (cdr (or (assoc (cadr repl) alist)
9319 (error "Undefined key `%s' as contextual replacement for `%s'"
9320 (cadr repl) (car c)))))
9321 r))))))
9322 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9323 (delq
9325 (delete-dups
9326 (mapcar (lambda (x)
9327 (let ((tpl (car x)))
9328 (when (not (delq
9330 (mapcar (lambda(y)
9331 (equal y tpl)) s))) x)))
9332 (reverse r))))))
9334 (defun org-contextualize-validate-key (key contexts)
9335 "Check CONTEXTS for agenda or capture KEY."
9336 (let (r rr res)
9337 (while (setq r (pop contexts))
9338 (mapc
9339 (lambda (rr)
9340 (when
9341 (and (equal key (car r))
9342 (if (functionp rr) (funcall rr)
9343 (or (and (eq (car rr) 'in-file)
9344 (buffer-file-name)
9345 (string-match (cdr rr) (buffer-file-name)))
9346 (and (eq (car rr) 'in-mode)
9347 (string-match (cdr rr) (symbol-name major-mode)))
9348 (and (eq (car rr) 'in-buffer)
9349 (string-match (cdr rr) (buffer-name)))
9350 (when (and (eq (car rr) 'not-in-file)
9351 (buffer-file-name))
9352 (not (string-match (cdr rr) (buffer-file-name))))
9353 (when (eq (car rr) 'not-in-mode)
9354 (not (string-match (cdr rr) (symbol-name major-mode))))
9355 (when (eq (car rr) 'not-in-buffer)
9356 (not (string-match (cdr rr) (buffer-name)))))))
9357 (push r res)))
9358 (car (last r))))
9359 (delete-dups (delq nil res))))
9361 (defun org-context-p (&rest contexts)
9362 "Check if local context is any of CONTEXTS.
9363 Possible values in the list of contexts are `table', `headline', and `item'."
9364 (let ((pos (point)))
9365 (goto-char (point-at-bol))
9366 (prog1 (or (and (memq 'table contexts)
9367 (looking-at "[ \t]*|"))
9368 (and (memq 'headline contexts)
9369 (looking-at org-outline-regexp))
9370 (and (memq 'item contexts)
9371 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9372 (and (memq 'item-body contexts)
9373 (org-in-item-p)))
9374 (goto-char pos))))
9376 (defun org-get-local-variables ()
9377 "Return a list of all local variables in an Org mode buffer."
9378 (let (varlist)
9379 (with-current-buffer (get-buffer-create "*Org tmp*")
9380 (erase-buffer)
9381 (org-mode)
9382 (setq varlist (buffer-local-variables)))
9383 (kill-buffer "*Org tmp*")
9384 (delq nil
9385 (mapcar
9386 (lambda (x)
9387 (setq x
9388 (if (symbolp x)
9389 (list x)
9390 (list (car x) (cdr x))))
9391 (if (and (not (get (car x) 'org-state))
9392 (string-match
9393 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9394 (symbol-name (car x))))
9395 x nil))
9396 varlist))))
9398 (defun org-clone-local-variables (from-buffer &optional regexp)
9399 "Clone local variables from FROM-BUFFER.
9400 Optional argument REGEXP selects variables to clone."
9401 (mapc
9402 (lambda (pair)
9403 (and (symbolp (car pair))
9404 (or (null regexp)
9405 (string-match regexp (symbol-name (car pair))))
9406 (set (make-local-variable (car pair))
9407 (cdr pair))))
9408 (buffer-local-variables from-buffer)))
9410 ;;;###autoload
9411 (defun org-run-like-in-org-mode (cmd)
9412 "Run a command, pretending that the current buffer is in Org-mode.
9413 This will temporarily bind local variables that are typically bound in
9414 Org-mode to the values they have in Org-mode, and then interactively
9415 call CMD."
9416 (org-load-modules-maybe)
9417 (unless org-local-vars
9418 (setq org-local-vars (org-get-local-variables)))
9419 (let (binds)
9420 (dolist (var org-local-vars)
9421 (when (or (not (boundp (car var)))
9422 (eq (symbol-value (car var))
9423 (default-value (car var))))
9424 (push (list (car var) `(quote ,(cadr var))) binds)))
9425 (eval `(let ,binds
9426 (call-interactively (quote ,cmd))))))
9428 (defun org-get-category (&optional pos force-refresh)
9429 "Get the category applying to position POS."
9430 (save-match-data
9431 (if force-refresh (org-refresh-category-properties))
9432 (let ((pos (or pos (point))))
9433 (or (get-text-property pos 'org-category)
9434 (progn (org-refresh-category-properties)
9435 (get-text-property pos 'org-category))))))
9437 ;;; Refresh properties
9439 (defun org-refresh-properties (dprop tprop)
9440 "Refresh buffer text properties.
9441 DPROP is the drawer property and TPROP is either the
9442 corresponding text property to set, or an alist with each element
9443 being a text property (as a symbol) and a function to apply to
9444 the value of the drawer property."
9445 (let ((case-fold-search t)
9446 (inhibit-read-only t))
9447 (org-with-silent-modifications
9448 (save-excursion
9449 (save-restriction
9450 (widen)
9451 (goto-char (point-min))
9452 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9453 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9455 (defun org-refresh-property (tprop p)
9456 "Refresh the buffer text property TPROP from the drawer property P.
9457 The refresh happens only for the current tree (not subtree)."
9458 (save-excursion
9459 (org-back-to-heading t)
9460 ;; tprop is a text property symbol
9461 (if (symbolp tprop)
9462 (put-text-property
9463 (point) (or (outline-next-heading) (point-max)) tprop p)
9464 ;; tprop is an alist with (properties . function) elements
9465 (mapc (lambda(al)
9466 (save-excursion
9467 (put-text-property
9468 (point-at-bol) (or (outline-next-heading) (point-max))
9469 (car al)
9470 (funcall (cdr al) p))))
9471 tprop))))
9473 (defun org-refresh-category-properties ()
9474 "Refresh category text properties in the buffer."
9475 (let ((case-fold-search t)
9476 (inhibit-read-only t)
9477 (def-cat (cond
9478 ((null org-category)
9479 (if buffer-file-name
9480 (file-name-sans-extension
9481 (file-name-nondirectory buffer-file-name))
9482 "???"))
9483 ((symbolp org-category) (symbol-name org-category))
9484 (t org-category)))
9485 beg end cat pos optionp)
9486 (org-with-silent-modifications
9487 (save-excursion
9488 (save-restriction
9489 (widen)
9490 (goto-char (point-min))
9491 (put-text-property (point) (point-max) 'org-category def-cat)
9492 (while (re-search-forward
9493 "^[ \t]*\\(\\(?:#\\+\\|:\\)CATEGORY:\\)\\(.*\\)" nil t)
9494 (setq pos (match-end 0)
9495 optionp (equal (char-after (match-beginning 0)) ?#)
9496 cat (org-trim (match-string 2)))
9497 (if optionp
9498 (setq beg (point-at-bol) end (point-max))
9499 (org-back-to-heading t)
9500 (setq beg (point) end (org-end-of-subtree t t)))
9501 (put-text-property beg end 'org-category cat)
9502 (goto-char pos)))))))
9504 (defun org-refresh-stats-properties ()
9505 "Refresh stats text properties in the buffer."
9506 (let (stats)
9507 (org-with-silent-modifications
9508 (save-excursion
9509 (save-restriction
9510 (widen)
9511 (goto-char (point-min))
9512 (while (re-search-forward
9513 (concat org-outline-regexp-bol ".*"
9514 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9515 nil t)
9516 (setq stats (cond ((equal (match-string 3) "0") 0)
9517 ((match-string 2)
9518 (/ (* (string-to-number (match-string 2)) 100)
9519 (string-to-number (match-string 3))))
9520 (t (string-to-number (match-string 1)))))
9521 (org-back-to-heading t)
9522 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9523 'org-stats stats)))))))
9525 (defun org-refresh-effort-properties ()
9526 "Refresh effort properties"
9527 (org-refresh-properties
9528 org-effort-property
9529 '((effort . identity)
9530 (effort-minutes . org-duration-string-to-minutes))))
9532 ;;;; Link Stuff
9534 ;;; Link abbreviations
9536 (defun org-link-expand-abbrev (link)
9537 "Apply replacements as defined in `org-link-abbrev-alist'."
9538 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9539 (let* ((key (match-string 1 link))
9540 (as (or (assoc key org-link-abbrev-alist-local)
9541 (assoc key org-link-abbrev-alist)))
9542 (tag (and (match-end 2) (match-string 3 link)))
9543 rpl)
9544 (if (not as)
9545 link
9546 (setq rpl (cdr as))
9547 (cond
9548 ((symbolp rpl) (funcall rpl tag))
9549 ((string-match "%(\\([^)]+\\))" rpl)
9550 (replace-match
9551 (save-match-data
9552 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9553 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9554 ((string-match "%h" rpl)
9555 (replace-match (url-hexify-string (or tag "")) t t rpl))
9556 (t (concat rpl tag)))))
9557 link))
9559 ;;; Storing and inserting links
9561 (defvar org-insert-link-history nil
9562 "Minibuffer history for links inserted with `org-insert-link'.")
9564 (defvar org-stored-links nil
9565 "Contains the links stored with `org-store-link'.")
9567 (defvar org-store-link-plist nil
9568 "Plist with info about the most recently link created with `org-store-link'.")
9570 (defvar org-link-protocols nil
9571 "Link protocols added to Org-mode using `org-add-link-type'.")
9573 (defvar org-store-link-functions nil
9574 "List of functions that are called to create and store a link.
9575 Each function will be called in turn until one returns a non-nil
9576 value. Each function should check if it is responsible for creating
9577 this link (for example by looking at the major mode).
9578 If not, it must exit and return nil.
9579 If yes, it should return a non-nil value after a calling
9580 `org-store-link-props' with a list of properties and values.
9581 Special properties are:
9583 :type The link prefix, like \"http\". This must be given.
9584 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9585 This is obligatory as well.
9586 :description Optional default description for the second pair
9587 of brackets in an Org-mode link. The user can still change
9588 this when inserting this link into an Org-mode buffer.
9590 In addition to these, any additional properties can be specified
9591 and then used in capture templates.")
9593 (defun org-add-link-type (type &optional follow export)
9594 "Add TYPE to the list of `org-link-types'.
9595 Re-compute all regular expressions depending on `org-link-types'
9597 FOLLOW and EXPORT are two functions.
9599 FOLLOW should take the link path as the single argument and do whatever
9600 is necessary to follow the link, for example find a file or display
9601 a mail message.
9603 EXPORT should format the link path for export to one of the export formats.
9604 It should be a function accepting three arguments:
9606 path the path of the link, the text after the prefix (like \"http:\")
9607 desc the description of the link, if any, or a description added by
9608 org-export-normalize-links if there is none
9609 format the export format, a symbol like `html' or `latex' or `ascii'..
9611 The function may use the FORMAT information to return different values
9612 depending on the format. The return value will be put literally into
9613 the exported file. If the return value is nil, this means Org should
9614 do what it normally does with links which do not have EXPORT defined.
9616 Org-mode has a built-in default for exporting links. If you are happy with
9617 this default, there is no need to define an export function for the link
9618 type. For a simple example of an export function, see `org-bbdb.el'."
9619 (add-to-list 'org-link-types type t)
9620 (org-make-link-regexps)
9621 (if (assoc type org-link-protocols)
9622 (setcdr (assoc type org-link-protocols) (list follow export))
9623 (push (list type follow export) org-link-protocols)))
9625 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9626 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9628 ;;;###autoload
9629 (defun org-store-link (arg)
9630 "\\<org-mode-map>Store an org-link to the current location.
9631 This link is added to `org-stored-links' and can later be inserted
9632 into an org-buffer with \\[org-insert-link].
9634 For some link types, a prefix arg is interpreted.
9635 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9636 For file links, arg negates `org-context-in-file-links'.
9638 A double prefix arg force skipping storing functions that are not
9639 part of Org's core.
9641 A triple prefix arg force storing a link for each line in the
9642 active region."
9643 (interactive "P")
9644 (org-load-modules-maybe)
9645 (if (and (equal arg '(64)) (org-region-active-p))
9646 (save-excursion
9647 (let ((end (region-end)))
9648 (goto-char (region-beginning))
9649 (set-mark (point))
9650 (while (< (point-at-eol) end)
9651 (move-end-of-line 1) (activate-mark)
9652 (let (current-prefix-arg)
9653 (call-interactively 'org-store-link))
9654 (move-beginning-of-line 2)
9655 (set-mark (point)))))
9656 (org-with-limited-levels
9657 (setq org-store-link-plist nil)
9658 (let (link cpltxt desc description search
9659 txt custom-id agenda-link sfuns sfunsn)
9660 (cond
9662 ;; Store a link using an external link type
9663 ((and (not (equal arg '(16)))
9664 (setq sfuns
9665 (delq
9666 nil (mapcar (lambda (f)
9667 (let (fs) (if (funcall f) (push f fs))))
9668 org-store-link-functions))
9669 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9670 (or (and (cdr sfuns)
9671 (funcall (intern
9672 (completing-read
9673 "Which function for creating the link? "
9674 sfunsn nil t (car sfunsn)))))
9675 (funcall (caar sfuns)))
9676 (setq link (plist-get org-store-link-plist :link)
9677 desc (or (plist-get org-store-link-plist
9678 :description) link))))
9680 ;; Store a link from a source code buffer
9681 ((org-src-edit-buffer-p)
9682 (let (label gc)
9683 (while (or (not label)
9684 (save-excursion
9685 (save-restriction
9686 (widen)
9687 (goto-char (point-min))
9688 (re-search-forward
9689 (regexp-quote (format org-coderef-label-format label))
9690 nil t))))
9691 (when label (message "Label exists already") (sit-for 2))
9692 (setq label (read-string "Code line label: " label)))
9693 (end-of-line 1)
9694 (setq link (format org-coderef-label-format label))
9695 (setq gc (- 79 (length link)))
9696 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9697 (insert link)
9698 (setq link (concat "(" label ")") desc nil)))
9700 ;; We are in the agenda, link to referenced location
9701 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9702 (let ((m (or (get-text-property (point) 'org-hd-marker)
9703 (get-text-property (point) 'org-marker))))
9704 (when m
9705 (org-with-point-at m
9706 (setq agenda-link
9707 (if (org-called-interactively-p 'any)
9708 (call-interactively 'org-store-link)
9709 (org-store-link nil)))))))
9711 ((eq major-mode 'calendar-mode)
9712 (let ((cd (calendar-cursor-to-date)))
9713 (setq link
9714 (format-time-string
9715 (car org-time-stamp-formats)
9716 (apply 'encode-time
9717 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9718 nil nil nil))))
9719 (org-store-link-props :type "calendar" :date cd)))
9721 ((eq major-mode 'help-mode)
9722 (setq link (concat "help:" (save-excursion
9723 (goto-char (point-min))
9724 (looking-at "^[^ ]+")
9725 (match-string 0))))
9726 (org-store-link-props :type "help"))
9728 ((eq major-mode 'w3-mode)
9729 (setq cpltxt (if (and (buffer-name)
9730 (not (string-match "Untitled" (buffer-name))))
9731 (buffer-name)
9732 (url-view-url t))
9733 link (url-view-url t))
9734 (org-store-link-props :type "w3" :url (url-view-url t)))
9736 ((eq major-mode 'image-mode)
9737 (setq cpltxt (concat "file:"
9738 (abbreviate-file-name buffer-file-name))
9739 link cpltxt)
9740 (org-store-link-props :type "image" :file buffer-file-name))
9742 ;; In dired, store a link to the file of the current line
9743 ((derived-mode-p 'dired-mode)
9744 (let ((file (dired-get-filename nil t)))
9745 (setq file (if file
9746 (abbreviate-file-name
9747 (expand-file-name (dired-get-filename nil t)))
9748 ;; otherwise, no file so use current directory.
9749 default-directory))
9750 (setq cpltxt (concat "file:" file)
9751 link cpltxt)))
9753 ((setq search (run-hook-with-args-until-success
9754 'org-create-file-search-functions))
9755 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9756 "::" search))
9757 (setq cpltxt (or description link)))
9759 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9760 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9761 (cond
9762 ;; Store a link using the target at point
9763 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9764 (setq cpltxt
9765 (concat "file:"
9766 (abbreviate-file-name
9767 (buffer-file-name (buffer-base-buffer)))
9768 "::" (match-string 1))
9769 link cpltxt))
9770 ((and (featurep 'org-id)
9771 (or (eq org-id-link-to-org-use-id t)
9772 (and (org-called-interactively-p 'any)
9773 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9774 (and (eq org-id-link-to-org-use-id
9775 'create-if-interactive-and-no-custom-id)
9776 (not custom-id))))
9777 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9778 ;; Store a link using the ID at point
9779 (setq link (condition-case nil
9780 (prog1 (org-id-store-link)
9781 (setq desc (or (plist-get org-store-link-plist
9782 :description)
9783 "")))
9784 (error
9785 ;; Probably before first headline, link only to file
9786 (concat "file:"
9787 (abbreviate-file-name
9788 (buffer-file-name (buffer-base-buffer))))))))
9790 ;; Just link to current headline
9791 (setq cpltxt (concat "file:"
9792 (abbreviate-file-name
9793 (buffer-file-name (buffer-base-buffer)))))
9794 ;; Add a context search string
9795 (when (org-xor org-context-in-file-links arg)
9796 (let* ((ee (org-element-at-point))
9797 (et (org-element-type ee))
9798 (ev (plist-get (cadr ee) :value))
9799 (ek (plist-get (cadr ee) :key))
9800 (eok (and (stringp ek) (string-match "name" ek))))
9801 (setq txt (cond
9802 ((org-at-heading-p) nil)
9803 ((and (eq et 'keyword) eok) ev)
9804 ((org-region-active-p)
9805 (buffer-substring (region-beginning) (region-end)))))
9806 (when (or (null txt) (string-match "\\S-" txt))
9807 (setq cpltxt
9808 (concat cpltxt "::"
9809 (condition-case nil
9810 (org-make-org-heading-search-string txt)
9811 (error "")))
9812 desc (or (and (eq et 'keyword) eok ev)
9813 (nth 4 (ignore-errors (org-heading-components)))
9814 "NONE")))))
9815 (if (string-match "::\\'" cpltxt)
9816 (setq cpltxt (substring cpltxt 0 -2)))
9817 (setq link cpltxt))))
9819 ((buffer-file-name (buffer-base-buffer))
9820 ;; Just link to this file here.
9821 (setq cpltxt (concat "file:"
9822 (abbreviate-file-name
9823 (buffer-file-name (buffer-base-buffer)))))
9824 ;; Add a context string.
9825 (when (org-xor org-context-in-file-links arg)
9826 (setq txt (if (org-region-active-p)
9827 (buffer-substring (region-beginning) (region-end))
9828 (buffer-substring (point-at-bol) (point-at-eol))))
9829 ;; Only use search option if there is some text.
9830 (when (string-match "\\S-" txt)
9831 (setq cpltxt
9832 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9833 desc "NONE")))
9834 (setq link cpltxt))
9836 ((org-called-interactively-p 'interactive)
9837 (user-error "No method for storing a link from this buffer"))
9839 (t (setq link nil)))
9841 ;; We're done setting link and desc, clean up
9842 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9843 (setq link (or link cpltxt)
9844 desc (or desc cpltxt))
9845 (cond ((equal desc "NONE") (setq desc nil))
9846 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9847 (let ((d0 (match-string 3 desc))
9848 (p0 (match-string 5 desc)))
9849 (setq desc
9850 (replace-regexp-in-string
9851 org-bracket-link-regexp
9852 (concat (or p0 d0)
9853 (if (equal (length (match-string 0 desc))
9854 (length desc)) "*" "")) desc)))))
9856 ;; Return the link
9857 (if (not (and (or (org-called-interactively-p 'any)
9858 executing-kbd-macro) link))
9859 (or agenda-link (and link (org-make-link-string link desc)))
9860 (push (list link desc) org-stored-links)
9861 (message "Stored: %s" (or desc link))
9862 (when custom-id
9863 (setq link (concat "file:" (abbreviate-file-name
9864 (buffer-file-name)) "::#" custom-id))
9865 (push (list link desc) org-stored-links))
9866 (car org-stored-links))))))
9868 (defun org-store-link-props (&rest plist)
9869 "Store link properties, extract names and addresses."
9870 (let (x adr)
9871 (when (setq x (plist-get plist :from))
9872 (setq adr (mail-extract-address-components x))
9873 (setq plist (plist-put plist :fromname (car adr)))
9874 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9875 (when (setq x (plist-get plist :to))
9876 (setq adr (mail-extract-address-components x))
9877 (setq plist (plist-put plist :toname (car adr)))
9878 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9879 (let ((from (plist-get plist :from))
9880 (to (plist-get plist :to)))
9881 (when (and from to org-from-is-user-regexp)
9882 (setq plist
9883 (plist-put plist :fromto
9884 (if (string-match org-from-is-user-regexp from)
9885 (concat "to %t")
9886 (concat "from %f"))))))
9887 (setq org-store-link-plist plist))
9889 (defun org-add-link-props (&rest plist)
9890 "Add these properties to the link property list."
9891 (let (key value)
9892 (while plist
9893 (setq key (pop plist) value (pop plist))
9894 (setq org-store-link-plist
9895 (plist-put org-store-link-plist key value)))))
9897 (defun org-email-link-description (&optional fmt)
9898 "Return the description part of an email link.
9899 This takes information from `org-store-link-plist' and formats it
9900 according to FMT (default from `org-email-link-description-format')."
9901 (setq fmt (or fmt org-email-link-description-format))
9902 (let* ((p org-store-link-plist)
9903 (to (plist-get p :toaddress))
9904 (from (plist-get p :fromaddress))
9905 (table
9906 (list
9907 (cons "%c" (plist-get p :fromto))
9908 (cons "%F" (plist-get p :from))
9909 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9910 (cons "%T" (plist-get p :to))
9911 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9912 (cons "%s" (plist-get p :subject))
9913 (cons "%d" (plist-get p :date))
9914 (cons "%m" (plist-get p :message-id)))))
9915 (when (string-match "%c" fmt)
9916 ;; Check if the user wrote this message
9917 (if (and org-from-is-user-regexp from to
9918 (save-match-data (string-match org-from-is-user-regexp from)))
9919 (setq fmt (replace-match "to %t" t t fmt))
9920 (setq fmt (replace-match "from %f" t t fmt))))
9921 (org-replace-escapes fmt table)))
9923 (defun org-make-org-heading-search-string (&optional string)
9924 "Make search string for the current headline or STRING."
9925 (let ((s (or string
9926 (and (derived-mode-p 'org-mode)
9927 (save-excursion
9928 (org-back-to-heading t)
9929 (org-element-property :raw-value (org-element-at-point))))))
9930 (lines org-context-in-file-links))
9931 (or string (setq s (concat "*" s))) ; Add * for headlines
9932 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9933 (when (and string (integerp lines) (> lines 0))
9934 (let ((slines (org-split-string s "\n")))
9935 (when (< lines (length slines))
9936 (setq s (mapconcat
9937 'identity
9938 (reverse (nthcdr (- (length slines) lines)
9939 (reverse slines))) "\n")))))
9940 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9942 (defun org-make-link-string (link &optional description)
9943 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9944 (unless (string-match "\\S-" link)
9945 (error "Empty link"))
9946 (when (and description
9947 (stringp description)
9948 (not (string-match "\\S-" description)))
9949 (setq description nil))
9950 (when (stringp description)
9951 ;; Remove brackets from the description, they are fatal.
9952 (while (string-match "\\[" description)
9953 (setq description (replace-match "{" t t description)))
9954 (while (string-match "\\]" description)
9955 (setq description (replace-match "}" t t description))))
9956 (when (equal link description)
9957 ;; No description needed, it is identical
9958 (setq description nil))
9959 (when (and (not description)
9960 (not (string-match (org-image-file-name-regexp) link))
9961 (not (equal link (org-link-escape link))))
9962 (setq description (org-extract-attributes link)))
9963 (setq link
9964 (cond ((string-match (org-image-file-name-regexp) link) link)
9965 ((string-match org-link-types-re link)
9966 (concat (match-string 1 link)
9967 (org-link-escape (substring link (match-end 1)))))
9968 (t (org-link-escape link))))
9969 (concat "[[" link "]"
9970 (if description (concat "[" description "]") "")
9971 "]"))
9973 (defconst org-link-escape-chars
9974 ;;%20 %5B %5D
9975 '(?\ ?\[ ?\])
9976 "List of characters that should be escaped in a link when stored to Org.
9977 This is the list that is used for internal purposes.")
9979 (defconst org-link-escape-chars-browser
9980 ;;%20 %22
9981 '(?\ ?\")
9982 "List of characters to be escaped before handing over to the browser.
9983 If you consider using this constant then you probably want to use
9984 the function `org-link-escape-browser' instead. See there why
9985 this constant is a candidate to be removed once Org drops support
9986 for Emacs 24.1 and 24.2.")
9988 (defun org-link-escape (text &optional table merge)
9989 "Return percent escaped representation of TEXT.
9990 TEXT is a string with the text to escape.
9991 Optional argument TABLE is a list with characters that should be
9992 escaped. When nil, `org-link-escape-chars' is used.
9993 If optional argument MERGE is set, merge TABLE into
9994 `org-link-escape-chars'."
9995 ;; Don't escape chars in internal links
9996 (if (string-match "^\\*[[:alnum:]]+" text)
9997 text
9998 (cond
9999 ((and table merge)
10000 (mapc (lambda (defchr)
10001 (unless (member defchr table)
10002 (setq table (cons defchr table))))
10003 org-link-escape-chars))
10004 ((null table)
10005 (setq table org-link-escape-chars)))
10006 (mapconcat
10007 (lambda (char)
10008 (if (or (member char table)
10009 (and (or (< char 32) (= char ?\%) (> char 126))
10010 org-url-hexify-p))
10011 (mapconcat (lambda (sequence-element)
10012 (format "%%%.2X" sequence-element))
10013 (or (encode-coding-char char 'utf-8)
10014 (error "Unable to percent escape character: %s"
10015 (char-to-string char))) "")
10016 (char-to-string char))) text "")))
10018 (defun org-link-escape-browser (text)
10019 "Escape some characters before handing over to the browser.
10020 This function is a candidate to be removed together with the
10021 constant `org-link-escape-chars-browser' once Org drops support
10022 for Emacs 24.1 and 24.2. All calls to this function will have to
10023 be replaced with `url-encode-url' which is available since Emacs
10024 24.3.1."
10025 ;; Example with the Org link
10026 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10027 ;; to open the browser with +subject:"Release 8.2" filled into the
10028 ;; query field: In this case the variable TEXT contains the
10029 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10030 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10031 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10032 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10033 (if (fboundp 'url-encode-url)
10034 (url-encode-url text)
10035 (if (org-string-match-p
10036 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10037 text)
10038 (org-link-escape text org-link-escape-chars-browser)
10039 text)))
10041 (defun org-link-unescape (str)
10042 "Unhex hexified Unicode strings as returned from the JavaScript function
10043 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
10044 (unless (and (null str) (string= "" str))
10045 (let ((pos 0) (case-fold-search t) unhexed)
10046 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
10047 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
10048 (setq str (replace-match unhexed t t str))
10049 (setq pos (+ pos (length unhexed))))))
10050 str)
10052 (defun org-link-unescape-compound (hex)
10053 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10054 Note: this function also decodes single byte encodings like
10055 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10056 (save-match-data
10057 (let* ((bytes (cdr (split-string hex "%")))
10058 (ret "")
10059 (eat 0)
10060 (sum 0))
10061 (while bytes
10062 (let* ((val (string-to-number (pop bytes) 16))
10063 (shift-xor
10064 (if (= 0 eat)
10065 (cond
10066 ((>= val 252) (cons 6 252))
10067 ((>= val 248) (cons 5 248))
10068 ((>= val 240) (cons 4 240))
10069 ((>= val 224) (cons 3 224))
10070 ((>= val 192) (cons 2 192))
10071 (t (cons 0 0)))
10072 (cons 6 128))))
10073 (if (>= val 192) (setq eat (car shift-xor)))
10074 (setq val (logxor val (cdr shift-xor)))
10075 (setq sum (+ (lsh sum (car shift-xor)) val))
10076 (if (> eat 0) (setq eat (- eat 1)))
10077 (cond
10078 ((= 0 eat) ;multi byte
10079 (setq ret (concat ret (org-char-to-string sum)))
10080 (setq sum 0))
10081 ((not bytes) ; single byte(s)
10082 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10083 ret)))
10085 (defun org-link-unescape-single-byte-sequence (hex)
10086 "Unhexify hex-encoded single byte character sequences."
10087 (mapconcat (lambda (byte)
10088 (char-to-string (string-to-number byte 16)))
10089 (cdr (split-string hex "%")) ""))
10091 (defun org-xor (a b)
10092 "Exclusive or."
10093 (if a (not b) b))
10095 (defun org-fixup-message-id-for-http (s)
10096 "Replace special characters in a message id, so it can be used in an http query."
10097 (when (string-match "%" s)
10098 (setq s (mapconcat (lambda (c)
10099 (if (eq c ?%)
10100 "%25"
10101 (char-to-string c)))
10102 s "")))
10103 (while (string-match "<" s)
10104 (setq s (replace-match "%3C" t t s)))
10105 (while (string-match ">" s)
10106 (setq s (replace-match "%3E" t t s)))
10107 (while (string-match "@" s)
10108 (setq s (replace-match "%40" t t s)))
10111 (defun org-link-prettify (link)
10112 "Return a human-readable representation of LINK.
10113 The car of LINK must be a raw link.
10114 The cdr of LINK must be either a link description or nil."
10115 (let ((desc (or (cadr link) "<no description>")))
10116 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10117 "<" (car link) ">")))
10119 ;;;###autoload
10120 (defun org-insert-link-global ()
10121 "Insert a link like Org-mode does.
10122 This command can be called in any mode to insert a link in Org-mode syntax."
10123 (interactive)
10124 (org-load-modules-maybe)
10125 (org-run-like-in-org-mode 'org-insert-link))
10127 (defun org-insert-all-links (arg &optional pre post)
10128 "Insert all links in `org-stored-links'.
10129 When a universal prefix, do not delete the links from `org-stored-links'.
10130 When `ARG' is a number, insert the last N link(s).
10131 `PRE' and `POST' are optional arguments to define a string to
10132 prepend or to append."
10133 (interactive "P")
10134 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10135 (links (copy-seq org-stored-links))
10136 (pr (or pre "- "))
10137 (po (or post "\n"))
10138 (cnt 1) l)
10139 (if (null org-stored-links)
10140 (message "No link to insert")
10141 (while (and (or (listp arg) (>= arg cnt))
10142 (setq l (if (listp arg)
10143 (pop links)
10144 (pop org-stored-links))))
10145 (setq cnt (1+ cnt))
10146 (insert pr)
10147 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10148 (insert po)))))
10150 (defun org-insert-last-stored-link (arg)
10151 "Insert the last link stored in `org-stored-links'."
10152 (interactive "p")
10153 (org-insert-all-links arg "" "\n"))
10155 (defun org-link-fontify-links-to-this-file ()
10156 "Fontify links to the current file in `org-stored-links'."
10157 (let ((f (buffer-file-name)) a b)
10158 (setq a (mapcar (lambda(l)
10159 (let ((ll (car l)))
10160 (when (and (string-match "^file:\\(.+\\)::" ll)
10161 (equal f (expand-file-name (match-string 1 ll))))
10162 ll)))
10163 org-stored-links))
10164 (when (featurep 'org-id)
10165 (setq b (mapcar (lambda(l)
10166 (let ((ll (car l)))
10167 (when (and (string-match "^id:\\(.+\\)$" ll)
10168 (equal f (expand-file-name
10169 (or (org-id-find-id-file
10170 (match-string 1 ll)) ""))))
10171 ll)))
10172 org-stored-links)))
10173 (mapcar (lambda(l)
10174 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10175 (delq nil (append a b)))))
10177 (defvar org-link-links-in-this-file nil)
10178 (defun org-insert-link (&optional complete-file link-location default-description)
10179 "Insert a link. At the prompt, enter the link.
10181 Completion can be used to insert any of the link protocol prefixes like
10182 http or ftp in use.
10184 The history can be used to select a link previously stored with
10185 `org-store-link'. When the empty string is entered (i.e. if you just
10186 press RET at the prompt), the link defaults to the most recently
10187 stored link. As SPC triggers completion in the minibuffer, you need to
10188 use M-SPC or C-q SPC to force the insertion of a space character.
10190 You will also be prompted for a description, and if one is given, it will
10191 be displayed in the buffer instead of the link.
10193 If there is already a link at point, this command will allow you to edit link
10194 and description parts.
10196 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10197 be selected using completion. The path to the file will be relative to the
10198 current directory if the file is in the current directory or a subdirectory.
10199 Otherwise, the link will be the absolute path as completed in the minibuffer
10200 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10201 option `org-link-file-path-type'.
10203 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10204 the current directory or below.
10206 With three \\[universal-argument] prefixes, negate the meaning of
10207 `org-keep-stored-link-after-insertion'.
10209 If `org-make-link-description-function' is non-nil, this function will be
10210 called with the link target, and the result will be the default
10211 link description.
10213 If the LINK-LOCATION parameter is non-nil, this value will be
10214 used as the link location instead of reading one interactively.
10216 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10217 be used as the default description."
10218 (interactive "P")
10219 (let* ((wcf (current-window-configuration))
10220 (origbuf (current-buffer))
10221 (region (if (org-region-active-p)
10222 (buffer-substring (region-beginning) (region-end))))
10223 (remove (and region (list (region-beginning) (region-end))))
10224 (desc region)
10225 tmphist ; byte-compile incorrectly complains about this
10226 (link link-location)
10227 (abbrevs org-link-abbrev-alist-local)
10228 entry file all-prefixes auto-desc)
10229 (cond
10230 (link-location) ; specified by arg, just use it.
10231 ((org-in-regexp org-bracket-link-regexp 1)
10232 ;; We do have a link at point, and we are going to edit it.
10233 (setq remove (list (match-beginning 0) (match-end 0)))
10234 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10235 (setq link (read-string "Link: "
10236 (org-link-unescape
10237 (org-match-string-no-properties 1)))))
10238 ((or (org-in-regexp org-angle-link-re)
10239 (org-in-regexp org-plain-link-re))
10240 ;; Convert to bracket link
10241 (setq remove (list (match-beginning 0) (match-end 0))
10242 link (read-string "Link: "
10243 (org-remove-angle-brackets (match-string 0)))))
10244 ((member complete-file '((4) (16)))
10245 ;; Completing read for file names.
10246 (setq link (org-file-complete-link complete-file)))
10248 ;; Read link, with completion for stored links.
10249 (org-link-fontify-links-to-this-file)
10250 (org-switch-to-buffer-other-window "*Org Links*")
10251 (with-current-buffer "*Org Links*"
10252 (erase-buffer)
10253 (insert "Insert a link.
10254 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10255 (when org-stored-links
10256 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10257 (insert (mapconcat 'org-link-prettify
10258 (reverse org-stored-links) "\n")))
10259 (goto-char (point-min)))
10260 (let ((cw (selected-window)))
10261 (select-window (get-buffer-window "*Org Links*" 'visible))
10262 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10263 (unless (pos-visible-in-window-p (point-max))
10264 (org-fit-window-to-buffer))
10265 (and (window-live-p cw) (select-window cw)))
10266 ;; Fake a link history, containing the stored links.
10267 (setq tmphist (append (mapcar 'car org-stored-links)
10268 org-insert-link-history))
10269 (setq all-prefixes (append (mapcar 'car abbrevs)
10270 (mapcar 'car org-link-abbrev-alist)
10271 org-link-types))
10272 (unwind-protect
10273 (progn
10274 (setq link
10275 (org-completing-read
10276 "Link: "
10277 (append
10278 (mapcar (lambda (x) (concat x ":"))
10279 all-prefixes)
10280 (mapcar 'car org-stored-links))
10281 nil nil nil
10282 'tmphist
10283 (caar org-stored-links)))
10284 (if (not (string-match "\\S-" link))
10285 (user-error "No link selected"))
10286 (mapc (lambda(l)
10287 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10288 org-stored-links)
10289 (if (or (member link all-prefixes)
10290 (and (equal ":" (substring link -1))
10291 (member (substring link 0 -1) all-prefixes)
10292 (setq link (substring link 0 -1))))
10293 (setq link (with-current-buffer origbuf
10294 (org-link-try-special-completion link)))))
10295 (set-window-configuration wcf)
10296 (kill-buffer "*Org Links*"))
10297 (setq entry (assoc link org-stored-links))
10298 (or entry (push link org-insert-link-history))
10299 (setq desc (or desc (nth 1 entry)))))
10301 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10302 (not org-keep-stored-link-after-insertion))
10303 (setq org-stored-links (delq (assoc link org-stored-links)
10304 org-stored-links)))
10306 (if (and (string-match org-plain-link-re link)
10307 (not (string-match org-ts-regexp link)))
10308 ;; URL-like link, normalize the use of angular brackets.
10309 (setq link (org-remove-angle-brackets link)))
10311 ;; Check if we are linking to the current file with a search
10312 ;; option If yes, simplify the link by using only the search
10313 ;; option.
10314 (when (and buffer-file-name
10315 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10316 (let* ((path (match-string 1 link))
10317 (case-fold-search nil)
10318 (search (match-string 2 link)))
10319 (save-match-data
10320 (if (equal (file-truename buffer-file-name) (file-truename path))
10321 ;; We are linking to this same file, with a search option
10322 (setq link search)))))
10324 ;; Check if we can/should use a relative path. If yes, simplify the link
10325 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10326 (let* ((type (match-string 1 link))
10327 (path (match-string 2 link))
10328 (origpath path)
10329 (case-fold-search nil))
10330 (cond
10331 ((or (eq org-link-file-path-type 'absolute)
10332 (equal complete-file '(16)))
10333 (setq path (abbreviate-file-name (expand-file-name path))))
10334 ((eq org-link-file-path-type 'noabbrev)
10335 (setq path (expand-file-name path)))
10336 ((eq org-link-file-path-type 'relative)
10337 (setq path (file-relative-name path)))
10339 (save-match-data
10340 (if (string-match (concat "^" (regexp-quote
10341 (expand-file-name
10342 (file-name-as-directory
10343 default-directory))))
10344 (expand-file-name path))
10345 ;; We are linking a file with relative path name.
10346 (setq path (substring (expand-file-name path)
10347 (match-end 0)))
10348 (setq path (abbreviate-file-name (expand-file-name path)))))))
10349 (setq link (concat type path))
10350 (if (equal desc origpath)
10351 (setq desc path))))
10353 (if org-make-link-description-function
10354 (setq desc
10355 (or (condition-case nil
10356 (funcall org-make-link-description-function link desc)
10357 (error (progn (message "Can't get link description from `%s'"
10358 (symbol-name org-make-link-description-function))
10359 (sit-for 2) nil)))
10360 (read-string "Description: " default-description)))
10361 (if default-description (setq desc default-description)
10362 (setq desc (or (and auto-desc desc)
10363 (read-string "Description: " desc)))))
10365 (unless (string-match "\\S-" desc) (setq desc nil))
10366 (if remove (apply 'delete-region remove))
10367 (insert (org-make-link-string link desc))))
10369 (defun org-link-try-special-completion (type)
10370 "If there is completion support for link type TYPE, offer it."
10371 (let ((fun (intern (concat "org-" type "-complete-link"))))
10372 (if (functionp fun)
10373 (funcall fun)
10374 (read-string "Link (no completion support): " (concat type ":")))))
10376 (defun org-file-complete-link (&optional arg)
10377 "Create a file link using completion."
10378 (let (file link)
10379 (setq file (org-iread-file-name "File: "))
10380 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10381 (pwd1 (file-name-as-directory (abbreviate-file-name
10382 (expand-file-name ".")))))
10383 (cond
10384 ((equal arg '(16))
10385 (setq link (concat
10386 "file:"
10387 (abbreviate-file-name (expand-file-name file)))))
10388 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10389 (setq link (concat "file:" (match-string 1 file))))
10390 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10391 (expand-file-name file))
10392 (setq link (concat
10393 "file:" (match-string 1 (expand-file-name file)))))
10394 (t (setq link (concat "file:" file)))))
10395 link))
10397 (defun org-iread-file-name (&rest args)
10398 "Read-file-name using `ido-mode' speedup if available.
10399 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10400 See `read-file-name' for a description of parameters."
10401 (org-without-partial-completion
10402 (if (and org-completion-use-ido
10403 (fboundp 'ido-read-file-name)
10404 (boundp 'ido-mode) ido-mode
10405 (listp (second args)))
10406 (let ((ido-enter-matching-directory nil))
10407 (apply 'ido-read-file-name args))
10408 (apply 'read-file-name args))))
10410 (defun org-completing-read (&rest args)
10411 "Completing-read with SPACE being a normal character."
10412 (let ((enable-recursive-minibuffers t)
10413 (minibuffer-local-completion-map
10414 (copy-keymap minibuffer-local-completion-map)))
10415 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10416 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10417 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10418 (apply 'org-icompleting-read args)))
10420 (defun org-completing-read-no-i (&rest args)
10421 (let (org-completion-use-ido org-completion-use-iswitchb)
10422 (apply 'org-completing-read args)))
10424 (defun org-iswitchb-completing-read (prompt choices &rest args)
10425 "Use iswitch as a completing-read replacement to choose from choices.
10426 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10427 from."
10428 (let* ((iswitchb-use-virtual-buffers nil)
10429 (iswitchb-make-buflist-hook
10430 (lambda ()
10431 (setq iswitchb-temp-buflist choices))))
10432 (iswitchb-read-buffer prompt)))
10434 (defun org-icompleting-read (&rest args)
10435 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10436 (org-without-partial-completion
10437 (if (and org-completion-use-ido
10438 (fboundp 'ido-completing-read)
10439 (boundp 'ido-mode) ido-mode
10440 (listp (second args)))
10441 (let ((ido-enter-matching-directory nil))
10442 (apply 'ido-completing-read (concat (car args))
10443 (if (consp (car (nth 1 args)))
10444 (mapcar 'car (nth 1 args))
10445 (nth 1 args))
10446 (cddr args)))
10447 (if (and org-completion-use-iswitchb
10448 (boundp 'iswitchb-mode) iswitchb-mode
10449 (listp (second args)))
10450 (apply 'org-iswitchb-completing-read (concat (car args))
10451 (if (consp (car (nth 1 args)))
10452 (mapcar 'car (nth 1 args))
10453 (nth 1 args))
10454 (cddr args))
10455 (apply 'completing-read args)))))
10457 (defun org-extract-attributes (s)
10458 "Extract the attributes cookie from a string and set as text property."
10459 (let (a attr (start 0) key value)
10460 (save-match-data
10461 (when (string-match "{{\\([^}]+\\)}}$" s)
10462 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10463 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10464 (setq key (match-string 1 a) value (match-string 2 a)
10465 start (match-end 0)
10466 attr (plist-put attr (intern key) value))))
10467 (org-add-props s nil 'org-attr attr))
10470 ;;; Opening/following a link
10472 (defvar org-link-search-failed nil)
10474 (defvar org-open-link-functions nil
10475 "Hook for functions finding a plain text link.
10476 These functions must take a single argument, the link content.
10477 They will be called for links that look like [[link text][description]]
10478 when LINK TEXT does not have a protocol like \"http:\" and does not look
10479 like a filename (e.g. \"./blue.png\").
10481 These functions will be called *before* Org attempts to resolve the
10482 link by doing text searches in the current buffer - so if you want a
10483 link \"[[target]]\" to still find \"<<target>>\", your function should
10484 handle this as a special case.
10486 When the function does handle the link, it must return a non-nil value.
10487 If it decides that it is not responsible for this link, it must return
10488 nil to indicate that that Org-mode can continue with other options
10489 like exact and fuzzy text search.")
10491 (defun org-next-link (&optional search-backward)
10492 "Move forward to the next link.
10493 If the link is in hidden text, expose it."
10494 (interactive "P")
10495 (when (and org-link-search-failed (eq this-command last-command))
10496 (goto-char (point-min))
10497 (message "Link search wrapped back to beginning of buffer"))
10498 (setq org-link-search-failed nil)
10499 (let* ((pos (point))
10500 (ct (org-context))
10501 (a (assoc :link ct))
10502 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10503 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10504 ((looking-at org-any-link-re)
10505 ;; Don't stay stuck at link without an org-link face
10506 (forward-char (if search-backward -1 1))))
10507 (if (funcall srch-fun org-any-link-re nil t)
10508 (progn
10509 (goto-char (match-beginning 0))
10510 (if (outline-invisible-p) (org-show-context)))
10511 (goto-char pos)
10512 (setq org-link-search-failed t)
10513 (message "No further link found"))))
10515 (defun org-previous-link ()
10516 "Move backward to the previous link.
10517 If the link is in hidden text, expose it."
10518 (interactive)
10519 (funcall 'org-next-link t))
10521 (defun org-translate-link (s)
10522 "Translate a link string if a translation function has been defined."
10523 (if (and org-link-translation-function
10524 (fboundp org-link-translation-function)
10525 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10526 (progn
10527 (setq s (funcall org-link-translation-function
10528 (match-string 1 s) (match-string 2 s)))
10529 (concat (car s) ":" (cdr s)))
10532 (defun org-translate-link-from-planner (type path)
10533 "Translate a link from Emacs Planner syntax so that Org can follow it.
10534 This is still an experimental function, your mileage may vary."
10535 (cond
10536 ((member type '("http" "https" "news" "ftp"))
10537 ;; standard Internet links are the same.
10538 nil)
10539 ((and (equal type "irc") (string-match "^//" path))
10540 ;; Planner has two / at the beginning of an irc link, we have 1.
10541 ;; We should have zero, actually....
10542 (setq path (substring path 1)))
10543 ((and (equal type "lisp") (string-match "^/" path))
10544 ;; Planner has a slash, we do not.
10545 (setq type "elisp" path (substring path 1)))
10546 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10547 ;; A typical message link. Planner has the id after the final slash,
10548 ;; we separate it with a hash mark
10549 (setq path (concat (match-string 1 path) "#"
10550 (org-remove-angle-brackets (match-string 2 path))))))
10551 (cons type path))
10553 (defun org-find-file-at-mouse (ev)
10554 "Open file link or URL at mouse."
10555 (interactive "e")
10556 (mouse-set-point ev)
10557 (org-open-at-point 'in-emacs))
10559 (defun org-open-at-mouse (ev)
10560 "Open file link or URL at mouse.
10561 See the docstring of `org-open-file' for details."
10562 (interactive "e")
10563 (mouse-set-point ev)
10564 (if (eq major-mode 'org-agenda-mode)
10565 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10566 (org-open-at-point))
10568 (defvar org-window-config-before-follow-link nil
10569 "The window configuration before following a link.
10570 This is saved in case the need arises to restore it.")
10572 (defvar org-open-link-marker (make-marker)
10573 "Marker pointing to the location where `org-open-at-point' was called.")
10575 ;;;###autoload
10576 (defun org-open-at-point-global ()
10577 "Follow a link like Org-mode does.
10578 This command can be called in any mode to follow a link that has
10579 Org-mode syntax."
10580 (interactive)
10581 (org-run-like-in-org-mode 'org-open-at-point))
10583 ;;;###autoload
10584 (defun org-open-link-from-string (s &optional arg reference-buffer)
10585 "Open a link in the string S, as if it was in Org-mode."
10586 (interactive "sLink: \nP")
10587 (let ((reference-buffer (or reference-buffer (current-buffer))))
10588 (with-temp-buffer
10589 (let ((org-inhibit-startup (not reference-buffer)))
10590 (org-mode)
10591 (insert s)
10592 (goto-char (point-min))
10593 (when reference-buffer
10594 (setq org-link-abbrev-alist-local
10595 (with-current-buffer reference-buffer
10596 org-link-abbrev-alist-local)))
10597 (org-open-at-point arg reference-buffer)))))
10599 (defvar org-open-at-point-functions nil
10600 "Hook that is run when following a link at point.
10602 Functions in this hook must return t if they identify and follow
10603 a link at point. If they don't find anything interesting at point,
10604 they must return nil.")
10606 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10607 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10608 (defun org-open-at-point (&optional arg reference-buffer)
10609 "Open link, timestamp, footnote or tags at point.
10611 When point is on a link, follow it. Normally, files will be
10612 opened by an appropriate application. If the optional prefix
10613 argument ARG is non-nil, Emacs will visit the file. With
10614 a double prefix argument, try to open outside of Emacs, in the
10615 application the system uses for this file type.
10617 When point is on a timestamp, open the agenda at the day
10618 specified.
10620 When point is a footnote definition, move to the first reference
10621 found. If it is on a reference, move to the associated
10622 definition.
10624 When point is on a headline, display a list of every link in the
10625 entry, so it is possible to pick one, or all, of them. If point
10626 is on a tag, call `org-tags-view' instead.
10628 When optional argument REFERENCE-BUFFER is non-nil, it should
10629 specify a buffer from where the link search should happen. This
10630 is used internally by `org-open-link-from-string'.
10632 On top of syntactically correct links, this function will open
10633 the link at point in comments or comment blocks and the first
10634 link in a property drawer line."
10635 (interactive "P")
10636 ;; On a code block, open block's results.
10637 (unless (call-interactively 'org-babel-open-src-block-result)
10638 (org-load-modules-maybe)
10639 (move-marker org-open-link-marker (point))
10640 (setq org-window-config-before-follow-link (current-window-configuration))
10641 (org-remove-occur-highlights nil nil t)
10642 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10643 (let* ((context (org-element-context)) type value)
10644 ;; On an unsupported type, check if point is contained within
10645 ;; a support one.
10646 (while (and (not (memq (setq type (org-element-type context))
10647 '(comment comment-block
10648 headline inlinetask link
10649 footnote-definition footnote-reference
10650 node-property timestamp)))
10651 (setq context (org-element-property :parent context))))
10652 (setq value (org-element-property :value context))
10653 (cond
10654 ;; Blank lines at the beginning of buffer: bail out.
10655 ((not context) (user-error "No link found"))
10656 ;; Exception n°1: links in property drawers
10657 ((eq type 'node-property)
10658 (org-open-link-from-string
10659 (and (string-match org-any-link-re value)
10660 (match-string-no-properties 0 value))))
10661 ;; Exception n°2: links in comments.
10662 ((memq type '(comment comment-block))
10663 (save-excursion
10664 (skip-chars-forward "\\S-" (point-at-eol))
10665 (let ((string-rear (replace-regexp-in-string
10666 "^[ \t]*# [ \t]*" ""
10667 (buffer-substring (point) (line-beginning-position))))
10668 (string-front (buffer-substring (point) (line-end-position))))
10669 (with-temp-buffer
10670 (let ((org-inhibit-startup t)) (org-mode))
10671 (insert value)
10672 (goto-char (point-min))
10673 (when (and (search-forward string-rear nil t)
10674 (search-forward string-front (line-end-position) t))
10675 (goto-char (match-beginning 0))
10676 (org-open-at-point)
10677 (when (string= string-rear "") (forward-char)))))))
10678 ;; On a headline or an inlinetask, but not on a timestamp,
10679 ;; a link, a footnote reference or on tags.
10680 ((and (memq type '(headline inlinetask))
10681 ;; Not on tags.
10682 (progn (save-excursion (beginning-of-line)
10683 (looking-at org-complex-heading-regexp))
10684 (or (not (match-beginning 5))
10685 (< (point) (match-beginning 5)))))
10686 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10687 (links (car data))
10688 (links-end (cdr data)))
10689 (if links
10690 (dolist (link (if (stringp links) (list links) links))
10691 (search-forward link nil links-end)
10692 (goto-char (match-beginning 0))
10693 (org-open-at-point))
10694 (require 'org-attach)
10695 (org-attach-reveal 'if-exists))))
10696 ;; Do nothing on white spaces after an object, unless point
10697 ;; is right after it.
10698 ((> (point)
10699 (save-excursion
10700 (goto-char (org-element-property :end context))
10701 (skip-chars-backward " \t")
10702 (point)))
10703 (user-error "No link found"))
10704 ((eq type 'timestamp) (org-follow-timestamp-link))
10705 ;; On tags within a headline or an inlinetask.
10706 ((and (memq type '(headline inlinetask))
10707 (progn (save-excursion (beginning-of-line)
10708 (looking-at org-complex-heading-regexp))
10709 (and (match-beginning 5)
10710 (>= (point) (match-beginning 5)))))
10711 (org-tags-view arg (substring (match-string 5) 0 -1)))
10712 ((eq type 'link)
10713 (let ((type (org-element-property :type context))
10714 (path (org-link-unescape (org-element-property :path context))))
10715 ;; Switch back to REFERENCE-BUFFER needed when called in
10716 ;; a temporary buffer through `org-open-link-from-string'.
10717 (with-current-buffer (or reference-buffer (current-buffer))
10718 (cond
10719 ((equal type "file")
10720 (if (string-match "[*?{]" (file-name-nondirectory path))
10721 (dired path)
10722 ;; Look into `org-link-protocols' in order to find
10723 ;; a DEDICATED-FUNCTION to open file. The function
10724 ;; will be applied on raw link instead of parsed
10725 ;; link due to the limitation in `org-add-link-type'
10726 ;; ("open" function called with a single argument).
10727 ;; If no such function is found, fallback to
10728 ;; `org-open-file'.
10730 ;; Note : "file+emacs" and "file+sys" types are
10731 ;; hard-coded in order to escape the previous
10732 ;; limitation.
10733 (let* ((option (org-element-property :search-option context))
10734 (app (org-element-property :application context))
10735 (dedicated-function
10736 (nth 1 (assoc app org-link-protocols))))
10737 (if dedicated-function
10738 (funcall dedicated-function
10739 (concat path
10740 (and option (concat "::" option))))
10741 (apply 'org-open-file
10742 path
10743 (cond (arg)
10744 ((equal app "emacs") 'emacs)
10745 ((equal app "sys") 'system))
10746 (cond ((not option) nil)
10747 ((org-string-match-p "\\`[0-9]+\\'" option)
10748 (list (string-to-number option)))
10749 (t (list nil
10750 (org-link-unescape option)))))))))
10751 ((assoc type org-link-protocols)
10752 (funcall (nth 1 (assoc type org-link-protocols)) path))
10753 ((equal type "help")
10754 (let ((f-or-v (intern path)))
10755 (cond ((fboundp f-or-v) (describe-function f-or-v))
10756 ((boundp f-or-v) (describe-variable f-or-v))
10757 (t (error "Not a known function or variable")))))
10758 ((member type '("http" "https" "ftp" "mailto" "news"))
10759 (browse-url (org-link-escape-browser (concat type ":" path))))
10760 ((equal type "doi")
10761 (browse-url
10762 (org-link-escape-browser (concat org-doi-server-url path))))
10763 ((equal type "message") (browse-url (concat type ":" path)))
10764 ((equal type "shell")
10765 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10766 (cmd path))
10767 (if (or (and (org-string-nw-p
10768 org-confirm-shell-link-not-regexp)
10769 (string-match
10770 org-confirm-shell-link-not-regexp cmd))
10771 (not org-confirm-shell-link-function)
10772 (funcall org-confirm-shell-link-function
10773 (format "Execute \"%s\" in shell? "
10774 (org-add-props cmd nil
10775 'face 'org-warning))))
10776 (progn
10777 (message "Executing %s" cmd)
10778 (shell-command cmd buf)
10779 (when (featurep 'midnight)
10780 (setq clean-buffer-list-kill-buffer-names
10781 (cons buf
10782 clean-buffer-list-kill-buffer-names))))
10783 (user-error "Abort"))))
10784 ((equal type "elisp")
10785 (let ((cmd path))
10786 (if (or (and (org-string-nw-p
10787 org-confirm-elisp-link-not-regexp)
10788 (org-string-match-p
10789 org-confirm-elisp-link-not-regexp cmd))
10790 (not org-confirm-elisp-link-function)
10791 (funcall org-confirm-elisp-link-function
10792 (format "Execute \"%s\" as elisp? "
10793 (org-add-props cmd nil
10794 'face 'org-warning))))
10795 (message "%s => %s" cmd
10796 (if (eq (string-to-char cmd) ?\()
10797 (eval (read cmd))
10798 (call-interactively (read cmd))))
10799 (user-error "Abort"))))
10800 ((equal type "id")
10801 (require 'ord-id)
10802 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10803 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10804 (unless (run-hook-with-args-until-success
10805 'org-open-link-functions path)
10806 (if (not arg) (org-mark-ring-push)
10807 (switch-to-buffer-other-window
10808 (org-get-buffer-for-internal-link (current-buffer))))
10809 (let ((cmd `(org-link-search
10810 ,(if (member type '("custom-id" "coderef"))
10811 (org-element-property :raw-link context)
10812 path)
10813 ,(cond ((equal arg '(4)) 'occur)
10814 ((equal arg '(16)) 'org-occur))
10815 ,(org-element-property :begin context))))
10816 (condition-case nil
10817 (let ((org-link-search-inhibit-query t))
10818 (eval cmd))
10819 (error (progn (widen) (eval cmd)))))))
10820 (t (browse-url-at-point))))))
10821 ;; On a footnote reference or at a footnote definition's label.
10822 ((or (eq type 'footnote-reference)
10823 (and (eq type 'footnote-definition)
10824 (save-excursion
10825 ;; Do not validate action when point is on the
10826 ;; spaces right after the footnote label, in
10827 ;; order to be on par with behaviour on links.
10828 (skip-chars-forward " \t")
10829 (let ((begin
10830 (org-element-property :contents-begin context)))
10831 (if begin (< (point) begin)
10832 (= (org-element-property :post-affiliated context)
10833 (line-beginning-position)))))))
10834 (org-footnote-action))
10835 (t (user-error "No link found")))))
10836 (move-marker org-open-link-marker nil)
10837 (run-hook-with-args 'org-follow-link-hook)))
10839 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10840 "Offer links in the current entry and return the selected link.
10841 If there is only one link, return it.
10842 If NTH is an integer, return the NTH link found.
10843 If ZERO is a string, check also this string for a link, and if
10844 there is one, return it."
10845 (with-current-buffer buffer
10846 (save-excursion
10847 (save-restriction
10848 (widen)
10849 (goto-char marker)
10850 (let ((cnt ?0)
10851 (in-emacs (if (integerp nth) nil nth))
10852 have-zero end links link c)
10853 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10854 (push (match-string 0 zero) links)
10855 (setq cnt (1- cnt) have-zero t))
10856 (save-excursion
10857 (org-back-to-heading t)
10858 (setq end (save-excursion (outline-next-heading) (point)))
10859 (while (re-search-forward org-any-link-re end t)
10860 (push (match-string 0) links))
10861 (setq links (org-uniquify (reverse links))))
10862 (cond
10863 ((null links)
10864 (message "No links"))
10865 ((equal (length links) 1)
10866 (setq link (car links)))
10867 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10868 (setq link (nth (if have-zero nth (1- nth)) links)))
10869 (t ; we have to select a link
10870 (save-excursion
10871 (save-window-excursion
10872 (delete-other-windows)
10873 (with-output-to-temp-buffer "*Select Link*"
10874 (mapc (lambda (l)
10875 (if (not (string-match org-bracket-link-regexp l))
10876 (princ (format "[%c] %s\n" (incf cnt)
10877 (org-remove-angle-brackets l)))
10878 (if (match-end 3)
10879 (princ (format "[%c] %s (%s)\n" (incf cnt)
10880 (match-string 3 l) (match-string 1 l)))
10881 (princ (format "[%c] %s\n" (incf cnt)
10882 (match-string 1 l))))))
10883 links))
10884 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10885 (message "Select link to open, RET to open all:")
10886 (setq c (read-char-exclusive))
10887 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10888 (when (equal c ?q) (user-error "Abort"))
10889 (if (equal c ?\C-m)
10890 (setq link links)
10891 (setq nth (- c ?0))
10892 (if have-zero (setq nth (1+ nth)))
10893 (unless (and (integerp nth) (>= (length links) nth))
10894 (user-error "Invalid link selection"))
10895 (setq link (nth (1- nth) links)))))
10896 (cons link end))))))
10898 ;; TODO: These functions are deprecated since `org-open-at-point'
10899 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10900 (defun org-open-file-with-system (path)
10901 "Open file at PATH using the system way of opening it."
10902 (org-open-file path 'system))
10903 (defun org-open-file-with-emacs (path)
10904 "Open file at PATH in Emacs."
10905 (org-open-file path 'emacs))
10908 ;;; File search
10910 (defvar org-create-file-search-functions nil
10911 "List of functions to construct the right search string for a file link.
10912 These functions are called in turn with point at the location to
10913 which the link should point.
10915 A function in the hook should first test if it would like to
10916 handle this file type, for example by checking the `major-mode'
10917 or the file extension. If it decides not to handle this file, it
10918 should just return nil to give other functions a chance. If it
10919 does handle the file, it must return the search string to be used
10920 when following the link. The search string will be part of the
10921 file link, given after a double colon, and `org-open-at-point'
10922 will automatically search for it. If special measures must be
10923 taken to make the search successful, another function should be
10924 added to the companion hook `org-execute-file-search-functions',
10925 which see.
10927 A function in this hook may also use `setq' to set the variable
10928 `description' to provide a suggestion for the descriptive text to
10929 be used for this link when it gets inserted into an Org-mode
10930 buffer with \\[org-insert-link].")
10932 (defvar org-execute-file-search-functions nil
10933 "List of functions to execute a file search triggered by a link.
10935 Functions added to this hook must accept a single argument, the
10936 search string that was part of the file link, the part after the
10937 double colon. The function must first check if it would like to
10938 handle this search, for example by checking the `major-mode' or
10939 the file extension. If it decides not to handle this search, it
10940 should just return nil to give other functions a chance. If it
10941 does handle the search, it must return a non-nil value to keep
10942 other functions from trying.
10944 Each function can access the current prefix argument through the
10945 variable `current-prefix-arg'. Note that a single prefix is used
10946 to force opening a link in Emacs, so it may be good to only use a
10947 numeric or double prefix to guide the search function.
10949 In case this is needed, a function in this hook can also restore
10950 the window configuration before `org-open-at-point' was called using:
10952 (set-window-configuration org-window-config-before-follow-link)")
10954 (defun org-link-search (s &optional type avoid-pos stealth)
10955 "Search for a link search option.
10956 If S is surrounded by forward slashes, it is interpreted as a
10957 regular expression. In org-mode files, this will create an `org-occur'
10958 sparse tree. In ordinary files, `occur' will be used to list matches.
10959 If the current buffer is in `dired-mode', grep will be used to search
10960 in all files. If AVOID-POS is given, ignore matches near that position.
10962 When optional argument STEALTH is non-nil, do not modify
10963 visibility around point, thus ignoring
10964 `org-show-hierarchy-above', `org-show-following-heading' and
10965 `org-show-siblings' variables."
10966 (let ((case-fold-search t)
10967 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10968 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10969 (append '(("") (" ") ("\t") ("\n"))
10970 org-emphasis-alist)
10971 "\\|") "\\)"))
10972 (pos (point))
10973 (pre nil) (post nil)
10974 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10975 (cond
10976 ;; First check if there are any special search functions
10977 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10978 ;; Now try the builtin stuff
10979 ((and (equal (string-to-char s0) ?#)
10980 (> (length s0) 1)
10981 (save-excursion
10982 (goto-char (point-min))
10983 (and
10984 (re-search-forward
10985 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10986 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10987 (setq type 'dedicated
10988 pos (match-beginning 0))))
10989 ;; There is an exact target for this
10990 (goto-char pos)
10991 (org-back-to-heading t)))
10992 ((save-excursion
10993 (goto-char (point-min))
10994 (and
10995 (re-search-forward
10996 (concat "<<" (regexp-quote s0) ">>") nil t)
10997 (setq type 'dedicated
10998 pos (match-beginning 0))))
10999 ;; There is an exact target for this
11000 (goto-char pos))
11001 ((save-excursion
11002 (goto-char (point-min))
11003 (and
11004 (re-search-forward
11005 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
11006 (setq type 'dedicated pos (match-beginning 0))))
11007 ;; Found an element with a matching #+name affiliated keyword.
11008 (goto-char pos))
11009 ((and (string-match "^(\\(.*\\))$" s0)
11010 (save-excursion
11011 (goto-char (point-min))
11012 (and
11013 (re-search-forward
11014 (concat "[^[]" (regexp-quote
11015 (format org-coderef-label-format
11016 (match-string 1 s0))))
11017 nil t)
11018 (setq type 'dedicated
11019 pos (1+ (match-beginning 0))))))
11020 ;; There is a coderef target for this
11021 (goto-char pos))
11022 ((string-match "^/\\(.*\\)/$" s)
11023 ;; A regular expression
11024 (cond
11025 ((derived-mode-p 'org-mode)
11026 (org-occur (match-string 1 s)))
11027 (t (org-do-occur (match-string 1 s)))))
11028 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
11029 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
11030 (goto-char (point-min))
11031 (cond
11032 ((let (case-fold-search)
11033 (re-search-forward (format org-complex-heading-regexp-format
11034 (regexp-quote s))
11035 nil t))
11036 ;; OK, found a match
11037 (setq type 'dedicated)
11038 (goto-char (match-beginning 0)))
11039 ((and (not org-link-search-inhibit-query)
11040 (eq org-link-search-must-match-exact-headline 'query-to-create)
11041 (y-or-n-p "No match - create this as a new heading? "))
11042 (goto-char (point-max))
11043 (or (bolp) (newline))
11044 (insert "* " s "\n")
11045 (beginning-of-line 0))
11047 (goto-char pos)
11048 (error "No match"))))
11050 ;; A normal search string
11051 (when (equal (string-to-char s) ?*)
11052 ;; Anchor on headlines, post may include tags.
11053 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11054 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
11055 s (substring s 1)))
11056 (remove-text-properties
11057 0 (length s)
11058 '(face nil mouse-face nil keymap nil fontified nil) s)
11059 ;; Make a series of regular expressions to find a match
11060 (setq words (org-split-string s "[ \n\r\t]+")
11062 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11063 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11064 "\\)" markers)
11065 re2a_ (concat "\\(" (mapconcat 'downcase words
11066 "[ \t\r\n]+") "\\)[ \t\r\n]")
11067 re2a (concat "[ \t\r\n]" re2a_)
11068 re4_ (concat "\\(" (mapconcat 'downcase words
11069 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11070 re4 (concat "[^a-zA-Z_]" re4_)
11072 re1 (concat pre re2 post)
11073 re3 (concat pre (if pre re4_ re4) post)
11074 re5 (concat pre ".*" re4)
11075 re2 (concat pre re2)
11076 re2a (concat pre (if pre re2a_ re2a))
11077 re4 (concat pre (if pre re4_ re4))
11078 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11079 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11080 re5 "\\)"))
11081 (cond
11082 ((eq type 'org-occur) (org-occur reall))
11083 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11084 (t (goto-char (point-min))
11085 (setq type 'fuzzy)
11086 (if (or (and (org-search-not-self 1 re0 nil t)
11087 (setq type 'dedicated))
11088 (org-search-not-self 1 re1 nil t)
11089 (org-search-not-self 1 re2 nil t)
11090 (org-search-not-self 1 re2a nil t)
11091 (org-search-not-self 1 re3 nil t)
11092 (org-search-not-self 1 re4 nil t)
11093 (org-search-not-self 1 re5 nil t))
11094 (goto-char (match-beginning 1))
11095 (goto-char pos)
11096 (error "No match"))))))
11097 (and (derived-mode-p 'org-mode)
11098 (not stealth)
11099 (org-show-context 'link-search))
11100 type))
11102 (defun org-search-not-self (group &rest args)
11103 "Execute `re-search-forward', but only accept matches that do not
11104 enclose the position of `org-open-link-marker'."
11105 (let ((m org-open-link-marker))
11106 (catch 'exit
11107 (while (apply 're-search-forward args)
11108 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11109 (goto-char (match-end group))
11110 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11111 (> (match-beginning 0) (marker-position m))
11112 (< (match-end 0) (marker-position m)))
11113 (save-match-data
11114 (or (not (org-in-regexp
11115 org-bracket-link-analytic-regexp 1))
11116 (not (match-end 4)) ; no description
11117 (and (<= (match-beginning 4) (point))
11118 (>= (match-end 4) (point))))))
11119 (throw 'exit (point))))))))
11121 (defun org-get-buffer-for-internal-link (buffer)
11122 "Return a buffer to be used for displaying the link target of internal links."
11123 (cond
11124 ((not org-display-internal-link-with-indirect-buffer)
11125 buffer)
11126 ((string-match "(Clone)$" (buffer-name buffer))
11127 (message "Buffer is already a clone, not making another one")
11128 ;; we also do not modify visibility in this case
11129 buffer)
11130 (t ; make a new indirect buffer for displaying the link
11131 (let* ((bn (buffer-name buffer))
11132 (ibn (concat bn "(Clone)"))
11133 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11134 (with-current-buffer ib (org-overview))
11135 ib))))
11137 (defun org-do-occur (regexp &optional cleanup)
11138 "Call the Emacs command `occur'.
11139 If CLEANUP is non-nil, remove the printout of the regular expression
11140 in the *Occur* buffer. This is useful if the regex is long and not useful
11141 to read."
11142 (occur regexp)
11143 (when cleanup
11144 (let ((cwin (selected-window)) win beg end)
11145 (when (setq win (get-buffer-window "*Occur*"))
11146 (select-window win))
11147 (goto-char (point-min))
11148 (when (re-search-forward "match[a-z]+" nil t)
11149 (setq beg (match-end 0))
11150 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11151 (setq end (1- (match-beginning 0)))))
11152 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11153 (goto-char (point-min))
11154 (select-window cwin))))
11156 ;;; The mark ring for links jumps
11158 (defvar org-mark-ring nil
11159 "Mark ring for positions before jumps in Org-mode.")
11160 (defvar org-mark-ring-last-goto nil
11161 "Last position in the mark ring used to go back.")
11162 ;; Fill and close the ring
11163 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11164 (loop for i from 1 to org-mark-ring-length do
11165 (push (make-marker) org-mark-ring))
11166 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11167 org-mark-ring)
11169 (defun org-mark-ring-push (&optional pos buffer)
11170 "Put the current position or POS into the mark ring and rotate it."
11171 (interactive)
11172 (setq pos (or pos (point)))
11173 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11174 (move-marker (car org-mark-ring)
11175 (or pos (point))
11176 (or buffer (current-buffer)))
11177 (message "%s"
11178 (substitute-command-keys
11179 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11181 (defun org-mark-ring-goto (&optional n)
11182 "Jump to the previous position in the mark ring.
11183 With prefix arg N, jump back that many stored positions. When
11184 called several times in succession, walk through the entire ring.
11185 Org-mode commands jumping to a different position in the current file,
11186 or to another Org-mode file, automatically push the old position
11187 onto the ring."
11188 (interactive "p")
11189 (let (p m)
11190 (if (eq last-command this-command)
11191 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11192 (setq p org-mark-ring))
11193 (setq org-mark-ring-last-goto p)
11194 (setq m (car p))
11195 (org-pop-to-buffer-same-window (marker-buffer m))
11196 (goto-char m)
11197 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11199 (defun org-remove-angle-brackets (s)
11200 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11201 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11203 (defun org-add-angle-brackets (s)
11204 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11205 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11207 (defun org-remove-double-quotes (s)
11208 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11209 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11212 ;;; Following specific links
11214 (defun org-follow-timestamp-link ()
11215 "Open an agenda view for the time-stamp date/range at point."
11216 (cond
11217 ((org-at-date-range-p t)
11218 (let ((org-agenda-start-on-weekday)
11219 (t1 (match-string 1))
11220 (t2 (match-string 2)) tt1 tt2)
11221 (setq tt1 (time-to-days (org-time-string-to-time t1))
11222 tt2 (time-to-days (org-time-string-to-time t2)))
11223 (let ((org-agenda-buffer-tmp-name
11224 (format "*Org Agenda(a:%s)"
11225 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11226 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11227 ((org-at-timestamp-p t)
11228 (let ((org-agenda-buffer-tmp-name
11229 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11230 (org-agenda-list nil (time-to-days (org-time-string-to-time
11231 (substring (match-string 1) 0 10)))
11232 1)))
11233 (t (error "This should not happen"))))
11236 ;;; Following file links
11237 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11238 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11239 (declare-function mailcap-mime-info
11240 "mailcap" (string &optional request no-decode))
11241 (defvar org-wait nil)
11242 (defun org-open-file (path &optional in-emacs line search)
11243 "Open the file at PATH.
11244 First, this expands any special file name abbreviations. Then the
11245 configuration variable `org-file-apps' is checked if it contains an
11246 entry for this file type, and if yes, the corresponding command is launched.
11248 If no application is found, Emacs simply visits the file.
11250 With optional prefix argument IN-EMACS, Emacs will visit the file.
11251 With a double \\[universal-argument] \\[universal-argument] \
11252 prefix arg, Org tries to avoid opening in Emacs
11253 and to use an external application to visit the file.
11255 Optional LINE specifies a line to go to, optional SEARCH a string
11256 to search for. If LINE or SEARCH is given, the file will be
11257 opened in Emacs, unless an entry from org-file-apps that makes
11258 use of groups in a regexp matches.
11260 If you want to change the way frames are used when following a
11261 link, please customize `org-link-frame-setup'.
11263 If the file does not exist, an error is thrown."
11264 (let* ((file (if (equal path "")
11265 buffer-file-name
11266 (substitute-in-file-name (expand-file-name path))))
11267 (file-apps (append org-file-apps (org-default-apps)))
11268 (apps (org-remove-if
11269 'org-file-apps-entry-match-against-dlink-p file-apps))
11270 (apps-dlink (org-remove-if-not
11271 'org-file-apps-entry-match-against-dlink-p file-apps))
11272 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11273 (dirp (if remp nil (file-directory-p file)))
11274 (file (if (and dirp org-open-directory-means-index-dot-org)
11275 (concat (file-name-as-directory file) "index.org")
11276 file))
11277 (a-m-a-p (assq 'auto-mode apps))
11278 (dfile (downcase file))
11279 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11280 (link (cond ((and (eq line nil)
11281 (eq search nil))
11282 file)
11283 (line
11284 (concat file "::" (number-to-string line)))
11285 (search
11286 (concat file "::" search))))
11287 (dlink (downcase link))
11288 (old-buffer (current-buffer))
11289 (old-pos (point))
11290 (old-mode major-mode)
11291 ext cmd link-match-data)
11292 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11293 (setq ext (match-string 1 dfile))
11294 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11295 (setq ext (match-string 1 dfile))))
11296 (cond
11297 ((member in-emacs '((16) system))
11298 (setq cmd (cdr (assoc 'system apps))))
11299 (in-emacs (setq cmd 'emacs))
11301 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11302 (and dirp (cdr (assoc 'directory apps)))
11303 ; first, try matching against apps-dlink
11304 ; if we get a match here, store the match data for later
11305 (let ((match (assoc-default dlink apps-dlink
11306 'string-match)))
11307 (if match
11308 (progn (setq link-match-data (match-data))
11309 match)
11310 (progn (setq in-emacs (or in-emacs line search))
11311 nil))) ; if we have no match in apps-dlink,
11312 ; always open the file in emacs if line or search
11313 ; is given (for backwards compatibility)
11314 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11315 'string-match)
11316 (cdr (assoc ext apps))
11317 (cdr (assoc t apps))))))
11318 (when (eq cmd 'system)
11319 (setq cmd (cdr (assoc 'system apps))))
11320 (when (eq cmd 'default)
11321 (setq cmd (cdr (assoc t apps))))
11322 (when (eq cmd 'mailcap)
11323 (require 'mailcap)
11324 (mailcap-parse-mailcaps)
11325 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11326 (command (mailcap-mime-info mime-type)))
11327 (if (stringp command)
11328 (setq cmd command)
11329 (setq cmd 'emacs))))
11330 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11331 (not (file-exists-p file))
11332 (not org-open-non-existing-files))
11333 (user-error "No such file: %s" file))
11334 (cond
11335 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11336 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11337 (while (string-match "['\"]%s['\"]" cmd)
11338 (setq cmd (replace-match "%s" t t cmd)))
11339 (while (string-match "%s" cmd)
11340 (setq cmd (replace-match
11341 (save-match-data
11342 (shell-quote-argument
11343 (convert-standard-filename file)))
11344 t t cmd)))
11346 ;; Replace "%1", "%2" etc. in command with group matches from regex
11347 (save-match-data
11348 (let ((match-index 1)
11349 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11350 (set-match-data link-match-data)
11351 (while (<= match-index number-of-groups)
11352 (let ((regex (concat "%" (number-to-string match-index)))
11353 (replace-with (match-string match-index dlink)))
11354 (while (string-match regex cmd)
11355 (setq cmd (replace-match replace-with t t cmd))))
11356 (setq match-index (+ match-index 1)))))
11358 (save-window-excursion
11359 (message "Running %s...done" cmd)
11360 (start-process-shell-command cmd nil cmd)
11361 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11362 ((or (stringp cmd)
11363 (eq cmd 'emacs))
11364 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11365 (widen)
11366 (if line (progn (org-goto-line line)
11367 (if (derived-mode-p 'org-mode)
11368 (org-reveal)))
11369 (if search (org-link-search search))))
11370 ((consp cmd)
11371 (let ((file (convert-standard-filename file)))
11372 (save-match-data
11373 (set-match-data link-match-data)
11374 (eval cmd))))
11375 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11376 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11377 (or (not (equal old-buffer (current-buffer)))
11378 (not (equal old-pos (point))))
11379 (org-mark-ring-push old-pos old-buffer))))
11381 (defun org-file-apps-entry-match-against-dlink-p (entry)
11382 "This function returns non-nil if `entry' uses a regular
11383 expression which should be matched against the whole link by
11384 org-open-file.
11386 It assumes that is the case when the entry uses a regular
11387 expression which has at least one grouping construct and the
11388 action is either a lisp form or a command string containing
11389 '%1', i.e. using at least one subexpression match as a
11390 parameter."
11391 (let ((selector (car entry))
11392 (action (cdr entry)))
11393 (if (stringp selector)
11394 (and (> (regexp-opt-depth selector) 0)
11395 (or (and (stringp action)
11396 (string-match "%[0-9]" action))
11397 (consp action)))
11398 nil)))
11400 (defun org-default-apps ()
11401 "Return the default applications for this operating system."
11402 (cond
11403 ((eq system-type 'darwin)
11404 org-file-apps-defaults-macosx)
11405 ((eq system-type 'windows-nt)
11406 org-file-apps-defaults-windowsnt)
11407 (t org-file-apps-defaults-gnu)))
11409 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11410 "Convert extensions to regular expressions in the cars of LIST.
11411 Also, weed out any non-string entries, because the return value is used
11412 only for regexp matching.
11413 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11414 point to the symbol `emacs', indicating that the file should
11415 be opened in Emacs."
11416 (append
11417 (delq nil
11418 (mapcar (lambda (x)
11419 (if (not (stringp (car x)))
11421 (if (string-match "\\W" (car x))
11423 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11424 list))
11425 (if add-auto-mode
11426 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11428 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11429 (defun org-file-remote-p (file)
11430 "Test whether FILE specifies a location on a remote system.
11431 Return non-nil if the location is indeed remote.
11433 For example, the filename \"/user@host:/foo\" specifies a location
11434 on the system \"/user@host:\"."
11435 (cond ((fboundp 'file-remote-p)
11436 (file-remote-p file))
11437 ((fboundp 'tramp-handle-file-remote-p)
11438 (tramp-handle-file-remote-p file))
11439 ((and (boundp 'ange-ftp-name-format)
11440 (string-match (car ange-ftp-name-format) file))
11441 t)))
11444 ;;;; Refiling
11446 (defun org-get-org-file ()
11447 "Read a filename, with default directory `org-directory'."
11448 (let ((default (or org-default-notes-file remember-data-file)))
11449 (read-file-name (format "File name [%s]: " default)
11450 (file-name-as-directory org-directory)
11451 default)))
11453 (defun org-notes-order-reversed-p ()
11454 "Check if the current file should receive notes in reversed order."
11455 (cond
11456 ((not org-reverse-note-order) nil)
11457 ((eq t org-reverse-note-order) t)
11458 ((not (listp org-reverse-note-order)) nil)
11459 (t (catch 'exit
11460 (let ((all org-reverse-note-order)
11461 entry)
11462 (while (setq entry (pop all))
11463 (if (string-match (car entry) buffer-file-name)
11464 (throw 'exit (cdr entry))))
11465 nil)))))
11467 (defvar org-refile-target-table nil
11468 "The list of refile targets, created by `org-refile'.")
11470 (defvar org-agenda-new-buffers nil
11471 "Buffers created to visit agenda files.")
11473 (defvar org-refile-cache nil
11474 "Cache for refile targets.")
11476 (defvar org-refile-markers nil
11477 "All the markers used for caching refile locations.")
11479 (defun org-refile-marker (pos)
11480 "Get a new refile marker, but only if caching is in use."
11481 (if (not org-refile-use-cache)
11483 (let ((m (make-marker)))
11484 (move-marker m pos)
11485 (push m org-refile-markers)
11486 m)))
11488 (defun org-refile-cache-clear ()
11489 "Clear the refile cache and disable all the markers."
11490 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11491 (setq org-refile-markers nil)
11492 (setq org-refile-cache nil)
11493 (message "Refile cache has been cleared"))
11495 (defun org-refile-cache-check-set (set)
11496 "Check if all the markers in the cache still have live buffers."
11497 (let (marker)
11498 (catch 'exit
11499 (while (and set (setq marker (nth 3 (pop set))))
11500 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11501 (when (and marker (null (marker-buffer marker)))
11502 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11503 (sit-for 3)
11504 (throw 'exit nil)))
11505 t)))
11507 (defun org-refile-cache-put (set &rest identifiers)
11508 "Push the refile targets SET into the cache, under IDENTIFIERS."
11509 (let* ((key (sha1 (prin1-to-string identifiers)))
11510 (entry (assoc key org-refile-cache)))
11511 (if entry
11512 (setcdr entry set)
11513 (push (cons key set) org-refile-cache))))
11515 (defun org-refile-cache-get (&rest identifiers)
11516 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11517 (cond
11518 ((not org-refile-cache) nil)
11519 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11521 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11522 org-refile-cache))))
11523 (and set (org-refile-cache-check-set set) set)))))
11525 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11526 "Produce a table with refile targets."
11527 (let ((case-fold-search nil)
11528 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11529 (entries (or org-refile-targets '((nil . (:level . 1)))))
11530 targets tgs txt re files f desc descre fast-path-p level pos0)
11531 (message "Getting targets...")
11532 (with-current-buffer (or default-buffer (current-buffer))
11533 (while (setq entry (pop entries))
11534 (setq files (car entry) desc (cdr entry))
11535 (setq fast-path-p nil)
11536 (cond
11537 ((null files) (setq files (list (current-buffer))))
11538 ((eq files 'org-agenda-files)
11539 (setq files (org-agenda-files 'unrestricted)))
11540 ((and (symbolp files) (fboundp files))
11541 (setq files (funcall files)))
11542 ((and (symbolp files) (boundp files))
11543 (setq files (symbol-value files))))
11544 (if (stringp files) (setq files (list files)))
11545 (cond
11546 ((eq (car desc) :tag)
11547 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11548 ((eq (car desc) :todo)
11549 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11550 ((eq (car desc) :regexp)
11551 (setq descre (cdr desc)))
11552 ((eq (car desc) :level)
11553 (setq descre (concat "^\\*\\{" (number-to-string
11554 (if org-odd-levels-only
11555 (1- (* 2 (cdr desc)))
11556 (cdr desc)))
11557 "\\}[ \t]")))
11558 ((eq (car desc) :maxlevel)
11559 (setq fast-path-p t)
11560 (setq descre (concat "^\\*\\{1," (number-to-string
11561 (if org-odd-levels-only
11562 (1- (* 2 (cdr desc)))
11563 (cdr desc)))
11564 "\\}[ \t]")))
11565 (t (error "Bad refiling target description %s" desc)))
11566 (while (setq f (pop files))
11567 (with-current-buffer
11568 (if (bufferp f) f (org-get-agenda-file-buffer f))
11570 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11571 (progn
11572 (if (bufferp f) (setq f (buffer-file-name
11573 (buffer-base-buffer f))))
11574 (setq f (and f (expand-file-name f)))
11575 (if (eq org-refile-use-outline-path 'file)
11576 (push (list (file-name-nondirectory f) f nil nil) tgs))
11577 (save-excursion
11578 (save-restriction
11579 (widen)
11580 (goto-char (point-min))
11581 (while (re-search-forward descre nil t)
11582 (goto-char (setq pos0 (point-at-bol)))
11583 (catch 'next
11584 (when org-refile-target-verify-function
11585 (save-match-data
11586 (or (funcall org-refile-target-verify-function)
11587 (throw 'next t))))
11588 (when (and (looking-at org-complex-heading-regexp)
11589 (not (member (match-string 4) excluded-entries))
11590 (match-string 4))
11591 (setq level (org-reduced-level
11592 (- (match-end 1) (match-beginning 1)))
11593 txt (org-link-display-format (match-string 4))
11594 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11595 re (format org-complex-heading-regexp-format
11596 (regexp-quote (match-string 4))))
11597 (when org-refile-use-outline-path
11598 (setq txt (mapconcat
11599 'org-protect-slash
11600 (append
11601 (if (eq org-refile-use-outline-path
11602 'file)
11603 (list (file-name-nondirectory
11604 (buffer-file-name
11605 (buffer-base-buffer))))
11606 (if (eq org-refile-use-outline-path
11607 'full-file-path)
11608 (list (buffer-file-name
11609 (buffer-base-buffer)))))
11610 (org-get-outline-path fast-path-p
11611 level txt)
11612 (list txt))
11613 "/")))
11614 (push (list txt f re (org-refile-marker (point)))
11615 tgs)))
11616 (when (= (point) pos0)
11617 ;; verification function has not moved point
11618 (goto-char (point-at-eol))))))))
11619 (when org-refile-use-cache
11620 (org-refile-cache-put tgs (buffer-file-name) descre))
11621 (setq targets (append tgs targets))))))
11622 (message "Getting targets...done")
11623 (nreverse targets)))
11625 (defun org-protect-slash (s)
11626 (while (string-match "/" s)
11627 (setq s (replace-match "\\" t t s)))
11630 (defvar org-olpa (make-vector 20 nil))
11632 (defun org-get-outline-path (&optional fastp level heading)
11633 "Return the outline path to the current entry, as a list.
11635 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11636 routine which makes outline path derivations for an entire file,
11637 avoiding backtracing. Refile target collection makes use of that."
11638 (if fastp
11639 (progn
11640 (if (> level 19)
11641 (error "Outline path failure, more than 19 levels"))
11642 (loop for i from level upto 19 do
11643 (aset org-olpa i nil))
11644 (prog1
11645 (delq nil (append org-olpa nil))
11646 (aset org-olpa level heading)))
11647 (let (rtn case-fold-search)
11648 (save-excursion
11649 (save-restriction
11650 (widen)
11651 (while (org-up-heading-safe)
11652 (when (looking-at org-complex-heading-regexp)
11653 (push (org-trim
11654 (replace-regexp-in-string
11655 ;; Remove statistical/checkboxes cookies
11656 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11657 (org-match-string-no-properties 4)))
11658 rtn)))
11659 rtn)))))
11661 (defun org-format-outline-path (path &optional width prefix separator)
11662 "Format the outline path PATH for display.
11663 WIDTH is the maximum number of characters that is available.
11664 PREFIX is a prefix to be included in the returned string,
11665 such as the file name.
11666 SEPARATOR is inserted between the different parts of the path,
11667 the default is \"/\"."
11668 (setq width (or width 79))
11669 (if prefix (setq width (- width (length prefix))))
11670 (if (not path)
11671 (or prefix "")
11672 (let* ((nsteps (length path))
11673 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11674 (maxwidth (if (<= total-width width)
11675 10000 ;; everything fits
11676 ;; we need to shorten the level headings
11677 (/ (- width nsteps) nsteps)))
11678 (org-odd-levels-only nil)
11679 (n 0)
11680 (total (1+ (length prefix))))
11681 (setq maxwidth (max maxwidth 10))
11682 (concat prefix
11683 (if prefix (or separator "/"))
11684 (mapconcat
11685 (lambda (h)
11686 (setq n (1+ n))
11687 (if (and (= n nsteps) (< maxwidth 10000))
11688 (setq maxwidth (- total-width total)))
11689 (if (< (length h) maxwidth)
11690 (progn (setq total (+ total (length h) 1)) h)
11691 (setq h (substring h 0 (- maxwidth 2))
11692 total (+ total maxwidth 1))
11693 (if (string-match "[ \t]+\\'" h)
11694 (setq h (substring h 0 (match-beginning 0))))
11695 (setq h (concat h "..")))
11696 (org-add-props h nil 'face
11697 (nth (% (1- n) org-n-level-faces)
11698 org-level-faces))
11700 path (or separator "/"))))))
11702 (defun org-display-outline-path (&optional file current separator just-return-string)
11703 "Display the current outline path in the echo area.
11705 If FILE is non-nil, prepend the output with the file name.
11706 If CURRENT is non-nil, append the current heading to the output.
11707 SEPARATOR is passed through to `org-format-outline-path'. It separates
11708 the different parts of the path and defaults to \"/\".
11709 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11710 (interactive "P")
11711 (let* (case-fold-search
11712 (bfn (buffer-file-name (buffer-base-buffer)))
11713 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11714 res)
11715 (if current (setq path (append path
11716 (save-excursion
11717 (org-back-to-heading t)
11718 (if (looking-at org-complex-heading-regexp)
11719 (list (match-string 4)))))))
11720 (setq res
11721 (org-format-outline-path
11722 path
11723 (1- (frame-width))
11724 (and file bfn (concat (file-name-nondirectory bfn) separator))
11725 separator))
11726 (if just-return-string
11727 (org-no-properties res)
11728 (org-unlogged-message "%s" res))))
11730 (defvar org-refile-history nil
11731 "History for refiling operations.")
11733 (defvar org-after-refile-insert-hook nil
11734 "Hook run after `org-refile' has inserted its stuff at the new location.
11735 Note that this is still *before* the stuff will be removed from
11736 the *old* location.")
11738 (defvar org-capture-last-stored-marker)
11739 (defvar org-refile-keep nil
11740 "Non-nil means `org-refile' will copy instead of refile.")
11742 (defun org-copy ()
11743 "Like `org-refile', but copy."
11744 (interactive)
11745 (let ((org-refile-keep t))
11746 (funcall 'org-refile nil nil nil "Copy")))
11748 (defun org-refile (&optional arg default-buffer rfloc msg)
11749 "Move the entry or entries at point to another heading.
11750 The list of target headings is compiled using the information in
11751 `org-refile-targets', which see.
11753 At the target location, the entry is filed as a subitem of the
11754 target heading. Depending on `org-reverse-note-order', the new
11755 subitem will either be the first or the last subitem.
11757 If there is an active region, all entries in that region will be
11758 refiled. However, the region must fulfill the requirement that
11759 the first heading sets the top-level of the moved text.
11761 With prefix arg ARG, the command will only visit the target
11762 location and not actually move anything.
11764 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11765 refiling operation has put the subtree.
11767 With a numeric prefix argument of `2', refile to the running clock.
11769 With a numeric prefix argument of `3', emulate `org-refile-keep'
11770 being set to `t' and copy to the target location, don't move it.
11771 Beware that keeping refiled entries may result in duplicated ID
11772 properties.
11774 RFLOC can be a refile location obtained in a different way.
11776 MSG is a string to replace \"Refile\" in the default prompt with
11777 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11779 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11781 If you are using target caching (see `org-refile-use-cache'), you
11782 have to clear the target cache in order to find new targets.
11783 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11784 prefix argument (`C-u C-u C-u C-c C-w')."
11785 (interactive "P")
11786 (if (member arg '(0 (64)))
11787 (org-refile-cache-clear)
11788 (let* ((actionmsg (cond (msg msg)
11789 ((equal arg 3) "Refile (and keep)")
11790 (t "Refile")))
11791 (cbuf (current-buffer))
11792 (regionp (org-region-active-p))
11793 (region-start (and regionp (region-beginning)))
11794 (region-end (and regionp (region-end)))
11795 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11796 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11797 pos it nbuf file re level reversed)
11798 (setq last-command nil)
11799 (when regionp
11800 (goto-char region-start)
11801 (or (bolp) (goto-char (point-at-bol)))
11802 (setq region-start (point))
11803 (unless (or (org-kill-is-subtree-p
11804 (buffer-substring region-start region-end))
11805 (prog1 org-refile-active-region-within-subtree
11806 (let ((s (point-at-eol)))
11807 (org-toggle-heading)
11808 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11809 (user-error "The region is not a (sequence of) subtree(s)")))
11810 (if (equal arg '(16))
11811 (org-refile-goto-last-stored)
11812 (when (or
11813 (and (equal arg 2)
11814 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11815 (prog1
11816 (setq it (list (or org-clock-heading "running clock")
11817 (buffer-file-name
11818 (marker-buffer org-clock-hd-marker))
11820 (marker-position org-clock-hd-marker)))
11821 (setq arg nil)))
11822 (setq it (or rfloc
11823 (let (heading-text)
11824 (save-excursion
11825 (unless (and arg (listp arg))
11826 (org-back-to-heading t)
11827 (setq heading-text
11828 (replace-regexp-in-string
11829 org-bracket-link-regexp
11830 "\\3"
11831 (nth 4 (org-heading-components)))))
11832 (org-refile-get-location
11833 (cond ((and arg (listp arg)) "Goto")
11834 (regionp (concat actionmsg " region to"))
11835 (t (concat actionmsg " subtree \""
11836 heading-text "\" to")))
11837 default-buffer
11838 (and (not (equal '(4) arg))
11839 org-refile-allow-creating-parent-nodes)
11840 arg))))))
11841 (setq file (nth 1 it)
11842 re (nth 2 it)
11843 pos (nth 3 it))
11844 (if (and (not arg)
11846 (equal (buffer-file-name) file)
11847 (if regionp
11848 (and (>= pos region-start)
11849 (<= pos region-end))
11850 (and (>= pos (point))
11851 (< pos (save-excursion
11852 (org-end-of-subtree t t))))))
11853 (error "Cannot refile to position inside the tree or region"))
11854 (setq nbuf (or (find-buffer-visiting file)
11855 (find-file-noselect file)))
11856 (if (and arg (not (equal arg 3)))
11857 (progn
11858 (org-pop-to-buffer-same-window nbuf)
11859 (goto-char pos)
11860 (org-show-context 'org-goto))
11861 (if regionp
11862 (progn
11863 (org-kill-new (buffer-substring region-start region-end))
11864 (org-save-markers-in-region region-start region-end))
11865 (org-copy-subtree 1 nil t))
11866 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11867 (find-file-noselect file)))
11868 (setq reversed (org-notes-order-reversed-p))
11869 (save-excursion
11870 (save-restriction
11871 (widen)
11872 (if pos
11873 (progn
11874 (goto-char pos)
11875 (looking-at org-outline-regexp)
11876 (setq level (org-get-valid-level (funcall outline-level) 1))
11877 (goto-char
11878 (if reversed
11879 (or (outline-next-heading) (point-max))
11880 (or (save-excursion (org-get-next-sibling))
11881 (org-end-of-subtree t t)
11882 (point-max)))))
11883 (setq level 1)
11884 (if (not reversed)
11885 (goto-char (point-max))
11886 (goto-char (point-min))
11887 (or (outline-next-heading) (goto-char (point-max)))))
11888 (if (not (bolp)) (newline))
11889 (org-paste-subtree level nil nil t)
11890 (when org-log-refile
11891 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11892 (unless (eq org-log-refile 'note)
11893 (save-excursion (org-add-log-note))))
11894 (and org-auto-align-tags
11895 (let ((org-loop-over-headlines-in-active-region nil))
11896 (org-set-tags nil t)))
11897 (let ((bookmark-name (plist-get org-bookmark-names-plist
11898 :last-refile)))
11899 (when bookmark-name
11900 (with-demoted-errors
11901 (bookmark-set bookmark-name))))
11902 ;; If we are refiling for capture, make sure that the
11903 ;; last-capture pointers point here
11904 (when (org-bound-and-true-p org-refile-for-capture)
11905 (let ((bookmark-name (plist-get org-bookmark-names-plist
11906 :last-capture-marker)))
11907 (when bookmark-name
11908 (with-demoted-errors
11909 (bookmark-set bookmark-name))))
11910 (move-marker org-capture-last-stored-marker (point)))
11911 (if (fboundp 'deactivate-mark) (deactivate-mark))
11912 (run-hooks 'org-after-refile-insert-hook))))
11913 (unless org-refile-keep
11914 (if regionp
11915 (delete-region (point) (+ (point) (- region-end region-start)))
11916 (delete-region
11917 (and (org-back-to-heading t) (point))
11918 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11919 (when (featurep 'org-inlinetask)
11920 (org-inlinetask-remove-END-maybe))
11921 (setq org-markers-to-move nil)
11922 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11924 (defun org-refile-goto-last-stored ()
11925 "Go to the location where the last refile was stored."
11926 (interactive)
11927 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11928 (message "This is the location of the last refile"))
11930 (defun org-refile--get-location (refloc tbl)
11931 "When user refile to REFLOC, find the associated target in TBL.
11932 Also check `org-refile-target-table'."
11933 (car (delq
11935 (mapcar
11936 (lambda (r) (or (assoc r tbl)
11937 (assoc r org-refile-target-table)))
11938 (list (replace-regexp-in-string "/$" "" refloc)
11939 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11941 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11942 no-exclude)
11943 "Prompt the user for a refile location, using PROMPT.
11944 PROMPT should not be suffixed with a colon and a space, because
11945 this function appends the default value from
11946 `org-refile-history' automatically, if that is not empty.
11947 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11948 this is used for the GOTO interface."
11949 (let ((org-refile-targets org-refile-targets)
11950 (org-refile-use-outline-path org-refile-use-outline-path)
11951 excluded-entries)
11952 (when (and (derived-mode-p 'org-mode)
11953 (not org-refile-use-cache)
11954 (not no-exclude))
11955 (org-map-tree
11956 (lambda()
11957 (setq excluded-entries
11958 (append excluded-entries (list (org-get-heading t t)))))))
11959 (setq org-refile-target-table
11960 (org-refile-get-targets default-buffer excluded-entries)))
11961 (unless org-refile-target-table
11962 (user-error "No refile targets"))
11963 (let* ((cbuf (current-buffer))
11964 (partial-completion-mode nil)
11965 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11966 (cfunc (if (and org-refile-use-outline-path
11967 org-outline-path-complete-in-steps)
11968 'org-olpath-completing-read
11969 'org-icompleting-read))
11970 (extra (if org-refile-use-outline-path "/" ""))
11971 (cbnex (concat (buffer-name) extra))
11972 (filename (and cfn (expand-file-name cfn)))
11973 (tbl (mapcar
11974 (lambda (x)
11975 (if (and (not (member org-refile-use-outline-path
11976 '(file full-file-path)))
11977 (not (equal filename (nth 1 x))))
11978 (cons (concat (car x) extra " ("
11979 (file-name-nondirectory (nth 1 x)) ")")
11980 (cdr x))
11981 (cons (concat (car x) extra) (cdr x))))
11982 org-refile-target-table))
11983 (completion-ignore-case t)
11984 cdef
11985 (prompt (concat prompt
11986 (or (and (car org-refile-history)
11987 (concat " (default " (car org-refile-history) ")"))
11988 (and (assoc cbnex tbl) (setq cdef cbnex)
11989 (concat " (default " cbnex ")"))) ": "))
11990 pa answ parent-target child parent old-hist)
11991 (setq old-hist org-refile-history)
11992 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11993 nil 'org-refile-history (or cdef (car org-refile-history))))
11994 (if (setq pa (org-refile--get-location answ tbl))
11995 (progn
11996 (org-refile-check-position pa)
11997 (when (or (not org-refile-history)
11998 (not (eq old-hist org-refile-history))
11999 (not (equal (car pa) (car org-refile-history))))
12000 (setq org-refile-history
12001 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12002 org-refile-history
12003 (cdr org-refile-history))))
12004 (if (equal (car org-refile-history) (nth 1 org-refile-history))
12005 (pop org-refile-history)))
12007 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12008 (progn
12009 (setq parent (match-string 1 answ)
12010 child (match-string 2 answ))
12011 (setq parent-target (org-refile--get-location parent tbl))
12012 (when (and parent-target
12013 (or (eq new-nodes t)
12014 (and (eq new-nodes 'confirm)
12015 (y-or-n-p (format "Create new node \"%s\"? "
12016 child)))))
12017 (org-refile-new-child parent-target child)))
12018 (user-error "Invalid target location")))))
12020 (declare-function org-string-nw-p "org-macs" (s))
12021 (defun org-refile-check-position (refile-pointer)
12022 "Check if the refile pointer matches the headline to which it points."
12023 (let* ((file (nth 1 refile-pointer))
12024 (re (nth 2 refile-pointer))
12025 (pos (nth 3 refile-pointer))
12026 buffer)
12027 (if (and (not (markerp pos)) (not file))
12028 (user-error "Please indicate a target file in the refile path")
12029 (when (org-string-nw-p re)
12030 (setq buffer (if (markerp pos)
12031 (marker-buffer pos)
12032 (or (find-buffer-visiting file)
12033 (find-file-noselect file))))
12034 (with-current-buffer buffer
12035 (save-excursion
12036 (save-restriction
12037 (widen)
12038 (goto-char pos)
12039 (beginning-of-line 1)
12040 (unless (org-looking-at-p re)
12041 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12043 (defun org-refile-new-child (parent-target child)
12044 "Use refile target PARENT-TARGET to add new CHILD below it."
12045 (unless parent-target
12046 (error "Cannot find parent for new node"))
12047 (let ((file (nth 1 parent-target))
12048 (pos (nth 3 parent-target))
12049 level)
12050 (with-current-buffer (or (find-buffer-visiting file)
12051 (find-file-noselect file))
12052 (save-excursion
12053 (save-restriction
12054 (widen)
12055 (if pos
12056 (goto-char pos)
12057 (goto-char (point-max))
12058 (if (not (bolp)) (newline)))
12059 (when (looking-at org-outline-regexp)
12060 (setq level (funcall outline-level))
12061 (org-end-of-subtree t t))
12062 (org-back-over-empty-lines)
12063 (insert "\n" (make-string
12064 (if pos (org-get-valid-level level 1) 1) ?*)
12065 " " child "\n")
12066 (beginning-of-line 0)
12067 (list (concat (car parent-target) "/" child) file "" (point)))))))
12069 (defun org-olpath-completing-read (prompt collection &rest args)
12070 "Read an outline path like a file name."
12071 (let ((thetable collection)
12072 (org-completion-use-ido nil) ; does not work with ido.
12073 (org-completion-use-iswitchb nil)) ; or iswitchb
12074 (apply
12075 'org-icompleting-read prompt
12076 (lambda (string predicate &optional flag)
12077 (let (rtn r f (l (length string)))
12078 (cond
12079 ((eq flag nil)
12080 ;; try completion
12081 (try-completion string thetable))
12082 ((eq flag t)
12083 ;; all-completions
12084 (setq rtn (all-completions string thetable predicate))
12085 (mapcar
12086 (lambda (x)
12087 (setq r (substring x l))
12088 (if (string-match " ([^)]*)$" x)
12089 (setq f (match-string 0 x))
12090 (setq f ""))
12091 (if (string-match "/" r)
12092 (concat string (substring r 0 (match-end 0)) f)
12094 rtn))
12095 ((eq flag 'lambda)
12096 ;; exact match?
12097 (assoc string thetable)))))
12098 args)))
12100 ;;;; Dynamic blocks
12102 (defun org-find-dblock (name)
12103 "Find the first dynamic block with name NAME in the buffer.
12104 If not found, stay at current position and return nil."
12105 (let ((case-fold-search t) pos)
12106 (save-excursion
12107 (goto-char (point-min))
12108 (setq pos (and (re-search-forward
12109 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12110 (match-beginning 0))))
12111 (if pos (goto-char pos))
12112 pos))
12114 (defun org-create-dblock (plist)
12115 "Create a dynamic block section, with parameters taken from PLIST.
12116 PLIST must contain a :name entry which is used as the name of the block."
12117 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12118 (end-of-line 1)
12119 (newline))
12120 (let ((col (current-column))
12121 (name (plist-get plist :name)))
12122 (insert "#+BEGIN: " name)
12123 (while plist
12124 (if (eq (car plist) :name)
12125 (setq plist (cddr plist))
12126 (insert " " (prin1-to-string (pop plist)))))
12127 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12128 (beginning-of-line -2)))
12130 (defun org-prepare-dblock ()
12131 "Prepare dynamic block for refresh.
12132 This empties the block, puts the cursor at the insert position and returns
12133 the property list including an extra property :name with the block name."
12134 (unless (looking-at org-dblock-start-re)
12135 (user-error "Not at a dynamic block"))
12136 (let* ((begdel (1+ (match-end 0)))
12137 (name (org-no-properties (match-string 1)))
12138 (params (append (list :name name)
12139 (read (concat "(" (match-string 3) ")")))))
12140 (save-excursion
12141 (beginning-of-line 1)
12142 (skip-chars-forward " \t")
12143 (setq params (plist-put params :indentation-column (current-column))))
12144 (unless (re-search-forward org-dblock-end-re nil t)
12145 (error "Dynamic block not terminated"))
12146 (setq params
12147 (append params
12148 (list :content (buffer-substring
12149 begdel (match-beginning 0)))))
12150 (delete-region begdel (match-beginning 0))
12151 (goto-char begdel)
12152 (open-line 1)
12153 params))
12155 (defun org-map-dblocks (&optional command)
12156 "Apply COMMAND to all dynamic blocks in the current buffer.
12157 If COMMAND is not given, use `org-update-dblock'."
12158 (let ((cmd (or command 'org-update-dblock)))
12159 (save-excursion
12160 (goto-char (point-min))
12161 (while (re-search-forward org-dblock-start-re nil t)
12162 (goto-char (match-beginning 0))
12163 (save-excursion
12164 (condition-case nil
12165 (funcall cmd)
12166 (error (message "Error during update of dynamic block"))))
12167 (unless (re-search-forward org-dblock-end-re nil t)
12168 (error "Dynamic block not terminated"))))))
12170 (defun org-dblock-update (&optional arg)
12171 "User command for updating dynamic blocks.
12172 Update the dynamic block at point. With prefix ARG, update all dynamic
12173 blocks in the buffer."
12174 (interactive "P")
12175 (if arg
12176 (org-update-all-dblocks)
12177 (or (looking-at org-dblock-start-re)
12178 (org-beginning-of-dblock))
12179 (org-update-dblock)))
12181 (defun org-update-dblock ()
12182 "Update the dynamic block at point.
12183 This means to empty the block, parse for parameters and then call
12184 the correct writing function."
12185 (interactive)
12186 (save-excursion
12187 (let* ((win (selected-window))
12188 (pos (point))
12189 (line (org-current-line))
12190 (params (org-prepare-dblock))
12191 (name (plist-get params :name))
12192 (indent (plist-get params :indentation-column))
12193 (cmd (intern (concat "org-dblock-write:" name))))
12194 (message "Updating dynamic block `%s' at line %d..." name line)
12195 (funcall cmd params)
12196 (message "Updating dynamic block `%s' at line %d...done" name line)
12197 (goto-char pos)
12198 (when (and indent (> indent 0))
12199 (setq indent (make-string indent ?\ ))
12200 (save-excursion
12201 (select-window win)
12202 (org-beginning-of-dblock)
12203 (forward-line 1)
12204 (while (not (looking-at org-dblock-end-re))
12205 (insert indent)
12206 (beginning-of-line 2))
12207 (when (looking-at org-dblock-end-re)
12208 (and (looking-at "[ \t]+")
12209 (replace-match ""))
12210 (insert indent)))))))
12212 (defun org-beginning-of-dblock ()
12213 "Find the beginning of the dynamic block at point.
12214 Error if there is no such block at point."
12215 (let ((pos (point))
12216 beg)
12217 (end-of-line 1)
12218 (if (and (re-search-backward org-dblock-start-re nil t)
12219 (setq beg (match-beginning 0))
12220 (re-search-forward org-dblock-end-re nil t)
12221 (> (match-end 0) pos))
12222 (goto-char beg)
12223 (goto-char pos)
12224 (error "Not in a dynamic block"))))
12226 (defun org-update-all-dblocks ()
12227 "Update all dynamic blocks in the buffer.
12228 This function can be used in a hook."
12229 (interactive)
12230 (when (derived-mode-p 'org-mode)
12231 (org-map-dblocks 'org-update-dblock)))
12234 ;;;; Completion
12236 (declare-function org-export-backend-name "org-export" (cl-x))
12237 (declare-function org-export-backend-options "org-export" (cl-x))
12238 (defun org-get-export-keywords ()
12239 "Return a list of all currently understood export keywords.
12240 Export keywords include options, block names, attributes and
12241 keywords relative to each registered export back-end."
12242 (let (keywords)
12243 (dolist (backend
12244 (org-bound-and-true-p org-export--registered-backends)
12245 (delq nil keywords))
12246 ;; Back-end name (for keywords, like #+LATEX:)
12247 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12248 (dolist (option-entry (org-export-backend-options backend))
12249 ;; Back-end options.
12250 (push (nth 1 option-entry) keywords)))))
12252 (defconst org-options-keywords
12253 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12254 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12255 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12256 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12257 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12259 (defcustom org-structure-template-alist
12260 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12261 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12262 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12263 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12264 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12265 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12266 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX")
12267 ("L" "#+LaTeX: ")
12268 ("h" "#+BEGIN_HTML\n?\n#+END_HTML")
12269 ("H" "#+HTML: ")
12270 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
12271 ("A" "#+ASCII: ")
12272 ("i" "#+INDEX: ?")
12273 ("I" "#+INCLUDE: %file ?"))
12274 "Structure completion elements.
12275 This is a list of abbreviation keys and values. The value gets inserted
12276 if you type `<' followed by the key and then press the completion key,
12277 usually `TAB'. %file will be replaced by a file name after prompting
12278 for the file using completion. The cursor will be placed at the position
12279 of the `?` in the template.
12280 There are two templates for each key, the first uses the original Org syntax,
12281 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12282 the default when the /org-mtags.el/ module has been loaded. See also the
12283 variable `org-mtags-prefer-muse-templates'."
12284 :group 'org-completion
12285 :type '(repeat
12286 (list
12287 (string :tag "Key")
12288 (string :tag "Template")))
12289 :version 24.4
12290 :package-version '(Org . "8.3"))
12292 (defun org-try-structure-completion ()
12293 "Try to complete a structure template before point.
12294 This looks for strings like \"<e\" on an otherwise empty line and
12295 expands them."
12296 (let ((l (buffer-substring (point-at-bol) (point)))
12298 (when (and (looking-at "[ \t]*$")
12299 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12300 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12301 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12302 (match-beginning 1)) a)
12303 t)))
12305 (defun org-complete-expand-structure-template (start cell)
12306 "Expand a structure template."
12307 (let ((rpl (nth 1 cell))
12308 (ind ""))
12309 (delete-region start (point))
12310 (when (string-match "\\`[ \t]*#\\+" rpl)
12311 (cond
12312 ((bolp))
12313 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12314 (setq ind (buffer-substring (point-at-bol) (point))))
12315 (t (newline))))
12316 (setq start (point))
12317 (if (string-match "%file" rpl)
12318 (setq rpl (replace-match
12319 (concat
12320 "\""
12321 (save-match-data
12322 (abbreviate-file-name (read-file-name "Include file: ")))
12323 "\"")
12324 t t rpl)))
12325 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12326 (concat "\n" ind)))
12327 (insert rpl)
12328 (if (re-search-backward "\\?" start t) (delete-char 1))))
12330 ;;;; TODO, DEADLINE, Comments
12332 (defun org-toggle-comment ()
12333 "Change the COMMENT state of an entry."
12334 (interactive)
12335 (save-excursion
12336 (org-back-to-heading)
12337 (looking-at org-complex-heading-regexp)
12338 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12339 (skip-chars-forward " \t")
12340 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12341 (if (org-in-commented-heading-p t)
12342 (delete-region (point)
12343 (progn (search-forward " " (line-end-position) 'move)
12344 (skip-chars-forward " \t")
12345 (point)))
12346 (insert org-comment-string)
12347 (unless (eolp) (insert " ")))))
12349 (defvar org-last-todo-state-is-todo nil
12350 "This is non-nil when the last TODO state change led to a TODO state.
12351 If the last change removed the TODO tag or switched to DONE, then
12352 this is nil.")
12354 (defvar org-setting-tags nil) ; dynamically skipped
12356 (defvar org-todo-setup-filter-hook nil
12357 "Hook for functions that pre-filter todo specs.
12358 Each function takes a todo spec and returns either nil or the spec
12359 transformed into canonical form." )
12361 (defvar org-todo-get-default-hook nil
12362 "Hook for functions that get a default item for todo.
12363 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12364 nil or a string to be used for the todo mark." )
12366 (defvar org-agenda-headline-snapshot-before-repeat)
12368 (defun org-current-effective-time ()
12369 "Return current time adjusted for `org-extend-today-until' variable."
12370 (let* ((ct (org-current-time))
12371 (dct (decode-time ct))
12372 (ct1
12373 (cond
12374 (org-use-last-clock-out-time-as-effective-time
12375 (or (org-clock-get-last-clock-out-time) ct))
12376 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12377 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12378 (t ct))))
12379 ct1))
12381 (defun org-todo-yesterday (&optional arg)
12382 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12383 (interactive "P")
12384 (if (eq major-mode 'org-agenda-mode)
12385 (apply 'org-agenda-todo-yesterday arg)
12386 (let* ((hour (third (decode-time
12387 (org-current-time))))
12388 (org-extend-today-until (1+ hour)))
12389 (org-todo arg))))
12391 (defvar org-block-entry-blocking ""
12392 "First entry preventing the TODO state change.")
12394 (defun org-cancel-repeater ()
12395 "Cancel a repeater by setting its numeric value to zero."
12396 (interactive)
12397 (save-excursion
12398 (org-back-to-heading t)
12399 (let ((bound1 (point))
12400 (bound0 (save-excursion (outline-next-heading) (point))))
12401 (when (re-search-forward
12402 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12403 org-deadline-time-regexp "\\)\\|\\("
12404 org-ts-regexp "\\)")
12405 bound0 t)
12406 (if (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]" bound1 t)
12407 (replace-match "0" t nil nil 1))))))
12409 (defun org-todo (&optional arg)
12410 "Change the TODO state of an item.
12411 The state of an item is given by a keyword at the start of the heading,
12412 like
12413 *** TODO Write paper
12414 *** DONE Call mom
12416 The different keywords are specified in the variable `org-todo-keywords'.
12417 By default the available states are \"TODO\" and \"DONE\".
12418 So for this example: when the item starts with TODO, it is changed to DONE.
12419 When it starts with DONE, the DONE is removed. And when neither TODO nor
12420 DONE are present, add TODO at the beginning of the heading.
12422 With \\[universal-argument] prefix arg, use completion to determine the new \
12423 state.
12424 With numeric prefix arg, switch to that state.
12425 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12426 keywords (nextset).
12427 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12428 With a numeric prefix arg of 0, inhibit note taking for the change.
12429 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12431 When called through ELisp, arg is also interpreted in the following way:
12432 'none -> empty state
12433 \"\"(empty string) -> switch to empty state
12434 'done -> switch to DONE
12435 'nextset -> switch to the next set of keywords
12436 'previousset -> switch to the previous set of keywords
12437 \"WAITING\" -> switch to the specified keyword, but only if it
12438 really is a member of `org-todo-keywords'."
12439 (interactive "P")
12440 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12441 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12442 'region-start-level 'region))
12443 org-loop-over-headlines-in-active-region)
12444 (org-map-entries
12445 `(org-todo ,arg)
12446 org-loop-over-headlines-in-active-region
12447 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12448 (if (equal arg '(16)) (setq arg 'nextset))
12449 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12450 (let ((org-blocker-hook org-blocker-hook)
12451 commentp
12452 case-fold-search)
12453 (when (equal arg '(64))
12454 (setq arg nil org-blocker-hook nil))
12455 (when (and org-blocker-hook
12456 (or org-inhibit-blocking
12457 (org-entry-get nil "NOBLOCKING")))
12458 (setq org-blocker-hook nil))
12459 (save-excursion
12460 (catch 'exit
12461 (org-back-to-heading t)
12462 (when (org-in-commented-heading-p t)
12463 (org-toggle-comment)
12464 (setq commentp t))
12465 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12466 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12467 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12468 (let* ((match-data (match-data))
12469 (startpos (point-at-bol))
12470 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12471 (org-log-done org-log-done)
12472 (org-log-repeat org-log-repeat)
12473 (org-todo-log-states org-todo-log-states)
12474 (org-inhibit-logging
12475 (if (equal arg 0)
12476 (progn (setq arg nil) 'note) org-inhibit-logging))
12477 (this (match-string 1))
12478 (hl-pos (match-beginning 0))
12479 (head (org-get-todo-sequence-head this))
12480 (ass (assoc head org-todo-kwd-alist))
12481 (interpret (nth 1 ass))
12482 (done-word (nth 3 ass))
12483 (final-done-word (nth 4 ass))
12484 (org-last-state (or this ""))
12485 (completion-ignore-case t)
12486 (member (member this org-todo-keywords-1))
12487 (tail (cdr member))
12488 (org-state (cond
12489 ((and org-todo-key-trigger
12490 (or (and (equal arg '(4))
12491 (eq org-use-fast-todo-selection 'prefix))
12492 (and (not arg) org-use-fast-todo-selection
12493 (not (eq org-use-fast-todo-selection
12494 'prefix)))))
12495 ;; Use fast selection
12496 (org-fast-todo-selection))
12497 ((and (equal arg '(4))
12498 (or (not org-use-fast-todo-selection)
12499 (not org-todo-key-trigger)))
12500 ;; Read a state with completion
12501 (org-icompleting-read
12502 "State: " (mapcar 'list org-todo-keywords-1)
12503 nil t))
12504 ((eq arg 'right)
12505 (if this
12506 (if tail (car tail) nil)
12507 (car org-todo-keywords-1)))
12508 ((eq arg 'left)
12509 (if (equal member org-todo-keywords-1)
12511 (if this
12512 (nth (- (length org-todo-keywords-1)
12513 (length tail) 2)
12514 org-todo-keywords-1)
12515 (org-last org-todo-keywords-1))))
12516 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12517 (setq arg nil))) ; hack to fall back to cycling
12518 (arg
12519 ;; user or caller requests a specific state
12520 (cond
12521 ((equal arg "") nil)
12522 ((eq arg 'none) nil)
12523 ((eq arg 'done) (or done-word (car org-done-keywords)))
12524 ((eq arg 'nextset)
12525 (or (car (cdr (member head org-todo-heads)))
12526 (car org-todo-heads)))
12527 ((eq arg 'previousset)
12528 (let ((org-todo-heads (reverse org-todo-heads)))
12529 (or (car (cdr (member head org-todo-heads)))
12530 (car org-todo-heads))))
12531 ((car (member arg org-todo-keywords-1)))
12532 ((stringp arg)
12533 (user-error "State `%s' not valid in this file" arg))
12534 ((nth (1- (prefix-numeric-value arg))
12535 org-todo-keywords-1))))
12536 ((null member) (or head (car org-todo-keywords-1)))
12537 ((equal this final-done-word) nil) ;; -> make empty
12538 ((null tail) nil) ;; -> first entry
12539 ((memq interpret '(type priority))
12540 (if (eq this-command last-command)
12541 (car tail)
12542 (if (> (length tail) 0)
12543 (or done-word (car org-done-keywords))
12544 nil)))
12546 (car tail))))
12547 (org-state (or
12548 (run-hook-with-args-until-success
12549 'org-todo-get-default-hook org-state org-last-state)
12550 org-state))
12551 (next (if org-state (concat " " org-state " ") " "))
12552 (change-plist (list :type 'todo-state-change :from this :to org-state
12553 :position startpos))
12554 dolog now-done-p)
12555 (when org-blocker-hook
12556 (setq org-last-todo-state-is-todo
12557 (not (member this org-done-keywords)))
12558 (unless (save-excursion
12559 (save-match-data
12560 (org-with-wide-buffer
12561 (run-hook-with-args-until-failure
12562 'org-blocker-hook change-plist))))
12563 (if (org-called-interactively-p 'interactive)
12564 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12565 this org-state org-block-entry-blocking)
12566 ;; fail silently
12567 (message "TODO state change from %s to %s blocked (by \"%s\")"
12568 this org-state org-block-entry-blocking)
12569 (throw 'exit nil))))
12570 (store-match-data match-data)
12571 (replace-match next t t)
12572 (cond ((equal this org-state)
12573 (message "TODO state was already %s" (org-trim next)))
12574 ((pos-visible-in-window-p hl-pos)
12575 (message "TODO state changed to %s" (org-trim next))))
12576 (unless head
12577 (setq head (org-get-todo-sequence-head org-state)
12578 ass (assoc head org-todo-kwd-alist)
12579 interpret (nth 1 ass)
12580 done-word (nth 3 ass)
12581 final-done-word (nth 4 ass)))
12582 (when (memq arg '(nextset previousset))
12583 (message "Keyword-Set %d/%d: %s"
12584 (- (length org-todo-sets) -1
12585 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12586 (length org-todo-sets)
12587 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12588 (setq org-last-todo-state-is-todo
12589 (not (member org-state org-done-keywords)))
12590 (setq now-done-p (and (member org-state org-done-keywords)
12591 (not (member this org-done-keywords))))
12592 (and logging (org-local-logging logging))
12593 (when (and (or org-todo-log-states org-log-done)
12594 (not (eq org-inhibit-logging t))
12595 (not (memq arg '(nextset previousset))))
12596 ;; we need to look at recording a time and note
12597 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12598 (nth 2 (assoc this org-todo-log-states))))
12599 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12600 (setq dolog 'time))
12601 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12602 (and org-state
12603 (member org-state org-not-done-keywords)
12604 (not (member this org-not-done-keywords))))
12605 ;; This is now a todo state and was not one before
12606 ;; If there was a CLOSED time stamp, get rid of it.
12607 (org-add-planning-info nil nil 'closed))
12608 (when (and now-done-p org-log-done)
12609 ;; It is now done, and it was not done before
12610 (org-add-planning-info 'closed (org-current-effective-time))
12611 (if (and (not dolog) (eq 'note org-log-done))
12612 (org-add-log-setup 'done org-state this 'findpos 'note)))
12613 (when (and org-state dolog)
12614 ;; This is a non-nil state, and we need to log it
12615 (org-add-log-setup 'state org-state this 'findpos dolog)))
12616 ;; Fixup tag positioning
12617 (org-todo-trigger-tag-changes org-state)
12618 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12619 (when org-provide-todo-statistics
12620 (org-update-parent-todo-statistics))
12621 (run-hooks 'org-after-todo-state-change-hook)
12622 (if (and arg (not (member org-state org-done-keywords)))
12623 (setq head (org-get-todo-sequence-head org-state)))
12624 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12625 ;; Do we need to trigger a repeat?
12626 (when now-done-p
12627 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12628 ;; This is for the agenda, take a snapshot of the headline.
12629 (save-match-data
12630 (setq org-agenda-headline-snapshot-before-repeat
12631 (org-get-heading))))
12632 (org-auto-repeat-maybe org-state))
12633 ;; Fixup cursor location if close to the keyword
12634 (if (and (outline-on-heading-p)
12635 (not (bolp))
12636 (save-excursion (beginning-of-line 1)
12637 (looking-at org-todo-line-regexp))
12638 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12639 (progn
12640 (goto-char (or (match-end 2) (match-end 1)))
12641 (and (looking-at " ") (just-one-space))))
12642 (when org-trigger-hook
12643 (save-excursion
12644 (run-hook-with-args 'org-trigger-hook change-plist)))
12645 (when commentp (org-toggle-comment))))))))
12647 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12648 "Block turning an entry into a TODO, using the hierarchy.
12649 This checks whether the current task should be blocked from state
12650 changes. Such blocking occurs when:
12652 1. The task has children which are not all in a completed state.
12654 2. A task has a parent with the property :ORDERED:, and there
12655 are siblings prior to the current task with incomplete
12656 status.
12658 3. The parent of the task is blocked because it has siblings that should
12659 be done first, or is child of a block grandparent TODO entry."
12661 (if (not org-enforce-todo-dependencies)
12662 t ; if locally turned off don't block
12663 (catch 'dont-block
12664 ;; If this is not a todo state change, or if this entry is already DONE,
12665 ;; do not block
12666 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12667 (member (plist-get change-plist :from)
12668 (cons 'done org-done-keywords))
12669 (member (plist-get change-plist :to)
12670 (cons 'todo org-not-done-keywords))
12671 (not (plist-get change-plist :to)))
12672 (throw 'dont-block t))
12673 ;; If this task has children, and any are undone, it's blocked
12674 (save-excursion
12675 (org-back-to-heading t)
12676 (let ((this-level (funcall outline-level)))
12677 (outline-next-heading)
12678 (let ((child-level (funcall outline-level)))
12679 (while (and (not (eobp))
12680 (> child-level this-level))
12681 ;; this todo has children, check whether they are all
12682 ;; completed
12683 (if (and (not (org-entry-is-done-p))
12684 (org-entry-is-todo-p))
12685 (progn (setq org-block-entry-blocking (org-get-heading))
12686 (throw 'dont-block nil)))
12687 (outline-next-heading)
12688 (setq child-level (funcall outline-level))))))
12689 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12690 ;; any previous siblings are undone, it's blocked
12691 (save-excursion
12692 (org-back-to-heading t)
12693 (let* ((pos (point))
12694 (parent-pos (and (org-up-heading-safe) (point))))
12695 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12696 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12697 (forward-line 1)
12698 (re-search-forward org-not-done-heading-regexp pos t))
12699 (setq org-block-entry-blocking (match-string 0))
12700 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12701 ;; Search further up the hierarchy, to see if an ancestor is blocked
12702 (while t
12703 (goto-char parent-pos)
12704 (if (not (looking-at org-not-done-heading-regexp))
12705 (throw 'dont-block t)) ; do not block, parent is not a TODO
12706 (setq pos (point))
12707 (setq 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 (org-get-heading)))
12713 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12715 (defcustom org-track-ordered-property-with-tag nil
12716 "Should the ORDERED property also be shown as a tag?
12717 The ORDERED property decides if an entry should require subtasks to be
12718 completed in sequence. Since a property is not very visible, setting
12719 this option means that toggling the ORDERED property with the command
12720 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12721 not relevant for the behavior, but it makes things more visible.
12723 Note that toggling the tag with tags commands will not change the property
12724 and therefore not influence behavior!
12726 This can be t, meaning the tag ORDERED should be used, It can also be a
12727 string to select a different tag for this task."
12728 :group 'org-todo
12729 :type '(choice
12730 (const :tag "No tracking" nil)
12731 (const :tag "Track with ORDERED tag" t)
12732 (string :tag "Use other tag")))
12734 (defun org-toggle-ordered-property ()
12735 "Toggle the ORDERED property of the current entry.
12736 For better visibility, you can track the value of this property with a tag.
12737 See variable `org-track-ordered-property-with-tag'."
12738 (interactive)
12739 (let* ((t1 org-track-ordered-property-with-tag)
12740 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12741 (save-excursion
12742 (org-back-to-heading)
12743 (if (org-entry-get nil "ORDERED")
12744 (progn
12745 (org-delete-property "ORDERED")
12746 (and tag (org-toggle-tag tag 'off))
12747 (message "Subtasks can be completed in arbitrary order"))
12748 (org-entry-put nil "ORDERED" "t")
12749 (and tag (org-toggle-tag tag 'on))
12750 (message "Subtasks must be completed in sequence")))))
12752 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12753 (defun org-block-todo-from-checkboxes (change-plist)
12754 "Block turning an entry into a TODO, using checkboxes.
12755 This checks whether the current task should be blocked from state
12756 changes because there are unchecked boxes in this entry."
12757 (if (not org-enforce-todo-checkbox-dependencies)
12758 t ; if locally turned off don't block
12759 (catch 'dont-block
12760 ;; If this is not a todo state change, or if this entry is already DONE,
12761 ;; do not block
12762 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12763 (member (plist-get change-plist :from)
12764 (cons 'done org-done-keywords))
12765 (member (plist-get change-plist :to)
12766 (cons 'todo org-not-done-keywords))
12767 (not (plist-get change-plist :to)))
12768 (throw 'dont-block t))
12769 ;; If this task has checkboxes that are not checked, it's blocked
12770 (save-excursion
12771 (org-back-to-heading t)
12772 (let ((beg (point)) end)
12773 (outline-next-heading)
12774 (setq end (point))
12775 (goto-char beg)
12776 (if (org-list-search-forward
12777 (concat (org-item-beginning-re)
12778 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12779 "\\[[- ]\\]")
12780 end t)
12781 (progn
12782 (if (boundp 'org-blocked-by-checkboxes)
12783 (setq org-blocked-by-checkboxes t))
12784 (throw 'dont-block nil)))))
12785 t))) ; do not block
12787 (defun org-entry-blocked-p ()
12788 "Is the current entry blocked?"
12789 (org-with-silent-modifications
12790 (if (org-entry-get nil "NOBLOCKING")
12791 nil ;; Never block this entry
12792 (not (run-hook-with-args-until-failure
12793 'org-blocker-hook
12794 (list :type 'todo-state-change
12795 :position (point)
12796 :from 'todo
12797 :to 'done))))))
12799 (defun org-update-statistics-cookies (all)
12800 "Update the statistics cookie, either from TODO or from checkboxes.
12801 This should be called with the cursor in a line with a statistics cookie."
12802 (interactive "P")
12803 (if all
12804 (progn
12805 (org-update-checkbox-count 'all)
12806 (org-map-entries 'org-update-parent-todo-statistics))
12807 (if (not (org-at-heading-p))
12808 (org-update-checkbox-count)
12809 (let ((pos (point-marker))
12810 end l1 l2)
12811 (ignore-errors (org-back-to-heading t))
12812 (if (not (org-at-heading-p))
12813 (org-update-checkbox-count)
12814 (setq l1 (org-outline-level))
12815 (setq end (save-excursion
12816 (outline-next-heading)
12817 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12818 (point)))
12819 (if (and (save-excursion
12820 (re-search-forward
12821 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12822 (not (save-excursion (re-search-forward
12823 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12824 (org-update-checkbox-count)
12825 (if (and l2 (> l2 l1))
12826 (progn
12827 (goto-char end)
12828 (org-update-parent-todo-statistics))
12829 (goto-char pos)
12830 (beginning-of-line 1)
12831 (while (re-search-forward
12832 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12833 (point-at-eol) t)
12834 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12835 (goto-char pos)
12836 (move-marker pos nil)))))
12838 (defvar org-entry-property-inherited-from) ;; defined below
12839 (defun org-update-parent-todo-statistics ()
12840 "Update any statistics cookie in the parent of the current headline.
12841 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12842 the entire subtree and this will travel up the hierarchy and update
12843 statistics everywhere."
12844 (let* ((prop (save-excursion (org-up-heading-safe)
12845 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12846 (recursive (or (not org-hierarchical-todo-statistics)
12847 (and prop (string-match "\\<recursive\\>" prop))))
12848 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12850 (first t)
12851 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12852 level ltoggle l1 new ndel
12853 (cnt-all 0) (cnt-done 0) is-percent kwd
12854 checkbox-beg ov ovs ove cookie-present)
12855 (catch 'exit
12856 (save-excursion
12857 (beginning-of-line 1)
12858 (setq ltoggle (funcall outline-level))
12859 ;; Three situations are to consider:
12861 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12862 ;; to the top-level ancestor on the headline;
12864 ;; 2. If parent has "recursive" property, repeat up to the
12865 ;; headline setting that property, taking inheritance into
12866 ;; account;
12868 ;; 3. Else, move up to direct parent and proceed only once.
12869 (while (and (setq level (org-up-heading-safe))
12870 (or recursive first)
12871 (>= (point) lim))
12872 (setq first nil cookie-present nil)
12873 (unless (and level
12874 (not (string-match
12875 "\\<checkbox\\>"
12876 (downcase (or (org-entry-get nil "COOKIE_DATA")
12877 "")))))
12878 (throw 'exit nil))
12879 (while (re-search-forward box-re (point-at-eol) t)
12880 (setq cnt-all 0 cnt-done 0 cookie-present t)
12881 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12882 (save-match-data
12883 (unless (outline-next-heading) (throw 'exit nil))
12884 (while (and (looking-at org-complex-heading-regexp)
12885 (> (setq l1 (length (match-string 1))) level))
12886 (setq kwd (and (or recursive (= l1 ltoggle))
12887 (match-string 2)))
12888 (if (or (eq org-provide-todo-statistics 'all-headlines)
12889 (and (eq org-provide-todo-statistics t)
12890 (or (member kwd org-done-keywords)))
12891 (and (listp org-provide-todo-statistics)
12892 (stringp (car org-provide-todo-statistics))
12893 (or (member kwd org-provide-todo-statistics)
12894 (member kwd org-done-keywords)))
12895 (and (listp org-provide-todo-statistics)
12896 (listp (car org-provide-todo-statistics))
12897 (or (member kwd (car org-provide-todo-statistics))
12898 (and (member kwd org-done-keywords)
12899 (member kwd (cadr org-provide-todo-statistics))))))
12900 (setq cnt-all (1+ cnt-all))
12901 (if (eq org-provide-todo-statistics t)
12902 (and kwd (setq cnt-all (1+ cnt-all)))))
12903 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12904 (member kwd org-done-keywords))
12905 (and (listp org-provide-todo-statistics)
12906 (listp (car org-provide-todo-statistics))
12907 (member kwd org-done-keywords)
12908 (member kwd (cadr org-provide-todo-statistics)))
12909 (and (listp org-provide-todo-statistics)
12910 (stringp (car org-provide-todo-statistics))
12911 (member kwd org-done-keywords)))
12912 (setq cnt-done (1+ cnt-done)))
12913 (outline-next-heading)))
12914 (setq new
12915 (if is-percent
12916 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12917 (format "[%d/%d]" cnt-done cnt-all))
12918 ndel (- (match-end 0) checkbox-beg))
12919 ;; handle overlays when updating cookie from column view
12920 (when (setq ov (car (overlays-at checkbox-beg)))
12921 (setq ovs (overlay-start ov) ove (overlay-end ov))
12922 (delete-overlay ov))
12923 (goto-char checkbox-beg)
12924 (insert new)
12925 (delete-region (point) (+ (point) ndel))
12926 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12927 (when ov (move-overlay ov ovs ove)))
12928 (when cookie-present
12929 (run-hook-with-args 'org-after-todo-statistics-hook
12930 cnt-done (- cnt-all cnt-done))))))
12931 (run-hooks 'org-todo-statistics-hook)))
12933 (defvar org-after-todo-statistics-hook nil
12934 "Hook that is called after a TODO statistics cookie has been updated.
12935 Each function is called with two arguments: the number of not-done entries
12936 and the number of done entries.
12938 For example, the following function, when added to this hook, will switch
12939 an entry to DONE when all children are done, and back to TODO when new
12940 entries are set to a TODO status. Note that this hook is only called
12941 when there is a statistics cookie in the headline!
12943 (defun org-summary-todo (n-done n-not-done)
12944 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12945 (let (org-log-done org-log-states) ; turn off logging
12946 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12949 (defvar org-todo-statistics-hook nil
12950 "Hook that is run whenever Org thinks TODO statistics should be updated.
12951 This hook runs even if there is no statistics cookie present, in which case
12952 `org-after-todo-statistics-hook' would not run.")
12954 (defun org-todo-trigger-tag-changes (state)
12955 "Apply the changes defined in `org-todo-state-tags-triggers'."
12956 (let ((l org-todo-state-tags-triggers)
12957 changes)
12958 (when (or (not state) (equal state ""))
12959 (setq changes (append changes (cdr (assoc "" l)))))
12960 (when (and (stringp state) (> (length state) 0))
12961 (setq changes (append changes (cdr (assoc state l)))))
12962 (when (member state org-not-done-keywords)
12963 (setq changes (append changes (cdr (assoc 'todo l)))))
12964 (when (member state org-done-keywords)
12965 (setq changes (append changes (cdr (assoc 'done l)))))
12966 (dolist (c changes)
12967 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12969 (defun org-local-logging (value)
12970 "Get logging settings from a property VALUE."
12971 (let* (words w a)
12972 ;; directly set the variables, they are already local.
12973 (setq org-log-done nil
12974 org-log-repeat nil
12975 org-todo-log-states nil)
12976 (setq words (org-split-string value))
12977 (while (setq w (pop words))
12978 (cond
12979 ((setq a (assoc w org-startup-options))
12980 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12981 (set (nth 1 a) (nth 2 a))))
12982 ((setq a (org-extract-log-state-settings w))
12983 (and (member (car a) org-todo-keywords-1)
12984 (push a org-todo-log-states)))))))
12986 (defun org-get-todo-sequence-head (kwd)
12987 "Return the head of the TODO sequence to which KWD belongs.
12988 If KWD is not set, check if there is a text property remembering the
12989 right sequence."
12990 (let (p)
12991 (cond
12992 ((not kwd)
12993 (or (get-text-property (point-at-bol) 'org-todo-head)
12994 (progn
12995 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12996 nil (point-at-eol)))
12997 (get-text-property p 'org-todo-head))))
12998 ((not (member kwd org-todo-keywords-1))
12999 (car org-todo-keywords-1))
13000 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13002 (defun org-fast-todo-selection ()
13003 "Fast TODO keyword selection with single keys.
13004 Returns the new TODO keyword, or nil if no state change should occur."
13005 (let* ((fulltable org-todo-key-alist)
13006 (done-keywords org-done-keywords) ;; needed for the faces.
13007 (maxlen (apply 'max (mapcar
13008 (lambda (x)
13009 (if (stringp (car x)) (string-width (car x)) 0))
13010 fulltable)))
13011 (expert nil)
13012 (fwidth (+ maxlen 3 1 3))
13013 (ncol (/ (- (window-width) 4) fwidth))
13014 tg cnt e c tbl
13015 groups ingroup)
13016 (save-excursion
13017 (save-window-excursion
13018 (if expert
13019 (set-buffer (get-buffer-create " *Org todo*"))
13020 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13021 (erase-buffer)
13022 (org-set-local 'org-done-keywords done-keywords)
13023 (setq tbl fulltable cnt 0)
13024 (while (setq e (pop tbl))
13025 (cond
13026 ((equal e '(:startgroup))
13027 (push '() groups) (setq ingroup t)
13028 (when (not (= cnt 0))
13029 (setq cnt 0)
13030 (insert "\n"))
13031 (insert "{ "))
13032 ((equal e '(:endgroup))
13033 (setq ingroup nil cnt 0)
13034 (insert "}\n"))
13035 ((equal e '(:newline))
13036 (when (not (= cnt 0))
13037 (setq cnt 0)
13038 (insert "\n")
13039 (setq e (car tbl))
13040 (while (equal (car tbl) '(:newline))
13041 (insert "\n")
13042 (setq tbl (cdr tbl)))))
13044 (setq tg (car e) c (cdr e))
13045 (if ingroup (push tg (car groups)))
13046 (setq tg (org-add-props tg nil 'face
13047 (org-get-todo-face tg)))
13048 (if (and (= cnt 0) (not ingroup)) (insert " "))
13049 (insert "[" c "] " tg (make-string
13050 (- fwidth 4 (length tg)) ?\ ))
13051 (when (= (setq cnt (1+ cnt)) ncol)
13052 (insert "\n")
13053 (if ingroup (insert " "))
13054 (setq cnt 0)))))
13055 (insert "\n")
13056 (goto-char (point-min))
13057 (if (not expert) (org-fit-window-to-buffer))
13058 (message "[a-z..]:Set [SPC]:clear")
13059 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13060 (cond
13061 ((or (= c ?\C-g)
13062 (and (= c ?q) (not (rassoc c fulltable))))
13063 (setq quit-flag t))
13064 ((= c ?\ ) nil)
13065 ((setq e (rassoc c fulltable) tg (car e))
13067 (t (setq quit-flag t)))))))
13069 (defun org-entry-is-todo-p ()
13070 (member (org-get-todo-state) org-not-done-keywords))
13072 (defun org-entry-is-done-p ()
13073 (member (org-get-todo-state) org-done-keywords))
13075 (defun org-get-todo-state ()
13076 "Return the TODO keyword of the current subtree."
13077 (save-excursion
13078 (org-back-to-heading t)
13079 (and (looking-at org-todo-line-regexp)
13080 (match-end 2)
13081 (match-string 2))))
13083 (defun org-at-date-range-p (&optional inactive-ok)
13084 "Is the cursor inside a date range?"
13085 (interactive)
13086 (save-excursion
13087 (catch 'exit
13088 (let ((pos (point)))
13089 (skip-chars-backward "^[<\r\n")
13090 (skip-chars-backward "<[")
13091 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13092 (>= (match-end 0) pos)
13093 (throw 'exit t))
13094 (skip-chars-backward "^<[\r\n")
13095 (skip-chars-backward "<[")
13096 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13097 (>= (match-end 0) pos)
13098 (throw 'exit t)))
13099 nil)))
13101 (defun org-get-repeat (&optional tagline)
13102 "Check if there is a deadline/schedule with repeater in this entry."
13103 (save-match-data
13104 (save-excursion
13105 (org-back-to-heading t)
13106 (and (re-search-forward (if tagline
13107 (concat tagline "\\s-*" org-repeat-re)
13108 org-repeat-re)
13109 (org-entry-end-position) t)
13110 (match-string-no-properties 1)))))
13112 (defvar org-last-changed-timestamp)
13113 (defvar org-last-inserted-timestamp)
13114 (defvar org-log-post-message)
13115 (defvar org-log-note-purpose)
13116 (defvar org-log-note-how nil)
13117 (defvar org-log-note-extra)
13118 (defun org-auto-repeat-maybe (done-word)
13119 "Check if the current headline contains a repeated deadline/schedule.
13120 If yes, set TODO state back to what it was and change the base date
13121 of repeating deadline/scheduled time stamps to new date.
13122 This function is run automatically after each state change to a DONE state."
13123 ;; last-state is dynamically scoped into this function
13124 (let* ((repeat (org-get-repeat))
13125 (aa (assoc org-last-state org-todo-kwd-alist))
13126 (interpret (nth 1 aa))
13127 (head (nth 2 aa))
13128 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13129 (msg "Entry repeats: ")
13130 (org-log-done nil)
13131 (org-todo-log-states nil)
13132 re type n what ts time to-state)
13133 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13134 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
13135 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
13136 org-todo-repeat-to-state))
13137 (unless (and to-state (member to-state org-todo-keywords-1))
13138 (setq to-state (if (eq interpret 'type) org-last-state head)))
13139 (org-todo to-state)
13140 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13141 (org-entry-put nil "LAST_REPEAT" (format-time-string
13142 (org-time-stamp-format t t))))
13143 (when org-log-repeat
13144 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13145 (memq 'org-add-log-note post-command-hook))
13146 ;; OK, we are already setup for some record
13147 (if (eq org-log-repeat 'note)
13148 ;; make sure we take a note, not only a time stamp
13149 (setq org-log-note-how 'note))
13150 ;; Set up for taking a record
13151 (org-add-log-setup 'state (or done-word (car org-done-keywords))
13152 org-last-state
13153 'findpos org-log-repeat)))
13154 (org-back-to-heading t)
13155 (org-add-planning-info nil nil 'closed)
13156 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13157 org-deadline-time-regexp "\\)\\|\\("
13158 org-ts-regexp "\\)"))
13159 (while (re-search-forward
13160 re (save-excursion (outline-next-heading) (point)) t)
13161 (setq type (if (match-end 1) org-scheduled-string
13162 (if (match-end 3) org-deadline-string "Plain:"))
13163 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
13164 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
13165 (setq n (string-to-number (match-string 2 ts))
13166 what (match-string 3 ts))
13167 (if (equal what "w") (setq n (* n 7) what "d"))
13168 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
13169 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
13170 ;; Preparation, see if we need to modify the start date for the change
13171 (when (match-end 1)
13172 (setq time (save-match-data (org-time-string-to-time ts)))
13173 (cond
13174 ((equal (match-string 1 ts) ".")
13175 ;; Shift starting date to today
13176 (org-timestamp-change
13177 (- (org-today) (time-to-days time))
13178 'day))
13179 ((equal (match-string 1 ts) "+")
13180 (let ((nshiftmax 10) (nshift 0))
13181 (while (or (= nshift 0)
13182 (<= (time-to-days time)
13183 (time-to-days (current-time))))
13184 (when (= (incf nshift) nshiftmax)
13185 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
13186 (user-error "Abort")))
13187 (org-timestamp-change n (cdr (assoc what whata)))
13188 (org-at-timestamp-p t)
13189 (setq ts (match-string 1))
13190 (setq time (save-match-data (org-time-string-to-time ts)))))
13191 (org-timestamp-change (- n) (cdr (assoc what whata)))
13192 ;; rematch, so that we have everything in place for the real shift
13193 (org-at-timestamp-p t)
13194 (setq ts (match-string 1))
13195 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
13196 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
13197 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
13198 (setq org-log-post-message msg)
13199 (message "%s" msg))))
13201 (defun org-show-todo-tree (arg)
13202 "Make a compact tree which shows all headlines marked with TODO.
13203 The tree will show the lines where the regexp matches, and all higher
13204 headlines above the match.
13205 With a \\[universal-argument] prefix, prompt for a regexp to match.
13206 With a numeric prefix N, construct a sparse tree for the Nth element
13207 of `org-todo-keywords-1'."
13208 (interactive "P")
13209 (let ((case-fold-search nil)
13210 (kwd-re
13211 (cond ((null arg) org-not-done-regexp)
13212 ((equal arg '(4))
13213 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
13214 (mapcar 'list org-todo-keywords-1))))
13215 (concat "\\("
13216 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13217 "\\)\\>")))
13218 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13219 (regexp-quote (nth (1- (prefix-numeric-value arg))
13220 org-todo-keywords-1)))
13221 (t (user-error "Invalid prefix argument: %s" arg)))))
13222 (message "%d TODO entries found"
13223 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13225 (defun org-deadline (arg &optional time)
13226 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13227 With one universal prefix argument, remove any deadline from the item.
13228 With two universal prefix arguments, prompt for a warning delay.
13229 With argument TIME, set the deadline at the corresponding date. TIME
13230 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13231 (interactive "P")
13232 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13233 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13234 'region-start-level 'region))
13235 org-loop-over-headlines-in-active-region)
13236 (org-map-entries
13237 `(org-deadline ',arg ,time)
13238 org-loop-over-headlines-in-active-region
13239 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13240 (let* ((old-date (org-entry-get nil "DEADLINE"))
13241 (old-date-time (if old-date (org-time-string-to-time old-date)))
13242 (repeater (and old-date
13243 (string-match
13244 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13245 old-date)
13246 (match-string 1 old-date))))
13247 (cond
13248 ((equal arg '(4))
13249 (when (and old-date org-log-redeadline)
13250 (org-add-log-setup 'deldeadline nil old-date 'findpos
13251 org-log-redeadline))
13252 (org-remove-timestamp-with-keyword org-deadline-string)
13253 (message "Item no longer has a deadline."))
13254 ((equal arg '(16))
13255 (save-excursion
13256 (org-back-to-heading t)
13257 (if (re-search-forward
13258 org-deadline-time-regexp
13259 (save-excursion (outline-next-heading) (point)) t)
13260 (let* ((rpl0 (match-string 1))
13261 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13262 (replace-match
13263 (concat org-deadline-string
13264 " <" rpl
13265 (format " -%dd"
13266 (abs
13267 (- (time-to-days
13268 (save-match-data
13269 (org-read-date nil t nil "Warn starting from" old-date-time)))
13270 (time-to-days old-date-time))))
13271 ">") t t))
13272 (user-error "No deadline information to update"))))
13274 (org-add-planning-info 'deadline time 'closed)
13275 (when (and old-date org-log-redeadline
13276 (not (equal old-date
13277 (substring org-last-inserted-timestamp 1 -1))))
13278 (org-add-log-setup 'redeadline nil old-date 'findpos
13279 org-log-redeadline))
13280 (when repeater
13281 (save-excursion
13282 (org-back-to-heading t)
13283 (when (re-search-forward (concat org-deadline-string " "
13284 org-last-inserted-timestamp)
13285 (save-excursion
13286 (outline-next-heading) (point)) t)
13287 (goto-char (1- (match-end 0)))
13288 (insert " " repeater)
13289 (setq org-last-inserted-timestamp
13290 (concat (substring org-last-inserted-timestamp 0 -1)
13291 " " repeater
13292 (substring org-last-inserted-timestamp -1))))))
13293 (message "Deadline on %s" org-last-inserted-timestamp))))))
13295 (defun org-schedule (arg &optional time)
13296 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13297 With one universal prefix argument, remove any scheduling date from the item.
13298 With two universal prefix arguments, prompt for a delay cookie.
13299 With argument TIME, scheduled at the corresponding date. TIME can
13300 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13301 (interactive "P")
13302 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13303 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13304 'region-start-level 'region))
13305 org-loop-over-headlines-in-active-region)
13306 (org-map-entries
13307 `(org-schedule ',arg ,time)
13308 org-loop-over-headlines-in-active-region
13309 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13310 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13311 (old-date-time (if old-date (org-time-string-to-time old-date)))
13312 (repeater (and old-date
13313 (string-match
13314 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13315 old-date)
13316 (match-string 1 old-date))))
13317 (cond
13318 ((equal arg '(4))
13319 (progn
13320 (when (and old-date org-log-reschedule)
13321 (org-add-log-setup 'delschedule nil old-date 'findpos
13322 org-log-reschedule))
13323 (org-remove-timestamp-with-keyword org-scheduled-string)
13324 (message "Item is no longer scheduled.")))
13325 ((equal arg '(16))
13326 (save-excursion
13327 (org-back-to-heading t)
13328 (if (re-search-forward
13329 org-scheduled-time-regexp
13330 (save-excursion (outline-next-heading) (point)) t)
13331 (let* ((rpl0 (match-string 1))
13332 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13333 (replace-match
13334 (concat org-scheduled-string
13335 " <" rpl
13336 (format " -%dd"
13337 (abs
13338 (- (time-to-days
13339 (save-match-data
13340 (org-read-date nil t nil "Delay until" old-date-time)))
13341 (time-to-days old-date-time))))
13342 ">") t t))
13343 (user-error "No scheduled information to update"))))
13345 (org-add-planning-info 'scheduled time 'closed)
13346 (when (and old-date org-log-reschedule
13347 (not (equal old-date
13348 (substring org-last-inserted-timestamp 1 -1))))
13349 (org-add-log-setup 'reschedule nil old-date 'findpos
13350 org-log-reschedule))
13351 (when repeater
13352 (save-excursion
13353 (org-back-to-heading t)
13354 (when (re-search-forward (concat org-scheduled-string " "
13355 org-last-inserted-timestamp)
13356 (save-excursion
13357 (outline-next-heading) (point)) t)
13358 (goto-char (1- (match-end 0)))
13359 (insert " " repeater)
13360 (setq org-last-inserted-timestamp
13361 (concat (substring org-last-inserted-timestamp 0 -1)
13362 " " repeater
13363 (substring org-last-inserted-timestamp -1))))))
13364 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13366 (defun org-get-scheduled-time (pom &optional inherit)
13367 "Get the scheduled time as a time tuple, of a format suitable
13368 for calling org-schedule with, or if there is no scheduling,
13369 returns nil."
13370 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13371 (when time
13372 (apply 'encode-time (org-parse-time-string time)))))
13374 (defun org-get-deadline-time (pom &optional inherit)
13375 "Get the deadline as a time tuple, of a format suitable for
13376 calling org-deadline with, or if there is no scheduling, returns
13377 nil."
13378 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13379 (when time
13380 (apply 'encode-time (org-parse-time-string time)))))
13382 (defun org-remove-timestamp-with-keyword (keyword)
13383 "Remove all time stamps with KEYWORD in the current entry."
13384 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13385 beg)
13386 (save-excursion
13387 (org-back-to-heading t)
13388 (setq beg (point))
13389 (outline-next-heading)
13390 (while (re-search-backward re beg t)
13391 (replace-match "")
13392 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13393 (equal (char-before) ?\ ))
13394 (backward-delete-char 1)
13395 (if (string-match "^[ \t]*$" (buffer-substring
13396 (point-at-bol) (point-at-eol)))
13397 (delete-region (point-at-bol)
13398 (min (point-max) (1+ (point-at-eol))))))))))
13400 (defvar org-time-was-given) ; dynamically scoped parameter
13401 (defvar org-end-time-was-given) ; dynamically scoped parameter
13403 (defun org-add-planning-info (what &optional time &rest remove)
13404 "Insert new timestamp with keyword in the line directly after the headline.
13405 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13406 If non is given, the user is prompted for a date.
13407 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13408 be removed."
13409 (interactive)
13410 (let (org-time-was-given org-end-time-was-given ts
13411 end default-time default-input)
13413 (catch 'exit
13414 (when (and (memq what '(scheduled deadline))
13415 (or (not time)
13416 (and (stringp time)
13417 (string-match "^[-+]+[0-9]" time))))
13418 ;; Try to get a default date/time from existing timestamp
13419 (save-excursion
13420 (org-back-to-heading t)
13421 (setq end (save-excursion (outline-next-heading) (point)))
13422 (when (re-search-forward (if (eq what 'scheduled)
13423 org-scheduled-time-regexp
13424 org-deadline-time-regexp)
13425 end t)
13426 (setq ts (match-string 1)
13427 default-time
13428 (apply 'encode-time (org-parse-time-string ts))
13429 default-input (and ts (org-get-compact-tod ts))))))
13430 (when what
13431 (setq time
13432 (if (stringp time)
13433 ;; This is a string (relative or absolute), set proper date
13434 (apply 'encode-time
13435 (org-read-date-analyze
13436 time default-time (decode-time default-time)))
13437 ;; If necessary, get the time from the user
13438 (or time (org-read-date nil 'to-time nil nil
13439 default-time default-input)))))
13441 (when (and org-insert-labeled-timestamps-at-point
13442 (member what '(scheduled deadline)))
13443 (insert
13444 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13445 (org-insert-time-stamp time org-time-was-given
13446 nil nil nil (list org-end-time-was-given))
13447 (setq what nil))
13448 (save-excursion
13449 (save-restriction
13450 (let (col list elt ts buffer-invisibility-spec)
13451 (org-back-to-heading t)
13452 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13453 (goto-char (match-end 1))
13454 (setq col (current-column))
13455 (goto-char (match-end 0))
13456 (if (eobp) (insert "\n") (forward-char 1))
13457 (when (and (not what)
13458 (not (looking-at
13459 (concat "[ \t]*"
13460 org-keyword-time-not-clock-regexp))))
13461 ;; Nothing to add, nothing to remove...... :-)
13462 (throw 'exit nil))
13463 (if (and (not (looking-at org-outline-regexp))
13464 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13465 "[^\r\n]*"))
13466 (not (equal (match-string 1) org-clock-string)))
13467 (narrow-to-region (match-beginning 0) (match-end 0))
13468 (insert-before-markers "\n")
13469 (backward-char 1)
13470 (narrow-to-region (point) (point))
13471 (and org-adapt-indentation (org-indent-to-column col)))
13472 ;; Check if we have to remove something.
13473 (setq list (cons what remove))
13474 (while list
13475 (setq elt (pop list))
13476 (when (or (and (eq elt 'scheduled)
13477 (re-search-forward org-scheduled-time-regexp nil t))
13478 (and (eq elt 'deadline)
13479 (re-search-forward org-deadline-time-regexp nil t))
13480 (and (eq elt 'closed)
13481 (re-search-forward org-closed-time-regexp nil t)))
13482 (replace-match "")
13483 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13484 (and (looking-at "[ \t]+") (replace-match ""))
13485 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13486 (when what
13487 (insert
13488 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13489 (cond ((eq what 'scheduled) org-scheduled-string)
13490 ((eq what 'deadline) org-deadline-string)
13491 ((eq what 'closed) org-closed-string))
13492 " ")
13493 (setq ts (org-insert-time-stamp
13494 time
13495 (or org-time-was-given
13496 (and (eq what 'closed) org-log-done-with-time))
13497 (eq what 'closed)
13498 nil nil (list org-end-time-was-given)))
13499 (insert
13500 (if (not (or (bolp) (eq (char-before) ?\ )
13501 (memq (char-after) '(32 10))
13502 (eobp))) " " ""))
13503 (end-of-line 1))
13504 (goto-char (point-min))
13505 (widen)
13506 (if (and (looking-at "[ \t]*\n")
13507 (equal (char-before) ?\n))
13508 (delete-region (1- (point)) (point-at-eol)))
13509 ts))))))
13511 (defvar org-log-note-marker (make-marker))
13512 (defvar org-log-note-purpose nil)
13513 (defvar org-log-note-state nil)
13514 (defvar org-log-note-previous-state nil)
13515 (defvar org-log-note-extra nil)
13516 (defvar org-log-note-window-configuration nil)
13517 (defvar org-log-note-return-to (make-marker))
13518 (defvar org-log-note-effective-time nil
13519 "Remembered current time so that dynamically scoped
13520 `org-extend-today-until' affects tha timestamps in state change
13521 log")
13523 (defvar org-log-post-message nil
13524 "Message to be displayed after a log note has been stored.
13525 The auto-repeater uses this.")
13527 (defun org-add-note ()
13528 "Add a note to the current entry.
13529 This is done in the same way as adding a state change note."
13530 (interactive)
13531 (org-add-log-setup 'note nil nil 'findpos nil))
13533 (defvar org-property-end-re)
13534 (defun org-add-log-setup (&optional purpose state prev-state
13535 findpos how extra)
13536 "Set up the post command hook to take a note.
13537 If this is about to TODO state change, the new state is expected in STATE.
13538 When FINDPOS is non-nil, find the correct position for the note in
13539 the current entry. If not, assume that it can be inserted at point.
13540 HOW is an indicator what kind of note should be created.
13541 EXTRA is additional text that will be inserted into the notes buffer."
13542 (let* ((org-log-into-drawer (org-log-into-drawer))
13543 (drawer (cond ((stringp org-log-into-drawer)
13544 org-log-into-drawer)
13545 (org-log-into-drawer "LOGBOOK"))))
13546 (save-restriction
13547 (save-excursion
13548 (when findpos
13549 (org-back-to-heading t)
13550 (narrow-to-region (point) (save-excursion
13551 (outline-next-heading) (point)))
13552 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13553 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13554 "[^\r\n]*\\)?"))
13555 (goto-char (match-end 0))
13556 (cond
13557 (drawer
13558 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13559 nil t)
13560 (progn
13561 (goto-char (match-end 0))
13562 (or org-log-states-order-reversed
13563 (and (re-search-forward org-property-end-re nil t)
13564 (goto-char (1- (match-beginning 0))))))
13565 (insert "\n:" drawer ":\n:END:")
13566 (beginning-of-line 0)
13567 (org-indent-line)
13568 (beginning-of-line 2)
13569 (org-indent-line)
13570 (end-of-line 0)))
13571 ((and org-log-state-notes-insert-after-drawers
13572 (save-excursion
13573 (forward-line) (looking-at org-drawer-regexp)))
13574 (forward-line)
13575 (while (looking-at org-drawer-regexp)
13576 (goto-char (match-end 0))
13577 (re-search-forward org-property-end-re (point-max) t)
13578 (forward-line))
13579 (forward-line -1)))
13580 (unless org-log-states-order-reversed
13581 (and (= (char-after) ?\n) (forward-char 1))
13582 (org-skip-over-state-notes)
13583 (skip-chars-backward " \t\n\r")))
13584 (move-marker org-log-note-marker (point))
13585 (setq org-log-note-purpose purpose
13586 org-log-note-state state
13587 org-log-note-previous-state prev-state
13588 org-log-note-how how
13589 org-log-note-extra extra
13590 org-log-note-effective-time (org-current-effective-time))
13591 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13593 (defun org-skip-over-state-notes ()
13594 "Skip past the list of State notes in an entry."
13595 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13596 (when (ignore-errors (goto-char (org-in-item-p)))
13597 (let* ((struct (org-list-struct))
13598 (prevs (org-list-prevs-alist struct)))
13599 (while (looking-at "[ \t]*- State")
13600 (goto-char (or (org-list-get-next-item (point) struct prevs)
13601 (org-list-get-item-end (point) struct)))))))
13603 (defun org-add-log-note (&optional purpose)
13604 "Pop up a window for taking a note, and add this note later at point."
13605 (remove-hook 'post-command-hook 'org-add-log-note)
13606 (setq org-log-note-window-configuration (current-window-configuration))
13607 (delete-other-windows)
13608 (move-marker org-log-note-return-to (point))
13609 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13610 (goto-char org-log-note-marker)
13611 (org-switch-to-buffer-other-window "*Org Note*")
13612 (erase-buffer)
13613 (if (memq org-log-note-how '(time state))
13614 (let (current-prefix-arg) (org-store-log-note))
13615 (let ((org-inhibit-startup t)) (org-mode))
13616 (insert (format "# Insert note for %s.
13617 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13618 (cond
13619 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13620 ((eq org-log-note-purpose 'done) "closed todo item")
13621 ((eq org-log-note-purpose 'state)
13622 (format "state change from \"%s\" to \"%s\""
13623 (or org-log-note-previous-state "")
13624 (or org-log-note-state "")))
13625 ((eq org-log-note-purpose 'reschedule)
13626 "rescheduling")
13627 ((eq org-log-note-purpose 'delschedule)
13628 "no longer scheduled")
13629 ((eq org-log-note-purpose 'redeadline)
13630 "changing deadline")
13631 ((eq org-log-note-purpose 'deldeadline)
13632 "removing deadline")
13633 ((eq org-log-note-purpose 'refile)
13634 "refiling")
13635 ((eq org-log-note-purpose 'note)
13636 "this entry")
13637 (t (error "This should not happen")))))
13638 (if org-log-note-extra (insert org-log-note-extra))
13639 (org-set-local 'org-finish-function 'org-store-log-note)
13640 (run-hooks 'org-log-buffer-setup-hook)))
13642 (defvar org-note-abort nil) ; dynamically scoped
13643 (defun org-store-log-note ()
13644 "Finish taking a log note, and insert it to where it belongs."
13645 (let ((txt (buffer-string)))
13646 (kill-buffer (current-buffer))
13647 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13648 lines ind bul)
13649 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13650 (setq txt (replace-match "" t t txt)))
13651 (if (string-match "\\s-+\\'" txt)
13652 (setq txt (replace-match "" t t txt)))
13653 (setq lines (org-split-string txt "\n"))
13654 (when (and note (string-match "\\S-" note))
13655 (setq note
13656 (org-replace-escapes
13657 note
13658 (list (cons "%u" (user-login-name))
13659 (cons "%U" user-full-name)
13660 (cons "%t" (format-time-string
13661 (org-time-stamp-format 'long 'inactive)
13662 org-log-note-effective-time))
13663 (cons "%T" (format-time-string
13664 (org-time-stamp-format 'long nil)
13665 org-log-note-effective-time))
13666 (cons "%d" (format-time-string
13667 (org-time-stamp-format nil 'inactive)
13668 org-log-note-effective-time))
13669 (cons "%D" (format-time-string
13670 (org-time-stamp-format nil nil)
13671 org-log-note-effective-time))
13672 (cons "%s" (if org-log-note-state
13673 (concat "\"" org-log-note-state "\"")
13674 ""))
13675 (cons "%S" (if org-log-note-previous-state
13676 (concat "\"" org-log-note-previous-state "\"")
13677 "\"\"")))))
13678 (if lines (setq note (concat note " \\\\")))
13679 (push note lines))
13680 (when (or current-prefix-arg org-note-abort)
13681 (when org-log-into-drawer
13682 (org-remove-empty-drawer-at org-log-note-marker))
13683 (setq lines nil))
13684 (when lines
13685 (with-current-buffer (marker-buffer org-log-note-marker)
13686 (save-excursion
13687 (goto-char org-log-note-marker)
13688 (move-marker org-log-note-marker nil)
13689 (end-of-line 1)
13690 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13691 (setq ind (save-excursion
13692 (if (ignore-errors (goto-char (org-in-item-p)))
13693 (let ((struct (org-list-struct)))
13694 (org-list-get-ind
13695 (org-list-get-top-point struct) struct))
13696 (skip-chars-backward " \r\t\n")
13697 (cond
13698 ((and (org-at-heading-p)
13699 org-adapt-indentation)
13700 (1+ (org-current-level)))
13701 ((org-at-heading-p) 0)
13702 (t (org-get-indentation))))))
13703 (setq bul (org-list-bullet-string "-"))
13704 (org-indent-line-to ind)
13705 (insert bul (pop lines))
13706 (let ((ind-body (+ (length bul) ind)))
13707 (while lines
13708 (insert "\n")
13709 (org-indent-line-to ind-body)
13710 (insert (pop lines))))
13711 (message "Note stored")
13712 (org-back-to-heading t)
13713 (org-cycle-hide-drawers 'children))
13714 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13715 ;; from within `org-add-log-note' because `buffer-undo-list'
13716 ;; is then modified outside of `org-with-remote-undo'.
13717 (when (eq this-command 'org-agenda-todo)
13718 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13719 ;; Don't add undo information when called from `org-agenda-todo'
13720 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13721 (set-window-configuration org-log-note-window-configuration)
13722 (with-current-buffer (marker-buffer org-log-note-return-to)
13723 (goto-char org-log-note-return-to))
13724 (move-marker org-log-note-return-to nil)
13725 (and org-log-post-message (message "%s" org-log-post-message))))
13727 (defun org-remove-empty-drawer-at (pos)
13728 "Remove an empty drawer at position POS.
13729 POS may also be a marker."
13730 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13731 (org-with-wide-buffer
13732 (goto-char pos)
13733 (let ((drawer (org-element-at-point)))
13734 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13735 (not (org-element-property :contents-begin drawer)))
13736 (delete-region (org-element-property :begin drawer)
13737 (progn (goto-char (org-element-property :end drawer))
13738 (skip-chars-backward " \r\t\n")
13739 (forward-line)
13740 (point))))))))
13742 (defvar org-ts-type nil)
13743 (defun org-sparse-tree (&optional arg type)
13744 "Create a sparse tree, prompt for the details.
13745 This command can create sparse trees. You first need to select the type
13746 of match used to create the tree:
13748 t Show all TODO entries.
13749 T Show entries with a specific TODO keyword.
13750 m Show entries selected by a tags/property match.
13751 p Enter a property name and its value (both with completion on existing
13752 names/values) and show entries with that property.
13753 r Show entries matching a regular expression (`/' can be used as well).
13754 b Show deadlines and scheduled items before a date.
13755 a Show deadlines and scheduled items after a date.
13756 d Show deadlines due within `org-deadline-warning-days'.
13757 D Show deadlines and scheduled items between a date range."
13758 (interactive "P")
13759 (setq type (or type org-sparse-tree-default-date-type))
13760 (setq org-ts-type type)
13761 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13762 [d]eadlines [b]efore-date [a]fter-date [D]ates range
13763 [c]ycle through date types: %s"
13764 (case type
13765 (all "all timestamps")
13766 (scheduled "only scheduled")
13767 (deadline "only deadline")
13768 (active "only active timestamps")
13769 (inactive "only inactive timestamps")
13770 (scheduled-or-deadline "scheduled/deadline")
13771 (closed "with a closed time-stamp")
13772 (otherwise "scheduled/deadline")))
13773 (let ((answer (read-char-exclusive)))
13774 (case answer
13776 (org-sparse-tree
13778 (cadr (memq type '(scheduled-or-deadline all scheduled deadline active
13779 inactive closed)))))
13780 (?d (call-interactively 'org-check-deadlines))
13781 (?b (call-interactively 'org-check-before-date))
13782 (?a (call-interactively 'org-check-after-date))
13783 (?D (call-interactively 'org-check-dates-range))
13784 (?t (call-interactively 'org-show-todo-tree))
13785 (?T (org-show-todo-tree '(4)))
13786 (?m (call-interactively 'org-match-sparse-tree))
13787 ((?p ?P)
13788 (let* ((kwd (org-icompleting-read
13789 "Property: " (mapcar 'list (org-buffer-property-keys))))
13790 (value (org-icompleting-read
13791 "Value: " (mapcar 'list (org-property-values kwd)))))
13792 (unless (string-match "\\`{.*}\\'" value)
13793 (setq value (concat "\"" value "\"")))
13794 (org-match-sparse-tree arg (concat kwd "=" value))))
13795 ((?r ?R ?/) (call-interactively 'org-occur))
13796 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13798 (defvar org-occur-highlights nil
13799 "List of overlays used for occur matches.")
13800 (make-variable-buffer-local 'org-occur-highlights)
13801 (defvar org-occur-parameters nil
13802 "Parameters of the active org-occur calls.
13803 This is a list, each call to org-occur pushes as cons cell,
13804 containing the regular expression and the callback, onto the list.
13805 The list can contain several entries if `org-occur' has been called
13806 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13807 will only contain one set of parameters. When the highlights are
13808 removed (for example with `C-c C-c', or with the next edit (depending
13809 on `org-remove-highlights-with-change'), this variable is emptied
13810 as well.")
13811 (make-variable-buffer-local 'org-occur-parameters)
13813 (defun org-occur (regexp &optional keep-previous callback)
13814 "Make a compact tree which shows all matches of REGEXP.
13815 The tree will show the lines where the regexp matches, and all higher
13816 headlines above the match. It will also show the heading after the match,
13817 to make sure editing the matching entry is easy.
13818 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13819 call to `org-occur' will be kept, to allow stacking of calls to this
13820 command.
13821 If CALLBACK is non-nil, it is a function which is called to confirm
13822 that the match should indeed be shown."
13823 (interactive "sRegexp: \nP")
13824 (when (equal regexp "")
13825 (user-error "Regexp cannot be empty"))
13826 (unless keep-previous
13827 (org-remove-occur-highlights nil nil t))
13828 (push (cons regexp callback) org-occur-parameters)
13829 (let ((cnt 0))
13830 (save-excursion
13831 (goto-char (point-min))
13832 (if (or (not keep-previous) ; do not want to keep
13833 (not org-occur-highlights)) ; no previous matches
13834 ;; hide everything
13835 (org-overview))
13836 (while (re-search-forward regexp nil t)
13837 (when (or (not callback)
13838 (save-match-data (funcall callback)))
13839 (setq cnt (1+ cnt))
13840 (when org-highlight-sparse-tree-matches
13841 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13842 (org-show-context 'occur-tree))))
13843 (when org-remove-highlights-with-change
13844 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13845 nil 'local))
13846 (unless org-sparse-tree-open-archived-trees
13847 (org-hide-archived-subtrees (point-min) (point-max)))
13848 (run-hooks 'org-occur-hook)
13849 (if (org-called-interactively-p 'interactive)
13850 (message "%d match(es) for regexp %s" cnt regexp))
13851 cnt))
13853 (defun org-occur-next-match (&optional n reset)
13854 "Function for `next-error-function' to find sparse tree matches.
13855 N is the number of matches to move, when negative move backwards.
13856 RESET is entirely ignored - this function always goes back to the
13857 starting point when no match is found."
13858 (let* ((limit (if (< n 0) (point-min) (point-max)))
13859 (search-func (if (< n 0)
13860 'previous-single-char-property-change
13861 'next-single-char-property-change))
13862 (n (abs n))
13863 (pos (point))
13865 (catch 'exit
13866 (while (setq p1 (funcall search-func (point) 'org-type))
13867 (when (equal p1 limit)
13868 (goto-char pos)
13869 (user-error "No more matches"))
13870 (when (equal (get-char-property p1 'org-type) 'org-occur)
13871 (setq n (1- n))
13872 (when (= n 0)
13873 (goto-char p1)
13874 (throw 'exit (point))))
13875 (goto-char p1))
13876 (goto-char p1)
13877 (user-error "No more matches"))))
13879 (defun org-show-context (&optional key)
13880 "Make sure point and context are visible.
13881 How much context is shown depends upon the variables
13882 `org-show-hierarchy-above', `org-show-following-heading',
13883 `org-show-entry-below' and `org-show-siblings'."
13884 (let ((heading-p (org-at-heading-p t))
13885 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13886 (following-p (org-get-alist-option org-show-following-heading key))
13887 (entry-p (org-get-alist-option org-show-entry-below key))
13888 (siblings-p (org-get-alist-option org-show-siblings key)))
13889 ;; Show heading or entry text
13890 (if (and heading-p (not entry-p))
13891 (org-flag-heading nil) ; only show the heading
13892 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13893 (org-show-hidden-entry))) ; show entire entry
13894 (when following-p
13895 ;; Show next sibling, or heading below text
13896 (save-excursion
13897 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13898 (org-flag-heading nil))))
13899 (when siblings-p (org-show-siblings))
13900 (when hierarchy-p
13901 ;; show all higher headings, possibly with siblings
13902 (save-excursion
13903 (while (and (ignore-errors (progn (org-up-heading-all 1) t))
13904 (not (bobp)))
13905 (org-flag-heading nil)
13906 (when siblings-p (org-show-siblings)))))))
13908 (defvar org-reveal-start-hook nil
13909 "Hook run before revealing a location.")
13911 (defun org-reveal (&optional siblings)
13912 "Show current entry, hierarchy above it, and the following headline.
13913 This can be used to show a consistent set of context around locations
13914 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13915 not t for the search context.
13917 With optional argument SIBLINGS, on each level of the hierarchy all
13918 siblings are shown. This repairs the tree structure to what it would
13919 look like when opened with hierarchical calls to `org-cycle'.
13920 With double optional argument \\[universal-argument] \\[universal-argument], \
13921 go to the parent and show the
13922 entire tree."
13923 (interactive "P")
13924 (run-hooks 'org-reveal-start-hook)
13925 (let ((org-show-hierarchy-above t)
13926 (org-show-following-heading t)
13927 (org-show-siblings (if siblings t org-show-siblings)))
13928 (org-show-context nil))
13929 (when (equal siblings '(16))
13930 (save-excursion
13931 (when (org-up-heading-safe)
13932 (org-show-subtree)
13933 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13935 (defun org-highlight-new-match (beg end)
13936 "Highlight from BEG to END and mark the highlight is an occur headline."
13937 (let ((ov (make-overlay beg end)))
13938 (overlay-put ov 'face 'secondary-selection)
13939 (overlay-put ov 'org-type 'org-occur)
13940 (push ov org-occur-highlights)))
13942 (defun org-remove-occur-highlights (&optional beg end noremove)
13943 "Remove the occur highlights from the buffer.
13944 BEG and END are ignored. If NOREMOVE is nil, remove this function
13945 from the `before-change-functions' in the current buffer."
13946 (interactive)
13947 (unless org-inhibit-highlight-removal
13948 (mapc 'delete-overlay org-occur-highlights)
13949 (setq org-occur-highlights nil)
13950 (setq org-occur-parameters nil)
13951 (unless noremove
13952 (remove-hook 'before-change-functions
13953 'org-remove-occur-highlights 'local))))
13955 ;;;; Priorities
13957 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13958 "Regular expression matching the priority indicator.")
13960 (defvar org-remove-priority-next-time nil)
13962 (defun org-priority-up ()
13963 "Increase the priority of the current item."
13964 (interactive)
13965 (org-priority 'up))
13967 (defun org-priority-down ()
13968 "Decrease the priority of the current item."
13969 (interactive)
13970 (org-priority 'down))
13972 (defun org-priority (&optional action show)
13973 "Change the priority of an item.
13974 ACTION can be `set', `up', `down', or a character."
13975 (interactive "P")
13976 (if (equal action '(4))
13977 (org-show-priority)
13978 (unless org-enable-priority-commands
13979 (user-error "Priority commands are disabled"))
13980 (setq action (or action 'set))
13981 (let (current new news have remove)
13982 (save-excursion
13983 (org-back-to-heading t)
13984 (if (looking-at org-priority-regexp)
13985 (setq current (string-to-char (match-string 2))
13986 have t))
13987 (cond
13988 ((eq action 'remove)
13989 (setq remove t new ?\ ))
13990 ((or (eq action 'set)
13991 (if (featurep 'xemacs) (characterp action) (integerp action)))
13992 (if (not (eq action 'set))
13993 (setq new action)
13994 (message "Priority %c-%c, SPC to remove: "
13995 org-highest-priority org-lowest-priority)
13996 (save-match-data
13997 (setq new (read-char-exclusive))))
13998 (if (and (= (upcase org-highest-priority) org-highest-priority)
13999 (= (upcase org-lowest-priority) org-lowest-priority))
14000 (setq new (upcase new)))
14001 (cond ((equal new ?\ ) (setq remove t))
14002 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14003 (user-error "Priority must be between `%c' and `%c'"
14004 org-highest-priority org-lowest-priority))))
14005 ((eq action 'up)
14006 (setq new (if have
14007 (1- current) ; normal cycling
14008 ;; last priority was empty
14009 (if (eq last-command this-command)
14010 org-lowest-priority ; wrap around empty to lowest
14011 ;; default
14012 (if org-priority-start-cycle-with-default
14013 org-default-priority
14014 (1- org-default-priority))))))
14015 ((eq action 'down)
14016 (setq new (if have
14017 (1+ current) ; normal cycling
14018 ;; last priority was empty
14019 (if (eq last-command this-command)
14020 org-highest-priority ; wrap around empty to highest
14021 ;; default
14022 (if org-priority-start-cycle-with-default
14023 org-default-priority
14024 (1+ org-default-priority))))))
14025 (t (user-error "Invalid action")))
14026 (if (or (< (upcase new) org-highest-priority)
14027 (> (upcase new) org-lowest-priority))
14028 (if (and (memq action '(up down))
14029 (not have) (not (eq last-command this-command)))
14030 ;; `new' is from default priority
14031 (error
14032 "The default can not be set, see `org-default-priority' why")
14033 ;; normal cycling: `new' is beyond highest/lowest priority
14034 ;; and is wrapped around to the empty priority
14035 (setq remove t)))
14036 (setq news (format "%c" new))
14037 (if have
14038 (if remove
14039 (replace-match "" t t nil 1)
14040 (replace-match news t t nil 2))
14041 (if remove
14042 (user-error "No priority cookie found in line")
14043 (let ((case-fold-search nil))
14044 (looking-at org-todo-line-regexp))
14045 (if (match-end 2)
14046 (progn
14047 (goto-char (match-end 2))
14048 (insert " [#" news "]"))
14049 (goto-char (match-beginning 3))
14050 (insert "[#" news "] "))))
14051 (org-set-tags nil 'align))
14052 (if remove
14053 (message "Priority removed")
14054 (message "Priority of current item set to %s" news)))))
14056 (defun org-show-priority ()
14057 "Show the priority of the current item.
14058 This priority is composed of the main priority given with the [#A] cookies,
14059 and by additional input from the age of a schedules or deadline entry."
14060 (interactive)
14061 (let ((pri (if (eq major-mode 'org-agenda-mode)
14062 (org-get-at-bol 'priority)
14063 (save-excursion
14064 (save-match-data
14065 (beginning-of-line)
14066 (and (looking-at org-heading-regexp)
14067 (org-get-priority (match-string 0))))))))
14068 (message "Priority is %d" (if pri pri -1000))))
14070 (defun org-get-priority (s)
14071 "Find priority cookie and return priority."
14072 (save-match-data
14073 (if (functionp org-get-priority-function)
14074 (funcall org-get-priority-function)
14075 (if (not (string-match org-priority-regexp s))
14076 (* 1000 (- org-lowest-priority org-default-priority))
14077 (* 1000 (- org-lowest-priority
14078 (string-to-char (match-string 2 s))))))))
14080 ;;;; Tags
14082 (defvar org-agenda-archives-mode)
14083 (defvar org-map-continue-from nil
14084 "Position from where mapping should continue.
14085 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14087 (defvar org-scanner-tags nil
14088 "The current tag list while the tags scanner is running.")
14089 (defvar org-trust-scanner-tags nil
14090 "Should `org-get-tags-at' use the tags for the scanner.
14091 This is for internal dynamical scoping only.
14092 When this is non-nil, the function `org-get-tags-at' will return the value
14093 of `org-scanner-tags' instead of building the list by itself. This
14094 can lead to large speed-ups when the tags scanner is used in a file with
14095 many entries, and when the list of tags is retrieved, for example to
14096 obtain a list of properties. Building the tags list for each entry in such
14097 a file becomes an N^2 operation - but with this variable set, it scales
14098 as N.")
14100 (defun org-scan-tags (action matcher todo-only &optional start-level)
14101 "Scan headline tags with inheritance and produce output ACTION.
14103 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14104 or `agenda' to produce an entry list for an agenda view. It can also be
14105 a Lisp form or a function that should be called at each matched headline, in
14106 this case the return value is a list of all return values from these calls.
14108 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
14109 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
14110 only lines with a not-done TODO keyword are included in the output.
14111 This should be the same variable that was scoped into
14112 and set by `org-make-tags-matcher' when it constructed MATCHER.
14114 START-LEVEL can be a string with asterisks, reducing the scope to
14115 headlines matching this string."
14116 (require 'org-agenda)
14117 (let* ((re (concat "^"
14118 (if start-level
14119 ;; Get the correct level to match
14120 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14121 org-outline-regexp)
14122 " *\\(\\<\\("
14123 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14124 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14125 (props (list 'face 'default
14126 'done-face 'org-agenda-done
14127 'undone-face 'default
14128 'mouse-face 'highlight
14129 'org-not-done-regexp org-not-done-regexp
14130 'org-todo-regexp org-todo-regexp
14131 'org-complex-heading-regexp org-complex-heading-regexp
14132 'help-echo
14133 (format "mouse-2 or RET jump to org file %s"
14134 (abbreviate-file-name
14135 (or (buffer-file-name (buffer-base-buffer))
14136 (buffer-name (buffer-base-buffer)))))))
14137 (org-map-continue-from nil)
14138 lspos tags tags-list
14139 (tags-alist (list (cons 0 org-file-tags)))
14140 (llast 0) rtn rtn1 level category i txt
14141 todo marker entry priority)
14142 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
14143 (setq action (list 'lambda nil action)))
14144 (save-excursion
14145 (goto-char (point-min))
14146 (when (eq action 'sparse-tree)
14147 (org-overview)
14148 (org-remove-occur-highlights))
14149 (while (let (case-fold-search)
14150 (re-search-forward re nil t))
14151 (setq org-map-continue-from nil)
14152 (catch :skip
14153 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
14154 tags (if (match-end 4) (org-match-string-no-properties 4)))
14155 (goto-char (setq lspos (match-beginning 0)))
14156 (setq level (org-reduced-level (org-outline-level))
14157 category (org-get-category))
14158 (setq i llast llast level)
14159 ;; remove tag lists from same and sublevels
14160 (while (>= i level)
14161 (when (setq entry (assoc i tags-alist))
14162 (setq tags-alist (delete entry tags-alist)))
14163 (setq i (1- i)))
14164 ;; add the next tags
14165 (when tags
14166 (setq tags (org-split-string tags ":")
14167 tags-alist
14168 (cons (cons level tags) tags-alist)))
14169 ;; compile tags for current headline
14170 (setq tags-list
14171 (if org-use-tag-inheritance
14172 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14173 tags)
14174 org-scanner-tags tags-list)
14175 (when org-use-tag-inheritance
14176 (setcdr (car tags-alist)
14177 (mapcar (lambda (x)
14178 (setq x (copy-sequence x))
14179 (org-add-prop-inherited x))
14180 (cdar tags-alist))))
14181 (when (and tags org-use-tag-inheritance
14182 (or (not (eq t org-use-tag-inheritance))
14183 org-tags-exclude-from-inheritance))
14184 ;; selective inheritance, remove uninherited ones
14185 (setcdr (car tags-alist)
14186 (org-remove-uninherited-tags (cdar tags-alist))))
14187 (when (and
14189 ;; eval matcher only when the todo condition is OK
14190 (and (or (not todo-only) (member todo org-not-done-keywords))
14191 (let ((case-fold-search t) (org-trust-scanner-tags t))
14192 (eval matcher)))
14194 ;; Call the skipper, but return t if it does not skip,
14195 ;; so that the `and' form continues evaluating
14196 (progn
14197 (unless (eq action 'sparse-tree) (org-agenda-skip))
14200 ;; Check if timestamps are deselecting this entry
14201 (or (not todo-only)
14202 (and (member todo org-not-done-keywords)
14203 (or (not org-agenda-tags-todo-honor-ignore-options)
14204 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14206 ;; select this headline
14207 (cond
14208 ((eq action 'sparse-tree)
14209 (and org-highlight-sparse-tree-matches
14210 (org-get-heading) (match-end 0)
14211 (org-highlight-new-match
14212 (match-beginning 1) (match-end 1)))
14213 (org-show-context 'tags-tree))
14214 ((eq action 'agenda)
14215 (setq txt (org-agenda-format-item
14217 (concat
14218 (if (eq org-tags-match-list-sublevels 'indented)
14219 (make-string (1- level) ?.) "")
14220 (org-get-heading))
14221 level category
14222 tags-list)
14223 priority (org-get-priority txt))
14224 (goto-char lspos)
14225 (setq marker (org-agenda-new-marker))
14226 (org-add-props txt props
14227 'org-marker marker 'org-hd-marker marker 'org-category category
14228 'todo-state todo
14229 'priority priority 'type "tagsmatch")
14230 (push txt rtn))
14231 ((functionp action)
14232 (setq org-map-continue-from nil)
14233 (save-excursion
14234 (setq rtn1 (funcall action))
14235 (push rtn1 rtn)))
14236 (t (user-error "Invalid action")))
14238 ;; if we are to skip sublevels, jump to end of subtree
14239 (unless org-tags-match-list-sublevels
14240 (org-end-of-subtree t)
14241 (backward-char 1))))
14242 ;; Get the correct position from where to continue
14243 (if org-map-continue-from
14244 (goto-char org-map-continue-from)
14245 (and (= (point) lspos) (end-of-line 1)))))
14246 (when (and (eq action 'sparse-tree)
14247 (not org-sparse-tree-open-archived-trees))
14248 (org-hide-archived-subtrees (point-min) (point-max)))
14249 (nreverse rtn)))
14251 (defun org-remove-uninherited-tags (tags)
14252 "Remove all tags that are not inherited from the list TAGS."
14253 (cond
14254 ((eq org-use-tag-inheritance t)
14255 (if org-tags-exclude-from-inheritance
14256 (org-delete-all org-tags-exclude-from-inheritance tags)
14257 tags))
14258 ((not org-use-tag-inheritance) nil)
14259 ((stringp org-use-tag-inheritance)
14260 (delq nil (mapcar
14261 (lambda (x)
14262 (if (and (string-match org-use-tag-inheritance x)
14263 (not (member x org-tags-exclude-from-inheritance)))
14264 x nil))
14265 tags)))
14266 ((listp org-use-tag-inheritance)
14267 (delq nil (mapcar
14268 (lambda (x)
14269 (if (member x org-use-tag-inheritance) x nil))
14270 tags)))))
14272 (defun org-match-sparse-tree (&optional todo-only match)
14273 "Create a sparse tree according to tags string MATCH.
14274 MATCH can contain positive and negative selection of tags, like
14275 \"+WORK+URGENT-WITHBOSS\".
14276 If optional argument TODO-ONLY is non-nil, only select lines that are
14277 also TODO lines."
14278 (interactive "P")
14279 (org-agenda-prepare-buffers (list (current-buffer)))
14280 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14282 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14284 (defvar org-cached-props nil)
14285 (defun org-cached-entry-get (pom property)
14286 (if (or (eq t org-use-property-inheritance)
14287 (and (stringp org-use-property-inheritance)
14288 (string-match org-use-property-inheritance property))
14289 (and (listp org-use-property-inheritance)
14290 (member property org-use-property-inheritance)))
14291 ;; Caching is not possible, check it directly
14292 (org-entry-get pom property 'inherit)
14293 ;; Get all properties, so that we can do complicated checks easily
14294 (cdr (assoc property (or org-cached-props
14295 (setq org-cached-props
14296 (org-entry-properties pom)))))))
14298 (defun org-global-tags-completion-table (&optional files)
14299 "Return the list of all tags in all agenda buffer/files.
14300 Optional FILES argument is a list of files which can be used
14301 instead of the agenda files."
14302 (save-excursion
14303 (org-uniquify
14304 (delq nil
14305 (apply 'append
14306 (mapcar
14307 (lambda (file)
14308 (set-buffer (find-file-noselect file))
14309 (append (org-get-buffer-tags)
14310 (mapcar (lambda (x) (if (stringp (car-safe x))
14311 (list (car-safe x)) nil))
14312 org-tag-alist)))
14313 (if (and files (car files))
14314 files
14315 (org-agenda-files))))))))
14317 (defun org-make-tags-matcher (match)
14318 "Create the TAGS/TODO matcher form for the selection string MATCH.
14320 The variable `todo-only' is scoped dynamically into this function.
14321 It will be set to t if the matcher restricts matching to TODO entries,
14322 otherwise will not be touched.
14324 Returns a cons of the selection string MATCH and the constructed
14325 lisp form implementing the matcher. The matcher is to be evaluated
14326 at an Org entry, with point on the headline, and returns t if the
14327 entry matches the selection string MATCH. The returned lisp form
14328 references two variables with information about the entry, which
14329 must be bound around the form's evaluation: todo, the TODO keyword
14330 at the entry (or nil of none); and tags-list, the list of all tags
14331 at the entry including inherited ones. Additionally, the category
14332 of the entry (if any) must be specified as the text property
14333 'org-category on the headline.
14335 See also `org-scan-tags'.
14337 (declare (special todo-only))
14338 (unless (boundp 'todo-only)
14339 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14340 (unless match
14341 ;; Get a new match request, with completion against the global
14342 ;; tags table and the local tags in current buffer
14343 (let ((org-last-tags-completion-table
14344 (org-uniquify
14345 (delq nil (append (org-get-buffer-tags)
14346 (org-global-tags-completion-table))))))
14347 (setq match (org-completing-read-no-i
14348 "Match: " 'org-tags-completion-function nil nil nil
14349 'org-tags-history))))
14351 ;; Parse the string and create a lisp form
14352 (let ((match0 match)
14353 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14354 minus tag mm
14355 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14356 orterms term orlist re-p str-p level-p level-op time-p
14357 prop-p pn pv po gv rest (start 0) (ss 0))
14358 ;; Expand group tags
14359 (setq match (org-tags-expand match))
14361 ;; Check if there is a TODO part of this match, which would be the
14362 ;; part after a "/". TO make sure that this slash is not part of
14363 ;; a property value to be matched against, we also check that there
14364 ;; is no " after that slash.
14365 ;; First, find the last slash
14366 (while (string-match "/+" match ss)
14367 (setq start (match-beginning 0) ss (match-end 0)))
14368 (if (and (string-match "/+" match start)
14369 (not (save-match-data (string-match "\"" match start))))
14370 ;; match contains also a todo-matching request
14371 (progn
14372 (setq tagsmatch (substring match 0 (match-beginning 0))
14373 todomatch (substring match (match-end 0)))
14374 (if (string-match "^!" todomatch)
14375 (setq todo-only t todomatch (substring todomatch 1)))
14376 (if (string-match "^\\s-*$" todomatch)
14377 (setq todomatch nil)))
14378 ;; only matching tags
14379 (setq tagsmatch match todomatch nil))
14381 ;; Make the tags matcher
14382 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14383 (setq tagsmatcher t)
14384 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14385 (while (setq term (pop orterms))
14386 (while (and (equal (substring term -1) "\\") orterms)
14387 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14388 (while (string-match re term)
14389 (setq rest (substring term (match-end 0))
14390 minus (and (match-end 1)
14391 (equal (match-string 1 term) "-"))
14392 tag (save-match-data (replace-regexp-in-string
14393 "\\\\-" "-"
14394 (match-string 2 term)))
14395 re-p (equal (string-to-char tag) ?{)
14396 level-p (match-end 4)
14397 prop-p (match-end 5)
14398 mm (cond
14399 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14400 (level-p
14401 (setq level-op (org-op-to-function (match-string 3 term)))
14402 `(,level-op level ,(string-to-number
14403 (match-string 4 term))))
14404 (prop-p
14405 (setq pn (match-string 5 term)
14406 po (match-string 6 term)
14407 pv (match-string 7 term)
14408 re-p (equal (string-to-char pv) ?{)
14409 str-p (equal (string-to-char pv) ?\")
14410 time-p (save-match-data
14411 (string-match "^\"[[<].*[]>]\"$" pv))
14412 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14413 (if time-p (setq pv (org-matcher-time pv)))
14414 (setq po (org-op-to-function po (if time-p 'time str-p)))
14415 (cond
14416 ((equal pn "CATEGORY")
14417 (setq gv '(get-text-property (point) 'org-category)))
14418 ((equal pn "TODO")
14419 (setq gv 'todo))
14421 (setq gv `(org-cached-entry-get nil ,pn))))
14422 (if re-p
14423 (if (eq po 'org<>)
14424 `(not (string-match ,pv (or ,gv "")))
14425 `(string-match ,pv (or ,gv "")))
14426 (if str-p
14427 `(,po (or ,gv "") ,pv)
14428 `(,po (string-to-number (or ,gv ""))
14429 ,(string-to-number pv) ))))
14430 (t `(member ,tag tags-list)))
14431 mm (if minus (list 'not mm) mm)
14432 term rest)
14433 (push mm tagsmatcher))
14434 (push (if (> (length tagsmatcher) 1)
14435 (cons 'and tagsmatcher)
14436 (car tagsmatcher))
14437 orlist)
14438 (setq tagsmatcher nil))
14439 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14440 (setq tagsmatcher
14441 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14442 ;; Make the todo matcher
14443 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14444 (setq todomatcher t)
14445 (setq orterms (org-split-string todomatch "|") orlist nil)
14446 (while (setq term (pop orterms))
14447 (while (string-match re term)
14448 (setq minus (and (match-end 1)
14449 (equal (match-string 1 term) "-"))
14450 kwd (match-string 2 term)
14451 re-p (equal (string-to-char kwd) ?{)
14452 term (substring term (match-end 0))
14453 mm (if re-p
14454 `(string-match ,(substring kwd 1 -1) todo)
14455 (list 'equal 'todo kwd))
14456 mm (if minus (list 'not mm) mm))
14457 (push mm todomatcher))
14458 (push (if (> (length todomatcher) 1)
14459 (cons 'and todomatcher)
14460 (car todomatcher))
14461 orlist)
14462 (setq todomatcher nil))
14463 (setq todomatcher (if (> (length orlist) 1)
14464 (cons 'or orlist) (car orlist))))
14466 ;; Return the string and lisp forms of the matcher
14467 (setq matcher (if todomatcher
14468 (list 'and tagsmatcher todomatcher)
14469 tagsmatcher))
14470 (when todo-only
14471 (setq matcher (list 'and '(member todo org-not-done-keywords)
14472 matcher)))
14473 (cons match0 matcher)))
14475 (defun org-tags-expand (match &optional single-as-list downcased)
14476 "Expand group tags in MATCH.
14478 This replaces every group tag in MATCH with a regexp tag search.
14479 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14480 will be replaced like this:
14482 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14483 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14484 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14486 Replacing by a regexp preserves the structure of the match.
14487 E.g., this expansion
14489 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14491 will match anything tagged with \"Lab\" and \"Home\", or tagged
14492 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14494 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14495 assumed to be a single group tag, and the function will return
14496 the list of tags in this group.
14498 When DOWNCASE is non-nil, expand downcased TAGS."
14499 (if org-group-tags
14500 (let* ((case-fold-search t)
14501 (stable org-mode-syntax-table)
14502 (tal (or org-tag-groups-alist-for-agenda
14503 org-tag-groups-alist))
14504 (tal (if downcased
14505 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14506 (tml (mapcar 'car tal))
14507 (rtnmatch match) rpl)
14508 ;; @ and _ are allowed as word-components in tags
14509 (modify-syntax-entry ?@ "w" stable)
14510 (modify-syntax-entry ?_ "w" stable)
14511 (while (and tml
14512 (with-syntax-table stable
14513 (string-match
14514 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14515 (regexp-opt tml) "\\>\\)") rtnmatch)))
14516 (let* ((dir (match-string 1 rtnmatch))
14517 (tag (match-string 2 rtnmatch))
14518 (tag (if downcased (downcase tag) tag)))
14519 (setq tml (delete tag tml))
14520 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14521 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14522 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14523 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14524 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14525 (if single-as-list
14526 (or (reverse rpl) (list rtnmatch))
14527 rtnmatch))
14528 (if single-as-list (list (if downcased (downcase match) match))
14529 match)))
14531 (defun org-op-to-function (op &optional stringp)
14532 "Turn an operator into the appropriate function."
14533 (setq op
14534 (cond
14535 ((equal op "<" ) '(< string< org-time<))
14536 ((equal op ">" ) '(> org-string> org-time>))
14537 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14538 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14539 ((member op '("=" "==")) '(= string= org-time=))
14540 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14541 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14543 (defun org<> (a b) (not (= a b)))
14544 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14545 (defun org-string>= (a b) (not (string< a b)))
14546 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14547 (defun org-string<> (a b) (not (string= a b)))
14548 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14549 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14550 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14551 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14552 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14553 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14554 (defun org-2ft (s)
14555 "Convert S to a floating point time.
14556 If S is already a number, just return it. If it is a string, parse
14557 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14558 (cond
14559 ((numberp s) s)
14560 ((stringp s)
14561 (condition-case nil
14562 (float-time (apply 'encode-time (org-parse-time-string s)))
14563 (error 0.)))
14564 (t 0.)))
14566 (defun org-time-today ()
14567 "Time in seconds today at 0:00.
14568 Returns the float number of seconds since the beginning of the
14569 epoch to the beginning of today (00:00)."
14570 (float-time (apply 'encode-time
14571 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14573 (defun org-matcher-time (s)
14574 "Interpret a time comparison value."
14575 (save-match-data
14576 (cond
14577 ((string= s "<now>") (float-time))
14578 ((string= s "<today>") (org-time-today))
14579 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14580 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14581 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14582 (+ (org-time-today)
14583 (* (string-to-number (match-string 1 s))
14584 (cdr (assoc (match-string 2 s)
14585 '(("d" . 86400.0) ("w" . 604800.0)
14586 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14587 (t (org-2ft s)))))
14589 (defun org-match-any-p (re list)
14590 "Does re match any element of list?"
14591 (setq list (mapcar (lambda (x) (string-match re x)) list))
14592 (delq nil list))
14594 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14595 (defvar org-tags-overlay (make-overlay 1 1))
14596 (org-detach-overlay org-tags-overlay)
14598 (defun org-get-local-tags-at (&optional pos)
14599 "Get a list of tags defined in the current headline."
14600 (org-get-tags-at pos 'local))
14602 (defun org-get-local-tags ()
14603 "Get a list of tags defined in the current headline."
14604 (org-get-tags-at nil 'local))
14606 (defun org-get-tags-at (&optional pos local)
14607 "Get a list of all headline tags applicable at POS.
14608 POS defaults to point. If tags are inherited, the list contains
14609 the targets in the same sequence as the headlines appear, i.e.
14610 the tags of the current headline come last.
14611 When LOCAL is non-nil, only return tags from the current headline,
14612 ignore inherited ones."
14613 (interactive)
14614 (if (and org-trust-scanner-tags
14615 (or (not pos) (equal pos (point)))
14616 (not local))
14617 org-scanner-tags
14618 (let (tags ltags lastpos parent)
14619 (save-excursion
14620 (save-restriction
14621 (widen)
14622 (goto-char (or pos (point)))
14623 (save-match-data
14624 (catch 'done
14625 (condition-case nil
14626 (progn
14627 (org-back-to-heading t)
14628 (while (not (equal lastpos (point)))
14629 (setq lastpos (point))
14630 (when (looking-at
14631 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14632 (setq ltags (org-split-string
14633 (org-match-string-no-properties 1) ":"))
14634 (when parent
14635 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14636 (setq tags (append
14637 (if parent
14638 (org-remove-uninherited-tags ltags)
14639 ltags)
14640 tags)))
14641 (or org-use-tag-inheritance (throw 'done t))
14642 (if local (throw 'done t))
14643 (or (org-up-heading-safe) (error nil))
14644 (setq parent t)))
14645 (error nil)))))
14646 (if local
14647 tags
14648 (reverse (delete-dups
14649 (reverse (append
14650 (org-remove-uninherited-tags
14651 org-file-tags) tags)))))))))
14653 (defun org-add-prop-inherited (s)
14654 (add-text-properties 0 (length s) '(inherited t) s)
14657 (defun org-toggle-tag (tag &optional onoff)
14658 "Toggle the tag TAG for the current line.
14659 If ONOFF is `on' or `off', don't toggle but set to this state."
14660 (let (res current)
14661 (save-excursion
14662 (org-back-to-heading t)
14663 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14664 (point-at-eol) t)
14665 (progn
14666 (setq current (match-string 1))
14667 (replace-match ""))
14668 (setq current ""))
14669 (setq current (nreverse (org-split-string current ":")))
14670 (cond
14671 ((eq onoff 'on)
14672 (setq res t)
14673 (or (member tag current) (push tag current)))
14674 ((eq onoff 'off)
14675 (or (not (member tag current)) (setq current (delete tag current))))
14676 (t (if (member tag current)
14677 (setq current (delete tag current))
14678 (setq res t)
14679 (push tag current))))
14680 (end-of-line 1)
14681 (if current
14682 (progn
14683 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14684 (org-set-tags nil t))
14685 (delete-horizontal-space))
14686 (run-hooks 'org-after-tags-change-hook))
14687 res))
14689 (defun org-align-tags-here (to-col)
14690 ;; Assumes that this is a headline
14691 "Align tags on the current headline to TO-COL."
14692 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14693 (beginning-of-line 1)
14694 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14695 (< pos (match-beginning 2)))
14696 (progn
14697 (setq tags-l (- (match-end 2) (match-beginning 2)))
14698 (goto-char (match-beginning 1))
14699 (insert " ")
14700 (delete-region (point) (1+ (match-beginning 2)))
14701 (setq ncol (max (current-column)
14702 (1+ col)
14703 (if (> to-col 0)
14704 to-col
14705 (- (abs to-col) tags-l))))
14706 (setq p (point))
14707 (insert (make-string (- ncol (current-column)) ?\ ))
14708 (setq ncol (current-column))
14709 (when indent-tabs-mode (tabify p (point-at-eol)))
14710 (org-move-to-column (min ncol col)))
14711 (goto-char pos))))
14713 (defun org-set-tags-command (&optional arg just-align)
14714 "Call the set-tags command for the current entry."
14715 (interactive "P")
14716 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14717 (org-set-tags arg just-align)
14718 (save-excursion
14719 (unless (and (org-region-active-p)
14720 org-loop-over-headlines-in-active-region)
14721 (org-back-to-heading t))
14722 (org-set-tags arg just-align))))
14724 (defun org-set-tags-to (data)
14725 "Set the tags of the current entry to DATA, replacing the current tags.
14726 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14727 If DATA is nil or the empty string, any tags will be removed."
14728 (interactive "sTags: ")
14729 (setq data
14730 (cond
14731 ((eq data nil) "")
14732 ((equal data "") "")
14733 ((stringp data)
14734 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14735 ":"))
14736 ((listp data)
14737 (concat ":" (mapconcat 'identity data ":") ":"))))
14738 (when data
14739 (save-excursion
14740 (org-back-to-heading t)
14741 (when (looking-at org-complex-heading-regexp)
14742 (if (match-end 5)
14743 (progn
14744 (goto-char (match-beginning 5))
14745 (insert data)
14746 (delete-region (point) (point-at-eol))
14747 (org-set-tags nil 'align))
14748 (goto-char (point-at-eol))
14749 (insert " " data)
14750 (org-set-tags nil 'align)))
14751 (beginning-of-line 1)
14752 (if (looking-at ".*?\\([ \t]+\\)$")
14753 (delete-region (match-beginning 1) (match-end 1))))))
14755 (defun org-align-all-tags ()
14756 "Align the tags i all headings."
14757 (interactive)
14758 (save-excursion
14759 (or (ignore-errors (org-back-to-heading t))
14760 (outline-next-heading))
14761 (if (org-at-heading-p)
14762 (org-set-tags t)
14763 (message "No headings"))))
14765 (defvar org-indent-indentation-per-level)
14766 (defun org-set-tags (&optional arg just-align)
14767 "Set the tags for the current headline.
14768 With prefix ARG, realign all tags in headings in the current buffer.
14769 When JUST-ALIGN is non-nil, only align tags."
14770 (interactive "P")
14771 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14772 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14773 'region-start-level 'region))
14774 org-loop-over-headlines-in-active-region)
14775 (org-map-entries
14776 ;; We don't use ARG and JUST-ALIGN here because these args
14777 ;; are not useful when looping over headlines.
14778 `(org-set-tags)
14779 org-loop-over-headlines-in-active-region
14780 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14781 (let* ((re org-outline-regexp-bol)
14782 (current (unless arg (org-get-tags-string)))
14783 (col (current-column))
14784 (org-setting-tags t)
14785 table current-tags inherited-tags ; computed below when needed
14786 tags p0 c0 c1 rpl di tc level)
14787 (if arg
14788 (save-excursion
14789 (goto-char (point-min))
14790 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14791 (while (re-search-forward re nil t)
14792 (org-set-tags nil t)
14793 (end-of-line 1)))
14794 (message "All tags realigned to column %d" org-tags-column))
14795 (if just-align
14796 (setq tags current)
14797 ;; Get a new set of tags from the user
14798 (save-excursion
14799 (setq table (append org-tag-persistent-alist
14800 (or org-tag-alist (org-get-buffer-tags))
14801 (and
14802 org-complete-tags-always-offer-all-agenda-tags
14803 (org-global-tags-completion-table
14804 (org-agenda-files))))
14805 org-last-tags-completion-table table
14806 current-tags (org-split-string current ":")
14807 inherited-tags (nreverse
14808 (nthcdr (length current-tags)
14809 (nreverse (org-get-tags-at))))
14810 tags
14811 (if (or (eq t org-use-fast-tag-selection)
14812 (and org-use-fast-tag-selection
14813 (delq nil (mapcar 'cdr table))))
14814 (org-fast-tag-selection
14815 current-tags inherited-tags table
14816 (if org-fast-tag-selection-include-todo
14817 org-todo-key-alist))
14818 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14819 (org-trim
14820 (org-icompleting-read "Tags: "
14821 'org-tags-completion-function
14822 nil nil current 'org-tags-history))))))
14823 (while (string-match "[-+&]+" tags)
14824 ;; No boolean logic, just a list
14825 (setq tags (replace-match ":" t t tags))))
14827 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14829 (if org-tags-sort-function
14830 (setq tags (mapconcat 'identity
14831 (sort (org-split-string
14832 tags (org-re "[^[:alnum:]_@#%]+"))
14833 org-tags-sort-function) ":")))
14835 (if (string-match "\\`[\t ]*\\'" tags)
14836 (setq tags "")
14837 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14838 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14840 ;; Insert new tags at the correct column
14841 (beginning-of-line 1)
14842 (setq level (or (and (looking-at org-outline-regexp)
14843 (- (match-end 0) (point) 1))
14845 (cond
14846 ((and (equal current "") (equal tags "")))
14847 ((re-search-forward
14848 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14849 (point-at-eol) t)
14850 (if (equal tags "")
14851 (setq rpl "")
14852 (goto-char (match-beginning 0))
14853 (setq c0 (current-column)
14854 ;; compute offset for the case of org-indent-mode active
14855 di (if (org-bound-and-true-p org-indent-mode)
14856 (* (1- org-indent-indentation-per-level) (1- level))
14858 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14859 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14860 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (string-width tags))))
14861 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14862 (replace-match rpl t t)
14863 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14864 tags)
14865 (t (error "Tags alignment failed")))
14866 (org-move-to-column col)
14867 (unless just-align
14868 (run-hooks 'org-after-tags-change-hook))))))
14870 (defun org-change-tag-in-region (beg end tag off)
14871 "Add or remove TAG for each entry in the region.
14872 This works in the agenda, and also in an org-mode buffer."
14873 (interactive
14874 (list (region-beginning) (region-end)
14875 (let ((org-last-tags-completion-table
14876 (if (derived-mode-p 'org-mode)
14877 (org-uniquify
14878 (delq nil (append (org-get-buffer-tags)
14879 (org-global-tags-completion-table))))
14880 (org-global-tags-completion-table))))
14881 (org-icompleting-read
14882 "Tag: " 'org-tags-completion-function nil nil nil
14883 'org-tags-history))
14884 (progn
14885 (message "[s]et or [r]emove? ")
14886 (equal (read-char-exclusive) ?r))))
14887 (if (fboundp 'deactivate-mark) (deactivate-mark))
14888 (let ((agendap (equal major-mode 'org-agenda-mode))
14889 l1 l2 m buf pos newhead (cnt 0))
14890 (goto-char end)
14891 (setq l2 (1- (org-current-line)))
14892 (goto-char beg)
14893 (setq l1 (org-current-line))
14894 (loop for l from l1 to l2 do
14895 (org-goto-line l)
14896 (setq m (get-text-property (point) 'org-hd-marker))
14897 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14898 (and agendap m))
14899 (setq buf (if agendap (marker-buffer m) (current-buffer))
14900 pos (if agendap m (point)))
14901 (with-current-buffer buf
14902 (save-excursion
14903 (save-restriction
14904 (goto-char pos)
14905 (setq cnt (1+ cnt))
14906 (org-toggle-tag tag (if off 'off 'on))
14907 (setq newhead (org-get-heading)))))
14908 (and agendap (org-agenda-change-all-lines newhead m))))
14909 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14911 (defun org-tags-completion-function (string predicate &optional flag)
14912 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14913 (confirm (lambda (x) (stringp (car x)))))
14914 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14915 (setq s1 (match-string 1 string)
14916 s2 (match-string 2 string))
14917 (setq s1 "" s2 string))
14918 (cond
14919 ((eq flag nil)
14920 ;; try completion
14921 (setq rtn (try-completion s2 ctable confirm))
14922 (if (stringp rtn)
14923 (setq rtn
14924 (concat s1 s2 (substring rtn (length s2))
14925 (if (and org-add-colon-after-tag-completion
14926 (assoc rtn ctable))
14927 ":" ""))))
14928 rtn)
14929 ((eq flag t)
14930 ;; all-completions
14931 (all-completions s2 ctable confirm))
14932 ((eq flag 'lambda)
14933 ;; exact match?
14934 (assoc s2 ctable)))))
14936 (defun org-fast-tag-insert (kwd tags face &optional end)
14937 "Insert KDW, and the TAGS, the latter with face FACE.
14938 Also insert END."
14939 (insert (format "%-12s" (concat kwd ":"))
14940 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14941 (or end "")))
14943 (defun org-fast-tag-show-exit (flag)
14944 (save-excursion
14945 (org-goto-line 3)
14946 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14947 (replace-match ""))
14948 (when flag
14949 (end-of-line 1)
14950 (org-move-to-column (- (window-width) 19) t)
14951 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14953 (defun org-set-current-tags-overlay (current prefix)
14954 "Add an overlay to CURRENT tag with PREFIX."
14955 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14956 (if (featurep 'xemacs)
14957 (org-overlay-display org-tags-overlay (concat prefix s)
14958 'secondary-selection)
14959 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14960 (org-overlay-display org-tags-overlay (concat prefix s)))))
14962 (defvar org-last-tag-selection-key nil)
14963 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14964 "Fast tag selection with single keys.
14965 CURRENT is the current list of tags in the headline, INHERITED is the
14966 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14967 possibly with grouping information. TODO-TABLE is a similar table with
14968 TODO keywords, should these have keys assigned to them.
14969 If the keys are nil, a-z are automatically assigned.
14970 Returns the new tags string, or nil to not change the current settings."
14971 (let* ((fulltable (append table todo-table))
14972 (maxlen (apply 'max (mapcar
14973 (lambda (x)
14974 (if (stringp (car x)) (string-width (car x)) 0))
14975 fulltable)))
14976 (buf (current-buffer))
14977 (expert (eq org-fast-tag-selection-single-key 'expert))
14978 (buffer-tags nil)
14979 (fwidth (+ maxlen 3 1 3))
14980 (ncol (/ (- (window-width) 4) fwidth))
14981 (i-face 'org-done)
14982 (c-face 'org-todo)
14983 tg cnt e c char c1 c2 ntable tbl rtn
14984 ov-start ov-end ov-prefix
14985 (exit-after-next org-fast-tag-selection-single-key)
14986 (done-keywords org-done-keywords)
14987 groups ingroup)
14988 (save-excursion
14989 (beginning-of-line 1)
14990 (if (looking-at
14991 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14992 (setq ov-start (match-beginning 1)
14993 ov-end (match-end 1)
14994 ov-prefix "")
14995 (setq ov-start (1- (point-at-eol))
14996 ov-end (1+ ov-start))
14997 (skip-chars-forward "^\n\r")
14998 (setq ov-prefix
14999 (concat
15000 (buffer-substring (1- (point)) (point))
15001 (if (> (current-column) org-tags-column)
15003 (make-string (- org-tags-column (current-column)) ?\ ))))))
15004 (move-overlay org-tags-overlay ov-start ov-end)
15005 (save-window-excursion
15006 (if expert
15007 (set-buffer (get-buffer-create " *Org tags*"))
15008 (delete-other-windows)
15009 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15010 (org-switch-to-buffer-other-window " *Org tags*"))
15011 (erase-buffer)
15012 (org-set-local 'org-done-keywords done-keywords)
15013 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15014 (org-fast-tag-insert "Current" current c-face "\n\n")
15015 (org-fast-tag-show-exit exit-after-next)
15016 (org-set-current-tags-overlay current ov-prefix)
15017 (setq tbl fulltable char ?a cnt 0)
15018 (while (setq e (pop tbl))
15019 (cond
15020 ((equal (car e) :startgroup)
15021 (push '() groups) (setq ingroup t)
15022 (when (not (= cnt 0))
15023 (setq cnt 0)
15024 (insert "\n"))
15025 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15026 ((equal (car e) :endgroup)
15027 (setq ingroup nil cnt 0)
15028 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15029 ((equal e '(:newline))
15030 (when (not (= cnt 0))
15031 (setq cnt 0)
15032 (insert "\n")
15033 (setq e (car tbl))
15034 (while (equal (car tbl) '(:newline))
15035 (insert "\n")
15036 (setq tbl (cdr tbl)))))
15037 ((equal e '(:grouptags)) nil)
15039 (setq tg (copy-sequence (car e)) c2 nil)
15040 (if (cdr e)
15041 (setq c (cdr e))
15042 ;; automatically assign a character.
15043 (setq c1 (string-to-char
15044 (downcase (substring
15045 tg (if (= (string-to-char tg) ?@) 1 0)))))
15046 (if (or (rassoc c1 ntable) (rassoc c1 table))
15047 (while (or (rassoc char ntable) (rassoc char table))
15048 (setq char (1+ char)))
15049 (setq c2 c1))
15050 (setq c (or c2 char)))
15051 (if ingroup (push tg (car groups)))
15052 (setq tg (org-add-props tg nil 'face
15053 (cond
15054 ((not (assoc tg table))
15055 (org-get-todo-face tg))
15056 ((member tg current) c-face)
15057 ((member tg inherited) i-face))))
15058 (if (equal (caar tbl) :grouptags)
15059 (org-add-props tg nil 'face 'org-tag-group))
15060 (if (and (= cnt 0) (not ingroup)) (insert " "))
15061 (insert "[" c "] " tg (make-string
15062 (- fwidth 4 (length tg)) ?\ ))
15063 (push (cons tg c) ntable)
15064 (when (= (setq cnt (1+ cnt)) ncol)
15065 (insert "\n")
15066 (if ingroup (insert " "))
15067 (setq cnt 0)))))
15068 (setq ntable (nreverse ntable))
15069 (insert "\n")
15070 (goto-char (point-min))
15071 (if (not expert) (org-fit-window-to-buffer))
15072 (setq rtn
15073 (catch 'exit
15074 (while t
15075 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15076 (if (not groups) "no " "")
15077 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15078 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15079 (setq org-last-tag-selection-key c)
15080 (cond
15081 ((= c ?\r) (throw 'exit t))
15082 ((= c ?!)
15083 (setq groups (not groups))
15084 (goto-char (point-min))
15085 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15086 ((= c ?\C-c)
15087 (if (not expert)
15088 (org-fast-tag-show-exit
15089 (setq exit-after-next (not exit-after-next)))
15090 (setq expert nil)
15091 (delete-other-windows)
15092 (set-window-buffer (split-window-vertically) " *Org tags*")
15093 (org-switch-to-buffer-other-window " *Org tags*")
15094 (org-fit-window-to-buffer)))
15095 ((or (= c ?\C-g)
15096 (and (= c ?q) (not (rassoc c ntable))))
15097 (org-detach-overlay org-tags-overlay)
15098 (setq quit-flag t))
15099 ((= c ?\ )
15100 (setq current nil)
15101 (if exit-after-next (setq exit-after-next 'now)))
15102 ((= c ?\t)
15103 (condition-case nil
15104 (setq tg (org-icompleting-read
15105 "Tag: "
15106 (or buffer-tags
15107 (with-current-buffer buf
15108 (org-get-buffer-tags)))))
15109 (quit (setq tg "")))
15110 (when (string-match "\\S-" tg)
15111 (add-to-list 'buffer-tags (list tg))
15112 (if (member tg current)
15113 (setq current (delete tg current))
15114 (push tg current)))
15115 (if exit-after-next (setq exit-after-next 'now)))
15116 ((setq e (rassoc c todo-table) tg (car e))
15117 (with-current-buffer buf
15118 (save-excursion (org-todo tg)))
15119 (if exit-after-next (setq exit-after-next 'now)))
15120 ((setq e (rassoc c ntable) tg (car e))
15121 (if (member tg current)
15122 (setq current (delete tg current))
15123 (loop for g in groups do
15124 (if (member tg g)
15125 (mapc (lambda (x)
15126 (setq current (delete x current)))
15127 g)))
15128 (push tg current))
15129 (if exit-after-next (setq exit-after-next 'now))))
15131 ;; Create a sorted list
15132 (setq current
15133 (sort current
15134 (lambda (a b)
15135 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15136 (if (eq exit-after-next 'now) (throw 'exit t))
15137 (goto-char (point-min))
15138 (beginning-of-line 2)
15139 (delete-region (point) (point-at-eol))
15140 (org-fast-tag-insert "Current" current c-face)
15141 (org-set-current-tags-overlay current ov-prefix)
15142 (while (re-search-forward
15143 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15144 (setq tg (match-string 1))
15145 (add-text-properties
15146 (match-beginning 1) (match-end 1)
15147 (list 'face
15148 (cond
15149 ((member tg current) c-face)
15150 ((member tg inherited) i-face)
15151 (t (get-text-property (match-beginning 1) 'face))))))
15152 (goto-char (point-min)))))
15153 (org-detach-overlay org-tags-overlay)
15154 (if rtn
15155 (mapconcat 'identity current ":")
15156 nil))))
15158 (defun org-get-tags-string ()
15159 "Get the TAGS string in the current headline."
15160 (unless (org-at-heading-p t)
15161 (user-error "Not on a heading"))
15162 (save-excursion
15163 (beginning-of-line 1)
15164 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15165 (org-match-string-no-properties 1)
15166 "")))
15168 (defun org-get-tags ()
15169 "Get the list of tags specified in the current headline."
15170 (org-split-string (org-get-tags-string) ":"))
15172 (defun org-get-buffer-tags ()
15173 "Get a table of all tags used in the buffer, for completion."
15174 (let (tags)
15175 (save-excursion
15176 (goto-char (point-min))
15177 (while (re-search-forward
15178 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
15179 (when (equal (char-after (point-at-bol 0)) ?*)
15180 (mapc (lambda (x) (add-to-list 'tags x))
15181 (org-split-string (org-match-string-no-properties 1) ":")))))
15182 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
15183 (mapcar 'list tags)))
15185 ;;;; The mapping API
15187 (defun org-map-entries (func &optional match scope &rest skip)
15188 "Call FUNC at each headline selected by MATCH in SCOPE.
15190 FUNC is a function or a lisp form. The function will be called without
15191 arguments, with the cursor positioned at the beginning of the headline.
15192 The return values of all calls to the function will be collected and
15193 returned as a list.
15195 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15196 does not need to preserve point. After evaluation, the cursor will be
15197 moved to the end of the line (presumably of the headline of the
15198 processed entry) and search continues from there. Under some
15199 circumstances, this may not produce the wanted results. For example,
15200 if you have removed (e.g. archived) the current (sub)tree it could
15201 mean that the next entry will be skipped entirely. In such cases, you
15202 can specify the position from where search should continue by making
15203 FUNC set the variable `org-map-continue-from' to the desired buffer
15204 position.
15206 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15207 Only headlines that are matched by this query will be considered during
15208 the iteration. When MATCH is nil or t, all headlines will be
15209 visited by the iteration.
15211 SCOPE determines the scope of this command. It can be any of:
15213 nil The current buffer, respecting the restriction if any
15214 tree The subtree started with the entry at point
15215 region The entries within the active region, if any
15216 region-start-level
15217 The entries within the active region, but only those at
15218 the same level than the first one.
15219 file The current buffer, without restriction
15220 file-with-archives
15221 The current buffer, and any archives associated with it
15222 agenda All agenda files
15223 agenda-with-archives
15224 All agenda files with any archive files associated with them
15225 \(file1 file2 ...)
15226 If this is a list, all files in the list will be scanned
15228 The remaining args are treated as settings for the skipping facilities of
15229 the scanner. The following items can be given here:
15231 archive skip trees with the archive tag
15232 comment skip trees with the COMMENT keyword
15233 function or Emacs Lisp form:
15234 will be used as value for `org-agenda-skip-function', so
15235 whenever the function returns a position, FUNC will not be
15236 called for that entry and search will continue from the
15237 position returned
15239 If your function needs to retrieve the tags including inherited tags
15240 at the *current* entry, you can use the value of the variable
15241 `org-scanner-tags' which will be much faster than getting the value
15242 with `org-get-tags-at'. If your function gets properties with
15243 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15244 to t around the call to `org-entry-properties' to get the same speedup.
15245 Note that if your function moves around to retrieve tags and properties at
15246 a *different* entry, you cannot use these techniques."
15247 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15248 (not (org-region-active-p)))
15249 (let* ((org-agenda-archives-mode nil) ; just to make sure
15250 (org-agenda-skip-archived-trees (memq 'archive skip))
15251 (org-agenda-skip-comment-trees (memq 'comment skip))
15252 (org-agenda-skip-function
15253 (car (org-delete-all '(comment archive) skip)))
15254 (org-tags-match-list-sublevels t)
15255 (start-level (eq scope 'region-start-level))
15256 matcher file res
15257 org-todo-keywords-for-agenda
15258 org-done-keywords-for-agenda
15259 org-todo-keyword-alist-for-agenda
15260 org-tag-alist-for-agenda
15261 todo-only)
15263 (cond
15264 ((eq match t) (setq matcher t))
15265 ((eq match nil) (setq matcher t))
15266 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15268 (save-excursion
15269 (save-restriction
15270 (cond ((eq scope 'tree)
15271 (org-back-to-heading t)
15272 (org-narrow-to-subtree)
15273 (setq scope nil))
15274 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15275 (org-region-active-p))
15276 ;; If needed, set start-level to a string like "2"
15277 (when start-level
15278 (save-excursion
15279 (goto-char (region-beginning))
15280 (unless (org-at-heading-p) (outline-next-heading))
15281 (setq start-level (org-current-level))))
15282 (narrow-to-region (region-beginning)
15283 (save-excursion
15284 (goto-char (region-end))
15285 (unless (and (bolp) (org-at-heading-p))
15286 (outline-next-heading))
15287 (point)))
15288 (setq scope nil)))
15290 (if (not scope)
15291 (progn
15292 (org-agenda-prepare-buffers
15293 (list (buffer-file-name (current-buffer))))
15294 (setq res (org-scan-tags func matcher todo-only start-level)))
15295 ;; Get the right scope
15296 (cond
15297 ((and scope (listp scope) (symbolp (car scope)))
15298 (setq scope (eval scope)))
15299 ((eq scope 'agenda)
15300 (setq scope (org-agenda-files t)))
15301 ((eq scope 'agenda-with-archives)
15302 (setq scope (org-agenda-files t))
15303 (setq scope (org-add-archive-files scope)))
15304 ((eq scope 'file)
15305 (setq scope (list (buffer-file-name))))
15306 ((eq scope 'file-with-archives)
15307 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15308 (org-agenda-prepare-buffers scope)
15309 (while (setq file (pop scope))
15310 (with-current-buffer (org-find-base-buffer-visiting file)
15311 (save-excursion
15312 (save-restriction
15313 (widen)
15314 (goto-char (point-min))
15315 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15316 res)))
15318 ;;;; Properties
15320 ;;; Setting and retrieving properties
15322 (defconst org-special-properties
15323 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15324 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15325 "The special properties valid in Org-mode.
15327 These are properties that are not defined in the property drawer,
15328 but in some other way.")
15330 (defconst org-default-properties
15331 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15332 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15333 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15334 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15335 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15336 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15337 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15338 "Some properties that are used by Org-mode for various purposes.
15339 Being in this list makes sure that they are offered for completion.")
15341 (defun org-property-action ()
15342 "Do an action on properties."
15343 (interactive)
15344 (let (c)
15345 (org-at-property-p)
15346 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15347 (setq c (read-char-exclusive))
15348 (cond
15349 ((equal c ?s)
15350 (call-interactively 'org-set-property))
15351 ((equal c ?d)
15352 (call-interactively 'org-delete-property))
15353 ((equal c ?D)
15354 (call-interactively 'org-delete-property-globally))
15355 ((equal c ?c)
15356 (call-interactively 'org-compute-property-at-point))
15357 (t (user-error "No such property action %c" c)))))
15359 (defun org-inc-effort ()
15360 "Increment the value of the effort property in the current entry."
15361 (interactive)
15362 (org-set-effort nil t))
15364 (defvar org-clock-effort) ;; Defined in org-clock.el
15365 (defvar org-clock-current-task) ;; Defined in org-clock.el
15366 (defun org-set-effort (&optional value increment)
15367 "Set the effort property of the current entry.
15368 With numerical prefix arg, use the nth allowed value, 0 stands for the
15369 10th allowed value.
15371 When INCREMENT is non-nil, set the property to the next allowed value."
15372 (interactive "P")
15373 (if (equal value 0) (setq value 10))
15374 (let* ((completion-ignore-case t)
15375 (prop org-effort-property)
15376 (cur (org-entry-get nil prop))
15377 (allowed (org-property-get-allowed-values nil prop 'table))
15378 (existing (mapcar 'list (org-property-values prop)))
15379 (heading (nth 4 (org-heading-components)))
15381 (val (cond
15382 ((stringp value) value)
15383 ((and allowed (integerp value))
15384 (or (car (nth (1- value) allowed))
15385 (car (org-last allowed))))
15386 ((and allowed increment)
15387 (or (caadr (member (list cur) allowed))
15388 (user-error "Allowed effort values are not set")))
15389 (allowed
15390 (message "Select 1-9,0, [RET%s]: %s"
15391 (if cur (concat "=" cur) "")
15392 (mapconcat 'car allowed " "))
15393 (setq rpl (read-char-exclusive))
15394 (if (equal rpl ?\r)
15396 (setq rpl (- rpl ?0))
15397 (if (equal rpl 0) (setq rpl 10))
15398 (if (and (> rpl 0) (<= rpl (length allowed)))
15399 (car (nth (1- rpl) allowed))
15400 (org-completing-read "Effort: " allowed nil))))
15402 (let (org-completion-use-ido org-completion-use-iswitchb)
15403 (org-completing-read
15404 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15405 (concat "[" cur "]") "")
15406 ": ")
15407 existing nil nil "" nil cur))))))
15408 (unless (equal (org-entry-get nil prop) val)
15409 (org-entry-put nil prop val))
15410 (org-refresh-property
15411 '((effort . identity)
15412 (effort-minutes . org-duration-string-to-minutes))
15413 val)
15414 (when (string= heading org-clock-current-task)
15415 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15416 (org-clock-update-mode-line))
15417 (message "%s is now %s" prop val)))
15419 (defun org-at-property-p ()
15420 "Non-nil when point is inside a property drawer.
15421 See `org-property-re' for match data, if applicable."
15422 (when (eq (org-element-type (org-element-at-point)) 'node-property)
15423 (save-excursion
15424 (beginning-of-line)
15425 (looking-at org-property-re))))
15427 (defun org-get-property-block (&optional beg end force)
15428 "Return the (beg . end) range of the body of the property drawer.
15429 BEG and END are the beginning and end of the current subtree, or of
15430 the part before the first headline. If they are not given, they will
15431 be found. If the drawer does not exist and FORCE is non-nil, create
15432 the drawer."
15433 (catch 'exit
15434 (save-excursion
15435 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15436 (progn (org-back-to-heading t) (point))))
15437 (end (or end (and (not (outline-next-heading)) (point-max))
15438 (point))))
15439 (goto-char beg)
15440 (if (re-search-forward org-property-start-re end t)
15441 (setq beg (1+ (match-end 0)))
15442 (if force
15443 (save-excursion
15444 (org-insert-property-drawer)
15445 (setq end (progn (outline-next-heading) (point))))
15446 (throw 'exit nil))
15447 (goto-char beg)
15448 (if (re-search-forward org-property-start-re end t)
15449 (setq beg (1+ (match-end 0)))))
15450 (if (re-search-forward org-property-end-re end t)
15451 (setq end (match-beginning 0))
15452 (or force (throw 'exit nil))
15453 (goto-char beg)
15454 (setq end beg)
15455 (org-indent-line)
15456 (insert ":END:\n"))
15457 (cons beg end)))))
15459 (defun org-entry-properties (&optional pom which specific)
15460 "Get all properties of the entry at point-or-marker POM.
15461 This includes the TODO keyword, the tags, time strings for deadline,
15462 scheduled, and clocking, and any additional properties defined in the
15463 entry. The return value is an alist, keys may occur multiple times
15464 if the property key was used several times.
15465 POM may also be nil, in which case the current entry is used.
15466 If WHICH is nil or `all', get all properties. If WHICH is
15467 `special' or `standard', only get that subclass. If WHICH
15468 is a string only get exactly this property. SPECIFIC can be a string, the
15469 specific property we are interested in. Specifying it can speed
15470 things up because then unnecessary parsing is avoided."
15471 (setq which (or which 'all))
15472 (org-with-wide-buffer
15473 (org-with-point-at pom
15474 (let ((clockstr (substring org-clock-string 0 -1))
15475 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15476 (case-fold-search nil)
15477 beg end range props sum-props key key1 value string clocksum clocksumt)
15478 (when (and (derived-mode-p 'org-mode)
15479 (ignore-errors (org-back-to-heading t)))
15480 (setq beg (point))
15481 (setq sum-props (get-text-property (point) 'org-summaries))
15482 (setq clocksum (get-text-property (point) :org-clock-minutes)
15483 clocksumt (get-text-property (point) :org-clock-minutes-today))
15484 (outline-next-heading)
15485 (setq end (point))
15486 (when (memq which '(all special))
15487 ;; Get the special properties, like TODO and tags
15488 (goto-char beg)
15489 (when (and (or (not specific) (string= specific "TODO"))
15490 (looking-at org-todo-line-regexp) (match-end 2))
15491 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15492 (when (and (or (not specific) (string= specific "PRIORITY"))
15493 (looking-at org-priority-regexp))
15494 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15495 (when (or (not specific) (string= specific "FILE"))
15496 (push (cons "FILE" buffer-file-name) props))
15497 (when (and (or (not specific) (string= specific "TAGS"))
15498 (setq value (org-get-tags-string))
15499 (string-match "\\S-" value))
15500 (push (cons "TAGS" value) props))
15501 (when (and (or (not specific) (string= specific "ALLTAGS"))
15502 (setq value (org-get-tags-at)))
15503 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15504 ":"))
15505 props))
15506 (when (or (not specific) (string= specific "BLOCKED"))
15507 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15508 (when (or (not specific)
15509 (member specific
15510 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15511 "TIMESTAMP" "TIMESTAMP_IA")))
15512 (catch 'match
15513 (while (and (re-search-forward org-maybe-keyword-time-regexp end t)
15514 (not (text-property-any 0 (length (match-string 0))
15515 'face 'font-lock-comment-face
15516 (match-string 0))))
15517 (setq key (if (match-end 1)
15518 (substring (org-match-string-no-properties 1)
15519 0 -1))
15520 string (if (equal key clockstr)
15521 (org-trim
15522 (buffer-substring-no-properties
15523 (match-beginning 3) (goto-char
15524 (point-at-eol))))
15525 (substring (org-match-string-no-properties 3)
15526 1 -1)))
15527 ;; Get the correct property name from the key. This is
15528 ;; necessary if the user has configured time keywords.
15529 (setq key1 (concat key ":"))
15530 (cond
15531 ((not key)
15532 (setq key
15533 (if (= (char-after (match-beginning 3)) ?\[)
15534 "TIMESTAMP_IA" "TIMESTAMP")))
15535 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15536 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15537 ((equal key1 org-closed-string) (setq key "CLOSED"))
15538 ((equal key1 org-clock-string) (setq key "CLOCK")))
15539 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15540 (progn
15541 (push (cons key string) props)
15542 ;; no need to search further if match is found
15543 (throw 'match t))
15544 (when (or (equal key "CLOCK") (not (assoc key props)))
15545 (push (cons key string) props)))))))
15547 (when (memq which '(all standard))
15548 ;; Get the standard properties, like :PROP: ...
15549 (setq range (org-get-property-block beg end))
15550 (when range
15551 (goto-char (car range))
15552 (while (re-search-forward org-property-re
15553 (cdr range) t)
15554 (setq key (org-match-string-no-properties 2)
15555 value (org-trim (or (org-match-string-no-properties 3) "")))
15556 (unless (member key excluded)
15557 (push (cons key (or value "")) props)))))
15558 (if clocksum
15559 (push (cons "CLOCKSUM"
15560 (org-columns-number-to-string (/ (float clocksum) 60.)
15561 'add_times))
15562 props))
15563 (if clocksumt
15564 (push (cons "CLOCKSUM_T"
15565 (org-columns-number-to-string (/ (float clocksumt) 60.)
15566 'add_times))
15567 props))
15568 (unless (assoc "CATEGORY" props)
15569 (push (cons "CATEGORY" (org-get-category)) props))
15570 (append sum-props (nreverse props)))))))
15572 (defun org-entry-get (pom property &optional inherit literal-nil)
15573 "Get value of PROPERTY for entry or content at point-or-marker POM.
15574 If INHERIT is non-nil and the entry does not have the property,
15575 then also check higher levels of the hierarchy.
15576 If INHERIT is the symbol `selective', use inheritance only if the setting
15577 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15578 If the property is present but empty, the return value is the empty string.
15579 If the property is not present at all, nil is returned.
15581 Return the value as a string.
15583 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15584 do not interpret it as the list atom nil. This is used for inheritance
15585 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15586 (org-with-point-at pom
15587 (if (and inherit (if (eq inherit 'selective)
15588 (org-property-inherit-p property)
15590 (org-entry-get-with-inheritance property literal-nil)
15591 (if (member property org-special-properties)
15592 ;; We need a special property. Use `org-entry-properties'
15593 ;; to retrieve it, but specify the wanted property
15594 (cdr (assoc property (org-entry-properties nil 'special property)))
15595 (org-with-wide-buffer
15596 (let ((range (org-get-property-block)))
15597 (when (and range (not (eq (car range) (cdr range)))
15598 (save-excursion
15599 (goto-char (car range))
15600 (re-search-forward
15601 (concat (org-re-property property) "\\|"
15602 (org-re-property (concat property "+")))
15603 (cdr range) t)))
15604 (let* ((props
15605 (list (or (assoc property org-file-properties)
15606 (assoc property org-global-properties)
15607 (assoc property org-global-properties-fixed))))
15608 (ap (lambda (key)
15609 (when (re-search-forward
15610 (org-re-property key) (cdr range) t)
15611 (setq props
15612 (org-update-property-plist
15614 (if (match-end 3)
15615 (org-match-string-no-properties 3) "")
15616 props)))))
15617 val)
15618 (goto-char (car range))
15619 (funcall ap property)
15620 (goto-char (car range))
15621 (while (funcall ap (concat property "+")))
15622 (setq val (cdr (assoc property props)))
15623 (when val (if literal-nil val (org-not-nil val)))))))))))
15625 (defun org-property-or-variable-value (var &optional inherit)
15626 "Check if there is a property fixing the value of VAR.
15627 If yes, return this value. If not, return the current value of the variable."
15628 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15629 (if (and prop (stringp prop) (string-match "\\S-" prop))
15630 (read prop)
15631 (symbol-value var))))
15633 (defun org-entry-delete (pom property)
15634 "Delete the property PROPERTY from entry at point-or-marker POM."
15635 (unless (member property org-special-properties)
15636 (org-with-point-at pom
15637 (let ((range (org-get-property-block)))
15638 (if (and range
15639 (goto-char (car range))
15640 (re-search-forward
15641 (org-re-property property nil t)
15642 (cdr range) t))
15643 (progn
15644 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15645 (org-remove-empty-drawer-at (car range))
15647 nil)))))
15649 ;; Multi-values properties are properties that contain multiple values
15650 ;; These values are assumed to be single words, separated by whitespace.
15651 (defun org-entry-add-to-multivalued-property (pom property value)
15652 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15653 (let* ((old (org-entry-get pom property))
15654 (values (and old (org-split-string old "[ \t]"))))
15655 (setq value (org-entry-protect-space value))
15656 (unless (member value values)
15657 (setq values (append values (list value)))
15658 (org-entry-put pom property
15659 (mapconcat 'identity values " ")))))
15661 (defun org-entry-remove-from-multivalued-property (pom property value)
15662 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15663 (let* ((old (org-entry-get pom property))
15664 (values (and old (org-split-string old "[ \t]"))))
15665 (setq value (org-entry-protect-space value))
15666 (when (member value values)
15667 (setq values (delete value values))
15668 (org-entry-put pom property
15669 (mapconcat 'identity values " ")))))
15671 (defun org-entry-member-in-multivalued-property (pom property value)
15672 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15673 (let* ((old (org-entry-get pom property))
15674 (values (and old (org-split-string old "[ \t]"))))
15675 (setq value (org-entry-protect-space value))
15676 (member value values)))
15678 (defun org-entry-get-multivalued-property (pom property)
15679 "Return a list of values in a multivalued property."
15680 (let* ((value (org-entry-get pom property))
15681 (values (and value (org-split-string value "[ \t]"))))
15682 (mapcar 'org-entry-restore-space values)))
15684 (defun org-entry-put-multivalued-property (pom property &rest values)
15685 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15686 VALUES should be a list of strings. Spaces will be protected."
15687 (org-entry-put pom property
15688 (mapconcat 'org-entry-protect-space values " "))
15689 (let* ((value (org-entry-get pom property))
15690 (values (and value (org-split-string value "[ \t]"))))
15691 (mapcar 'org-entry-restore-space values)))
15693 (defun org-entry-protect-space (s)
15694 "Protect spaces and newline in string S."
15695 (while (string-match " " s)
15696 (setq s (replace-match "%20" t t s)))
15697 (while (string-match "\n" s)
15698 (setq s (replace-match "%0A" t t s)))
15701 (defun org-entry-restore-space (s)
15702 "Restore spaces and newline in string S."
15703 (while (string-match "%20" s)
15704 (setq s (replace-match " " t t s)))
15705 (while (string-match "%0A" s)
15706 (setq s (replace-match "\n" t t s)))
15709 (defvar org-entry-property-inherited-from (make-marker)
15710 "Marker pointing to the entry from where a property was inherited.
15711 Each call to `org-entry-get-with-inheritance' will set this marker to the
15712 location of the entry where the inheritance search matched. If there was
15713 no match, the marker will point nowhere.
15714 Note that also `org-entry-get' calls this function, if the INHERIT flag
15715 is set.")
15717 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15718 "Get PROPERTY of entry or content at point, search higher levels if needed.
15719 The search will stop at the first ancestor which has the property defined.
15720 If the value found is \"nil\", return nil to show that the property
15721 should be considered as undefined (this is the meaning of nil here).
15722 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15723 (move-marker org-entry-property-inherited-from nil)
15724 (let (tmp)
15725 (save-excursion
15726 (save-restriction
15727 (widen)
15728 (catch 'ex
15729 (while t
15730 (when (setq tmp (org-entry-get nil property nil literal-nil))
15731 (or (ignore-errors (org-back-to-heading t))
15732 (goto-char (point-min)))
15733 (move-marker org-entry-property-inherited-from (point))
15734 (throw 'ex tmp))
15735 (or (ignore-errors (org-up-heading-safe))
15736 (throw 'ex nil))))))
15737 (setq tmp (or tmp
15738 (cdr (assoc property org-file-properties))
15739 (cdr (assoc property org-global-properties))
15740 (cdr (assoc property org-global-properties-fixed))))
15741 (if literal-nil tmp (org-not-nil tmp))))
15743 (defvar org-property-changed-functions nil
15744 "Hook called when the value of a property has changed.
15745 Each hook function should accept two arguments, the name of the property
15746 and the new value.")
15748 (defun org-entry-put (pom property value)
15749 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15750 If the value is `nil', it is converted to the empty string.
15751 If it is not a string, an error is raised."
15752 (cond ((null value) (setq value ""))
15753 ((not (stringp value))
15754 (error "Properties values should be strings.")))
15755 (org-with-point-at pom
15756 (org-back-to-heading t)
15757 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15758 range)
15759 (cond
15760 ((equal property "TODO")
15761 (when (and (string-match "\\S-" value)
15762 (not (member value org-todo-keywords-1)))
15763 (user-error "\"%s\" is not a valid TODO state" value))
15764 (if (or (not value)
15765 (not (string-match "\\S-" value)))
15766 (setq value 'none))
15767 (org-todo value)
15768 (org-set-tags nil 'align))
15769 ((equal property "PRIORITY")
15770 (org-priority (if (and value (string-match "\\S-" value))
15771 (string-to-char value) ?\ ))
15772 (org-set-tags nil 'align))
15773 ((equal property "CLOCKSUM")
15774 (if (not (re-search-forward
15775 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15776 (error "Cannot find a clock log")
15777 (goto-char (- (match-end 1) 2))
15778 (cond
15779 ((eq value 'earlier) (org-timestamp-down))
15780 ((eq value 'later) (org-timestamp-up)))
15781 (org-clock-sum-current-item)))
15782 ((equal property "SCHEDULED")
15783 (if (re-search-forward org-scheduled-time-regexp end t)
15784 (cond
15785 ((eq value 'earlier) (org-timestamp-change -1 'day))
15786 ((eq value 'later) (org-timestamp-change 1 'day))
15787 (t (call-interactively 'org-schedule)))
15788 (call-interactively 'org-schedule)))
15789 ((equal property "DEADLINE")
15790 (if (re-search-forward org-deadline-time-regexp end t)
15791 (cond
15792 ((eq value 'earlier) (org-timestamp-change -1 'day))
15793 ((eq value 'later) (org-timestamp-change 1 'day))
15794 (t (call-interactively 'org-deadline)))
15795 (call-interactively 'org-deadline)))
15796 ((member property org-special-properties)
15797 (error "The %s property can not yet be set with `org-entry-put'"
15798 property))
15799 (t ; a non-special property
15800 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15801 (setq range (org-get-property-block beg end 'force))
15802 (goto-char (car range))
15803 (if (re-search-forward
15804 (org-re-property property nil t) (cdr range) t)
15805 (progn
15806 (delete-region (match-beginning 0) (match-end 0))
15807 (goto-char (match-beginning 0)))
15808 (goto-char (cdr range))
15809 (insert "\n")
15810 (backward-char 1)
15811 (org-indent-line))
15812 (insert ":" property ":")
15813 (and value (insert " " value))
15814 (org-indent-line)))))
15815 (run-hook-with-args 'org-property-changed-functions property value)))
15817 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15818 "Get all property keys in the current buffer.
15819 With INCLUDE-SPECIALS, also list the special properties that reflect things
15820 like tags and TODO state.
15821 With INCLUDE-DEFAULTS, also include properties that has special meaning
15822 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15823 and others.
15824 With INCLUDE-COLUMNS, also include property names given in COLUMN
15825 formats in the current buffer."
15826 (let (rtn range cfmt s p)
15827 (save-excursion
15828 (save-restriction
15829 (widen)
15830 (goto-char (point-min))
15831 (while (re-search-forward org-property-start-re nil t)
15832 (catch 'cont
15833 (setq range (or (org-get-property-block)
15834 (if (y-or-n-p
15835 (format "Malformed drawer at %d, repair?" (point)))
15836 (org-get-property-block nil nil t)
15837 (throw 'cont nil))))
15838 (goto-char (car range))
15839 (while (re-search-forward org-property-re
15840 (cdr range) t)
15841 (add-to-list 'rtn (org-match-string-no-properties 2)))
15842 (outline-next-heading)))))
15844 (when include-specials
15845 (setq rtn (append org-special-properties rtn)))
15847 (when include-defaults
15848 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15849 (add-to-list 'rtn org-effort-property))
15851 (when include-columns
15852 (save-excursion
15853 (save-restriction
15854 (widen)
15855 (goto-char (point-min))
15856 (while (re-search-forward
15857 "^[ \t]*\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15858 nil t)
15859 (setq cfmt (match-string 2) s 0)
15860 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15861 cfmt s)
15862 (setq s (match-end 0)
15863 p (match-string 1 cfmt))
15864 (unless (or (equal p "ITEM")
15865 (member p org-special-properties))
15866 (add-to-list 'rtn (match-string 1 cfmt))))))))
15868 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15870 (defun org-property-values (key)
15871 "Return a list of all values of property KEY in the current buffer."
15872 (save-excursion
15873 (save-restriction
15874 (widen)
15875 (goto-char (point-min))
15876 (let ((re (org-re-property key))
15877 values)
15878 (while (re-search-forward re nil t)
15879 (add-to-list 'values (org-trim (match-string 3))))
15880 (delete "" values)))))
15882 (defun org-insert-property-drawer ()
15883 "Insert a property drawer into the current entry."
15884 (org-back-to-heading t)
15885 (looking-at org-outline-regexp)
15886 (let ((indent (if org-adapt-indentation
15887 (- (match-end 0) (match-beginning 0))
15889 (beg (point))
15890 (re (concat "^[ \t]*" org-keyword-time-regexp))
15891 (org-clock-re (format "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|%s\\|:END:\\)"
15892 org-clock-string))
15893 (org-skip-line-list (list org-clock-string ":END:"))
15894 end hiddenp)
15895 (outline-next-heading)
15896 (setq end (point))
15897 (goto-char beg)
15898 (while (re-search-forward re end t))
15899 (setq hiddenp (outline-invisible-p))
15900 (end-of-line 1)
15901 (and (equal (char-after) ?\n) (forward-char 1))
15902 (while (looking-at org-clock-re)
15903 (if (member (match-string 1) org-skip-line-list)
15904 ;; just skip this line
15905 (beginning-of-line 2)
15906 ;; Drawer start, find the end
15907 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15908 (beginning-of-line 1)))
15909 (org-skip-over-state-notes)
15910 (skip-chars-backward " \t\n\r")
15911 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15912 (forward-char 1))
15913 (goto-char (point-at-eol))
15914 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15915 (beginning-of-line 0)
15916 (org-indent-to-column indent)
15917 (beginning-of-line 2)
15918 (org-indent-to-column indent)
15919 (beginning-of-line 0)
15920 (if hiddenp
15921 (save-excursion
15922 (org-back-to-heading t)
15923 (hide-entry))
15924 (org-flag-drawer t))))
15926 (defun org-insert-drawer (&optional arg drawer)
15927 "Insert a drawer at point.
15929 Optional argument DRAWER, when non-nil, is a string representing
15930 drawer's name. Otherwise, the user is prompted for a name.
15932 If a region is active, insert the drawer around that region
15933 instead.
15935 Point is left between drawer's boundaries."
15936 (interactive "P")
15937 (let* ((drawer (if arg "PROPERTIES"
15938 (or drawer (read-from-minibuffer "Drawer: ")))))
15939 (cond
15940 ;; With C-u, fall back on `org-insert-property-drawer'
15941 (arg (org-insert-property-drawer))
15943 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
15944 (user-error "Invalid drawer name"))
15945 ;; With an active region, insert a drawer at point.
15946 ((not (org-region-active-p))
15947 (progn
15948 (unless (bolp) (insert "\n"))
15949 (insert (format ":%s:\n\n:END:\n" drawer))
15950 (forward-line -2)))
15951 ;; Otherwise, insert the drawer at point
15953 (let ((rbeg (region-beginning))
15954 (rend (copy-marker (region-end))))
15955 (unwind-protect
15956 (progn
15957 (goto-char rbeg)
15958 (beginning-of-line)
15959 (when (save-excursion
15960 (re-search-forward org-outline-regexp-bol rend t))
15961 (user-error "Drawers cannot contain headlines"))
15962 ;; Position point at the beginning of the first
15963 ;; non-blank line in region. Insert drawer's opening
15964 ;; there, then indent it.
15965 (org-skip-whitespace)
15966 (beginning-of-line)
15967 (insert ":" drawer ":\n")
15968 (forward-line -1)
15969 (indent-for-tab-command)
15970 ;; Move point to the beginning of the first blank line
15971 ;; after the last non-blank line in region. Insert
15972 ;; drawer's closing, then indent it.
15973 (goto-char rend)
15974 (skip-chars-backward " \r\t\n")
15975 (insert "\n:END:")
15976 (deactivate-mark t)
15977 (indent-for-tab-command)
15978 (unless (eolp) (insert "\n")))
15979 ;; Clear marker, whatever the outcome of insertion is.
15980 (set-marker rend nil)))))))
15982 (defvar org-property-set-functions-alist nil
15983 "Property set function alist.
15984 Each entry should have the following format:
15986 (PROPERTY . READ-FUNCTION)
15988 The read function will be called with the same argument as
15989 `org-completing-read'.")
15991 (defun org-set-property-function (property)
15992 "Get the function that should be used to set PROPERTY.
15993 This is computed according to `org-property-set-functions-alist'."
15994 (or (cdr (assoc property org-property-set-functions-alist))
15995 'org-completing-read))
15997 (defun org-read-property-value (property)
15998 "Read PROPERTY value from user."
15999 (let* ((completion-ignore-case t)
16000 (allowed (org-property-get-allowed-values nil property 'table))
16001 (cur (org-entry-get nil property))
16002 (prompt (concat property " value"
16003 (if (and cur (string-match "\\S-" cur))
16004 (concat " [" cur "]") "") ": "))
16005 (set-function (org-set-property-function property))
16006 (val (if allowed
16007 (funcall set-function prompt allowed nil
16008 (not (get-text-property 0 'org-unrestricted
16009 (caar allowed))))
16010 (let (org-completion-use-ido org-completion-use-iswitchb)
16011 (funcall set-function prompt
16012 (mapcar 'list (org-property-values property))
16013 nil nil "" nil cur)))))
16014 (org-trim val)))
16016 (defvar org-last-set-property nil)
16017 (defvar org-last-set-property-value nil)
16018 (defun org-read-property-name ()
16019 "Read a property name."
16020 (let* ((completion-ignore-case t)
16021 (keys (org-buffer-property-keys nil t t))
16022 (default-prop (or (save-excursion
16023 (save-match-data
16024 (beginning-of-line)
16025 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
16026 (null (string= (match-string 1) "END"))
16027 (match-string 1))))
16028 org-last-set-property))
16029 (property (org-icompleting-read
16030 (concat "Property"
16031 (if default-prop (concat " [" default-prop "]") "")
16032 ": ")
16033 (mapcar 'list keys)
16034 nil nil nil nil
16035 default-prop)))
16036 (if (member property keys)
16037 property
16038 (or (cdr (assoc (downcase property)
16039 (mapcar (lambda (x) (cons (downcase x) x))
16040 keys)))
16041 property))))
16043 (defun org-set-property-and-value (use-last)
16044 "Allow to set [PROPERTY]: [value] direction from prompt.
16045 When use-default, don't even ask, just use the last
16046 \"[PROPERTY]: [value]\" string from the history."
16047 (interactive "P")
16048 (let* ((completion-ignore-case t)
16049 (pv (or (and use-last org-last-set-property-value)
16050 (org-completing-read
16051 "Enter a \"[Property]: [value]\" pair: "
16052 nil nil nil nil nil
16053 org-last-set-property-value)))
16054 prop val)
16055 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16056 (setq prop (match-string 1 pv)
16057 val (match-string 2 pv))
16058 (org-set-property prop val))))
16060 (defun org-set-property (property value)
16061 "In the current entry, set PROPERTY to VALUE.
16062 When called interactively, this will prompt for a property name, offering
16063 completion on existing and default properties. And then it will prompt
16064 for a value, offering completion either on allowed values (via an inherited
16065 xxx_ALL property) or on existing values in other instances of this property
16066 in the current file."
16067 (interactive (list nil nil))
16068 (let* ((property (or property (org-read-property-name)))
16069 (value (or value (org-read-property-value property)))
16070 (fn (cdr (assoc property org-properties-postprocess-alist))))
16071 (setq org-last-set-property property)
16072 (setq org-last-set-property-value (concat property ": " value))
16073 ;; Possibly postprocess the inserted value:
16074 (when fn (setq value (funcall fn value)))
16075 (unless (equal (org-entry-get nil property) value)
16076 (org-entry-put nil property value))))
16078 (defun org-delete-property (property)
16079 "In the current entry, delete PROPERTY."
16080 (interactive
16081 (let* ((completion-ignore-case t)
16082 (cat (org-entry-get (point) "CATEGORY"))
16083 (props0 (org-entry-properties nil 'standard))
16084 (props (if cat props0
16085 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16086 (prop (if (< 1 (length props))
16087 (org-icompleting-read "Property: " props nil t)
16088 (caar props))))
16089 (list prop)))
16090 (if (not property)
16091 (message "No property to delete in this entry")
16092 (org-entry-delete nil property)
16093 (message "Property \"%s\" deleted" property)))
16095 (defun org-delete-property-globally (property)
16096 "Remove PROPERTY globally, from all entries."
16097 (interactive
16098 (let* ((completion-ignore-case t)
16099 (prop (org-icompleting-read
16100 "Globally remove property: "
16101 (mapcar 'list (org-buffer-property-keys)))))
16102 (list prop)))
16103 (save-excursion
16104 (save-restriction
16105 (widen)
16106 (goto-char (point-min))
16107 (let ((cnt 0))
16108 (while (re-search-forward
16109 (org-re-property property)
16110 nil t)
16111 (setq cnt (1+ cnt))
16112 (delete-region (match-beginning 0) (1+ (point-at-eol))))
16113 (message "Property \"%s\" removed from %d entries" property cnt)))))
16115 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16117 (defun org-compute-property-at-point ()
16118 "Compute the property at point.
16119 This looks for an enclosing column format, extracts the operator and
16120 then applies it to the property in the column format's scope."
16121 (interactive)
16122 (unless (org-at-property-p)
16123 (user-error "Not at a property"))
16124 (let ((prop (org-match-string-no-properties 2)))
16125 (org-columns-get-format-and-top-level)
16126 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16127 (user-error "No operator defined for property %s" prop))
16128 (org-columns-compute prop)))
16130 (defvar org-property-allowed-value-functions nil
16131 "Hook for functions supplying allowed values for a specific property.
16132 The functions must take a single argument, the name of the property, and
16133 return a flat list of allowed values. If \":ETC\" is one of
16134 the values, this means that these values are intended as defaults for
16135 completion, but that other values should be allowed too.
16136 The functions must return nil if they are not responsible for this
16137 property.")
16139 (defun org-property-get-allowed-values (pom property &optional table)
16140 "Get allowed values for the property PROPERTY.
16141 When TABLE is non-nil, return an alist that can directly be used for
16142 completion."
16143 (let (vals)
16144 (cond
16145 ((equal property "TODO")
16146 (setq vals (org-with-point-at pom
16147 (append org-todo-keywords-1 '("")))))
16148 ((equal property "PRIORITY")
16149 (let ((n org-lowest-priority))
16150 (while (>= n org-highest-priority)
16151 (push (char-to-string n) vals)
16152 (setq n (1- n)))))
16153 ((member property org-special-properties))
16154 ((setq vals (run-hook-with-args-until-success
16155 'org-property-allowed-value-functions property)))
16157 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16158 (when (and vals (string-match "\\S-" vals))
16159 (setq vals (car (read-from-string (concat "(" vals ")"))))
16160 (setq vals (mapcar (lambda (x)
16161 (cond ((stringp x) x)
16162 ((numberp x) (number-to-string x))
16163 ((symbolp x) (symbol-name x))
16164 (t "???")))
16165 vals)))))
16166 (when (member ":ETC" vals)
16167 (setq vals (remove ":ETC" vals))
16168 (org-add-props (car vals) '(org-unrestricted t)))
16169 (if table (mapcar 'list vals) vals)))
16171 (defun org-property-previous-allowed-value (&optional previous)
16172 "Switch to the next allowed value for this property."
16173 (interactive)
16174 (org-property-next-allowed-value t))
16176 (defun org-property-next-allowed-value (&optional previous)
16177 "Switch to the next allowed value for this property."
16178 (interactive)
16179 (unless (org-at-property-p)
16180 (user-error "Not at a property"))
16181 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16182 (key (match-string 2))
16183 (value (match-string 3))
16184 (allowed (or (org-property-get-allowed-values (point) key)
16185 (and (member value '("[ ]" "[-]" "[X]"))
16186 '("[ ]" "[X]"))))
16187 (heading (save-match-data (nth 4 (org-heading-components))))
16188 nval)
16189 (unless allowed
16190 (user-error "Allowed values for this property have not been defined"))
16191 (if previous (setq allowed (reverse allowed)))
16192 (if (member value allowed)
16193 (setq nval (car (cdr (member value allowed)))))
16194 (setq nval (or nval (car allowed)))
16195 (if (equal nval value)
16196 (user-error "Only one allowed value for this property"))
16197 (org-at-property-p)
16198 (replace-match (concat " :" key ": " nval) t t)
16199 (org-indent-line)
16200 (beginning-of-line 1)
16201 (skip-chars-forward " \t")
16202 (when (equal prop org-effort-property)
16203 (org-refresh-property
16204 '((effort . identity)
16205 (effort-minutes . org-duration-string-to-minutes))
16206 nval)
16207 (when (string= org-clock-current-task heading)
16208 (setq org-clock-effort nval)
16209 (org-clock-update-mode-line)))
16210 (run-hook-with-args 'org-property-changed-functions key nval)))
16212 (defun org-find-olp (path &optional this-buffer)
16213 "Return a marker pointing to the entry at outline path OLP.
16214 If anything goes wrong, throw an error.
16215 You can wrap this call to catch the error like this:
16217 (condition-case msg
16218 (org-mobile-locate-entry (match-string 4))
16219 (error (nth 1 msg)))
16221 The return value will then be either a string with the error message,
16222 or a marker if everything is OK.
16224 If THIS-BUFFER is set, the outline path does not contain a file,
16225 only headings."
16226 (let* ((file (if this-buffer buffer-file-name (pop path)))
16227 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16228 (level 1)
16229 (lmin 1)
16230 (lmax 1)
16231 limit re end found pos heading cnt flevel)
16232 (unless buffer (error "File not found :%s" file))
16233 (with-current-buffer buffer
16234 (save-excursion
16235 (save-restriction
16236 (widen)
16237 (setq limit (point-max))
16238 (goto-char (point-min))
16239 (while (setq heading (pop path))
16240 (setq re (format org-complex-heading-regexp-format
16241 (regexp-quote heading)))
16242 (setq cnt 0 pos (point))
16243 (while (re-search-forward re end t)
16244 (setq level (- (match-end 1) (match-beginning 1)))
16245 (if (and (>= level lmin) (<= level lmax))
16246 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16247 (when (= cnt 0) (error "Heading not found on level %d: %s"
16248 lmax heading))
16249 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16250 lmax heading))
16251 (goto-char found)
16252 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16253 (setq end (save-excursion (org-end-of-subtree t t))))
16254 (when (org-at-heading-p)
16255 (point-marker)))))))
16257 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16258 "Find node HEADING in BUFFER.
16259 Return a marker to the heading if it was found, or nil if not.
16260 If POS-ONLY is set, return just the position instead of a marker.
16262 The heading text must match exact, but it may have a TODO keyword,
16263 a priority cookie and tags in the standard locations."
16264 (with-current-buffer (or buffer (current-buffer))
16265 (save-excursion
16266 (save-restriction
16267 (widen)
16268 (goto-char (point-min))
16269 (let (case-fold-search)
16270 (if (re-search-forward
16271 (format org-complex-heading-regexp-format
16272 (regexp-quote heading)) nil t)
16273 (if pos-only
16274 (match-beginning 0)
16275 (move-marker (make-marker) (match-beginning 0)))))))))
16277 (defun org-find-exact-heading-in-directory (heading &optional dir)
16278 "Find Org node headline HEADING in all .org files in directory DIR.
16279 When the target headline is found, return a marker to this location."
16280 (let ((files (directory-files (or dir default-directory)
16281 t "\\`[^.#].*\\.org\\'"))
16282 file visiting m buffer)
16283 (catch 'found
16284 (while (setq file (pop files))
16285 (message "trying %s" file)
16286 (setq visiting (org-find-base-buffer-visiting file))
16287 (setq buffer (or visiting (find-file-noselect file)))
16288 (setq m (org-find-exact-headline-in-buffer
16289 heading buffer))
16290 (when (and (not m) (not visiting)) (kill-buffer buffer))
16291 (and m (throw 'found m))))))
16293 (defun org-find-entry-with-id (ident)
16294 "Locate the entry that contains the ID property with exact value IDENT.
16295 IDENT can be a string, a symbol or a number, this function will search for
16296 the string representation of it.
16297 Return the position where this entry starts, or nil if there is no such entry."
16298 (interactive "sID: ")
16299 (let ((id (cond
16300 ((stringp ident) ident)
16301 ((symbol-name ident) (symbol-name ident))
16302 ((numberp ident) (number-to-string ident))
16303 (t (error "IDENT %s must be a string, symbol or number" ident))))
16304 (case-fold-search nil))
16305 (save-excursion
16306 (save-restriction
16307 (widen)
16308 (goto-char (point-min))
16309 (when (re-search-forward
16310 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16311 nil t)
16312 (org-back-to-heading t)
16313 (point))))))
16315 ;;;; Timestamps
16317 (defvar org-last-changed-timestamp nil)
16318 (defvar org-last-inserted-timestamp nil
16319 "The last time stamp inserted with `org-insert-time-stamp'.")
16320 (defvar org-ts-what) ; dynamically scoped parameter
16322 (defun org-time-stamp (arg &optional inactive)
16323 "Prompt for a date/time and insert a time stamp.
16324 If the user specifies a time like HH:MM or if this command is
16325 called with at least one prefix argument, the time stamp contains
16326 the date and the time. Otherwise, only the date is be included.
16328 All parts of a date not specified by the user is filled in from
16329 the current date/time. So if you just press return without
16330 typing anything, the time stamp will represent the current
16331 date/time.
16333 If there is already a timestamp at the cursor, it will be
16334 modified.
16336 With two universal prefix arguments, insert an active timestamp
16337 with the current time without prompting the user.
16339 When called from lisp, the timestamp is inactive if INACTIVE is
16340 non-nil."
16341 (interactive "P")
16342 (let* ((ts nil)
16343 (default-time
16344 ;; Default time is either today, or, when entering a range,
16345 ;; the range start.
16346 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16347 (save-excursion
16348 (re-search-backward
16349 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16350 (- (point) 20) t)))
16351 (apply 'encode-time (org-parse-time-string (match-string 1)))
16352 (current-time)))
16353 (default-input (and ts (org-get-compact-tod ts)))
16354 (repeater (save-excursion
16355 (save-match-data
16356 (beginning-of-line)
16357 (when (re-search-forward
16358 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16359 (save-excursion (progn (end-of-line) (point))) t)
16360 (match-string 0)))))
16361 org-time-was-given org-end-time-was-given time)
16362 (cond
16363 ((and (org-at-timestamp-p t)
16364 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16365 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16366 (insert "--")
16367 (setq time (let ((this-command this-command))
16368 (org-read-date arg 'totime nil nil
16369 default-time default-input inactive)))
16370 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16371 ((org-at-timestamp-p t)
16372 (setq time (let ((this-command this-command))
16373 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16374 (when (org-at-timestamp-p t) ; just to get the match data
16375 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16376 (replace-match "")
16377 (setq org-last-changed-timestamp
16378 (org-insert-time-stamp
16379 time (or org-time-was-given arg)
16380 inactive nil nil (list org-end-time-was-given)))
16381 (when repeater (goto-char (1- (point))) (insert " " repeater)
16382 (setq org-last-changed-timestamp
16383 (concat (substring org-last-inserted-timestamp 0 -1)
16384 " " repeater ">"))))
16385 (message "Timestamp updated"))
16386 ((equal arg '(16))
16387 (org-insert-time-stamp (current-time) t inactive))
16389 (setq time (let ((this-command this-command))
16390 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16391 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16392 nil nil (list org-end-time-was-given))))))
16394 ;; FIXME: can we use this for something else, like computing time differences?
16395 (defun org-get-compact-tod (s)
16396 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16397 (let* ((t1 (match-string 1 s))
16398 (h1 (string-to-number (match-string 2 s)))
16399 (m1 (string-to-number (match-string 3 s)))
16400 (t2 (and (match-end 4) (match-string 5 s)))
16401 (h2 (and t2 (string-to-number (match-string 6 s))))
16402 (m2 (and t2 (string-to-number (match-string 7 s))))
16403 dh dm)
16404 (if (not t2)
16406 (setq dh (- h2 h1) dm (- m2 m1))
16407 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16408 (concat t1 "+" (number-to-string dh)
16409 (and (/= 0 dm) (format ":%02d" dm)))))))
16411 (defun org-time-stamp-inactive (&optional arg)
16412 "Insert an inactive time stamp.
16413 An inactive time stamp is enclosed in square brackets instead of angle
16414 brackets. It is inactive in the sense that it does not trigger agenda entries,
16415 does not link to the calendar and cannot be changed with the S-cursor keys.
16416 So these are more for recording a certain time/date."
16417 (interactive "P")
16418 (org-time-stamp arg 'inactive))
16420 (defvar org-date-ovl (make-overlay 1 1))
16421 (overlay-put org-date-ovl 'face 'org-date-selected)
16422 (org-detach-overlay org-date-ovl)
16424 (defvar org-ans1) ; dynamically scoped parameter
16425 (defvar org-ans2) ; dynamically scoped parameter
16427 (defvar org-plain-time-of-day-regexp) ; defined below
16429 (defvar org-overriding-default-time nil) ; dynamically scoped
16430 (defvar org-read-date-overlay nil)
16431 (defvar org-dcst nil) ; dynamically scoped
16432 (defvar org-read-date-history nil)
16433 (defvar org-read-date-final-answer nil)
16434 (defvar org-read-date-analyze-futurep nil)
16435 (defvar org-read-date-analyze-forced-year nil)
16436 (defvar org-read-date-inactive)
16438 (defvar org-read-date-minibuffer-local-map
16439 (let* ((org-replace-disputed-keys nil)
16440 (map (make-sparse-keymap)))
16441 (set-keymap-parent map minibuffer-local-map)
16442 (org-defkey map (kbd ".")
16443 (lambda () (interactive)
16444 ;; Are we at the beginning of the prompt?
16445 (if (looking-back "^[^:]+: ")
16446 (org-eval-in-calendar '(calendar-goto-today))
16447 (insert "."))))
16448 (org-defkey map (kbd "C-.")
16449 (lambda () (interactive)
16450 (org-eval-in-calendar '(calendar-goto-today))))
16451 (org-defkey map [(meta shift left)]
16452 (lambda () (interactive)
16453 (org-eval-in-calendar '(calendar-backward-month 1))))
16454 (org-defkey map [(meta shift right)]
16455 (lambda () (interactive)
16456 (org-eval-in-calendar '(calendar-forward-month 1))))
16457 (org-defkey map [(meta shift up)]
16458 (lambda () (interactive)
16459 (org-eval-in-calendar '(calendar-backward-year 1))))
16460 (org-defkey map [(meta shift down)]
16461 (lambda () (interactive)
16462 (org-eval-in-calendar '(calendar-forward-year 1))))
16463 (org-defkey map [?\e (shift left)]
16464 (lambda () (interactive)
16465 (org-eval-in-calendar '(calendar-backward-month 1))))
16466 (org-defkey map [?\e (shift right)]
16467 (lambda () (interactive)
16468 (org-eval-in-calendar '(calendar-forward-month 1))))
16469 (org-defkey map [?\e (shift up)]
16470 (lambda () (interactive)
16471 (org-eval-in-calendar '(calendar-backward-year 1))))
16472 (org-defkey map [?\e (shift down)]
16473 (lambda () (interactive)
16474 (org-eval-in-calendar '(calendar-forward-year 1))))
16475 (org-defkey map [(shift up)]
16476 (lambda () (interactive)
16477 (org-eval-in-calendar '(calendar-backward-week 1))))
16478 (org-defkey map [(shift down)]
16479 (lambda () (interactive)
16480 (org-eval-in-calendar '(calendar-forward-week 1))))
16481 (org-defkey map [(shift left)]
16482 (lambda () (interactive)
16483 (org-eval-in-calendar '(calendar-backward-day 1))))
16484 (org-defkey map [(shift right)]
16485 (lambda () (interactive)
16486 (org-eval-in-calendar '(calendar-forward-day 1))))
16487 (org-defkey map "!"
16488 (lambda () (interactive)
16489 (org-eval-in-calendar '(diary-view-entries))
16490 (message "")))
16491 (org-defkey map ">"
16492 (lambda () (interactive)
16493 (org-eval-in-calendar '(scroll-calendar-left 1))))
16494 (org-defkey map "<"
16495 (lambda () (interactive)
16496 (org-eval-in-calendar '(scroll-calendar-right 1))))
16497 (org-defkey map "\C-v"
16498 (lambda () (interactive)
16499 (org-eval-in-calendar
16500 '(calendar-scroll-left-three-months 1))))
16501 (org-defkey map "\M-v"
16502 (lambda () (interactive)
16503 (org-eval-in-calendar
16504 '(calendar-scroll-right-three-months 1))))
16505 map)
16506 "Keymap for minibuffer commands when using `org-read-date'.")
16508 (defvar org-def)
16509 (defvar org-defdecode)
16510 (defvar org-with-time)
16512 (defun org-read-date (&optional org-with-time to-time from-string prompt
16513 default-time default-input inactive)
16514 "Read a date, possibly a time, and make things smooth for the user.
16515 The prompt will suggest to enter an ISO date, but you can also enter anything
16516 which will at least partially be understood by `parse-time-string'.
16517 Unrecognized parts of the date will default to the current day, month, year,
16518 hour and minute. If this command is called to replace a timestamp at point,
16519 or to enter the second timestamp of a range, the default time is taken
16520 from the existing stamp. Furthermore, the command prefers the future,
16521 so if you are giving a date where the year is not given, and the day-month
16522 combination is already past in the current year, it will assume you
16523 mean next year. For details, see the manual. A few examples:
16525 3-2-5 --> 2003-02-05
16526 feb 15 --> currentyear-02-15
16527 2/15 --> currentyear-02-15
16528 sep 12 9 --> 2009-09-12
16529 12:45 --> today 12:45
16530 22 sept 0:34 --> currentyear-09-22 0:34
16531 12 --> currentyear-currentmonth-12
16532 Fri --> nearest Friday after today
16533 -Tue --> last Tuesday
16534 etc.
16536 Furthermore you can specify a relative date by giving, as the *first* thing
16537 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16538 change in days weeks, months, years.
16539 With a single plus or minus, the date is relative to today. With a double
16540 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16541 +4d --> four days from today
16542 +4 --> same as above
16543 +2w --> two weeks from today
16544 ++5 --> five days from default date
16546 The function understands only English month and weekday abbreviations.
16548 While prompting, a calendar is popped up - you can also select the
16549 date with the mouse (button 1). The calendar shows a period of three
16550 months. To scroll it to other months, use the keys `>' and `<'.
16551 If you don't like the calendar, turn it off with
16552 \(setq org-read-date-popup-calendar nil)
16554 With optional argument TO-TIME, the date will immediately be converted
16555 to an internal time.
16556 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16557 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16558 still enter a time, and this function will inform the calling routine
16559 about this change. The calling routine may then choose to change the
16560 format used to insert the time stamp into the buffer to include the time.
16561 With optional argument FROM-STRING, read from this string instead from
16562 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16563 the time/date that is used for everything that is not specified by the
16564 user."
16565 (require 'parse-time)
16566 (let* ((org-time-stamp-rounding-minutes
16567 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16568 (org-dcst org-display-custom-times)
16569 (ct (org-current-time))
16570 (org-def (or org-overriding-default-time default-time ct))
16571 (org-defdecode (decode-time org-def))
16572 (dummy (progn
16573 (when (< (nth 2 org-defdecode) org-extend-today-until)
16574 (setcar (nthcdr 2 org-defdecode) -1)
16575 (setcar (nthcdr 1 org-defdecode) 59)
16576 (setq org-def (apply 'encode-time org-defdecode)
16577 org-defdecode (decode-time org-def)))))
16578 (mouse-autoselect-window nil) ; Don't let the mouse jump
16579 (calendar-frame-setup nil)
16580 (calendar-setup nil)
16581 (calendar-move-hook nil)
16582 (calendar-view-diary-initially-flag nil)
16583 (calendar-view-holidays-initially-flag nil)
16584 (timestr (format-time-string
16585 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16586 (prompt (concat (if prompt (concat prompt " ") "")
16587 (format "Date+time [%s]: " timestr)))
16588 ans (org-ans0 "") org-ans1 org-ans2 final)
16590 (cond
16591 (from-string (setq ans from-string))
16592 (org-read-date-popup-calendar
16593 (save-excursion
16594 (save-window-excursion
16595 (calendar)
16596 (org-eval-in-calendar '(setq cursor-type nil) t)
16597 (unwind-protect
16598 (progn
16599 (calendar-forward-day (- (time-to-days org-def)
16600 (calendar-absolute-from-gregorian
16601 (calendar-current-date))))
16602 (org-eval-in-calendar nil t)
16603 (let* ((old-map (current-local-map))
16604 (map (copy-keymap calendar-mode-map))
16605 (minibuffer-local-map
16606 (copy-keymap org-read-date-minibuffer-local-map)))
16607 (org-defkey map (kbd "RET") 'org-calendar-select)
16608 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16609 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16610 (unwind-protect
16611 (progn
16612 (use-local-map map)
16613 (setq org-read-date-inactive inactive)
16614 (add-hook 'post-command-hook 'org-read-date-display)
16615 (setq org-ans0 (read-string prompt default-input
16616 'org-read-date-history nil))
16617 ;; org-ans0: from prompt
16618 ;; org-ans1: from mouse click
16619 ;; org-ans2: from calendar motion
16620 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16621 (remove-hook 'post-command-hook 'org-read-date-display)
16622 (use-local-map old-map)
16623 (when org-read-date-overlay
16624 (delete-overlay org-read-date-overlay)
16625 (setq org-read-date-overlay nil)))))
16626 (bury-buffer "*Calendar*")))))
16628 (t ; Naked prompt only
16629 (unwind-protect
16630 (setq ans (read-string prompt default-input
16631 'org-read-date-history timestr))
16632 (when org-read-date-overlay
16633 (delete-overlay org-read-date-overlay)
16634 (setq org-read-date-overlay nil)))))
16636 (setq final (org-read-date-analyze ans org-def org-defdecode))
16638 (when org-read-date-analyze-forced-year
16639 (message "Year was forced into %s"
16640 (if org-read-date-force-compatible-dates
16641 "compatible range (1970-2037)"
16642 "range representable on this machine"))
16643 (ding))
16645 ;; One round trip to get rid of 34th of August and stuff like that....
16646 (setq final (decode-time (apply 'encode-time final)))
16648 (setq org-read-date-final-answer ans)
16650 (if to-time
16651 (apply 'encode-time final)
16652 (if (and (boundp 'org-time-was-given) org-time-was-given)
16653 (format "%04d-%02d-%02d %02d:%02d"
16654 (nth 5 final) (nth 4 final) (nth 3 final)
16655 (nth 2 final) (nth 1 final))
16656 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16658 (defun org-read-date-display ()
16659 "Display the current date prompt interpretation in the minibuffer."
16660 (when org-read-date-display-live
16661 (when org-read-date-overlay
16662 (delete-overlay org-read-date-overlay))
16663 (when (minibufferp (current-buffer))
16664 (save-excursion
16665 (end-of-line 1)
16666 (while (not (equal (buffer-substring
16667 (max (point-min) (- (point) 4)) (point))
16668 " "))
16669 (insert " ")))
16670 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16671 " " (or org-ans1 org-ans2)))
16672 (org-end-time-was-given nil)
16673 (f (org-read-date-analyze ans org-def org-defdecode))
16674 (fmts (if org-dcst
16675 org-time-stamp-custom-formats
16676 org-time-stamp-formats))
16677 (fmt (if (or org-with-time
16678 (and (boundp 'org-time-was-given) org-time-was-given))
16679 (cdr fmts)
16680 (car fmts)))
16681 (txt (format-time-string fmt (apply 'encode-time f)))
16682 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16683 (txt (concat "=> " txt)))
16684 (when (and org-end-time-was-given
16685 (string-match org-plain-time-of-day-regexp txt))
16686 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16687 org-end-time-was-given
16688 (substring txt (match-end 0)))))
16689 (when org-read-date-analyze-futurep
16690 (setq txt (concat txt " (=>F)")))
16691 (setq org-read-date-overlay
16692 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16693 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16695 (defun org-read-date-analyze (ans org-def org-defdecode)
16696 "Analyze the combined answer of the date prompt."
16697 ;; FIXME: cleanup and comment
16698 (let ((nowdecode (decode-time (current-time)))
16699 delta deltan deltaw deltadef year month day
16700 hour minute second wday pm h2 m2 tl wday1
16701 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16702 (setq org-read-date-analyze-futurep nil
16703 org-read-date-analyze-forced-year nil)
16704 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16705 (setq ans "+0"))
16707 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16708 (setq ans (replace-match "" t t ans)
16709 deltan (car delta)
16710 deltaw (nth 1 delta)
16711 deltadef (nth 2 delta)))
16713 ;; Check if there is an iso week date in there. If yes, store the
16714 ;; info and postpone interpreting it until the rest of the parsing
16715 ;; is done.
16716 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16717 (setq iso-year (if (match-end 1)
16718 (org-small-year-to-year
16719 (string-to-number (match-string 1 ans))))
16720 iso-weekday (if (match-end 3)
16721 (string-to-number (match-string 3 ans)))
16722 iso-week (string-to-number (match-string 2 ans)))
16723 (setq ans (replace-match "" t t ans)))
16725 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16726 (when (string-match
16727 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16728 (setq year (if (match-end 2)
16729 (string-to-number (match-string 2 ans))
16730 (progn (setq kill-year t)
16731 (string-to-number (format-time-string "%Y"))))
16732 month (string-to-number (match-string 3 ans))
16733 day (string-to-number (match-string 4 ans)))
16734 (if (< year 100) (setq year (+ 2000 year)))
16735 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16736 t nil ans)))
16738 ;; Help matching dotted european dates
16739 (when (string-match
16740 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16741 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16742 (setq kill-year t)
16743 (string-to-number (format-time-string "%Y")))
16744 day (string-to-number (match-string 1 ans))
16745 month (string-to-number (match-string 2 ans))
16746 ans (replace-match (format "%04d-%02d-%02d" year month day)
16747 t nil ans)))
16749 ;; Help matching american dates, like 5/30 or 5/30/7
16750 (when (string-match
16751 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16752 (setq year (if (match-end 4)
16753 (string-to-number (match-string 4 ans))
16754 (progn (setq kill-year t)
16755 (string-to-number (format-time-string "%Y"))))
16756 month (string-to-number (match-string 1 ans))
16757 day (string-to-number (match-string 2 ans)))
16758 (if (< year 100) (setq year (+ 2000 year)))
16759 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16760 t nil ans)))
16761 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16762 ;; If there is a time with am/pm, and *no* time without it, we convert
16763 ;; so that matching will be successful.
16764 (loop for i from 1 to 2 do ; twice, for end time as well
16765 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16766 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16767 (setq hour (string-to-number (match-string 1 ans))
16768 minute (if (match-end 3)
16769 (string-to-number (match-string 3 ans))
16771 pm (equal ?p
16772 (string-to-char (downcase (match-string 4 ans)))))
16773 (if (and (= hour 12) (not pm))
16774 (setq hour 0)
16775 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16776 (setq ans (replace-match (format "%02d:%02d" hour minute)
16777 t t ans))))
16779 ;; Check if a time range is given as a duration
16780 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16781 (setq hour (string-to-number (match-string 1 ans))
16782 h2 (+ hour (string-to-number (match-string 3 ans)))
16783 minute (string-to-number (match-string 2 ans))
16784 m2 (+ minute (if (match-end 5) (string-to-number
16785 (match-string 5 ans))0)))
16786 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16787 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16788 t t ans)))
16790 ;; Check if there is a time range
16791 (when (boundp 'org-end-time-was-given)
16792 (setq org-time-was-given nil)
16793 (when (and (string-match org-plain-time-of-day-regexp ans)
16794 (match-end 8))
16795 (setq org-end-time-was-given (match-string 8 ans))
16796 (setq ans (concat (substring ans 0 (match-beginning 7))
16797 (substring ans (match-end 7))))))
16799 (setq tl (parse-time-string ans)
16800 day (or (nth 3 tl) (nth 3 org-defdecode))
16801 month (or (nth 4 tl)
16802 (if (and org-read-date-prefer-future
16803 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16804 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16805 (nth 4 org-defdecode)))
16806 year (or (and (not kill-year) (nth 5 tl))
16807 (if (and org-read-date-prefer-future
16808 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16809 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16810 (nth 5 org-defdecode)))
16811 hour (or (nth 2 tl) (nth 2 org-defdecode))
16812 minute (or (nth 1 tl) (nth 1 org-defdecode))
16813 second (or (nth 0 tl) 0)
16814 wday (nth 6 tl))
16816 (when (and (eq org-read-date-prefer-future 'time)
16817 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16818 (equal day (nth 3 nowdecode))
16819 (equal month (nth 4 nowdecode))
16820 (equal year (nth 5 nowdecode))
16821 (nth 2 tl)
16822 (or (< (nth 2 tl) (nth 2 nowdecode))
16823 (and (= (nth 2 tl) (nth 2 nowdecode))
16824 (nth 1 tl)
16825 (< (nth 1 tl) (nth 1 nowdecode)))))
16826 (setq day (1+ day)
16827 futurep t))
16829 ;; Special date definitions below
16830 (cond
16831 (iso-week
16832 ;; There was an iso week
16833 (require 'cal-iso)
16834 (setq futurep nil)
16835 (setq year (or iso-year year)
16836 day (or iso-weekday wday 1)
16837 wday nil ; to make sure that the trigger below does not match
16838 iso-date (calendar-gregorian-from-absolute
16839 (calendar-absolute-from-iso
16840 (list iso-week day year))))
16841 ; FIXME: Should we also push ISO weeks into the future?
16842 ; (when (and org-read-date-prefer-future
16843 ; (not iso-year)
16844 ; (< (calendar-absolute-from-gregorian iso-date)
16845 ; (time-to-days (current-time))))
16846 ; (setq year (1+ year)
16847 ; iso-date (calendar-gregorian-from-absolute
16848 ; (calendar-absolute-from-iso
16849 ; (list iso-week day year)))))
16850 (setq month (car iso-date)
16851 year (nth 2 iso-date)
16852 day (nth 1 iso-date)))
16853 (deltan
16854 (setq futurep nil)
16855 (unless deltadef
16856 (let ((now (decode-time (current-time))))
16857 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16858 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16859 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16860 ((equal deltaw "m") (setq month (+ month deltan)))
16861 ((equal deltaw "y") (setq year (+ year deltan)))))
16862 ((and wday (not (nth 3 tl)))
16863 ;; Weekday was given, but no day, so pick that day in the week
16864 ;; on or after the derived date.
16865 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16866 (unless (equal wday wday1)
16867 (setq day (+ day (% (- wday wday1 -7) 7))))))
16868 (if (and (boundp 'org-time-was-given)
16869 (nth 2 tl))
16870 (setq org-time-was-given t))
16871 (if (< year 100) (setq year (+ 2000 year)))
16872 ;; Check of the date is representable
16873 (if org-read-date-force-compatible-dates
16874 (progn
16875 (if (< year 1970)
16876 (setq year 1970 org-read-date-analyze-forced-year t))
16877 (if (> year 2037)
16878 (setq year 2037 org-read-date-analyze-forced-year t)))
16879 (condition-case nil
16880 (ignore (encode-time second minute hour day month year))
16881 (error
16882 (setq year (nth 5 org-defdecode))
16883 (setq org-read-date-analyze-forced-year t))))
16884 (setq org-read-date-analyze-futurep futurep)
16885 (list second minute hour day month year)))
16887 (defvar parse-time-weekdays)
16888 (defun org-read-date-get-relative (s today default)
16889 "Check string S for special relative date string.
16890 TODAY and DEFAULT are internal times, for today and for a default.
16891 Return shift list (N what def-flag)
16892 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16893 N is the number of WHATs to shift.
16894 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16895 the DEFAULT date rather than TODAY."
16896 (require 'parse-time)
16897 (when (and
16898 (string-match
16899 (concat
16900 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16901 "\\([0-9]+\\)?"
16902 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16903 "\\([ \t]\\|$\\)") s)
16904 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16905 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16906 (string-to-char (substring (match-string 1 s) -1))
16907 ?+))
16908 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16909 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16910 (what (if (match-end 3) (match-string 3 s) "d"))
16911 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16912 (date (if rel default today))
16913 (wday (nth 6 (decode-time date)))
16914 delta)
16915 (if wday1
16916 (progn
16917 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16918 (if (= delta 0) (setq delta 7))
16919 (if (= dir ?-)
16920 (progn
16921 (setq delta (- delta 7))
16922 (if (= delta 0) (setq delta -7))))
16923 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16924 (list delta "d" rel))
16925 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16927 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16928 "Turn a user-specified date into the internal representation.
16929 The internal representation needed by the calendar is (month day year).
16930 This is a wrapper to handle the brain-dead convention in calendar that
16931 user function argument order change dependent on argument order."
16932 (if (boundp 'calendar-date-style)
16933 (cond
16934 ((eq calendar-date-style 'american)
16935 (list arg1 arg2 arg3))
16936 ((eq calendar-date-style 'european)
16937 (list arg2 arg1 arg3))
16938 ((eq calendar-date-style 'iso)
16939 (list arg2 arg3 arg1)))
16940 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16941 (if (org-bound-and-true-p european-calendar-style)
16942 (list arg2 arg1 arg3)
16943 (list arg1 arg2 arg3)))))
16945 (defun org-eval-in-calendar (form &optional keepdate)
16946 "Eval FORM in the calendar window and return to current window.
16947 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16948 otherwise stick to the current value of `org-ans2'."
16949 (let ((sf (selected-frame))
16950 (sw (selected-window)))
16951 (select-window (get-buffer-window "*Calendar*" t))
16952 (eval form)
16953 (when (and (not keepdate) (calendar-cursor-to-date))
16954 (let* ((date (calendar-cursor-to-date))
16955 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16956 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16957 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16958 (select-window sw)
16959 (org-select-frame-set-input-focus sf)))
16961 (defun org-calendar-select ()
16962 "Return to `org-read-date' with the date currently selected.
16963 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16964 (interactive)
16965 (when (calendar-cursor-to-date)
16966 (let* ((date (calendar-cursor-to-date))
16967 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16968 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16969 (if (active-minibuffer-window) (exit-minibuffer))))
16971 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16972 "Insert a date stamp for the date given by the internal TIME.
16973 WITH-HM means use the stamp format that includes the time of the day.
16974 INACTIVE means use square brackets instead of angular ones, so that the
16975 stamp will not contribute to the agenda.
16976 PRE and POST are optional strings to be inserted before and after the
16977 stamp.
16978 The command returns the inserted time stamp."
16979 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16980 stamp)
16981 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16982 (insert-before-markers (or pre ""))
16983 (when (listp extra)
16984 (setq extra (car extra))
16985 (if (and (stringp extra)
16986 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16987 (setq extra (format "-%02d:%02d"
16988 (string-to-number (match-string 1 extra))
16989 (string-to-number (match-string 2 extra))))
16990 (setq extra nil)))
16991 (when extra
16992 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16993 (insert-before-markers (setq stamp (format-time-string fmt time)))
16994 (insert-before-markers (or post ""))
16995 (setq org-last-inserted-timestamp stamp)))
16997 (defun org-toggle-time-stamp-overlays ()
16998 "Toggle the use of custom time stamp formats."
16999 (interactive)
17000 (setq org-display-custom-times (not org-display-custom-times))
17001 (unless org-display-custom-times
17002 (let ((p (point-min)) (bmp (buffer-modified-p)))
17003 (while (setq p (next-single-property-change p 'display))
17004 (if (and (get-text-property p 'display)
17005 (eq (get-text-property p 'face) 'org-date))
17006 (remove-text-properties
17007 p (setq p (next-single-property-change p 'display))
17008 '(display t))))
17009 (set-buffer-modified-p bmp)))
17010 (if (featurep 'xemacs)
17011 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17012 (org-restart-font-lock)
17013 (setq org-table-may-need-update t)
17014 (if org-display-custom-times
17015 (message "Time stamps are overlaid with custom format")
17016 (message "Time stamp overlays removed")))
17018 (defun org-display-custom-time (beg end)
17019 "Overlay modified time stamp format over timestamp between BEG and END."
17020 (let* ((ts (buffer-substring beg end))
17021 t1 w1 with-hm tf time str w2 (off 0))
17022 (save-match-data
17023 (setq t1 (org-parse-time-string ts t))
17024 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17025 (setq off (- (match-end 0) (match-beginning 0)))))
17026 (setq end (- end off))
17027 (setq w1 (- end beg)
17028 with-hm (and (nth 1 t1) (nth 2 t1))
17029 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17030 time (org-fix-decoded-time t1)
17031 str (org-add-props
17032 (format-time-string
17033 (substring tf 1 -1) (apply 'encode-time time))
17034 nil 'mouse-face 'highlight)
17035 w2 (length str))
17036 (if (not (= w2 w1))
17037 (add-text-properties (1+ beg) (+ 2 beg)
17038 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17039 (if (featurep 'xemacs)
17040 (progn
17041 (put-text-property beg end 'invisible t)
17042 (put-text-property beg end 'end-glyph (make-glyph str)))
17043 (put-text-property beg end 'display str))))
17045 (defun org-translate-time (string)
17046 "Translate all timestamps in STRING to custom format.
17047 But do this only if the variable `org-display-custom-times' is set."
17048 (when org-display-custom-times
17049 (save-match-data
17050 (let* ((start 0)
17051 (re org-ts-regexp-both)
17052 t1 with-hm inactive tf time str beg end)
17053 (while (setq start (string-match re string start))
17054 (setq beg (match-beginning 0)
17055 end (match-end 0)
17056 t1 (save-match-data
17057 (org-parse-time-string (substring string beg end) t))
17058 with-hm (and (nth 1 t1) (nth 2 t1))
17059 inactive (equal (substring string beg (1+ beg)) "[")
17060 tf (funcall (if with-hm 'cdr 'car)
17061 org-time-stamp-custom-formats)
17062 time (org-fix-decoded-time t1)
17063 str (format-time-string
17064 (concat
17065 (if inactive "[" "<") (substring tf 1 -1)
17066 (if inactive "]" ">"))
17067 (apply 'encode-time time))
17068 string (replace-match str t t string)
17069 start (+ start (length str)))))))
17070 string)
17072 (defun org-fix-decoded-time (time)
17073 "Set 0 instead of nil for the first 6 elements of time.
17074 Don't touch the rest."
17075 (let ((n 0))
17076 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17078 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17080 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17081 "Difference between TIMESTAMP-STRING and now in days.
17082 If SECONDS is non-nil, return the difference in seconds."
17083 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17084 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17085 (funcall fdiff (current-time)))))
17087 (defun org-deadline-close (timestamp-string &optional ndays)
17088 "Is the time in TIMESTAMP-STRING close to the current date?"
17089 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17090 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17091 (not (org-entry-is-done-p))))
17093 (defun org-get-wdays (ts &optional delay zero-delay)
17094 "Get the deadline lead time appropriate for timestring TS.
17095 When DELAY is non-nil, get the delay time for scheduled items
17096 instead of the deadline lead time. When ZERO-DELAY is non-nil
17097 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17098 don't try to find the delay cookie in the scheduled timestamp."
17099 (let ((tv (if delay org-scheduled-delay-days
17100 org-deadline-warning-days)))
17101 (cond
17102 ((or (and delay (< tv 0))
17103 (and delay zero-delay (<= tv 0))
17104 (and (not delay) (<= tv 0)))
17105 ;; Enforce this value no matter what
17106 (- tv))
17107 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17108 ;; lead time is specified.
17109 (floor (* (string-to-number (match-string 1 ts))
17110 (cdr (assoc (match-string 2 ts)
17111 '(("d" . 1) ("w" . 7)
17112 ("m" . 30.4) ("y" . 365.25)
17113 ("h" . 0.041667)))))))
17114 ;; go for the default.
17115 (t tv))))
17117 (defun org-calendar-select-mouse (ev)
17118 "Return to `org-read-date' with the date currently selected.
17119 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17120 (interactive "e")
17121 (mouse-set-point ev)
17122 (when (calendar-cursor-to-date)
17123 (let* ((date (calendar-cursor-to-date))
17124 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17125 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17126 (if (active-minibuffer-window) (exit-minibuffer))))
17128 (defun org-check-deadlines (ndays)
17129 "Check if there are any deadlines due or past due.
17130 A deadline is considered due if it happens within `org-deadline-warning-days'
17131 days from today's date. If the deadline appears in an entry marked DONE,
17132 it is not shown. The prefix arg NDAYS can be used to test that many
17133 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17134 (interactive "P")
17135 (let* ((org-warn-days
17136 (cond
17137 ((equal ndays '(4)) 100000)
17138 (ndays (prefix-numeric-value ndays))
17139 (t (abs org-deadline-warning-days))))
17140 (case-fold-search nil)
17141 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17142 (callback
17143 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17145 (message "%d deadlines past-due or due within %d days"
17146 (org-occur regexp nil callback)
17147 org-warn-days)))
17149 (defsubst org-re-timestamp (type)
17150 "Return a regexp for timestamp TYPE.
17151 Allowed values for TYPE are:
17153 all: all timestamps
17154 active: only active timestamps (<...>)
17155 inactive: only inactive timestamps ([...])
17156 scheduled: only scheduled timestamps
17157 deadline: only deadline timestamps
17158 closed: only closed time-stamps
17160 When TYPE is nil, fall back on returning a regexp that matches
17161 both scheduled and deadline timestamps."
17162 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
17163 ((eq type 'active) org-ts-regexp)
17164 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
17165 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
17166 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17167 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
17168 ((eq type 'scheduled-or-deadline)
17169 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
17171 (defun org-check-before-date (date)
17172 "Check if there are deadlines or scheduled entries before DATE."
17173 (interactive (list (org-read-date)))
17174 (let ((case-fold-search nil)
17175 (regexp (org-re-timestamp org-ts-type))
17176 (callback
17177 (lambda () (time-less-p
17178 (org-time-string-to-time (match-string 1))
17179 (org-time-string-to-time date)))))
17180 (message "%d entries before %s"
17181 (org-occur regexp nil callback) date)))
17183 (defun org-check-after-date (date)
17184 "Check if there are deadlines or scheduled entries after DATE."
17185 (interactive (list (org-read-date)))
17186 (let ((case-fold-search nil)
17187 (regexp (org-re-timestamp org-ts-type))
17188 (callback
17189 (lambda () (not
17190 (time-less-p
17191 (org-time-string-to-time (match-string 1))
17192 (org-time-string-to-time date))))))
17193 (message "%d entries after %s"
17194 (org-occur regexp nil callback) date)))
17196 (defun org-check-dates-range (start-date end-date)
17197 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17198 (interactive (list (org-read-date nil nil nil "Range starts")
17199 (org-read-date nil nil nil "Range end")))
17200 (let ((case-fold-search nil)
17201 (regexp (org-re-timestamp org-ts-type))
17202 (callback
17203 (lambda ()
17204 (let ((match (match-string 1)))
17205 (and
17206 (not (time-less-p
17207 (org-time-string-to-time match)
17208 (org-time-string-to-time start-date)))
17209 (time-less-p
17210 (org-time-string-to-time match)
17211 (org-time-string-to-time end-date)))))))
17212 (message "%d entries between %s and %s"
17213 (org-occur regexp nil callback) start-date end-date)))
17215 (defun org-evaluate-time-range (&optional to-buffer)
17216 "Evaluate a time range by computing the difference between start and end.
17217 Normally the result is just printed in the echo area, but with prefix arg
17218 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17219 If the time range is actually in a table, the result is inserted into the
17220 next column.
17221 For time difference computation, a year is assumed to be exactly 365
17222 days in order to avoid rounding problems."
17223 (interactive "P")
17225 (org-clock-update-time-maybe)
17226 (save-excursion
17227 (unless (org-at-date-range-p t)
17228 (goto-char (point-at-bol))
17229 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17230 (if (not (org-at-date-range-p t))
17231 (user-error "Not at a time-stamp range, and none found in current line")))
17232 (let* ((ts1 (match-string 1))
17233 (ts2 (match-string 2))
17234 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17235 (match-end (match-end 0))
17236 (time1 (org-time-string-to-time ts1))
17237 (time2 (org-time-string-to-time ts2))
17238 (t1 (org-float-time time1))
17239 (t2 (org-float-time time2))
17240 (diff (abs (- t2 t1)))
17241 (negative (< (- t2 t1) 0))
17242 ;; (ys (floor (* 365 24 60 60)))
17243 (ds (* 24 60 60))
17244 (hs (* 60 60))
17245 (fy "%dy %dd %02d:%02d")
17246 (fy1 "%dy %dd")
17247 (fd "%dd %02d:%02d")
17248 (fd1 "%dd")
17249 (fh "%02d:%02d")
17250 y d h m align)
17251 (if havetime
17252 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17254 d (floor (/ diff ds)) diff (mod diff ds)
17255 h (floor (/ diff hs)) diff (mod diff hs)
17256 m (floor (/ diff 60)))
17257 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17259 d (floor (+ (/ diff ds) 0.5))
17260 h 0 m 0))
17261 (if (not to-buffer)
17262 (message "%s" (org-make-tdiff-string y d h m))
17263 (if (org-at-table-p)
17264 (progn
17265 (goto-char match-end)
17266 (setq align t)
17267 (and (looking-at " *|") (goto-char (match-end 0))))
17268 (goto-char match-end))
17269 (if (looking-at
17270 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17271 (replace-match ""))
17272 (if negative (insert " -"))
17273 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17274 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17275 (insert " " (format fh h m))))
17276 (if align (org-table-align))
17277 (message "Time difference inserted")))))
17279 (defun org-make-tdiff-string (y d h m)
17280 (let ((fmt "")
17281 (l nil))
17282 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17283 l (push y l)))
17284 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17285 l (push d l)))
17286 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17287 l (push h l)))
17288 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17289 l (push m l)))
17290 (apply 'format fmt (nreverse l))))
17292 (defun org-time-string-to-time (s &optional buffer pos)
17293 "Convert a timestamp string into internal time."
17294 (condition-case errdata
17295 (apply 'encode-time (org-parse-time-string s))
17296 (error (error "Bad timestamp `%s'%s\nError was: %s"
17297 s (if (not (and buffer pos))
17299 (format " at %d in buffer `%s'" pos buffer))
17300 (cdr errdata)))))
17302 (defun org-time-string-to-seconds (s)
17303 "Convert a timestamp string to a number of seconds."
17304 (org-float-time (org-time-string-to-time s)))
17306 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17307 "Convert a time stamp to an absolute day number.
17308 If there is a specifier for a cyclic time stamp, get the closest
17309 date to DAYNR.
17310 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17311 The variable `date' is bound by the calendar when this is called."
17312 (cond
17313 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17314 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17315 daynr
17316 (+ daynr 1000)))
17317 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17318 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17319 (time-to-days (current-time))) (match-string 0 s)
17320 prefer show-all))
17321 (t (time-to-days
17322 (condition-case errdata
17323 (apply 'encode-time (org-parse-time-string s))
17324 (error (error "Bad timestamp `%s'%s\nError was: %s"
17325 s (if (not (and buffer pos))
17327 (format " at %d in buffer `%s'" pos buffer))
17328 (cdr errdata))))))))
17330 (defun org-days-to-iso-week (days)
17331 "Return the iso week number."
17332 (require 'cal-iso)
17333 (car (calendar-iso-from-absolute days)))
17335 (defun org-small-year-to-year (year)
17336 "Convert 2-digit years into 4-digit years.
17337 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17338 The year 2000 cannot be abbreviated. Any year larger than 99
17339 is returned unchanged."
17340 (if (< year 38)
17341 (setq year (+ 2000 year))
17342 (if (< year 100)
17343 (setq year (+ 1900 year))))
17344 year)
17346 (defun org-time-from-absolute (d)
17347 "Return the time corresponding to date D.
17348 D may be an absolute day number, or a calendar-type list (month day year)."
17349 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17350 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17352 (defun org-calendar-holiday ()
17353 "List of holidays, for Diary display in Org-mode."
17354 (require 'holidays)
17355 (let ((hl (funcall
17356 (if (fboundp 'calendar-check-holidays)
17357 'calendar-check-holidays 'check-calendar-holidays) date)))
17358 (if hl (mapconcat 'identity hl "; "))))
17360 (defun org-diary-sexp-entry (sexp entry date)
17361 "Process a SEXP diary ENTRY for DATE."
17362 (require 'diary-lib)
17363 (let ((result (if calendar-debug-sexp
17364 (let ((stack-trace-on-error t))
17365 (eval (car (read-from-string sexp))))
17366 (condition-case nil
17367 (eval (car (read-from-string sexp)))
17368 (error
17369 (beep)
17370 (message "Bad sexp at line %d in %s: %s"
17371 (org-current-line)
17372 (buffer-file-name) sexp)
17373 (sleep-for 2))))))
17374 (cond ((stringp result) (split-string result "; "))
17375 ((and (consp result)
17376 (not (consp (cdr result)))
17377 (stringp (cdr result))) (cdr result))
17378 ((and (consp result)
17379 (stringp (car result))) result)
17380 (result entry))))
17382 (defun org-diary-to-ical-string (frombuf)
17383 "Get iCalendar entries from diary entries in buffer FROMBUF.
17384 This uses the icalendar.el library."
17385 (let* ((tmpdir (if (featurep 'xemacs)
17386 (temp-directory)
17387 temporary-file-directory))
17388 (tmpfile (make-temp-name
17389 (expand-file-name "orgics" tmpdir)))
17390 buf rtn b e)
17391 (with-current-buffer frombuf
17392 (icalendar-export-region (point-min) (point-max) tmpfile)
17393 (setq buf (find-buffer-visiting tmpfile))
17394 (set-buffer buf)
17395 (goto-char (point-min))
17396 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17397 (setq b (match-beginning 0)))
17398 (goto-char (point-max))
17399 (if (re-search-backward "^END:VEVENT" nil t)
17400 (setq e (match-end 0)))
17401 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17402 (kill-buffer buf)
17403 (delete-file tmpfile)
17404 rtn))
17406 (defun org-closest-date (start current change prefer show-all)
17407 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17408 When PREFER is `past', return a date that is either CURRENT or past.
17409 When PREFER is `future', return a date that is either CURRENT or future.
17410 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17411 ;; Make the proper lists from the dates
17412 (catch 'exit
17413 (let ((a1 '(("h" . hour)
17414 ("d" . day)
17415 ("w" . week)
17416 ("m" . month)
17417 ("y" . year)))
17418 (shour (nth 2 (org-parse-time-string start)))
17419 dn dw sday cday n1 n2 n0
17420 d m y y1 y2 date1 date2 nmonths nm ny m2)
17422 (setq start (org-date-to-gregorian start)
17423 current (org-date-to-gregorian
17424 (if show-all
17425 current
17426 (time-to-days (current-time))))
17427 sday (calendar-absolute-from-gregorian start)
17428 cday (calendar-absolute-from-gregorian current))
17430 (if (<= cday sday) (throw 'exit sday))
17432 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17433 (setq dn (string-to-number (match-string 1 change))
17434 dw (cdr (assoc (match-string 2 change) a1)))
17435 (user-error "Invalid change specifier: %s" change))
17436 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17437 (cond
17438 ((eq dw 'hour)
17439 (let ((missing-hours
17440 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17441 dn)))
17442 (setq n1 (if (zerop missing-hours) cday
17443 (- cday (1+ (floor (/ missing-hours 24)))))
17444 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17445 ((eq dw 'day)
17446 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17447 n2 (+ n1 dn)))
17448 ((eq dw 'year)
17449 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17450 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17451 (setq date1 (list m d y1)
17452 n1 (calendar-absolute-from-gregorian date1)
17453 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17454 n2 (calendar-absolute-from-gregorian date2)))
17455 ((eq dw 'month)
17456 ;; approx number of month between the two dates
17457 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17458 ;; How often does dn fit in there?
17459 (setq d (nth 1 start) m (car start) y (nth 2 start)
17460 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17461 m (+ m nm)
17462 ny (floor (/ m 12))
17463 y (+ y ny)
17464 m (- m (* ny 12)))
17465 (while (> m 12) (setq m (- m 12) y (1+ y)))
17466 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17467 (setq m2 (+ m dn) y2 y)
17468 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17469 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17470 (while (<= n2 cday)
17471 (setq n1 n2 m m2 y y2)
17472 (setq m2 (+ m dn) y2 y)
17473 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17474 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17475 ;; Make sure n1 is the earlier date
17476 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17477 (if show-all
17478 (cond
17479 ((eq prefer 'past) (if (= cday n2) n2 n1))
17480 ((eq prefer 'future) (if (= cday n1) n1 n2))
17481 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17482 (cond
17483 ((eq prefer 'past) (if (= cday n2) n2 n1))
17484 ((eq prefer 'future) (if (= cday n1) n1 n2))
17485 (t (if (= cday n1) n1 n2)))))))
17487 (defun org-date-to-gregorian (date)
17488 "Turn any specification of DATE into a Gregorian date for the calendar."
17489 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17490 ((and (listp date) (= (length date) 3)) date)
17491 ((stringp date)
17492 (setq date (org-parse-time-string date))
17493 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17494 ((listp date)
17495 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17497 (defun org-parse-time-string (s &optional nodefault)
17498 "Parse the standard Org-mode time string.
17499 This should be a lot faster than the normal `parse-time-string'.
17500 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17501 hour and minute fields will be nil if not given."
17502 (cond ((string-match org-ts-regexp0 s)
17503 (list 0
17504 (if (or (match-beginning 8) (not nodefault))
17505 (string-to-number (or (match-string 8 s) "0")))
17506 (if (or (match-beginning 7) (not nodefault))
17507 (string-to-number (or (match-string 7 s) "0")))
17508 (string-to-number (match-string 4 s))
17509 (string-to-number (match-string 3 s))
17510 (string-to-number (match-string 2 s))
17511 nil nil nil))
17512 ((string-match "^<[^>]+>$" s)
17513 (decode-time (seconds-to-time (org-matcher-time s))))
17514 (t (error "Not a standard Org-mode time string: %s" s))))
17516 (defun org-timestamp-up (&optional arg)
17517 "Increase the date item at the cursor by one.
17518 If the cursor is on the year, change the year. If it is on the month,
17519 the day or the time, change that.
17520 With prefix ARG, change by that many units."
17521 (interactive "p")
17522 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17524 (defun org-timestamp-down (&optional arg)
17525 "Decrease the date item at the cursor by one.
17526 If the cursor is on the year, change the year. If it is on the month,
17527 the day or the time, change that.
17528 With prefix ARG, change by that many units."
17529 (interactive "p")
17530 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17532 (defun org-timestamp-up-day (&optional arg)
17533 "Increase the date in the time stamp by one day.
17534 With prefix ARG, change that many days."
17535 (interactive "p")
17536 (if (and (not (org-at-timestamp-p t))
17537 (org-at-heading-p))
17538 (org-todo 'up)
17539 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17541 (defun org-timestamp-down-day (&optional arg)
17542 "Decrease the date in the time stamp by one day.
17543 With prefix ARG, change that many days."
17544 (interactive "p")
17545 (if (and (not (org-at-timestamp-p t))
17546 (org-at-heading-p))
17547 (org-todo 'down)
17548 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17550 (defun org-at-timestamp-p (&optional inactive-ok)
17551 "Determine if the cursor is in or at a timestamp."
17552 (interactive)
17553 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17554 (pos (point))
17555 (ans (or (looking-at tsr)
17556 (save-excursion
17557 (skip-chars-backward "^[<\n\r\t")
17558 (if (> (point) (point-min)) (backward-char 1))
17559 (and (looking-at tsr)
17560 (> (- (match-end 0) pos) -1))))))
17561 (and ans
17562 (boundp 'org-ts-what)
17563 (setq org-ts-what
17564 (cond
17565 ((= pos (match-beginning 0)) 'bracket)
17566 ;; Point is considered to be "on the bracket" whether
17567 ;; it's really on it or right after it.
17568 ((= pos (1- (match-end 0))) 'bracket)
17569 ((= pos (match-end 0)) 'after)
17570 ((org-pos-in-match-range pos 2) 'year)
17571 ((org-pos-in-match-range pos 3) 'month)
17572 ((org-pos-in-match-range pos 7) 'hour)
17573 ((org-pos-in-match-range pos 8) 'minute)
17574 ((or (org-pos-in-match-range pos 4)
17575 (org-pos-in-match-range pos 5)) 'day)
17576 ((and (> pos (or (match-end 8) (match-end 5)))
17577 (< pos (match-end 0)))
17578 (- pos (or (match-end 8) (match-end 5))))
17579 (t 'day))))
17580 ans))
17582 (defun org-toggle-timestamp-type ()
17583 "Toggle the type (<active> or [inactive]) of a time stamp."
17584 (interactive)
17585 (when (org-at-timestamp-p t)
17586 (let ((beg (match-beginning 0)) (end (match-end 0))
17587 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17588 (save-excursion
17589 (goto-char beg)
17590 (while (re-search-forward "[][<>]" end t)
17591 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17592 t t)))
17593 (message "Timestamp is now %sactive"
17594 (if (equal (char-after beg) ?<) "" "in")))))
17596 (defun org-at-clock-log-p nil
17597 "Is the cursor on the clock log line?"
17598 (save-excursion
17599 (move-beginning-of-line 1)
17600 (looking-at org-clock-line-re)))
17602 (defvar org-clock-history) ; defined in org-clock.el
17603 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17604 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17605 "Change the date in the time stamp at point.
17606 The date will be changed by N times WHAT. WHAT can be `day', `month',
17607 `year', `minute', `second'. If WHAT is not given, the cursor position
17608 in the timestamp determines what will be changed.
17609 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17610 (let ((origin (point)) origin-cat
17611 with-hm inactive
17612 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17613 org-ts-what
17614 extra rem
17615 ts time time0 fixnext clrgx)
17616 (if (not (org-at-timestamp-p t))
17617 (user-error "Not at a timestamp"))
17618 (if (and (not what) (eq org-ts-what 'bracket))
17619 (org-toggle-timestamp-type)
17620 ;; Point isn't on brackets. Remember the part of the time-stamp
17621 ;; the point was in. Indeed, size of time-stamps may change,
17622 ;; but point must be kept in the same category nonetheless.
17623 (setq origin-cat org-ts-what)
17624 (if (and (not what) (not (eq org-ts-what 'day))
17625 org-display-custom-times
17626 (get-text-property (point) 'display)
17627 (not (get-text-property (1- (point)) 'display)))
17628 (setq org-ts-what 'day))
17629 (setq org-ts-what (or what org-ts-what)
17630 inactive (= (char-after (match-beginning 0)) ?\[)
17631 ts (match-string 0))
17632 (replace-match "")
17633 (when (string-match
17634 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17636 (setq extra (match-string 1 ts))
17637 (if suppress-tmp-delay
17638 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17639 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17640 (setq with-hm t))
17641 (setq time0 (org-parse-time-string ts))
17642 (when (and updown
17643 (eq org-ts-what 'minute)
17644 (not current-prefix-arg))
17645 ;; This looks like s-up and s-down. Change by one rounding step.
17646 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17647 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17648 (setcar (cdr time0) (+ (nth 1 time0)
17649 (if (> n 0) (- rem) (- dm rem))))))
17650 (setq time
17651 (encode-time (or (car time0) 0)
17652 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17653 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17654 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17655 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17656 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17657 (nthcdr 6 time0)))
17658 (when (and (member org-ts-what '(hour minute))
17659 extra
17660 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17661 (setq extra (org-modify-ts-extra
17662 extra
17663 (if (eq org-ts-what 'hour) 2 5)
17664 n dm)))
17665 (when (integerp org-ts-what)
17666 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17667 (if (eq what 'calendar)
17668 (let ((cal-date (org-get-date-from-calendar)))
17669 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17670 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17671 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17672 (setcar time0 (or (car time0) 0))
17673 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17674 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17675 (setq time (apply 'encode-time time0))))
17676 ;; Insert the new time-stamp, and ensure point stays in the same
17677 ;; category as before (i.e. not after the last position in that
17678 ;; category).
17679 (let ((pos (point)))
17680 ;; Stay before inserted string. `save-excursion' is of no use.
17681 (setq org-last-changed-timestamp
17682 (org-insert-time-stamp time with-hm inactive nil nil extra))
17683 (goto-char pos))
17684 (save-match-data
17685 (looking-at org-ts-regexp3)
17686 (goto-char (cond
17687 ;; `day' category ends before `hour' if any, or at
17688 ;; the end of the day name.
17689 ((eq origin-cat 'day)
17690 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17691 ((eq origin-cat 'hour) (min (match-end 7) origin))
17692 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17693 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17694 ;; `year' and `month' have both fixed size: point
17695 ;; couldn't have moved into another part.
17696 (t origin))))
17697 ;; Update clock if on a CLOCK line.
17698 (org-clock-update-time-maybe)
17699 ;; Maybe adjust the closest clock in `org-clock-history'
17700 (when org-clock-adjust-closest
17701 (if (not (and (org-at-clock-log-p)
17702 (< 1 (length (delq nil (mapcar 'marker-position
17703 org-clock-history))))))
17704 (message "No clock to adjust")
17705 (cond ((save-excursion ; fix previous clock?
17706 (re-search-backward org-ts-regexp0 nil t)
17707 (org-looking-back (concat org-clock-string " \\[")))
17708 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17709 ((save-excursion ; fix next clock?
17710 (re-search-backward org-ts-regexp0 nil t)
17711 (looking-at (concat org-ts-regexp0 "\\] =>")))
17712 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17713 (save-window-excursion
17714 ;; Find closest clock to point, adjust the previous/next one in history
17715 (let* ((p (save-excursion (org-back-to-heading t)))
17716 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17717 (clfixnth
17718 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17719 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17720 (if (not clfixpos)
17721 (message "No clock to adjust")
17722 (save-excursion
17723 (org-goto-marker-or-bmk clfixpos)
17724 (org-show-subtree)
17725 (when (re-search-forward clrgx nil t)
17726 (goto-char (match-beginning 1))
17727 (let (org-clock-adjust-closest)
17728 (org-timestamp-change n org-ts-what updown))
17729 (message "Clock adjusted in %s for heading: %s"
17730 (file-name-nondirectory (buffer-file-name))
17731 (org-get-heading t t)))))))))
17732 ;; Try to recenter the calendar window, if any.
17733 (if (and org-calendar-follow-timestamp-change
17734 (get-buffer-window "*Calendar*" t)
17735 (memq org-ts-what '(day month year)))
17736 (org-recenter-calendar (time-to-days time))))))
17738 (defun org-modify-ts-extra (s pos n dm)
17739 "Change the different parts of the lead-time and repeat fields in timestamp."
17740 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17741 ng h m new rem)
17742 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17743 (cond
17744 ((or (org-pos-in-match-range pos 2)
17745 (org-pos-in-match-range pos 3))
17746 (setq m (string-to-number (match-string 3 s))
17747 h (string-to-number (match-string 2 s)))
17748 (if (org-pos-in-match-range pos 2)
17749 (setq h (+ h n))
17750 (setq n (* dm (org-no-warnings (signum n))))
17751 (when (not (= 0 (setq rem (% m dm))))
17752 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17753 (setq m (+ m n)))
17754 (if (< m 0) (setq m (+ m 60) h (1- h)))
17755 (if (> m 59) (setq m (- m 60) h (1+ h)))
17756 (setq h (min 24 (max 0 h)))
17757 (setq ng 1 new (format "-%02d:%02d" h m)))
17758 ((org-pos-in-match-range pos 6)
17759 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17760 ((org-pos-in-match-range pos 5)
17761 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17763 ((org-pos-in-match-range pos 9)
17764 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17765 ((org-pos-in-match-range pos 8)
17766 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17768 (when ng
17769 (setq s (concat
17770 (substring s 0 (match-beginning ng))
17772 (substring s (match-end ng))))))
17775 (defun org-recenter-calendar (date)
17776 "If the calendar is visible, recenter it to DATE."
17777 (let ((cwin (get-buffer-window "*Calendar*" t)))
17778 (when cwin
17779 (let ((calendar-move-hook nil))
17780 (with-selected-window cwin
17781 (calendar-goto-date (if (listp date) date
17782 (calendar-gregorian-from-absolute date))))))))
17784 (defun org-goto-calendar (&optional arg)
17785 "Go to the Emacs calendar at the current date.
17786 If there is a time stamp in the current line, go to that date.
17787 A prefix ARG can be used to force the current date."
17788 (interactive "P")
17789 (let ((tsr org-ts-regexp) diff
17790 (calendar-move-hook nil)
17791 (calendar-view-holidays-initially-flag nil)
17792 (calendar-view-diary-initially-flag nil))
17793 (if (or (org-at-timestamp-p)
17794 (save-excursion
17795 (beginning-of-line 1)
17796 (looking-at (concat ".*" tsr))))
17797 (let ((d1 (time-to-days (current-time)))
17798 (d2 (time-to-days
17799 (org-time-string-to-time (match-string 1)))))
17800 (setq diff (- d2 d1))))
17801 (calendar)
17802 (calendar-goto-today)
17803 (if (and diff (not arg)) (calendar-forward-day diff))))
17805 (defun org-get-date-from-calendar ()
17806 "Return a list (month day year) of date at point in calendar."
17807 (with-current-buffer "*Calendar*"
17808 (save-match-data
17809 (calendar-cursor-to-date))))
17811 (defun org-date-from-calendar ()
17812 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17813 If there is already a time stamp at the cursor position, update it."
17814 (interactive)
17815 (if (org-at-timestamp-p t)
17816 (org-timestamp-change 0 'calendar)
17817 (let ((cal-date (org-get-date-from-calendar)))
17818 (org-insert-time-stamp
17819 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17821 (defcustom org-effort-durations
17822 `(("h" . 60)
17823 ("d" . ,(* 60 8))
17824 ("w" . ,(* 60 8 5))
17825 ("m" . ,(* 60 8 5 4))
17826 ("y" . ,(* 60 8 5 40)))
17827 "Conversion factor to minutes for an effort modifier.
17829 Each entry has the form (MODIFIER . MINUTES).
17831 In an effort string, a number followed by MODIFIER is multiplied
17832 by the specified number of MINUTES to obtain an effort in
17833 minutes.
17835 For example, if the value of this variable is ((\"hours\" . 60)), then an
17836 effort string \"2hours\" is equivalent to 120 minutes."
17837 :group 'org-agenda
17838 :version "24.1"
17839 :type '(alist :key-type (string :tag "Modifier")
17840 :value-type (number :tag "Minutes")))
17842 (defun org-minutes-to-clocksum-string (m)
17843 "Format number of minutes as a clocksum string.
17844 The format is determined by `org-time-clocksum-format',
17845 `org-time-clocksum-use-fractional' and
17846 `org-time-clocksum-fractional-format' and
17847 `org-time-clocksum-use-effort-durations'."
17848 (let ((clocksum "")
17849 (m (round m)) ; Don't allow fractions of minutes
17850 h d w mo y fmt n)
17851 (setq h (if org-time-clocksum-use-effort-durations
17852 (cdr (assoc "h" org-effort-durations)) 60)
17853 d (if org-time-clocksum-use-effort-durations
17854 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17855 w (if org-time-clocksum-use-effort-durations
17856 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17857 mo (if org-time-clocksum-use-effort-durations
17858 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17859 y (if org-time-clocksum-use-effort-durations
17860 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17861 ;; fractional format
17862 (if org-time-clocksum-use-fractional
17863 (cond
17864 ;; single format string
17865 ((stringp org-time-clocksum-fractional-format)
17866 (format org-time-clocksum-fractional-format (/ m (float h))))
17867 ;; choice of fractional formats for different time units
17868 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17869 (> (/ (truncate m) (* y d h)) 0))
17870 (format fmt (/ m (* y d (float h)))))
17871 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17872 (> (/ (truncate m) (* mo d h)) 0))
17873 (format fmt (/ m (* mo d (float h)))))
17874 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17875 (> (/ (truncate m) (* w d h)) 0))
17876 (format fmt (/ m (* w d (float h)))))
17877 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17878 (> (/ (truncate m) (* d h)) 0))
17879 (format fmt (/ m (* d (float h)))))
17880 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17881 (> (/ (truncate m) h) 0))
17882 (format fmt (/ m (float h))))
17883 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17884 (format fmt m))
17885 ;; fall back to smallest time unit with a format
17886 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17887 (format fmt (/ m (float h))))
17888 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17889 (format fmt (/ m (* d (float h)))))
17890 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17891 (format fmt (/ m (* w d (float h)))))
17892 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17893 (format fmt (/ m (* mo d (float h)))))
17894 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17895 (format fmt (/ m (* y d (float h))))))
17896 ;; standard (non-fractional) format, with single format string
17897 (if (stringp org-time-clocksum-format)
17898 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17899 ;; separate formats components
17900 (and (setq fmt (plist-get org-time-clocksum-format :years))
17901 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17902 (plist-get org-time-clocksum-format :require-years))
17903 (setq clocksum (concat clocksum (format fmt n))
17904 m (- m (* n y d h))))
17905 (and (setq fmt (plist-get org-time-clocksum-format :months))
17906 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17907 (plist-get org-time-clocksum-format :require-months))
17908 (setq clocksum (concat clocksum (format fmt n))
17909 m (- m (* n mo d h))))
17910 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17911 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17912 (plist-get org-time-clocksum-format :require-weeks))
17913 (setq clocksum (concat clocksum (format fmt n))
17914 m (- m (* n w d h))))
17915 (and (setq fmt (plist-get org-time-clocksum-format :days))
17916 (or (> (setq n (/ (truncate m) (* d h))) 0)
17917 (plist-get org-time-clocksum-format :require-days))
17918 (setq clocksum (concat clocksum (format fmt n))
17919 m (- m (* n d h))))
17920 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17921 (or (> (setq n (/ (truncate m) h)) 0)
17922 (plist-get org-time-clocksum-format :require-hours))
17923 (setq clocksum (concat clocksum (format fmt n))
17924 m (- m (* n h))))
17925 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17926 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17927 (setq clocksum (concat clocksum (format fmt m))))
17928 ;; return formatted time duration
17929 clocksum))))
17931 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17932 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17933 "Org mode version 8.0")
17935 (defun org-hours-to-clocksum-string (n)
17936 (org-minutes-to-clocksum-string (* n 60)))
17938 (defun org-hh:mm-string-to-minutes (s)
17939 "Convert a string H:MM to a number of minutes.
17940 If the string is just a number, interpret it as minutes.
17941 In fact, the first hh:mm or number in the string will be taken,
17942 there can be extra stuff in the string.
17943 If no number is found, the return value is 0."
17944 (cond
17945 ((integerp s) s)
17946 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17947 (+ (* (string-to-number (match-string 1 s)) 60)
17948 (string-to-number (match-string 2 s))))
17949 ((string-match "\\([0-9]+\\)" s)
17950 (string-to-number (match-string 1 s)))
17951 (t 0)))
17953 (defcustom org-image-actual-width t
17954 "Should we use the actual width of images when inlining them?
17956 When set to `t', always use the image width.
17958 When set to a number, use imagemagick (when available) to set
17959 the image's width to this value.
17961 When set to a number in a list, try to get the width from any
17962 #+ATTR.* keyword if it matches a width specification like
17964 #+ATTR_HTML: :width 300px
17966 and fall back on that number if none is found.
17968 When set to nil, try to get the width from an #+ATTR.* keyword
17969 and fall back on the original width if none is found.
17971 This requires Emacs >= 24.1, build with imagemagick support."
17972 :group 'org-appearance
17973 :version "24.4"
17974 :package-version '(Org . "8.0")
17975 :type '(choice
17976 (const :tag "Use the image width" t)
17977 (integer :tag "Use a number of pixels")
17978 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17979 (const :tag "Use #+ATTR* or don't resize" nil)))
17981 (defcustom org-agenda-inhibit-startup nil
17982 "Inhibit startup when preparing agenda buffers.
17983 When this variable is `t', the initialization of the Org agenda
17984 buffers is inhibited: e.g. the visibility state is not set, the
17985 tables are not re-aligned, etc."
17986 :type 'boolean
17987 :version "24.3"
17988 :group 'org-agenda)
17990 (define-obsolete-variable-alias
17991 'org-agenda-ignore-drawer-properties
17992 'org-agenda-ignore-properties "24.5")
17994 (defcustom org-agenda-ignore-properties nil
17995 "Avoid updating text properties when building the agenda.
17996 Properties are used to prepare buffers for effort estimates,
17997 appointments, statistics and subtree-local categories.
17998 If you don't use these in the agenda, you can add them to this
17999 list and agenda building will be a bit faster.
18000 The value is a list, with zero or more of the symbols `effort', `appt',
18001 `stats' or `category'."
18002 :type '(set :greedy t
18003 (const effort)
18004 (const appt)
18005 (const stats)
18006 (const category))
18007 :version "24.5"
18008 :package-version '(Org . "8.3")
18009 :group 'org-agenda)
18011 (defun org-duration-string-to-minutes (s &optional output-to-string)
18012 "Convert a duration string S to minutes.
18014 A bare number is interpreted as minutes, modifiers can be set by
18015 customizing `org-effort-durations' (which see).
18017 Entries containing a colon are interpreted as H:MM by
18018 `org-hh:mm-string-to-minutes'."
18019 (let ((result 0)
18020 (re (concat "\\([0-9.]+\\) *\\("
18021 (regexp-opt (mapcar 'car org-effort-durations))
18022 "\\)")))
18023 (while (string-match re s)
18024 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18025 (string-to-number (match-string 1 s))))
18026 (setq s (replace-match "" nil t s)))
18027 (setq result (floor result))
18028 (incf result (org-hh:mm-string-to-minutes s))
18029 (if output-to-string (number-to-string result) result)))
18031 ;;;; Files
18033 (defun org-save-all-org-buffers ()
18034 "Save all Org-mode buffers without user confirmation."
18035 (interactive)
18036 (message "Saving all Org-mode buffers...")
18037 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18038 (when (featurep 'org-id) (org-id-locations-save))
18039 (message "Saving all Org-mode buffers... done"))
18041 (defun org-revert-all-org-buffers ()
18042 "Revert all Org-mode buffers.
18043 Prompt for confirmation when there are unsaved changes.
18044 Be sure you know what you are doing before letting this function
18045 overwrite your changes.
18047 This function is useful in a setup where one tracks org files
18048 with a version control system, to revert on one machine after pulling
18049 changes from another. I believe the procedure must be like this:
18051 1. M-x org-save-all-org-buffers
18052 2. Pull changes from the other machine, resolve conflicts
18053 3. M-x org-revert-all-org-buffers"
18054 (interactive)
18055 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18056 (user-error "Abort"))
18057 (save-excursion
18058 (save-window-excursion
18059 (mapc
18060 (lambda (b)
18061 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18062 (with-current-buffer b buffer-file-name))
18063 (org-pop-to-buffer-same-window b)
18064 (revert-buffer t 'no-confirm)))
18065 (buffer-list))
18066 (when (and (featurep 'org-id) org-id-track-globally)
18067 (org-id-locations-load)))))
18069 ;;;; Agenda files
18071 ;;;###autoload
18072 (defun org-switchb (&optional arg)
18073 "Switch between Org buffers.
18074 With one prefix argument, restrict available buffers to files.
18075 With two prefix arguments, restrict available buffers to agenda files.
18077 Defaults to `iswitchb' for buffer name completion.
18078 Set `org-completion-use-ido' to make it use ido instead."
18079 (interactive "P")
18080 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
18081 ((equal arg '(16)) (org-buffer-list 'agenda))
18082 (t (org-buffer-list))))
18083 (org-completion-use-iswitchb org-completion-use-iswitchb)
18084 (org-completion-use-ido org-completion-use-ido))
18085 (unless (or org-completion-use-ido org-completion-use-iswitchb)
18086 (setq org-completion-use-iswitchb t))
18087 (org-pop-to-buffer-same-window
18088 (org-icompleting-read "Org buffer: "
18089 (mapcar 'list (mapcar 'buffer-name blist))
18090 nil t))))
18092 ;;; Define some older names previously used for this functionality
18093 ;;;###autoload
18094 (defalias 'org-ido-switchb 'org-switchb)
18095 ;;;###autoload
18096 (defalias 'org-iswitchb 'org-switchb)
18098 (defun org-buffer-list (&optional predicate exclude-tmp)
18099 "Return a list of Org buffers.
18100 PREDICATE can be `export', `files' or `agenda'.
18102 export restrict the list to Export buffers.
18103 files restrict the list to buffers visiting Org files.
18104 agenda restrict the list to buffers visiting agenda files.
18106 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18107 (let* ((bfn nil)
18108 (agenda-files (and (eq predicate 'agenda)
18109 (mapcar 'file-truename (org-agenda-files t))))
18110 (filter
18111 (cond
18112 ((eq predicate 'files)
18113 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18114 ((eq predicate 'export)
18115 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
18116 ((eq predicate 'agenda)
18117 (lambda (b)
18118 (with-current-buffer b
18119 (and (derived-mode-p 'org-mode)
18120 (setq bfn (buffer-file-name b))
18121 (member (file-truename bfn) agenda-files)))))
18122 (t (lambda (b) (with-current-buffer b
18123 (or (derived-mode-p 'org-mode)
18124 (string-match "\*Org .*Export"
18125 (buffer-name b)))))))))
18126 (delq nil
18127 (mapcar
18128 (lambda(b)
18129 (if (and (funcall filter b)
18130 (or (not exclude-tmp)
18131 (not (string-match "tmp" (buffer-name b)))))
18133 nil))
18134 (buffer-list)))))
18136 (defun org-agenda-files (&optional unrestricted archives)
18137 "Get the list of agenda files.
18138 Optional UNRESTRICTED means return the full list even if a restriction
18139 is currently in place.
18140 When ARCHIVES is t, include all archive files that are really being
18141 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18142 `org-agenda-archives-mode' is t."
18143 (let ((files
18144 (cond
18145 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18146 ((stringp org-agenda-files) (org-read-agenda-file-list))
18147 ((listp org-agenda-files) org-agenda-files)
18148 (t (error "Invalid value of `org-agenda-files'")))))
18149 (setq files (apply 'append
18150 (mapcar (lambda (f)
18151 (if (file-directory-p f)
18152 (directory-files
18153 f t org-agenda-file-regexp)
18154 (list f)))
18155 files)))
18156 (when org-agenda-skip-unavailable-files
18157 (setq files (delq nil
18158 (mapcar (function
18159 (lambda (file)
18160 (and (file-readable-p file) file)))
18161 files))))
18162 (when (or (eq archives t)
18163 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18164 (setq files (org-add-archive-files files)))
18165 files))
18167 (defun org-agenda-file-p (&optional file)
18168 "Return non-nil, if FILE is an agenda file.
18169 If FILE is omitted, use the file associated with the current
18170 buffer."
18171 (member (or file (buffer-file-name))
18172 (org-agenda-files t)))
18174 (defun org-edit-agenda-file-list ()
18175 "Edit the list of agenda files.
18176 Depending on setup, this either uses customize to edit the variable
18177 `org-agenda-files', or it visits the file that is holding the list. In the
18178 latter case, the buffer is set up in a way that saving it automatically kills
18179 the buffer and restores the previous window configuration."
18180 (interactive)
18181 (if (stringp org-agenda-files)
18182 (let ((cw (current-window-configuration)))
18183 (find-file org-agenda-files)
18184 (org-set-local 'org-window-configuration cw)
18185 (org-add-hook 'after-save-hook
18186 (lambda ()
18187 (set-window-configuration
18188 (prog1 org-window-configuration
18189 (kill-buffer (current-buffer))))
18190 (org-install-agenda-files-menu)
18191 (message "New agenda file list installed"))
18192 nil 'local)
18193 (message "%s" (substitute-command-keys
18194 "Edit list and finish with \\[save-buffer]")))
18195 (customize-variable 'org-agenda-files)))
18197 (defun org-store-new-agenda-file-list (list)
18198 "Set new value for the agenda file list and save it correctly."
18199 (if (stringp org-agenda-files)
18200 (let ((fe (org-read-agenda-file-list t)) b u)
18201 (while (setq b (find-buffer-visiting org-agenda-files))
18202 (kill-buffer b))
18203 (with-temp-file org-agenda-files
18204 (insert
18205 (mapconcat
18206 (lambda (f) ;; Keep un-expanded entries.
18207 (if (setq u (assoc f fe))
18208 (cdr u)
18210 list "\n")
18211 "\n")))
18212 (let ((org-mode-hook nil) (org-inhibit-startup t)
18213 (org-insert-mode-line-in-empty-file nil))
18214 (setq org-agenda-files list)
18215 (customize-save-variable 'org-agenda-files org-agenda-files))))
18217 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18218 "Read the list of agenda files from a file.
18219 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18220 filenames, used by `org-store-new-agenda-file-list' to write back
18221 un-expanded file names."
18222 (when (file-directory-p org-agenda-files)
18223 (error "`org-agenda-files' cannot be a single directory"))
18224 (when (stringp org-agenda-files)
18225 (with-temp-buffer
18226 (insert-file-contents org-agenda-files)
18227 (mapcar
18228 (lambda (f)
18229 (let ((e (expand-file-name (substitute-in-file-name f)
18230 org-directory)))
18231 (if pair-with-expansion
18232 (cons e f)
18233 e)))
18234 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18236 ;;;###autoload
18237 (defun org-cycle-agenda-files ()
18238 "Cycle through the files in `org-agenda-files'.
18239 If the current buffer visits an agenda file, find the next one in the list.
18240 If the current buffer does not, find the first agenda file."
18241 (interactive)
18242 (let* ((fs (org-agenda-files t))
18243 (files (append fs (list (car fs))))
18244 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18245 file)
18246 (unless files (user-error "No agenda files"))
18247 (catch 'exit
18248 (while (setq file (pop files))
18249 (if (equal (file-truename file) tcf)
18250 (when (car files)
18251 (find-file (car files))
18252 (throw 'exit t))))
18253 (find-file (car fs)))
18254 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18256 (defun org-agenda-file-to-front (&optional to-end)
18257 "Move/add the current file to the top of the agenda file list.
18258 If the file is not present in the list, it is added to the front. If it is
18259 present, it is moved there. With optional argument TO-END, add/move to the
18260 end of the list."
18261 (interactive "P")
18262 (let ((org-agenda-skip-unavailable-files nil)
18263 (file-alist (mapcar (lambda (x)
18264 (cons (file-truename x) x))
18265 (org-agenda-files t)))
18266 (ctf (file-truename
18267 (or buffer-file-name
18268 (user-error "Please save the current buffer to a file"))))
18269 x had)
18270 (setq x (assoc ctf file-alist) had x)
18272 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18273 (if to-end
18274 (setq file-alist (append (delq x file-alist) (list x)))
18275 (setq file-alist (cons x (delq x file-alist))))
18276 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18277 (org-install-agenda-files-menu)
18278 (message "File %s to %s of agenda file list"
18279 (if had "moved" "added") (if to-end "end" "front"))))
18281 (defun org-remove-file (&optional file)
18282 "Remove current file from the list of files in variable `org-agenda-files'.
18283 These are the files which are being checked for agenda entries.
18284 Optional argument FILE means use this file instead of the current."
18285 (interactive)
18286 (let* ((org-agenda-skip-unavailable-files nil)
18287 (file (or file buffer-file-name
18288 (user-error "Current buffer does not visit a file")))
18289 (true-file (file-truename file))
18290 (afile (abbreviate-file-name file))
18291 (files (delq nil (mapcar
18292 (lambda (x)
18293 (if (equal true-file
18294 (file-truename x))
18295 nil x))
18296 (org-agenda-files t)))))
18297 (if (not (= (length files) (length (org-agenda-files t))))
18298 (progn
18299 (org-store-new-agenda-file-list files)
18300 (org-install-agenda-files-menu)
18301 (message "Removed file: %s" afile))
18302 (message "File was not in list: %s (not removed)" afile))))
18304 (defun org-file-menu-entry (file)
18305 (vector file (list 'find-file file) t))
18307 (defun org-check-agenda-file (file)
18308 "Make sure FILE exists. If not, ask user what to do."
18309 (when (not (file-exists-p file))
18310 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18311 (abbreviate-file-name file))
18312 (let ((r (downcase (read-char-exclusive))))
18313 (cond
18314 ((equal r ?r)
18315 (org-remove-file file)
18316 (throw 'nextfile t))
18317 (t (user-error "Abort"))))))
18319 (defun org-get-agenda-file-buffer (file)
18320 "Get an agenda buffer visiting FILE.
18321 If the buffer needs to be created, add it to the list of buffers
18322 which might be released later."
18323 (let ((buf (org-find-base-buffer-visiting file)))
18324 (if buf
18325 buf ; just return it
18326 ;; Make a new buffer and remember it
18327 (setq buf (find-file-noselect file))
18328 (if buf (push buf org-agenda-new-buffers))
18329 buf)))
18331 (defun org-release-buffers (blist)
18332 "Release all buffers in list, asking the user for confirmation when needed.
18333 When a buffer is unmodified, it is just killed. When modified, it is saved
18334 \(if the user agrees) and then killed."
18335 (let (buf file)
18336 (while (setq buf (pop blist))
18337 (setq file (buffer-file-name buf))
18338 (when (and (buffer-modified-p buf)
18339 file
18340 (y-or-n-p (format "Save file %s? " file)))
18341 (with-current-buffer buf (save-buffer)))
18342 (kill-buffer buf))))
18344 (defun org-agenda-prepare-buffers (files)
18345 "Create buffers for all agenda files, protect archived trees and comments."
18346 (interactive)
18347 (let ((pa '(:org-archived t))
18348 (pc '(:org-comment t))
18349 (pall '(:org-archived t :org-comment t))
18350 (inhibit-read-only t)
18351 (org-inhibit-startup org-agenda-inhibit-startup)
18352 (rea (concat ":" org-archive-tag ":"))
18353 file re pos)
18354 (setq org-tag-alist-for-agenda nil
18355 org-tag-groups-alist-for-agenda nil)
18356 (save-excursion
18357 (save-restriction
18358 (while (setq file (pop files))
18359 (catch 'nextfile
18360 (if (bufferp file)
18361 (set-buffer file)
18362 (org-check-agenda-file file)
18363 (set-buffer (org-get-agenda-file-buffer file)))
18364 (widen)
18365 (org-set-regexps-and-options-for-tags)
18366 (setq pos (point))
18367 (goto-char (point-min))
18368 (let ((case-fold-search t))
18369 (when (search-forward "#+setupfile" nil t)
18370 ;; Don't set all regexps and options systematically as
18371 ;; this is only run for setting agenda tags from setup
18372 ;; file
18373 (org-set-regexps-and-options)))
18374 (or (memq 'category org-agenda-ignore-properties)
18375 (org-refresh-category-properties))
18376 (or (memq 'stats org-agenda-ignore-properties)
18377 (org-refresh-stats-properties))
18378 (or (memq 'effort org-agenda-ignore-properties)
18379 (org-refresh-effort-properties))
18380 (or (memq 'appt org-agenda-ignore-properties)
18381 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18382 (setq org-todo-keywords-for-agenda
18383 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18384 (setq org-done-keywords-for-agenda
18385 (append org-done-keywords-for-agenda org-done-keywords))
18386 (setq org-todo-keyword-alist-for-agenda
18387 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18388 (setq org-tag-alist-for-agenda
18389 (org-uniquify
18390 (append org-tag-alist-for-agenda
18391 org-tag-alist
18392 org-tag-persistent-alist)))
18393 (if org-group-tags
18394 (setq org-tag-groups-alist-for-agenda
18395 (org-uniquify-alist
18396 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18397 (org-with-silent-modifications
18398 (save-excursion
18399 (remove-text-properties (point-min) (point-max) pall)
18400 (when org-agenda-skip-archived-trees
18401 (goto-char (point-min))
18402 (while (re-search-forward rea nil t)
18403 (if (org-at-heading-p t)
18404 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18405 (goto-char (point-min))
18406 (setq re (format "^\\* .*\\<%s\\>" org-comment-string))
18407 (while (re-search-forward re nil t)
18408 (when (save-match-data (org-in-commented-heading-p t))
18409 (add-text-properties
18410 (match-beginning 0) (org-end-of-subtree t) pc)))))
18411 (goto-char pos)))))
18412 (setq org-todo-keywords-for-agenda
18413 (org-uniquify org-todo-keywords-for-agenda))
18414 (setq org-todo-keyword-alist-for-agenda
18415 (org-uniquify org-todo-keyword-alist-for-agenda))))
18418 ;;;; CDLaTeX minor mode
18420 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18421 "Keymap for the minor `org-cdlatex-mode'.")
18423 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18424 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18425 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18426 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18427 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18429 (defvar org-cdlatex-texmathp-advice-is-done nil
18430 "Flag remembering if we have applied the advice to texmathp already.")
18432 (define-minor-mode org-cdlatex-mode
18433 "Toggle the minor `org-cdlatex-mode'.
18434 This mode supports entering LaTeX environment and math in LaTeX fragments
18435 in Org-mode.
18436 \\{org-cdlatex-mode-map}"
18437 nil " OCDL" nil
18438 (when org-cdlatex-mode
18439 (require 'cdlatex)
18440 (run-hooks 'cdlatex-mode-hook)
18441 (cdlatex-compute-tables))
18442 (unless org-cdlatex-texmathp-advice-is-done
18443 (setq org-cdlatex-texmathp-advice-is-done t)
18444 (defadvice texmathp (around org-math-always-on activate)
18445 "Always return t in org-mode buffers.
18446 This is because we want to insert math symbols without dollars even outside
18447 the LaTeX math segments. If Orgmode thinks that point is actually inside
18448 an embedded LaTeX fragment, let texmathp do its job.
18449 \\[org-cdlatex-mode-map]"
18450 (interactive)
18451 (let (p)
18452 (cond
18453 ((not (derived-mode-p 'org-mode)) ad-do-it)
18454 ((eq this-command 'cdlatex-math-symbol)
18455 (setq ad-return-value t
18456 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18458 (let ((p (org-inside-LaTeX-fragment-p)))
18459 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18460 (setq ad-return-value t
18461 texmathp-why '("Org-mode embedded math" . 0))
18462 (if p ad-do-it)))))))))
18464 (defun turn-on-org-cdlatex ()
18465 "Unconditionally turn on `org-cdlatex-mode'."
18466 (org-cdlatex-mode 1))
18468 (defun org-try-cdlatex-tab ()
18469 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18470 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18471 - inside a LaTeX fragment, or
18472 - after the first word in a line, where an abbreviation expansion could
18473 insert a LaTeX environment."
18474 (when org-cdlatex-mode
18475 (cond
18476 ;; Before any word on the line: No expansion possible.
18477 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18478 ;; Just after first word on the line: Expand it. Make sure it
18479 ;; cannot happen on headlines, though.
18480 ((save-excursion
18481 (skip-chars-backward "a-zA-Z0-9*")
18482 (skip-chars-backward " \t")
18483 (and (bolp) (not (org-at-heading-p))))
18484 (cdlatex-tab) t)
18485 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18487 (defun org-cdlatex-underscore-caret (&optional arg)
18488 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18489 Revert to the normal definition outside of these fragments."
18490 (interactive "P")
18491 (if (org-inside-LaTeX-fragment-p)
18492 (call-interactively 'cdlatex-sub-superscript)
18493 (let (org-cdlatex-mode)
18494 (call-interactively (key-binding (vector last-input-event))))))
18496 (defun org-cdlatex-math-modify (&optional arg)
18497 "Execute `cdlatex-math-modify' in LaTeX fragments.
18498 Revert to the normal definition outside of these fragments."
18499 (interactive "P")
18500 (if (org-inside-LaTeX-fragment-p)
18501 (call-interactively 'cdlatex-math-modify)
18502 (let (org-cdlatex-mode)
18503 (call-interactively (key-binding (vector last-input-event))))))
18505 (defun org-cdlatex-environment-indent (&optional environment item)
18506 "Execute `cdlatex-environment' and indent the inserted environment."
18507 (interactive)
18508 (cdlatex-environment environment item)
18509 (let ((element (org-element-at-point)))
18510 (org-indent-region (org-element-property :begin element)
18511 (org-element-property :end element))))
18514 ;;;; LaTeX fragments
18516 (defun org-inside-LaTeX-fragment-p ()
18517 "Test if point is inside a LaTeX fragment.
18518 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18519 sequence appearing also before point.
18520 Even though the matchers for math are configurable, this function assumes
18521 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18522 delimiters are skipped when they have been removed by customization.
18523 The return value is nil, or a cons cell with the delimiter and the
18524 position of this delimiter.
18526 This function does a reasonably good job, but can locally be fooled by
18527 for example currency specifications. For example it will assume being in
18528 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18529 fragments that are properly closed, but during editing, we have to live
18530 with the uncertainty caused by missing closing delimiters. This function
18531 looks only before point, not after."
18532 (catch 'exit
18533 (let ((pos (point))
18534 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18535 (lim (progn
18536 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18537 (point)))
18538 dd-on str (start 0) m re)
18539 (goto-char pos)
18540 (when dodollar
18541 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18542 re (nth 1 (assoc "$" org-latex-regexps)))
18543 (while (string-match re str start)
18544 (cond
18545 ((= (match-end 0) (length str))
18546 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18547 ((= (match-end 0) (- (length str) 5))
18548 (throw 'exit nil))
18549 (t (setq start (match-end 0))))))
18550 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18551 (goto-char pos)
18552 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18553 (and (match-beginning 2) (throw 'exit nil))
18554 ;; count $$
18555 (while (re-search-backward "\\$\\$" lim t)
18556 (setq dd-on (not dd-on)))
18557 (goto-char pos)
18558 (if dd-on (cons "$$" m))))))
18560 (defun org-inside-latex-macro-p ()
18561 "Is point inside a LaTeX macro or its arguments?"
18562 (save-match-data
18563 (org-in-regexp
18564 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18566 (defvar org-latex-fragment-image-overlays nil
18567 "List of overlays carrying the images of latex fragments.")
18568 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18570 (defun org-remove-latex-fragment-image-overlays ()
18571 "Remove all overlays with LaTeX fragment images in current buffer."
18572 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18573 (setq org-latex-fragment-image-overlays nil))
18575 (define-obsolete-function-alias
18576 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18577 (defun org-toggle-latex-fragment (&optional subtree)
18578 "Preview the LaTeX fragment at point, or all locally or globally.
18579 If the cursor is in a LaTeX fragment, create the image and overlay
18580 it over the source code. If there is no fragment at point, display
18581 all fragments in the current text, from one headline to the next. With
18582 prefix SUBTREE, display all fragments in the current subtree. With a
18583 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18584 the cursor is before the first headline,
18585 display all fragments in the buffer.
18586 The images can be removed again with \\[org-toggle-latex-fragment]."
18587 (interactive "P")
18588 (unless buffer-file-name
18589 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18590 (if org-latex-fragment-image-overlays
18591 (progn (org-remove-latex-fragment-image-overlays)
18592 (message "LaTeX fragments images removed"))
18593 (when (display-graphic-p)
18594 (org-remove-latex-fragment-image-overlays)
18595 (save-excursion
18596 (save-restriction
18597 (let (beg end at msg)
18598 (cond
18599 ((or (equal subtree '(16))
18600 (not (save-excursion
18601 (re-search-backward org-outline-regexp-bol nil t))))
18602 (setq beg (point-min) end (point-max)
18603 msg "Creating images for buffer...%s"))
18604 ((equal subtree '(4))
18605 (org-back-to-heading)
18606 (setq beg (point) end (org-end-of-subtree t)
18607 msg "Creating images for subtree...%s"))
18609 (if (setq at (org-inside-LaTeX-fragment-p))
18610 (goto-char (max (point-min) (- (cdr at) 2)))
18611 (org-back-to-heading))
18612 (setq beg (point) end (progn (outline-next-heading) (point))
18613 msg (if at "Creating image...%s"
18614 "Creating images for entry...%s"))))
18615 (message msg "")
18616 (narrow-to-region beg end)
18617 (goto-char beg)
18618 (org-format-latex
18619 (concat org-latex-preview-ltxpng-directory
18620 (file-name-sans-extension
18621 (file-name-nondirectory buffer-file-name)))
18622 default-directory 'overlays msg at 'forbuffer
18623 org-latex-create-formula-image-program)
18624 (message msg "done. Use `C-c C-x C-l' to remove images.")))))))
18626 (defun org-format-latex (prefix &optional dir overlays msg at
18627 forbuffer processing-type)
18628 "Replace LaTeX fragments with links to an image, and produce images.
18629 Some of the options can be changed using the variable
18630 `org-format-latex-options'."
18631 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18632 (let* ((prefixnodir (file-name-nondirectory prefix))
18633 (absprefix (expand-file-name prefix dir))
18634 (todir (file-name-directory absprefix))
18635 (opt org-format-latex-options)
18636 (optnew org-format-latex-options)
18637 (matchers (plist-get opt :matchers))
18638 (re-list org-latex-regexps)
18639 (cnt 0) txt hash link beg end re e checkdir
18640 string
18641 m n block-type block linkfile movefile ov)
18642 ;; Check the different regular expressions
18643 (while (setq e (pop re-list))
18644 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18645 block (if block-type "\n\n" ""))
18646 (when (member m matchers)
18647 (goto-char (point-min))
18648 (while (re-search-forward re nil t)
18649 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18650 (or (not overlays)
18651 (not (eq (get-char-property (match-beginning n)
18652 'org-overlay-type)
18653 'org-latex-overlay))))
18654 (cond
18655 ((eq processing-type 'verbatim))
18656 ((eq processing-type 'mathjax)
18657 ;; Prepare for MathJax processing.
18658 (setq string (match-string n))
18659 (when (member m '("$" "$1"))
18660 (save-excursion
18661 (delete-region (match-beginning n) (match-end n))
18662 (goto-char (match-beginning n))
18663 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18664 ((or (eq processing-type 'dvipng)
18665 (eq processing-type 'imagemagick))
18666 ;; Process to an image.
18667 (setq txt (match-string n)
18668 beg (match-beginning n) end (match-end n)
18669 cnt (1+ cnt))
18670 (let ((face (face-at-point))
18671 (fg (plist-get opt :foreground))
18672 (bg (plist-get opt :background))
18673 ;; Ensure full list is printed.
18674 print-length print-level)
18675 (when forbuffer
18676 ;; Get the colors from the face at point.
18677 (goto-char beg)
18678 (when (eq fg 'auto)
18679 (setq fg (face-attribute face :foreground nil 'default)))
18680 (when (eq bg 'auto)
18681 (setq bg (face-attribute face :background nil 'default)))
18682 (setq optnew (copy-sequence opt))
18683 (plist-put optnew :foreground fg)
18684 (plist-put optnew :background bg))
18685 (setq hash (sha1 (prin1-to-string
18686 (list org-format-latex-header
18687 org-latex-default-packages-alist
18688 org-latex-packages-alist
18689 org-format-latex-options
18690 forbuffer txt fg bg)))
18691 linkfile (format "%s_%s.png" prefix hash)
18692 movefile (format "%s_%s.png" absprefix hash)))
18693 (setq link (concat block "[[file:" linkfile "]]" block))
18694 (if msg (message msg cnt))
18695 (goto-char beg)
18696 (unless checkdir ; Ensure the directory exists.
18697 (setq checkdir t)
18698 (or (file-directory-p todir) (make-directory todir t)))
18699 (unless (file-exists-p movefile)
18700 (org-create-formula-image
18701 txt movefile optnew forbuffer processing-type))
18702 (if overlays
18703 (progn
18704 (mapc (lambda (o)
18705 (if (eq (overlay-get o 'org-overlay-type)
18706 'org-latex-overlay)
18707 (delete-overlay o)))
18708 (overlays-in beg end))
18709 (setq ov (make-overlay beg end))
18710 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18711 (if (featurep 'xemacs)
18712 (progn
18713 (overlay-put ov 'invisible t)
18714 (overlay-put
18715 ov 'end-glyph
18716 (make-glyph (vector 'png :file movefile))))
18717 (overlay-put
18718 ov 'display
18719 (list 'image :type 'png :file movefile :ascent 'center)))
18720 (push ov org-latex-fragment-image-overlays)
18721 (goto-char end))
18722 (delete-region beg end)
18723 (insert (org-add-props link
18724 (list 'org-latex-src
18725 (replace-regexp-in-string
18726 "\"" "" txt)
18727 'org-latex-src-embed-type
18728 (if block-type 'paragraph 'character))))))
18729 ((eq processing-type 'mathml)
18730 ;; Process to MathML
18731 (unless (save-match-data (org-format-latex-mathml-available-p))
18732 (user-error "LaTeX to MathML converter not configured"))
18733 (setq txt (match-string n)
18734 beg (match-beginning n) end (match-end n)
18735 cnt (1+ cnt))
18736 (if msg (message msg cnt))
18737 (goto-char beg)
18738 (delete-region beg end)
18739 (insert (org-format-latex-as-mathml
18740 txt block-type prefix dir)))
18742 (error "Unknown conversion type %s for LaTeX fragments"
18743 processing-type)))))))))
18745 (defun org-create-math-formula (latex-frag &optional mathml-file)
18746 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18747 Use `org-latex-to-mathml-convert-command'. If the conversion is
18748 sucessful, return the portion between \"<math...> </math>\"
18749 elements otherwise return nil. When MATHML-FILE is specified,
18750 write the results in to that file. When invoked as an
18751 interactive command, prompt for LATEX-FRAG, with initial value
18752 set to the current active region and echo the results for user
18753 inspection."
18754 (interactive (list (let ((frag (when (org-region-active-p)
18755 (buffer-substring-no-properties
18756 (region-beginning) (region-end)))))
18757 (read-string "LaTeX Fragment: " frag nil frag))))
18758 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18759 (let* ((tmp-in-file (file-relative-name
18760 (make-temp-name (expand-file-name "ltxmathml-in"))))
18761 (ignore (write-region latex-frag nil tmp-in-file))
18762 (tmp-out-file (file-relative-name
18763 (make-temp-name (expand-file-name "ltxmathml-out"))))
18764 (cmd (format-spec
18765 org-latex-to-mathml-convert-command
18766 `((?j . ,(shell-quote-argument
18767 (expand-file-name org-latex-to-mathml-jar-file)))
18768 (?I . ,(shell-quote-argument tmp-in-file))
18769 (?o . ,(shell-quote-argument tmp-out-file)))))
18770 mathml shell-command-output)
18771 (when (org-called-interactively-p 'any)
18772 (unless (org-format-latex-mathml-available-p)
18773 (user-error "LaTeX to MathML converter not configured")))
18774 (message "Running %s" cmd)
18775 (setq shell-command-output (shell-command-to-string cmd))
18776 (setq mathml
18777 (when (file-readable-p tmp-out-file)
18778 (with-current-buffer (find-file-noselect tmp-out-file t)
18779 (goto-char (point-min))
18780 (when (re-search-forward
18781 (concat
18782 (regexp-quote
18783 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18784 "\\(.\\|\n\\)*"
18785 (regexp-quote "</math>")) nil t)
18786 (prog1 (match-string 0) (kill-buffer))))))
18787 (cond
18788 (mathml
18789 (setq mathml
18790 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18791 (when mathml-file
18792 (write-region mathml nil mathml-file))
18793 (when (org-called-interactively-p 'any)
18794 (message mathml)))
18795 ((message "LaTeX to MathML conversion failed")
18796 (message shell-command-output)))
18797 (delete-file tmp-in-file)
18798 (when (file-exists-p tmp-out-file)
18799 (delete-file tmp-out-file))
18800 mathml))
18802 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18803 prefix &optional dir)
18804 "Use `org-create-math-formula' but check local cache first."
18805 (let* ((absprefix (expand-file-name prefix dir))
18806 (print-length nil) (print-level nil)
18807 (formula-id (concat
18808 "formula-"
18809 (sha1
18810 (prin1-to-string
18811 (list latex-frag
18812 org-latex-to-mathml-convert-command)))))
18813 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18814 (formula-cache-dir (file-name-directory formula-cache)))
18816 (unless (file-directory-p formula-cache-dir)
18817 (make-directory formula-cache-dir t))
18819 (unless (file-exists-p formula-cache)
18820 (org-create-math-formula latex-frag formula-cache))
18822 (if (file-exists-p formula-cache)
18823 ;; Successful conversion. Return the link to MathML file.
18824 (org-add-props
18825 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18826 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18827 'org-latex-src-embed-type (if latex-frag-type
18828 'paragraph 'character)))
18829 ;; Failed conversion. Return the LaTeX fragment verbatim
18830 latex-frag)))
18832 (defun org-create-formula-image (string tofile options buffer &optional type)
18833 "Create an image from LaTeX source using dvipng or convert.
18834 This function calls either `org-create-formula-image-with-dvipng'
18835 or `org-create-formula-image-with-imagemagick' depending on the
18836 value of `org-latex-create-formula-image-program' or on the value
18837 of the optional TYPE variable.
18839 Note: ultimately these two function should be combined as they
18840 share a good deal of logic."
18841 (org-check-external-command
18842 "latex" "needed to convert LaTeX fragments to images")
18843 (funcall
18844 (case (or type org-latex-create-formula-image-program)
18845 ('dvipng
18846 (org-check-external-command
18847 "dvipng" "needed to convert LaTeX fragments to images")
18848 'org-create-formula-image-with-dvipng)
18849 ('imagemagick
18850 (org-check-external-command
18851 "convert" "you need to install imagemagick")
18852 'org-create-formula-image-with-imagemagick)
18853 (t (error
18854 "Invalid value of `org-latex-create-formula-image-program'")))
18855 string tofile options buffer))
18857 (declare-function org-export-get-backend "ox" (name))
18858 (declare-function org-export--get-global-options "ox" (&optional backend))
18859 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18860 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18861 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18862 (defun org-create-formula--latex-header ()
18863 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18864 (let ((info (org-combine-plists (org-export--get-global-options
18865 (org-export-get-backend 'latex))
18866 (org-export--get-inbuffer-options
18867 (org-export-get-backend 'latex)))))
18868 (org-latex-guess-babel-language
18869 (org-latex-guess-inputenc
18870 (org-splice-latex-header
18871 org-format-latex-header
18872 org-latex-default-packages-alist
18873 org-latex-packages-alist t
18874 (plist-get info :latex-header)))
18875 info)))
18877 ;; This function borrows from Ganesh Swami's latex2png.el
18878 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18879 "This calls dvipng."
18880 (require 'ox-latex)
18881 (let* ((tmpdir (if (featurep 'xemacs)
18882 (temp-directory)
18883 temporary-file-directory))
18884 (texfilebase (make-temp-name
18885 (expand-file-name "orgtex" tmpdir)))
18886 (texfile (concat texfilebase ".tex"))
18887 (dvifile (concat texfilebase ".dvi"))
18888 (pngfile (concat texfilebase ".png"))
18889 (fnh (if (featurep 'xemacs)
18890 (font-height (face-font 'default))
18891 (face-attribute 'default :height nil)))
18892 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18893 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18894 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18895 "Black"))
18896 (bg (or (plist-get options (if buffer :background :html-background))
18897 "Transparent")))
18898 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18899 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18900 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18901 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18902 (let ((latex-header (org-create-formula--latex-header)))
18903 (with-temp-file texfile
18904 (insert latex-header)
18905 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18906 (let ((dir default-directory))
18907 (ignore-errors
18908 (cd tmpdir)
18909 (call-process "latex" nil nil nil texfile))
18910 (cd dir))
18911 (if (not (file-exists-p dvifile))
18912 (progn (message "Failed to create dvi file from %s" texfile) nil)
18913 (ignore-errors
18914 (if (featurep 'xemacs)
18915 (call-process "dvipng" nil nil nil
18916 "-fg" fg "-bg" bg
18917 "-T" "tight"
18918 "-o" pngfile
18919 dvifile)
18920 (call-process "dvipng" nil nil nil
18921 "-fg" fg "-bg" bg
18922 "-D" dpi
18923 ;;"-x" scale "-y" scale
18924 "-T" "tight"
18925 "-o" pngfile
18926 dvifile)))
18927 (if (not (file-exists-p pngfile))
18928 (if org-format-latex-signal-error
18929 (error "Failed to create png file from %s" texfile)
18930 (message "Failed to create png file from %s" texfile)
18931 nil)
18932 ;; Use the requested file name and clean up
18933 (copy-file pngfile tofile 'replace)
18934 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18935 (if (file-exists-p (concat texfilebase e))
18936 (delete-file (concat texfilebase e))))
18937 pngfile))))
18939 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18940 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18941 "This calls convert, which is included into imagemagick."
18942 (require 'ox-latex)
18943 (let* ((tmpdir (if (featurep 'xemacs)
18944 (temp-directory)
18945 temporary-file-directory))
18946 (texfilebase (make-temp-name
18947 (expand-file-name "orgtex" tmpdir)))
18948 (texfile (concat texfilebase ".tex"))
18949 (pdffile (concat texfilebase ".pdf"))
18950 (pngfile (concat texfilebase ".png"))
18951 (fnh (if (featurep 'xemacs)
18952 (font-height (face-font 'default))
18953 (face-attribute 'default :height nil)))
18954 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18955 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18956 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18957 "black"))
18958 (bg (or (plist-get options (if buffer :background :html-background))
18959 "white")))
18960 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18961 (setq fg (org-latex-color-format fg)))
18962 (if (eq bg 'default) (setq bg (org-latex-color :background))
18963 (setq bg (org-latex-color-format
18964 (if (string= bg "Transparent") "white" bg))))
18965 (let ((latex-header (org-create-formula--latex-header)))
18966 (with-temp-file texfile
18967 (insert latex-header)
18968 (insert "\n\\begin{document}\n"
18969 "\\definecolor{fg}{rgb}{" fg "}\n"
18970 "\\definecolor{bg}{rgb}{" bg "}\n"
18971 "\n\\pagecolor{bg}\n"
18972 "\n{\\color{fg}\n"
18973 string
18974 "\n}\n"
18975 "\n\\end{document}\n")))
18976 (org-latex-compile texfile t)
18977 (if (not (file-exists-p pdffile))
18978 (progn (message "Failed to create pdf file from %s" texfile) nil)
18979 (ignore-errors
18980 (if (featurep 'xemacs)
18981 (call-process "convert" nil nil nil
18982 "-density" "96"
18983 "-trim"
18984 "-antialias"
18985 pdffile
18986 "-quality" "100"
18987 ;; "-sharpen" "0x1.0"
18988 pngfile)
18989 (call-process "convert" nil nil nil
18990 "-density" dpi
18991 "-trim"
18992 "-antialias"
18993 pdffile
18994 "-quality" "100"
18995 ;; "-sharpen" "0x1.0"
18996 pngfile)))
18997 (if (not (file-exists-p pngfile))
18998 (if org-format-latex-signal-error
18999 (error "Failed to create png file from %s" texfile)
19000 (message "Failed to create png file from %s" texfile)
19001 nil)
19002 ;; Use the requested file name and clean up
19003 (copy-file pngfile tofile 'replace)
19004 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
19005 (if (file-exists-p (concat texfilebase e))
19006 (delete-file (concat texfilebase e))))
19007 pngfile))))
19009 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19010 "Fill a LaTeX header template TPL.
19011 In the template, the following place holders will be recognized:
19013 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19014 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19015 [PACKAGES] \\usepackage statements for PKG
19016 [NO-PACKAGES] do not include PKG
19017 [EXTRA] the string EXTRA
19018 [NO-EXTRA] do not include EXTRA
19020 For backward compatibility, if both the positive and the negative place
19021 holder is missing, the positive one (without the \"NO-\") will be
19022 assumed to be present at the end of the template.
19023 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19024 EXTRA is a string.
19025 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19026 (let (rpl (end ""))
19027 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19028 (setq rpl (if (or (match-end 1) (not def-pkg))
19029 "" (org-latex-packages-to-string def-pkg snippets-p t))
19030 tpl (replace-match rpl t t tpl))
19031 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19033 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19034 (setq rpl (if (or (match-end 1) (not pkg))
19035 "" (org-latex-packages-to-string pkg snippets-p t))
19036 tpl (replace-match rpl t t tpl))
19037 (if pkg (setq end
19038 (concat end "\n"
19039 (org-latex-packages-to-string pkg snippets-p)))))
19041 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19042 (setq rpl (if (or (match-end 1) (not extra))
19043 "" (concat extra "\n"))
19044 tpl (replace-match rpl t t tpl))
19045 (if (and extra (string-match "\\S-" extra))
19046 (setq end (concat end "\n" extra))))
19048 (if (string-match "\\S-" end)
19049 (concat tpl "\n" end)
19050 tpl)))
19052 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19053 "Turn an alist of packages into a string with the \\usepackage macros."
19054 (setq pkg (mapconcat (lambda(p)
19055 (cond
19056 ((stringp p) p)
19057 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19058 (format "%% Package %s omitted" (cadr p)))
19059 ((equal "" (car p))
19060 (format "\\usepackage{%s}" (cadr p)))
19062 (format "\\usepackage[%s]{%s}"
19063 (car p) (cadr p)))))
19065 "\n"))
19066 (if newline (concat pkg "\n") pkg))
19068 (defun org-dvipng-color (attr)
19069 "Return a RGB color specification for dvipng."
19070 (apply 'format "rgb %s %s %s"
19071 (mapcar 'org-normalize-color
19072 (if (featurep 'xemacs)
19073 (color-rgb-components
19074 (face-property 'default
19075 (cond ((eq attr :foreground) 'foreground)
19076 ((eq attr :background) 'background))))
19077 (color-values (face-attribute 'default attr nil))))))
19079 (defun org-dvipng-color-format (color-name)
19080 "Convert COLOR-NAME to a RGB color value for dvipng."
19081 (apply 'format "rgb %s %s %s"
19082 (mapcar 'org-normalize-color
19083 (color-values color-name))))
19085 (defun org-latex-color (attr)
19086 "Return a RGB color for the LaTeX color package."
19087 (apply 'format "%s,%s,%s"
19088 (mapcar 'org-normalize-color
19089 (if (featurep 'xemacs)
19090 (color-rgb-components
19091 (face-property 'default
19092 (cond ((eq attr :foreground) 'foreground)
19093 ((eq attr :background) 'background))))
19094 (color-values (face-attribute 'default attr nil))))))
19096 (defun org-latex-color-format (color-name)
19097 "Convert COLOR-NAME to a RGB color value."
19098 (apply 'format "%s,%s,%s"
19099 (mapcar 'org-normalize-color
19100 (color-values color-name))))
19102 (defun org-normalize-color (value)
19103 "Return string to be used as color value for an RGB component."
19104 (format "%g" (/ value 65535.0)))
19108 ;; Image display
19110 (defvar org-inline-image-overlays nil)
19111 (make-variable-buffer-local 'org-inline-image-overlays)
19113 (defun org-toggle-inline-images (&optional include-linked)
19114 "Toggle the display of inline images.
19115 INCLUDE-LINKED is passed to `org-display-inline-images'."
19116 (interactive "P")
19117 (if org-inline-image-overlays
19118 (progn
19119 (org-remove-inline-images)
19120 (message "Inline image display turned off"))
19121 (org-display-inline-images include-linked)
19122 (if (and (org-called-interactively-p)
19123 org-inline-image-overlays)
19124 (message "%d images displayed inline"
19125 (length org-inline-image-overlays))
19126 (message "No images to display inline"))))
19128 (defun org-redisplay-inline-images ()
19129 "Refresh the display of inline images."
19130 (interactive)
19131 (if (not org-inline-image-overlays)
19132 (org-toggle-inline-images)
19133 (org-toggle-inline-images)
19134 (org-toggle-inline-images)))
19136 (defun org-display-inline-images (&optional include-linked refresh beg end)
19137 "Display inline images.
19139 An inline image is a link which follows either of these
19140 conventions:
19142 1. Its path is a file with an extension matching return value
19143 from `image-file-name-regexp' and it has no contents.
19145 2. Its description consists in a single link of the previous
19146 type.
19148 When optional argument INCLUDE-LINKED is non-nil, also links with
19149 a text description part will be inlined. This can be nice for
19150 a quick look at those images, but it does not reflect what
19151 exported files will look like.
19153 When optional argument REFRESH is non-nil, refresh existing
19154 images between BEG and END. This will create new image displays
19155 only if necessary. BEG and END default to the buffer
19156 boundaries."
19157 (interactive "P")
19158 (when (display-graphic-p)
19159 (unless refresh
19160 (org-remove-inline-images)
19161 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19162 (org-with-wide-buffer
19163 (goto-char (or beg (point-min)))
19164 (let ((case-fold-search t)
19165 (file-extension-re (org-image-file-name-regexp)))
19166 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19167 (let ((link (save-match-data (org-element-context))))
19168 ;; Check if we're at an inline image.
19169 (when (and (equal (org-element-property :type link) "file")
19170 (or include-linked
19171 (not (org-element-property :contents-begin link)))
19172 (let ((parent (org-element-property :parent link)))
19173 (or (not (eq (org-element-type parent) 'link))
19174 (not (cdr (org-element-contents parent)))))
19175 (org-string-match-p file-extension-re
19176 (org-element-property :path link)))
19177 (let ((file (expand-file-name (org-element-property :path link))))
19178 (when (file-exists-p file)
19179 (let ((width
19180 ;; Apply `org-image-actual-width' specifications.
19181 (cond
19182 ((not (image-type-available-p 'imagemagick)) nil)
19183 ((eq org-image-actual-width t) nil)
19184 ((listp org-image-actual-width)
19186 ;; First try to find a width among
19187 ;; attributes associated to the paragraph
19188 ;; containing link.
19189 (let ((paragraph
19190 (let ((e link))
19191 (while (and (setq e (org-element-property
19192 :parent e))
19193 (not (eq (org-element-type e)
19194 'paragraph))))
19195 e)))
19196 (when paragraph
19197 (save-excursion
19198 (goto-char (org-element-property :begin paragraph))
19199 (when
19200 (re-search-forward
19201 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19202 (org-element-property
19203 :post-affiliated paragraph)
19205 (string-to-number (match-string 1))))))
19206 ;; Otherwise, fall-back to provided number.
19207 (car org-image-actual-width)))
19208 ((numberp org-image-actual-width)
19209 org-image-actual-width)))
19210 (old (get-char-property-and-overlay
19211 (org-element-property :begin link)
19212 'org-image-overlay)))
19213 (if (and (car-safe old) refresh)
19214 (image-refresh (overlay-get (cdr old) 'display))
19215 (let ((image (create-image file
19216 (and width 'imagemagick)
19218 :width width)))
19219 (when image
19220 (let* ((link
19221 ;; If inline image is the description
19222 ;; of another link, be sure to
19223 ;; consider the latter as the one to
19224 ;; apply the overlay on.
19225 (let ((parent
19226 (org-element-property :parent link)))
19227 (if (eq (org-element-type parent) 'link)
19228 parent
19229 link)))
19230 (ov (make-overlay
19231 (org-element-property :begin link)
19232 (progn
19233 (goto-char
19234 (org-element-property :end link))
19235 (skip-chars-backward " \t")
19236 (point)))))
19237 (overlay-put ov 'display image)
19238 (overlay-put ov 'face 'default)
19239 (overlay-put ov 'org-image-overlay t)
19240 (overlay-put
19241 ov 'modification-hooks
19242 (list 'org-display-inline-remove-overlay))
19243 (push ov org-inline-image-overlays)))))))))))))))
19245 (define-obsolete-function-alias
19246 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19248 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
19249 "Remove inline-display overlay if a corresponding region is modified."
19250 (let ((inhibit-modification-hooks t))
19251 (when (and ov after)
19252 (delete ov org-inline-image-overlays)
19253 (delete-overlay ov))))
19255 (defun org-remove-inline-images ()
19256 "Remove inline display of images."
19257 (interactive)
19258 (mapc 'delete-overlay org-inline-image-overlays)
19259 (setq org-inline-image-overlays nil))
19261 ;;;; Key bindings
19263 ;; Outline functions from `outline-mode-prefix-map'
19264 ;; that can be remapped in Org:
19265 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19266 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
19267 (define-key org-mode-map [remap outline-forward-same-level]
19268 'org-forward-heading-same-level)
19269 (define-key org-mode-map [remap outline-backward-same-level]
19270 'org-backward-heading-same-level)
19271 (define-key org-mode-map [remap show-branches]
19272 'org-kill-note-or-show-branches)
19273 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19274 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19275 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19277 ;; Outline functions from `outline-mode-prefix-map' that can not
19278 ;; be remapped in Org:
19280 ;; - the column "key binding" shows whether the Outline function is still
19281 ;; available in Org mode on the same key that it has been bound to in
19282 ;; Outline mode:
19283 ;; - "overridden": key used for a different functionality in Org mode
19284 ;; - else: key still bound to the same Outline function in Org mode
19286 ;; | Outline function | key binding | Org replacement |
19287 ;; |------------------------------------+-------------+-----------------------|
19288 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
19289 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
19290 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19291 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19292 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19293 ;; | `show-entry' | overridden | no replacement |
19294 ;; | `show-children' | `C-c C-i' | visibility cycling |
19295 ;; | `show-branches' | `C-c C-k' | still same function |
19296 ;; | `show-subtree' | overridden | visibility cycling |
19297 ;; | `show-all' | overridden | no replacement |
19298 ;; | `hide-subtree' | overridden | visibility cycling |
19299 ;; | `hide-body' | overridden | no replacement |
19300 ;; | `hide-entry' | overridden | visibility cycling |
19301 ;; | `hide-leaves' | overridden | no replacement |
19302 ;; | `hide-sublevels' | overridden | no replacement |
19303 ;; | `hide-other' | overridden | no replacement |
19305 ;; Make `C-c C-x' a prefix key
19306 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19308 ;; TAB key with modifiers
19309 (org-defkey org-mode-map "\C-i" 'org-cycle)
19310 (org-defkey org-mode-map [(tab)] 'org-cycle)
19311 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19312 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19313 ;; The following line is necessary under Suse GNU/Linux
19314 (unless (featurep 'xemacs)
19315 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19316 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19317 (define-key org-mode-map [backtab] 'org-shifttab)
19319 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19320 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19321 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19323 ;; Cursor keys with modifiers
19324 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19325 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19326 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19327 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19329 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19330 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19331 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19332 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19333 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19334 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19336 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19337 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19338 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19339 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19341 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19342 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19343 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19344 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19346 ;; Babel keys
19347 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19348 (mapc (lambda (pair)
19349 (define-key org-babel-map (car pair) (cdr pair)))
19350 org-babel-key-bindings)
19352 ;;; Extra keys for tty access.
19353 ;; We only set them when really needed because otherwise the
19354 ;; menus don't show the simple keys
19356 (when (or org-use-extra-keys
19357 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19358 (not window-system))
19359 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19360 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19361 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19362 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19363 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19364 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19365 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19366 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19367 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19368 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19369 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19370 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19371 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19372 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19373 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19374 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19375 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19376 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19377 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19378 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19379 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19380 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19381 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19382 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19383 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19384 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19385 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19386 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19388 ;; All the other keys
19390 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19391 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19392 (if (boundp 'narrow-map)
19393 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19394 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19395 (if (boundp 'narrow-map)
19396 (org-defkey narrow-map "b" 'org-narrow-to-block)
19397 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19398 (if (boundp 'narrow-map)
19399 (org-defkey narrow-map "e" 'org-narrow-to-element)
19400 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19401 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19402 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19403 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19404 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19405 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19406 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19407 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19408 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19409 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19410 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19411 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19412 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19413 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19414 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19415 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19416 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19417 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19418 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19419 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19420 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19421 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19422 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19423 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19424 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19425 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19426 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19427 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19428 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19429 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19430 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19431 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19432 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19433 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19434 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19435 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19436 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19437 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19438 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19439 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19440 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19441 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19442 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19443 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19444 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19445 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19446 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19447 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19448 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19449 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19450 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19451 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19452 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19453 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19454 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19455 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19456 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19457 (org-defkey org-mode-map "\C-c^" 'org-sort)
19458 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19459 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19460 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19461 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19462 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19463 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19464 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19465 (org-defkey org-mode-map "\C-m" 'org-return)
19466 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19467 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19468 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19469 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19470 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19471 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19472 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19473 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19474 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19475 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19476 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19477 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19478 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19479 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19480 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19481 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19482 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19483 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19484 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19485 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19486 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19487 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19488 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19490 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19491 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19492 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19494 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19495 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19496 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19497 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19498 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19499 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19500 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19501 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19502 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19503 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19504 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19505 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19506 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19507 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19508 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19509 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19510 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19511 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19512 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19513 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19514 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19515 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19516 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19518 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19519 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19520 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19521 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19522 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19524 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19526 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19528 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19529 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19531 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19534 (when (featurep 'xemacs)
19535 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19538 (defconst org-speed-commands-default
19540 ("Outline Navigation")
19541 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19542 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19543 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19544 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19545 ("F" . org-next-block)
19546 ("B" . org-previous-block)
19547 ("u" . (org-speed-move-safe 'outline-up-heading))
19548 ("j" . org-goto)
19549 ("g" . (org-refile t))
19550 ("Outline Visibility")
19551 ("c" . org-cycle)
19552 ("C" . org-shifttab)
19553 (" " . org-display-outline-path)
19554 ("s" . org-narrow-to-subtree)
19555 ("=" . org-columns)
19556 ("Outline Structure Editing")
19557 ("U" . org-metaup)
19558 ("D" . org-metadown)
19559 ("r" . org-metaright)
19560 ("l" . org-metaleft)
19561 ("R" . org-shiftmetaright)
19562 ("L" . org-shiftmetaleft)
19563 ("i" . (progn (forward-char 1) (call-interactively
19564 'org-insert-heading-respect-content)))
19565 ("^" . org-sort)
19566 ("w" . org-refile)
19567 ("a" . org-archive-subtree-default-with-confirmation)
19568 ("@" . org-mark-subtree)
19569 ("#" . org-toggle-comment)
19570 ("Clock Commands")
19571 ("I" . org-clock-in)
19572 ("O" . org-clock-out)
19573 ("Meta Data Editing")
19574 ("t" . org-todo)
19575 ("," . (org-priority))
19576 ("0" . (org-priority ?\ ))
19577 ("1" . (org-priority ?A))
19578 ("2" . (org-priority ?B))
19579 ("3" . (org-priority ?C))
19580 (":" . org-set-tags-command)
19581 ("e" . org-set-effort)
19582 ("E" . org-inc-effort)
19583 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19584 (org-entry-put (point) "APPT_WARNTIME" m)))
19585 ("Agenda Views etc")
19586 ("v" . org-agenda)
19587 ("/" . org-sparse-tree)
19588 ("Misc")
19589 ("o" . org-open-at-point)
19590 ("?" . org-speed-command-help)
19591 ("<" . (org-agenda-set-restriction-lock 'subtree))
19592 (">" . (org-agenda-remove-restriction-lock))
19594 "The default speed commands.")
19596 (defun org-print-speed-command (e)
19597 (if (> (length (car e)) 1)
19598 (progn
19599 (princ "\n")
19600 (princ (car e))
19601 (princ "\n")
19602 (princ (make-string (length (car e)) ?-))
19603 (princ "\n"))
19604 (princ (car e))
19605 (princ " ")
19606 (if (symbolp (cdr e))
19607 (princ (symbol-name (cdr e)))
19608 (prin1 (cdr e)))
19609 (princ "\n")))
19611 (defun org-speed-command-help ()
19612 "Show the available speed commands."
19613 (interactive)
19614 (if (not org-use-speed-commands)
19615 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19616 (with-output-to-temp-buffer "*Help*"
19617 (princ "User-defined Speed commands\n===========================\n")
19618 (mapc 'org-print-speed-command org-speed-commands-user)
19619 (princ "\n")
19620 (princ "Built-in Speed commands\n=======================\n")
19621 (mapc 'org-print-speed-command org-speed-commands-default))
19622 (with-current-buffer "*Help*"
19623 (setq truncate-lines t))))
19625 (defun org-speed-move-safe (cmd)
19626 "Execute CMD, but make sure that the cursor always ends up in a headline.
19627 If not, return to the original position and throw an error."
19628 (interactive)
19629 (let ((pos (point)))
19630 (call-interactively cmd)
19631 (unless (and (bolp) (org-at-heading-p))
19632 (goto-char pos)
19633 (error "Boundary reached while executing %s" cmd))))
19635 (defvar org-self-insert-command-undo-counter 0)
19637 (defvar org-table-auto-blank-field) ; defined in org-table.el
19638 (defvar org-speed-command nil)
19640 (define-obsolete-function-alias
19641 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19643 (defun org-speed-command-activate (keys)
19644 "Hook for activating single-letter speed commands.
19645 `org-speed-commands-default' specifies a minimal command set.
19646 Use `org-speed-commands-user' for further customization."
19647 (when (or (and (bolp) (looking-at org-outline-regexp))
19648 (and (functionp org-use-speed-commands)
19649 (funcall org-use-speed-commands)))
19650 (cdr (assoc keys (append org-speed-commands-user
19651 org-speed-commands-default)))))
19653 (define-obsolete-function-alias
19654 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19656 (defun org-babel-speed-command-activate (keys)
19657 "Hook for activating single-letter code block commands."
19658 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19659 (cdr (assoc keys org-babel-key-bindings))))
19661 (defcustom org-speed-command-hook
19662 '(org-speed-command-default-hook org-babel-speed-command-hook)
19663 "Hook for activating speed commands at strategic locations.
19664 Hook functions are called in sequence until a valid handler is
19665 found.
19667 Each hook takes a single argument, a user-pressed command key
19668 which is also a `self-insert-command' from the global map.
19670 Within the hook, examine the cursor position and the command key
19671 and return nil or a valid handler as appropriate. Handler could
19672 be one of an interactive command, a function, or a form.
19674 Set `org-use-speed-commands' to non-nil value to enable this
19675 hook. The default setting is `org-speed-command-activate'."
19676 :group 'org-structure
19677 :version "24.1"
19678 :type 'hook)
19680 (defun org-self-insert-command (N)
19681 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19682 If the cursor is in a table looking at whitespace, the whitespace is
19683 overwritten, and the table is not marked as requiring realignment."
19684 (interactive "p")
19685 (org-check-before-invisible-edit 'insert)
19686 (cond
19687 ((and org-use-speed-commands
19688 (setq org-speed-command
19689 (run-hook-with-args-until-success
19690 'org-speed-command-hook (this-command-keys))))
19691 (cond
19692 ((commandp org-speed-command)
19693 (setq this-command org-speed-command)
19694 (call-interactively org-speed-command))
19695 ((functionp org-speed-command)
19696 (funcall org-speed-command))
19697 ((and org-speed-command (listp org-speed-command))
19698 (eval org-speed-command))
19699 (t (let (org-use-speed-commands)
19700 (call-interactively 'org-self-insert-command)))))
19701 ((and
19702 (org-table-p)
19703 (progn
19704 ;; check if we blank the field, and if that triggers align
19705 (and (featurep 'org-table) org-table-auto-blank-field
19706 (member last-command
19707 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas-expand))
19708 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19709 ;; got extra space, this field does not determine column width
19710 (let (org-table-may-need-update) (org-table-blank-field))
19711 ;; no extra space, this field may determine column width
19712 (org-table-blank-field)))
19714 (eq N 1)
19715 (looking-at "[^|\n]* |"))
19716 (let (org-table-may-need-update)
19717 (goto-char (1- (match-end 0)))
19718 (backward-delete-char 1)
19719 (goto-char (match-beginning 0))
19720 (self-insert-command N)))
19722 (setq org-table-may-need-update t)
19723 (self-insert-command N)
19724 (org-fix-tags-on-the-fly)
19725 (if org-self-insert-cluster-for-undo
19726 (if (not (eq last-command 'org-self-insert-command))
19727 (setq org-self-insert-command-undo-counter 1)
19728 (if (>= org-self-insert-command-undo-counter 20)
19729 (setq org-self-insert-command-undo-counter 1)
19730 (and (> org-self-insert-command-undo-counter 0)
19731 buffer-undo-list (listp buffer-undo-list)
19732 (not (cadr buffer-undo-list)) ; remove nil entry
19733 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19734 (setq org-self-insert-command-undo-counter
19735 (1+ org-self-insert-command-undo-counter))))))))
19737 (defun org-check-before-invisible-edit (kind)
19738 "Check is editing if kind KIND would be dangerous with invisible text around.
19739 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19740 ;; First, try to get out of here as quickly as possible, to reduce overhead
19741 (if (and org-catch-invisible-edits
19742 (or (not (boundp 'visible-mode)) (not visible-mode))
19743 (or (get-char-property (point) 'invisible)
19744 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19745 ;; OK, we need to take a closer look
19746 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19747 (invisible-before-point (if (bobp) nil (get-char-property
19748 (1- (point)) 'invisible)))
19749 (border-and-ok-direction
19751 ;; Check if we are acting predictably before invisible text
19752 (and invisible-at-point (not invisible-before-point)
19753 (memq kind '(insert delete-backward)))
19754 ;; Check if we are acting predictably after invisible text
19755 ;; This works not well, and I have turned it off. It seems
19756 ;; better to always show and stop after invisible text.
19757 ;; (and (not invisible-at-point) invisible-before-point
19758 ;; (memq kind '(insert delete)))
19760 (when (or (memq invisible-at-point '(outline org-hide-block t))
19761 (memq invisible-before-point '(outline org-hide-block t)))
19762 (if (eq org-catch-invisible-edits 'error)
19763 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19764 (if (and org-custom-properties-overlays
19765 (y-or-n-p "Display invisible properties in this buffer? "))
19766 (org-toggle-custom-properties-visibility)
19767 ;; Make the area visible
19768 (save-excursion
19769 (if invisible-before-point
19770 (goto-char (previous-single-char-property-change
19771 (point) 'invisible)))
19772 (show-subtree))
19773 (cond
19774 ((eq org-catch-invisible-edits 'show)
19775 ;; That's it, we do the edit after showing
19776 (message
19777 "Unfolding invisible region around point before editing")
19778 (sit-for 1))
19779 ((and (eq org-catch-invisible-edits 'smart)
19780 border-and-ok-direction)
19781 (message "Unfolding invisible region around point before editing"))
19783 ;; Don't do the edit, make the user repeat it in full visibility
19784 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19786 (defun org-fix-tags-on-the-fly ()
19787 (when (and (equal (char-after (point-at-bol)) ?*)
19788 (org-at-heading-p))
19789 (org-align-tags-here org-tags-column)))
19791 (defun org-delete-backward-char (N)
19792 "Like `delete-backward-char', insert whitespace at field end in tables.
19793 When deleting backwards, in tables this function will insert whitespace in
19794 front of the next \"|\" separator, to keep the table aligned. The table will
19795 still be marked for re-alignment if the field did fill the entire column,
19796 because, in this case the deletion might narrow the column."
19797 (interactive "p")
19798 (save-match-data
19799 (org-check-before-invisible-edit 'delete-backward)
19800 (if (and (org-table-p)
19801 (eq N 1)
19802 (string-match "|" (buffer-substring (point-at-bol) (point)))
19803 (looking-at ".*?|"))
19804 (let ((pos (point))
19805 (noalign (looking-at "[^|\n\r]* |"))
19806 (c org-table-may-need-update))
19807 (backward-delete-char N)
19808 (if (not overwrite-mode)
19809 (progn
19810 (skip-chars-forward "^|")
19811 (insert " ")
19812 (goto-char (1- pos))))
19813 ;; noalign: if there were two spaces at the end, this field
19814 ;; does not determine the width of the column.
19815 (if noalign (setq org-table-may-need-update c)))
19816 (backward-delete-char N)
19817 (org-fix-tags-on-the-fly))))
19819 (defun org-delete-char (N)
19820 "Like `delete-char', but insert whitespace at field end in tables.
19821 When deleting characters, in tables this function will insert whitespace in
19822 front of the next \"|\" separator, to keep the table aligned. The table will
19823 still be marked for re-alignment if the field did fill the entire column,
19824 because, in this case the deletion might narrow the column."
19825 (interactive "p")
19826 (save-match-data
19827 (org-check-before-invisible-edit 'delete)
19828 (if (and (org-table-p)
19829 (not (bolp))
19830 (not (= (char-after) ?|))
19831 (eq N 1))
19832 (if (looking-at ".*?|")
19833 (let ((pos (point))
19834 (noalign (looking-at "[^|\n\r]* |"))
19835 (c org-table-may-need-update))
19836 (replace-match
19837 (concat (substring (match-string 0) 1 -1) " |") nil t)
19838 (goto-char pos)
19839 ;; noalign: if there were two spaces at the end, this field
19840 ;; does not determine the width of the column.
19841 (if noalign (setq org-table-may-need-update c)))
19842 (delete-char N))
19843 (delete-char N)
19844 (org-fix-tags-on-the-fly))))
19846 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19847 (put 'org-self-insert-command 'delete-selection
19848 (lambda ()
19849 (not (run-hook-with-args-until-success
19850 'self-insert-uses-region-functions))))
19851 (put 'orgtbl-self-insert-command 'delete-selection
19852 (lambda ()
19853 (not (run-hook-with-args-until-success
19854 'self-insert-uses-region-functions))))
19855 (put 'org-delete-char 'delete-selection 'supersede)
19856 (put 'org-delete-backward-char 'delete-selection 'supersede)
19857 (put 'org-yank 'delete-selection 'yank)
19859 ;; Make `flyspell-mode' delay after some commands
19860 (put 'org-self-insert-command 'flyspell-delayed t)
19861 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19862 (put 'org-delete-char 'flyspell-delayed t)
19863 (put 'org-delete-backward-char 'flyspell-delayed t)
19865 ;; Make pabbrev-mode expand after org-mode commands
19866 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19867 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19869 (defun org-remap (map &rest commands)
19870 "In MAP, remap the functions given in COMMANDS.
19871 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19872 (let (new old)
19873 (while commands
19874 (setq old (pop commands) new (pop commands))
19875 (if (fboundp 'command-remapping)
19876 (org-defkey map (vector 'remap old) new)
19877 (substitute-key-definition old new map global-map)))))
19879 (defun org-transpose-words ()
19880 "Transpose words for Org.
19881 This uses the `org-mode-transpose-word-syntax-table' syntax
19882 table, which interprets characters in `org-emphasis-alist' as
19883 word constituents."
19884 (interactive)
19885 (with-syntax-table org-mode-transpose-word-syntax-table
19886 (call-interactively 'transpose-words)))
19887 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19889 (when (eq org-enable-table-editor 'optimized)
19890 ;; If the user wants maximum table support, we need to hijack
19891 ;; some standard editing functions
19892 (org-remap org-mode-map
19893 'self-insert-command 'org-self-insert-command
19894 'delete-char 'org-delete-char
19895 'delete-backward-char 'org-delete-backward-char)
19896 (org-defkey org-mode-map "|" 'org-force-self-insert))
19898 (defvar org-ctrl-c-ctrl-c-hook nil
19899 "Hook for functions attaching themselves to `C-c C-c'.
19901 This can be used to add additional functionality to the C-c C-c
19902 key which executes context-dependent commands. This hook is run
19903 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19904 run after the last test.
19906 Each function will be called with no arguments. The function
19907 must check if the context is appropriate for it to act. If yes,
19908 it should do its thing and then return a non-nil value. If the
19909 context is wrong, just do nothing and return nil.")
19911 (defvar org-ctrl-c-ctrl-c-final-hook nil
19912 "Hook for functions attaching themselves to `C-c C-c'.
19914 This can be used to add additional functionality to the C-c C-c
19915 key which executes context-dependent commands. This hook is run
19916 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19917 before the first test.
19919 Each function will be called with no arguments. The function
19920 must check if the context is appropriate for it to act. If yes,
19921 it should do its thing and then return a non-nil value. If the
19922 context is wrong, just do nothing and return nil.")
19924 (defvar org-tab-first-hook nil
19925 "Hook for functions to attach themselves to TAB.
19926 See `org-ctrl-c-ctrl-c-hook' for more information.
19927 This hook runs as the first action when TAB is pressed, even before
19928 `org-cycle' messes around with the `outline-regexp' to cater for
19929 inline tasks and plain list item folding.
19930 If any function in this hook returns t, any other actions that
19931 would have been caused by TAB (such as table field motion or visibility
19932 cycling) will not occur.")
19934 (defvar org-tab-after-check-for-table-hook nil
19935 "Hook for functions to attach themselves to TAB.
19936 See `org-ctrl-c-ctrl-c-hook' for more information.
19937 This hook runs after it has been established that the cursor is not in a
19938 table, but before checking if the cursor is in a headline or if global cycling
19939 should be done.
19940 If any function in this hook returns t, not other actions like visibility
19941 cycling will be done.")
19943 (defvar org-tab-after-check-for-cycling-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 after it has been established that not table field motion and
19947 not visibility should be done because of current context. This is probably
19948 the place where a package like yasnippets can hook in.")
19950 (defvar org-tab-before-tab-emulation-hook nil
19951 "Hook for functions to attach themselves to TAB.
19952 See `org-ctrl-c-ctrl-c-hook' for more information.
19953 This hook runs after every other options for TAB have been exhausted, but
19954 before indentation and \t insertion takes place.")
19956 (defvar org-metaleft-hook nil
19957 "Hook for functions attaching themselves to `M-left'.
19958 See `org-ctrl-c-ctrl-c-hook' for more information.")
19959 (defvar org-metaright-hook nil
19960 "Hook for functions attaching themselves to `M-right'.
19961 See `org-ctrl-c-ctrl-c-hook' for more information.")
19962 (defvar org-metaup-hook nil
19963 "Hook for functions attaching themselves to `M-up'.
19964 See `org-ctrl-c-ctrl-c-hook' for more information.")
19965 (defvar org-metadown-hook nil
19966 "Hook for functions attaching themselves to `M-down'.
19967 See `org-ctrl-c-ctrl-c-hook' for more information.")
19968 (defvar org-shiftmetaleft-hook nil
19969 "Hook for functions attaching themselves to `M-S-left'.
19970 See `org-ctrl-c-ctrl-c-hook' for more information.")
19971 (defvar org-shiftmetaright-hook nil
19972 "Hook for functions attaching themselves to `M-S-right'.
19973 See `org-ctrl-c-ctrl-c-hook' for more information.")
19974 (defvar org-shiftmetaup-hook nil
19975 "Hook for functions attaching themselves to `M-S-up'.
19976 See `org-ctrl-c-ctrl-c-hook' for more information.")
19977 (defvar org-shiftmetadown-hook nil
19978 "Hook for functions attaching themselves to `M-S-down'.
19979 See `org-ctrl-c-ctrl-c-hook' for more information.")
19980 (defvar org-metareturn-hook nil
19981 "Hook for functions attaching themselves to `M-RET'.
19982 See `org-ctrl-c-ctrl-c-hook' for more information.")
19983 (defvar org-shiftup-hook nil
19984 "Hook for functions attaching themselves to `S-up'.
19985 See `org-ctrl-c-ctrl-c-hook' for more information.")
19986 (defvar org-shiftup-final-hook nil
19987 "Hook for functions attaching themselves to `S-up'.
19988 This one runs after all other options except shift-select have been excluded.
19989 See `org-ctrl-c-ctrl-c-hook' for more information.")
19990 (defvar org-shiftdown-hook nil
19991 "Hook for functions attaching themselves to `S-down'.
19992 See `org-ctrl-c-ctrl-c-hook' for more information.")
19993 (defvar org-shiftdown-final-hook nil
19994 "Hook for functions attaching themselves to `S-down'.
19995 This one runs after all other options except shift-select have been excluded.
19996 See `org-ctrl-c-ctrl-c-hook' for more information.")
19997 (defvar org-shiftleft-hook nil
19998 "Hook for functions attaching themselves to `S-left'.
19999 See `org-ctrl-c-ctrl-c-hook' for more information.")
20000 (defvar org-shiftleft-final-hook nil
20001 "Hook for functions attaching themselves to `S-left'.
20002 This one runs after all other options except shift-select have been excluded.
20003 See `org-ctrl-c-ctrl-c-hook' for more information.")
20004 (defvar org-shiftright-hook nil
20005 "Hook for functions attaching themselves to `S-right'.
20006 See `org-ctrl-c-ctrl-c-hook' for more information.")
20007 (defvar org-shiftright-final-hook nil
20008 "Hook for functions attaching themselves to `S-right'.
20009 This one runs after all other options except shift-select have been excluded.
20010 See `org-ctrl-c-ctrl-c-hook' for more information.")
20012 (defun org-modifier-cursor-error ()
20013 "Throw an error, a modified cursor command was applied in wrong context."
20014 (user-error "This command is active in special context like tables, headlines or items"))
20016 (defun org-shiftselect-error ()
20017 "Throw an error because Shift-Cursor command was applied in wrong context."
20018 (if (and (boundp 'shift-select-mode) shift-select-mode)
20019 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20020 (user-error "This command works only in special context like headlines or timestamps")))
20022 (defun org-call-for-shift-select (cmd)
20023 (let ((this-command-keys-shift-translated t))
20024 (call-interactively cmd)))
20026 (defun org-shifttab (&optional arg)
20027 "Global visibility cycling or move to previous table field.
20028 Call `org-table-previous-field' within a table.
20029 When ARG is nil, cycle globally through visibility states.
20030 When ARG is a numeric prefix, show contents of this level."
20031 (interactive "P")
20032 (cond
20033 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20034 ((integerp arg)
20035 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20036 (message "Content view to level: %d" arg)
20037 (org-content (prefix-numeric-value arg2))
20038 (org-cycle-show-empty-lines t)
20039 (setq org-cycle-global-status 'overview)))
20040 (t (call-interactively 'org-global-cycle))))
20042 (defun org-shiftmetaleft ()
20043 "Promote subtree or delete table column.
20044 Calls `org-promote-subtree', `org-outdent-item-tree', or
20045 `org-table-delete-column', depending on context. See the
20046 individual commands for more information."
20047 (interactive)
20048 (cond
20049 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20050 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20051 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20052 ((if (not (org-region-active-p)) (org-at-item-p)
20053 (save-excursion (goto-char (region-beginning))
20054 (org-at-item-p)))
20055 (call-interactively 'org-outdent-item-tree))
20056 (t (org-modifier-cursor-error))))
20058 (defun org-shiftmetaright ()
20059 "Demote subtree or insert table column.
20060 Calls `org-demote-subtree', `org-indent-item-tree', or
20061 `org-table-insert-column', depending on context. See the
20062 individual commands for more information."
20063 (interactive)
20064 (cond
20065 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20066 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20067 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20068 ((if (not (org-region-active-p)) (org-at-item-p)
20069 (save-excursion (goto-char (region-beginning))
20070 (org-at-item-p)))
20071 (call-interactively 'org-indent-item-tree))
20072 (t (org-modifier-cursor-error))))
20074 (defun org-shiftmetaup (&optional arg)
20075 "Drag the line at point up.
20076 In a table, kill the current row.
20077 On a clock timestamp, update the value of the timestamp like `S-<up>'
20078 but also adjust the previous clocked item in the clock history.
20079 Everywhere else, drag the line at point up."
20080 (interactive "P")
20081 (cond
20082 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20083 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20084 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20085 (call-interactively 'org-timestamp-up)))
20086 (t (call-interactively 'org-drag-line-backward))))
20088 (defun org-shiftmetadown (&optional arg)
20089 "Drag the line at point down.
20090 In a table, insert an empty row at the current line.
20091 On a clock timestamp, update the value of the timestamp like `S-<down>'
20092 but also adjust the previous clocked item in the clock history.
20093 Everywhere else, drag the line at point down."
20094 (interactive "P")
20095 (cond
20096 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20097 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20098 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20099 (call-interactively 'org-timestamp-down)))
20100 (t (call-interactively 'org-drag-line-forward))))
20102 (defsubst org-hidden-tree-error ()
20103 (user-error
20104 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20106 (defun org-metaleft (&optional arg)
20107 "Promote heading or move table column to left.
20108 Calls `org-do-promote' or `org-table-move-column', depending on context.
20109 With no specific context, calls the Emacs default `backward-word'.
20110 See the individual commands for more information."
20111 (interactive "P")
20112 (cond
20113 ((run-hook-with-args-until-success 'org-metaleft-hook))
20114 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20115 ((org-with-limited-levels
20116 (or (org-at-heading-p)
20117 (and (org-region-active-p)
20118 (save-excursion
20119 (goto-char (region-beginning))
20120 (org-at-heading-p)))))
20121 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20122 (call-interactively 'org-do-promote))
20123 ;; At an inline task.
20124 ((org-at-heading-p)
20125 (call-interactively 'org-inlinetask-promote))
20126 ((or (org-at-item-p)
20127 (and (org-region-active-p)
20128 (save-excursion
20129 (goto-char (region-beginning))
20130 (org-at-item-p))))
20131 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20132 (call-interactively 'org-outdent-item))
20133 (t (call-interactively 'backward-word))))
20135 (defun org-metaright (&optional arg)
20136 "Demote a subtree, a list item or move table column to right.
20137 In front of a drawer or a block keyword, indent it correctly.
20138 With no specific context, calls the Emacs default `forward-word'.
20139 See the individual commands for more information."
20140 (interactive "P")
20141 (cond
20142 ((run-hook-with-args-until-success 'org-metaright-hook))
20143 ((org-at-table-p) (call-interactively 'org-table-move-column))
20144 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20145 ((org-at-block-p) (call-interactively 'org-indent-block))
20146 ((org-with-limited-levels
20147 (or (org-at-heading-p)
20148 (and (org-region-active-p)
20149 (save-excursion
20150 (goto-char (region-beginning))
20151 (org-at-heading-p)))))
20152 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20153 (call-interactively 'org-do-demote))
20154 ;; At an inline task.
20155 ((org-at-heading-p)
20156 (call-interactively 'org-inlinetask-demote))
20157 ((or (org-at-item-p)
20158 (and (org-region-active-p)
20159 (save-excursion
20160 (goto-char (region-beginning))
20161 (org-at-item-p))))
20162 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20163 (call-interactively 'org-indent-item))
20164 (t (call-interactively 'forward-word))))
20166 (defun org-check-for-hidden (what)
20167 "Check if there are hidden headlines/items in the current visual line.
20168 WHAT can be either `headlines' or `items'. If the current line is
20169 an outline or item heading and it has a folded subtree below it,
20170 this function returns t, nil otherwise."
20171 (let ((re (cond
20172 ((eq what 'headlines) org-outline-regexp-bol)
20173 ((eq what 'items) (org-item-beginning-re))
20174 (t (error "This should not happen"))))
20175 beg end)
20176 (save-excursion
20177 (catch 'exit
20178 (unless (org-region-active-p)
20179 (setq beg (point-at-bol))
20180 (beginning-of-line 2)
20181 (while (and (not (eobp)) ;; this is like `next-line'
20182 (get-char-property (1- (point)) 'invisible))
20183 (beginning-of-line 2))
20184 (setq end (point))
20185 (goto-char beg)
20186 (goto-char (point-at-eol))
20187 (setq end (max end (point)))
20188 (while (re-search-forward re end t)
20189 (if (get-char-property (match-beginning 0) 'invisible)
20190 (throw 'exit t))))
20191 nil))))
20193 (defun org-metaup (&optional arg)
20194 "Move subtree up or move table row up.
20195 Calls `org-move-subtree-up' or `org-table-move-row' or
20196 `org-move-item-up', depending on context. See the individual commands
20197 for more information."
20198 (interactive "P")
20199 (cond
20200 ((run-hook-with-args-until-success 'org-metaup-hook))
20201 ((org-region-active-p)
20202 (let* ((a (min (region-beginning) (region-end)))
20203 (b (1- (max (region-beginning) (region-end))))
20204 (c (save-excursion (goto-char a)
20205 (move-beginning-of-line 0)))
20206 (d (save-excursion (goto-char a)
20207 (move-end-of-line 0) (point))))
20208 (transpose-regions a b c d)
20209 (goto-char c)))
20210 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20211 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20212 ((org-at-item-p) (call-interactively 'org-move-item-up))
20213 (t (org-drag-element-backward))))
20215 (defun org-metadown (&optional arg)
20216 "Move subtree down or move table row down.
20217 Calls `org-move-subtree-down' or `org-table-move-row' or
20218 `org-move-item-down', depending on context. See the individual
20219 commands for more information."
20220 (interactive "P")
20221 (cond
20222 ((run-hook-with-args-until-success 'org-metadown-hook))
20223 ((org-region-active-p)
20224 (let* ((a (min (region-beginning) (region-end)))
20225 (b (max (region-beginning) (region-end)))
20226 (c (save-excursion (goto-char b)
20227 (move-beginning-of-line 1)))
20228 (d (save-excursion (goto-char b)
20229 (move-end-of-line 1) (1+ (point)))))
20230 (transpose-regions a b c d)
20231 (goto-char d)))
20232 ((org-at-table-p) (call-interactively 'org-table-move-row))
20233 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20234 ((org-at-item-p) (call-interactively 'org-move-item-down))
20235 (t (org-drag-element-forward))))
20237 (defun org-shiftup (&optional arg)
20238 "Increase item in timestamp or increase priority of current headline.
20239 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20240 depending on context. See the individual commands for more information."
20241 (interactive "P")
20242 (cond
20243 ((run-hook-with-args-until-success 'org-shiftup-hook))
20244 ((and org-support-shift-select (org-region-active-p))
20245 (org-call-for-shift-select 'previous-line))
20246 ((org-at-timestamp-p t)
20247 (call-interactively (if org-edit-timestamp-down-means-later
20248 'org-timestamp-down 'org-timestamp-up)))
20249 ((and (not (eq org-support-shift-select 'always))
20250 org-enable-priority-commands
20251 (org-at-heading-p))
20252 (call-interactively 'org-priority-up))
20253 ((and (not org-support-shift-select) (org-at-item-p))
20254 (call-interactively 'org-previous-item))
20255 ((org-clocktable-try-shift 'up arg))
20256 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20257 (org-support-shift-select
20258 (org-call-for-shift-select 'previous-line))
20259 (t (org-shiftselect-error))))
20261 (defun org-shiftdown (&optional arg)
20262 "Decrease item in timestamp or decrease priority of current headline.
20263 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20264 depending on context. See the individual commands for more information."
20265 (interactive "P")
20266 (cond
20267 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20268 ((and org-support-shift-select (org-region-active-p))
20269 (org-call-for-shift-select 'next-line))
20270 ((org-at-timestamp-p t)
20271 (call-interactively (if org-edit-timestamp-down-means-later
20272 'org-timestamp-up 'org-timestamp-down)))
20273 ((and (not (eq org-support-shift-select 'always))
20274 org-enable-priority-commands
20275 (org-at-heading-p))
20276 (call-interactively 'org-priority-down))
20277 ((and (not org-support-shift-select) (org-at-item-p))
20278 (call-interactively 'org-next-item))
20279 ((org-clocktable-try-shift 'down arg))
20280 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20281 (org-support-shift-select
20282 (org-call-for-shift-select 'next-line))
20283 (t (org-shiftselect-error))))
20285 (defun org-shiftright (&optional arg)
20286 "Cycle the thing at point or in the current line, depending on context.
20287 Depending on context, this does one of the following:
20289 - switch a timestamp at point one day into the future
20290 - on a headline, switch to the next TODO keyword.
20291 - on an item, switch entire list to the next bullet type
20292 - on a property line, switch to the next allowed value
20293 - on a clocktable definition line, move time block into the future"
20294 (interactive "P")
20295 (cond
20296 ((run-hook-with-args-until-success 'org-shiftright-hook))
20297 ((and org-support-shift-select (org-region-active-p))
20298 (org-call-for-shift-select 'forward-char))
20299 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20300 ((and (not (eq org-support-shift-select 'always))
20301 (org-at-heading-p))
20302 (let ((org-inhibit-logging
20303 (not org-treat-S-cursor-todo-selection-as-state-change))
20304 (org-inhibit-blocking
20305 (not org-treat-S-cursor-todo-selection-as-state-change)))
20306 (org-call-with-arg 'org-todo 'right)))
20307 ((or (and org-support-shift-select
20308 (not (eq org-support-shift-select 'always))
20309 (org-at-item-bullet-p))
20310 (and (not org-support-shift-select) (org-at-item-p)))
20311 (org-call-with-arg 'org-cycle-list-bullet nil))
20312 ((and (not (eq org-support-shift-select 'always))
20313 (org-at-property-p))
20314 (call-interactively 'org-property-next-allowed-value))
20315 ((org-clocktable-try-shift 'right arg))
20316 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20317 (org-support-shift-select
20318 (org-call-for-shift-select 'forward-char))
20319 (t (org-shiftselect-error))))
20321 (defun org-shiftleft (&optional arg)
20322 "Cycle the thing at point or in the current line, depending on context.
20323 Depending on context, this does one of the following:
20325 - switch a timestamp at point one day into the past
20326 - on a headline, switch to the previous TODO keyword.
20327 - on an item, switch entire list to the previous bullet type
20328 - on a property line, switch to the previous allowed value
20329 - on a clocktable definition line, move time block into the past"
20330 (interactive "P")
20331 (cond
20332 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20333 ((and org-support-shift-select (org-region-active-p))
20334 (org-call-for-shift-select 'backward-char))
20335 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20336 ((and (not (eq org-support-shift-select 'always))
20337 (org-at-heading-p))
20338 (let ((org-inhibit-logging
20339 (not org-treat-S-cursor-todo-selection-as-state-change))
20340 (org-inhibit-blocking
20341 (not org-treat-S-cursor-todo-selection-as-state-change)))
20342 (org-call-with-arg 'org-todo 'left)))
20343 ((or (and org-support-shift-select
20344 (not (eq org-support-shift-select 'always))
20345 (org-at-item-bullet-p))
20346 (and (not org-support-shift-select) (org-at-item-p)))
20347 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20348 ((and (not (eq org-support-shift-select 'always))
20349 (org-at-property-p))
20350 (call-interactively 'org-property-previous-allowed-value))
20351 ((org-clocktable-try-shift 'left arg))
20352 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20353 (org-support-shift-select
20354 (org-call-for-shift-select 'backward-char))
20355 (t (org-shiftselect-error))))
20357 (defun org-shiftcontrolright ()
20358 "Switch to next TODO set."
20359 (interactive)
20360 (cond
20361 ((and org-support-shift-select (org-region-active-p))
20362 (org-call-for-shift-select 'forward-word))
20363 ((and (not (eq org-support-shift-select 'always))
20364 (org-at-heading-p))
20365 (org-call-with-arg 'org-todo 'nextset))
20366 (org-support-shift-select
20367 (org-call-for-shift-select 'forward-word))
20368 (t (org-shiftselect-error))))
20370 (defun org-shiftcontrolleft ()
20371 "Switch to previous TODO set."
20372 (interactive)
20373 (cond
20374 ((and org-support-shift-select (org-region-active-p))
20375 (org-call-for-shift-select 'backward-word))
20376 ((and (not (eq org-support-shift-select 'always))
20377 (org-at-heading-p))
20378 (org-call-with-arg 'org-todo 'previousset))
20379 (org-support-shift-select
20380 (org-call-for-shift-select 'backward-word))
20381 (t (org-shiftselect-error))))
20383 (defun org-shiftcontrolup (&optional n)
20384 "Change timestamps synchronously up in CLOCK log lines.
20385 Optional argument N tells to change by that many units."
20386 (interactive "P")
20387 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20388 (let (org-support-shift-select)
20389 (org-clock-timestamps-up n))
20390 (user-error "Not at a clock log")))
20392 (defun org-shiftcontroldown (&optional n)
20393 "Change timestamps synchronously down in CLOCK log lines.
20394 Optional argument N tells to change by that many units."
20395 (interactive "P")
20396 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20397 (let (org-support-shift-select)
20398 (org-clock-timestamps-down n))
20399 (user-error "Not at a clock log")))
20401 (defun org-increase-number-at-point (&optional inc)
20402 "Increment the number at point.
20403 With an optional prefix numeric argument INC, increment using
20404 this numeric value."
20405 (interactive "p")
20406 (if (not (number-at-point))
20407 (user-error "Not on a number")
20408 (unless inc (setq inc 1))
20409 (let ((pos (point))
20410 (beg (skip-chars-backward "-+^/*0-9eE."))
20411 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20412 (setq nap (buffer-substring-no-properties
20413 (+ pos beg) (+ pos beg end)))
20414 (delete-region (+ pos beg) (+ pos beg end))
20415 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20416 (when (org-at-table-p)
20417 (org-table-align)
20418 (org-table-end-of-field 1))))
20420 (defun org-decrease-number-at-point (&optional inc)
20421 "Decrement the number at point.
20422 With an optional prefix numeric argument INC, decrement using
20423 this numeric value."
20424 (interactive "p")
20425 (org-increase-number-at-point (- inc)))
20427 (defun org-ctrl-c-ret ()
20428 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20429 (interactive)
20430 (cond
20431 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20432 (t (call-interactively 'org-insert-heading))))
20434 (defun org-find-visible ()
20435 (let ((s (point)))
20436 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20437 (get-char-property s 'invisible)))
20439 (defun org-find-invisible ()
20440 (let ((s (point)))
20441 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20442 (not (get-char-property s 'invisible))))
20445 (defun org-copy-visible (beg end)
20446 "Copy the visible parts of the region."
20447 (interactive "r")
20448 (let (snippets s)
20449 (save-excursion
20450 (save-restriction
20451 (narrow-to-region beg end)
20452 (setq s (goto-char (point-min)))
20453 (while (not (= (point) (point-max)))
20454 (goto-char (org-find-invisible))
20455 (push (buffer-substring s (point)) snippets)
20456 (setq s (goto-char (org-find-visible))))))
20457 (kill-new (apply 'concat (nreverse snippets)))))
20459 (defun org-copy-special ()
20460 "Copy region in table or copy current subtree.
20461 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20462 See the individual commands for more information."
20463 (interactive)
20464 (call-interactively
20465 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20467 (defun org-cut-special ()
20468 "Cut region in table or cut current subtree.
20469 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20470 See the individual commands for more information."
20471 (interactive)
20472 (call-interactively
20473 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20475 (defun org-paste-special (arg)
20476 "Paste rectangular region into table, or past subtree relative to level.
20477 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20478 See the individual commands for more information."
20479 (interactive "P")
20480 (if (org-at-table-p)
20481 (org-table-paste-rectangle)
20482 (org-paste-subtree arg)))
20484 (defsubst org-in-fixed-width-region-p ()
20485 "Is point in a fixed-width region?"
20486 (save-match-data
20487 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20489 (defun org-edit-special (&optional arg)
20490 "Call a special editor for the element at point.
20491 When at a table, call the formula editor with `org-table-edit-formulas'.
20492 When in a source code block, call `org-edit-src-code'.
20493 When in a fixed-width region, call `org-edit-fixed-width-region'.
20494 When at an #+INCLUDE keyword, visit the included file.
20495 On a link, call `ffap' to visit the link at point.
20496 Otherwise, return a user error."
20497 (interactive "P")
20498 (let ((element (org-element-at-point)))
20499 (assert (not buffer-read-only) nil
20500 "Buffer is read-only: %s" (buffer-name))
20501 (case (org-element-type element)
20502 (src-block
20503 (if (not arg) (org-edit-src-code)
20504 (let* ((info (org-babel-get-src-block-info))
20505 (lang (nth 0 info))
20506 (params (nth 2 info))
20507 (session (cdr (assq :session params))))
20508 (if (not session) (org-edit-src-code)
20509 ;; At a src-block with a session and function called with
20510 ;; an ARG: switch to the buffer related to the inferior
20511 ;; process.
20512 (switch-to-buffer
20513 (funcall (intern (concat "org-babel-prep-session:" lang))
20514 session params))))))
20515 (keyword
20516 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20517 (find-file-other-window
20518 (org-remove-double-quotes
20519 (car (org-split-string (org-element-property :value element)))))
20520 (user-error "No special environment to edit here")))
20521 (table
20522 (if (eq (org-element-property :type element) 'table.el)
20523 (org-edit-src-code)
20524 (call-interactively 'org-table-edit-formulas)))
20525 ;; Only Org tables contain `table-row' type elements.
20526 (table-row (call-interactively 'org-table-edit-formulas))
20527 ((example-block export-block) (org-edit-src-code))
20528 (fixed-width (org-edit-fixed-width-region))
20529 (otherwise
20530 ;; No notable element at point. Though, we may be at a link,
20531 ;; which is an object. Thus, scan deeper.
20532 (if (eq (org-element-type (org-element-context element)) 'link)
20533 (call-interactively 'ffap)
20534 (user-error "No special environment to edit here"))))))
20536 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20537 (defun org-ctrl-c-ctrl-c (&optional arg)
20538 "Set tags in headline, or update according to changed information at point.
20540 This command does many different things, depending on context:
20542 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20543 this is what we do.
20545 - If the cursor is on a statistics cookie, update it.
20547 - If the cursor is in a headline, prompt for tags and insert them
20548 into the current line, aligned to `org-tags-column'. When called
20549 with prefix arg, realign all tags in the current buffer.
20551 - If the cursor is in one of the special #+KEYWORD lines, this
20552 triggers scanning the buffer for these lines and updating the
20553 information.
20555 - If the cursor is inside a table, realign the table. This command
20556 works even if the automatic table editor has been turned off.
20558 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20559 the entire table.
20561 - If the cursor is at a footnote reference or definition, jump to
20562 the corresponding definition or references, respectively.
20564 - If the cursor is a the beginning of a dynamic block, update it.
20566 - If the current buffer is a capture buffer, close note and file it.
20568 - If the cursor is on a <<<target>>>, update radio targets and
20569 corresponding links in this buffer.
20571 - If the cursor is on a numbered item in a plain list, renumber the
20572 ordered list.
20574 - If the cursor is on a checkbox, toggle it.
20576 - If the cursor is on a code block, evaluate it. The variable
20577 `org-confirm-babel-evaluate' can be used to control prompting
20578 before code block evaluation, by default every code block
20579 evaluation requires confirmation. Code block evaluation can be
20580 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20581 (interactive "P")
20582 (cond
20583 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20584 org-occur-highlights)
20585 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20586 (org-remove-occur-highlights)
20587 (message "Temporary highlights/overlays removed from current buffer"))
20588 ((and (local-variable-p 'org-finish-function (current-buffer))
20589 (fboundp org-finish-function))
20590 (funcall org-finish-function))
20591 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20593 (let* ((context (org-element-context)) (type (org-element-type context)))
20594 ;; Test if point is within a blank line.
20595 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20596 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20597 (user-error "C-c C-c can do nothing useful at this location"))
20598 (case type
20599 ;; When at a link, act according to the parent instead.
20600 (link (setq context (org-element-property :parent context))
20601 (setq type (org-element-type context)))
20602 ;; Unsupported object types: refer to the first supported
20603 ;; element or object containing it.
20604 ((bold code entity export-snippet inline-babel-call inline-src-block
20605 italic latex-fragment line-break macro strike-through subscript
20606 superscript underline verbatim)
20607 (while (and (setq context (org-element-property :parent context))
20608 (not (memq (setq type (org-element-type context))
20609 '(radio-target paragraph verse-block
20610 table-cell)))))))
20611 ;; For convenience: at the first line of a paragraph on the
20612 ;; same line as an item, apply function on that item instead.
20613 (when (eq type 'paragraph)
20614 (let ((parent (org-element-property :parent context)))
20615 (when (and (eq (org-element-type parent) 'item)
20616 (= (point-at-bol) (org-element-property :begin parent)))
20617 (setq context parent type 'item))))
20618 ;; Act according to type of element or object at point.
20619 (case type
20620 (clock (org-clock-update-time-maybe))
20621 (dynamic-block
20622 (save-excursion
20623 (goto-char (org-element-property :post-affiliated context))
20624 (org-update-dblock)))
20625 (footnote-definition
20626 (goto-char (org-element-property :post-affiliated context))
20627 (call-interactively 'org-footnote-action))
20628 (footnote-reference (call-interactively 'org-footnote-action))
20629 ((headline inlinetask)
20630 (save-excursion (goto-char (org-element-property :begin context))
20631 (call-interactively 'org-set-tags)))
20632 (item
20633 ;; At an item: a double C-u set checkbox to "[-]"
20634 ;; unconditionally, whereas a single one will toggle its
20635 ;; presence. Without an universal argument, if the item
20636 ;; has a checkbox, toggle it. Otherwise repair the list.
20637 (let* ((box (org-element-property :checkbox context))
20638 (struct (org-element-property :structure context))
20639 (old-struct (copy-tree struct))
20640 (parents (org-list-parents-alist struct))
20641 (prevs (org-list-prevs-alist struct))
20642 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20643 (org-list-set-checkbox
20644 (org-element-property :begin context) struct
20645 (cond ((equal arg '(16)) "[-]")
20646 ((and (not box) (equal arg '(4))) "[ ]")
20647 ((or (not box) (equal arg '(4))) nil)
20648 ((eq box 'on) "[ ]")
20649 (t "[X]")))
20650 ;; Mimic `org-list-write-struct' but with grabbing
20651 ;; a return value from `org-list-struct-fix-box'.
20652 (org-list-struct-fix-ind struct parents 2)
20653 (org-list-struct-fix-item-end struct)
20654 (org-list-struct-fix-bul struct prevs)
20655 (org-list-struct-fix-ind struct parents)
20656 (let ((block-item
20657 (org-list-struct-fix-box struct parents prevs orderedp)))
20658 (if (and box (equal struct old-struct))
20659 (if (equal arg '(16))
20660 (message "Checkboxes already reset")
20661 (user-error "Cannot toggle this checkbox: %s"
20662 (if (eq box 'on)
20663 "all subitems checked"
20664 "unchecked subitems")))
20665 (org-list-struct-apply-struct struct old-struct)
20666 (org-update-checkbox-count-maybe))
20667 (when block-item
20668 (message "Checkboxes were removed due to empty box at line %d"
20669 (org-current-line block-item))))))
20670 (keyword
20671 (let ((org-inhibit-startup-visibility-stuff t)
20672 (org-startup-align-all-tables nil))
20673 (when (boundp 'org-table-coordinate-overlays)
20674 (mapc 'delete-overlay org-table-coordinate-overlays)
20675 (setq org-table-coordinate-overlays nil))
20676 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20677 (message "Local setup has been refreshed"))
20678 (plain-list
20679 ;; At a plain list, with a double C-u argument, set
20680 ;; checkboxes of each item to "[-]", whereas a single one
20681 ;; will toggle their presence according to the state of the
20682 ;; first item in the list. Without an argument, repair the
20683 ;; list.
20684 (let* ((begin (org-element-property :contents-begin context))
20685 (beginm (move-marker (make-marker) begin))
20686 (struct (org-element-property :structure context))
20687 (old-struct (copy-tree struct))
20688 (first-box (save-excursion
20689 (goto-char begin)
20690 (looking-at org-list-full-item-re)
20691 (match-string-no-properties 3)))
20692 (new-box (cond ((equal arg '(16)) "[-]")
20693 ((equal arg '(4)) (unless first-box "[ ]"))
20694 ((equal first-box "[X]") "[ ]")
20695 (t "[X]"))))
20696 (cond
20697 (arg
20698 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20699 (org-list-get-all-items
20700 begin struct (org-list-prevs-alist struct))))
20701 ((and first-box (eq (point) begin))
20702 ;; For convenience, when point is at bol on the first
20703 ;; item of the list and no argument is provided, simply
20704 ;; toggle checkbox of that item, if any.
20705 (org-list-set-checkbox begin struct new-box)))
20706 (org-list-write-struct
20707 struct (org-list-parents-alist struct) old-struct)
20708 (org-update-checkbox-count-maybe)
20709 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20710 ((property-drawer node-property)
20711 (call-interactively 'org-property-action))
20712 ((radio-target target)
20713 (call-interactively 'org-update-radio-target-regexp))
20714 (statistics-cookie
20715 (call-interactively 'org-update-statistics-cookies))
20716 ((table table-cell table-row)
20717 ;; At a table, recalculate every field and align it. Also
20718 ;; send the table if necessary. If the table has
20719 ;; a `table.el' type, just give up. At a table row or
20720 ;; cell, maybe recalculate line but always align table.
20721 (if (eq (org-element-property :type context) 'table.el)
20722 (message "Use C-c ' to edit table.el tables")
20723 (let ((org-enable-table-editor t))
20724 (if (or (eq type 'table)
20725 ;; Check if point is at a TBLFM line.
20726 (and (eq type 'table-row)
20727 (= (point) (org-element-property :end context))))
20728 (save-excursion
20729 (if (org-at-TBLFM-p)
20730 (progn (require 'org-table)
20731 (org-table-calc-current-TBLFM))
20732 (goto-char (org-element-property :contents-begin context))
20733 (org-call-with-arg 'org-table-recalculate (or arg t))
20734 (orgtbl-send-table 'maybe)))
20735 (org-table-maybe-eval-formula)
20736 (cond (arg (call-interactively 'org-table-recalculate))
20737 ((org-table-maybe-recalculate-line))
20738 (t (org-table-align)))))))
20739 (timestamp (org-timestamp-change 0 'day))
20740 (otherwise
20741 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20742 (user-error
20743 "C-c C-c can do nothing useful at this location")))))))))
20745 (defun org-mode-restart ()
20746 (interactive)
20747 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20748 (funcall major-mode)
20749 (hack-local-variables)
20750 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20751 (org-indent-mode -1)))
20752 (message "%s restarted" major-mode))
20754 (defun org-kill-note-or-show-branches ()
20755 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20756 (interactive)
20757 (if (not org-finish-function)
20758 (progn
20759 (hide-subtree)
20760 (call-interactively 'show-branches))
20761 (let ((org-note-abort t))
20762 (funcall org-finish-function))))
20764 (defun org-open-line (n)
20765 "Insert a new row in tables, call `open-line' elsewhere.
20766 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20767 (interactive "*p")
20768 (cond
20769 ((not org-special-ctrl-o)
20770 (open-line n))
20771 ((org-at-table-p)
20772 (org-table-insert-row))
20774 (open-line n))))
20776 (defun org-return (&optional indent)
20777 "Goto next table row or insert a newline.
20778 Calls `org-table-next-row' or `newline', depending on context.
20779 See the individual commands for more information."
20780 (interactive)
20781 (let (org-ts-what)
20782 (cond
20783 ((or (bobp) (org-in-src-block-p))
20784 (if indent (newline-and-indent) (newline)))
20785 ((org-at-table-p)
20786 (org-table-justify-field-maybe)
20787 (call-interactively 'org-table-next-row))
20788 ;; when `newline-and-indent' is called within a list, make sure
20789 ;; text moved stays inside the item.
20790 ((and (org-in-item-p) indent)
20791 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20792 (progn
20793 (save-match-data (newline))
20794 (org-indent-line-to (length (match-string 0))))
20795 (let ((ind (org-get-indentation)))
20796 (newline)
20797 (if (org-looking-back org-list-end-re)
20798 (org-indent-line)
20799 (org-indent-line-to ind)))))
20800 ((and org-return-follows-link
20801 (org-at-timestamp-p t)
20802 (not (eq org-ts-what 'after)))
20803 (org-follow-timestamp-link))
20804 ((and org-return-follows-link
20805 (let ((tprop (get-text-property (point) 'face)))
20806 (or (eq tprop 'org-link)
20807 (and (listp tprop) (memq 'org-link tprop)))))
20808 (call-interactively 'org-open-at-point))
20809 ((and (org-at-heading-p)
20810 (looking-at
20811 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20812 (org-show-entry)
20813 (end-of-line 1)
20814 (newline))
20815 (t (if indent (newline-and-indent) (newline))))))
20817 (defun org-return-indent ()
20818 "Goto next table row or insert a newline and indent.
20819 Calls `org-table-next-row' or `newline-and-indent', depending on
20820 context. See the individual commands for more information."
20821 (interactive)
20822 (org-return t))
20824 (defun org-ctrl-c-star ()
20825 "Compute table, or change heading status of lines.
20826 Calls `org-table-recalculate' or `org-toggle-heading',
20827 depending on context."
20828 (interactive)
20829 (cond
20830 ((org-at-table-p)
20831 (call-interactively 'org-table-recalculate))
20833 ;; Convert all lines in region to list items
20834 (call-interactively 'org-toggle-heading))))
20836 (defun org-ctrl-c-minus ()
20837 "Insert separator line in table or modify bullet status of line.
20838 Also turns a plain line or a region of lines into list items.
20839 Calls `org-table-insert-hline', `org-toggle-item', or
20840 `org-cycle-list-bullet', depending on context."
20841 (interactive)
20842 (cond
20843 ((org-at-table-p)
20844 (call-interactively 'org-table-insert-hline))
20845 ((org-region-active-p)
20846 (call-interactively 'org-toggle-item))
20847 ((org-in-item-p)
20848 (call-interactively 'org-cycle-list-bullet))
20850 (call-interactively 'org-toggle-item))))
20852 (defun org-toggle-item (arg)
20853 "Convert headings or normal lines to items, items to normal lines.
20854 If there is no active region, only the current line is considered.
20856 If the first non blank line in the region is a headline, convert
20857 all headlines to items, shifting text accordingly.
20859 If it is an item, convert all items to normal lines.
20861 If it is normal text, change region into a list of items.
20862 With a prefix argument ARG, change the region in a single item."
20863 (interactive "P")
20864 (let ((shift-text
20865 (function
20866 ;; Shift text in current section to IND, from point to END.
20867 ;; The function leaves point to END line.
20868 (lambda (ind end)
20869 (let ((min-i 1000) (end (copy-marker end)))
20870 ;; First determine the minimum indentation (MIN-I) of
20871 ;; the text.
20872 (save-excursion
20873 (catch 'exit
20874 (while (< (point) end)
20875 (let ((i (org-get-indentation)))
20876 (cond
20877 ;; Skip blank lines and inline tasks.
20878 ((looking-at "^[ \t]*$"))
20879 ((looking-at org-outline-regexp-bol))
20880 ;; We can't find less than 0 indentation.
20881 ((zerop i) (throw 'exit (setq min-i 0)))
20882 ((< i min-i) (setq min-i i))))
20883 (forward-line))))
20884 ;; Then indent each line so that a line indented to
20885 ;; MIN-I becomes indented to IND. Ignore blank lines
20886 ;; and inline tasks in the process.
20887 (let ((delta (- ind min-i)))
20888 (while (< (point) end)
20889 (unless (or (looking-at "^[ \t]*$")
20890 (looking-at org-outline-regexp-bol))
20891 (org-indent-line-to (+ (org-get-indentation) delta)))
20892 (forward-line)))))))
20893 (skip-blanks
20894 (function
20895 ;; Return beginning of first non-blank line, starting from
20896 ;; line at POS.
20897 (lambda (pos)
20898 (save-excursion
20899 (goto-char pos)
20900 (skip-chars-forward " \r\t\n")
20901 (point-at-bol)))))
20902 beg end)
20903 ;; Determine boundaries of changes.
20904 (if (org-region-active-p)
20905 (setq beg (funcall skip-blanks (region-beginning))
20906 end (copy-marker (region-end)))
20907 (setq beg (funcall skip-blanks (point-at-bol))
20908 end (copy-marker (point-at-eol))))
20909 ;; Depending on the starting line, choose an action on the text
20910 ;; between BEG and END.
20911 (org-with-limited-levels
20912 (save-excursion
20913 (goto-char beg)
20914 (cond
20915 ;; Case 1. Start at an item: de-itemize. Note that it only
20916 ;; happens when a region is active: `org-ctrl-c-minus'
20917 ;; would call `org-cycle-list-bullet' otherwise.
20918 ((org-at-item-p)
20919 (while (< (point) end)
20920 (when (org-at-item-p)
20921 (skip-chars-forward " \t")
20922 (delete-region (point) (match-end 0)))
20923 (forward-line)))
20924 ;; Case 2. Start at an heading: convert to items.
20925 ((org-at-heading-p)
20926 (let* ((bul (org-list-bullet-string "-"))
20927 (bul-len (length bul))
20928 (done (org-entry-is-done-p))
20929 (todo (org-entry-is-todo-p))
20930 ;; Indentation of the first heading. It should be
20931 ;; relative to the indentation of its parent, if any.
20932 (start-ind (save-excursion
20933 (cond
20934 ((not org-adapt-indentation) 0)
20935 ((not (outline-previous-heading)) 0)
20936 (t (length (match-string 0))))))
20937 ;; Level of first heading. Further headings will be
20938 ;; compared to it to determine hierarchy in the list.
20939 (ref-level (org-reduced-level (org-outline-level))))
20940 (when (or done todo) (org-todo ""))
20941 (while (< (point) end)
20942 (let* ((level (org-reduced-level (org-outline-level)))
20943 (delta (max 0 (- level ref-level))))
20944 ;; If current headline is less indented than the first
20945 ;; one, set it as reference, in order to preserve
20946 ;; subtrees.
20947 (when (< level ref-level) (setq ref-level level))
20948 (replace-match bul t t)
20949 (org-indent-line-to (+ start-ind (* delta bul-len)))
20950 (when (or done todo)
20951 (let* ((struct (org-list-struct))
20952 (old (copy-tree struct)))
20953 (org-list-set-checkbox (line-beginning-position)
20954 struct
20955 (if done "[X]" "[ ]"))
20956 (org-list-write-struct struct
20957 (org-list-parents-alist struct)
20958 old)))
20959 ;; Ensure all text down to END (or SECTION-END) belongs
20960 ;; to the newly created item.
20961 (let ((section-end (save-excursion
20962 (or (outline-next-heading) (point)))))
20963 (forward-line)
20964 (funcall shift-text
20965 (+ start-ind (* (1+ delta) bul-len))
20966 (min end section-end)))))))
20967 ;; Case 3. Normal line with ARG: make the first line of region
20968 ;; an item, and shift indentation of others lines to
20969 ;; set them as item's body.
20970 (arg (let* ((bul (org-list-bullet-string "-"))
20971 (bul-len (length bul))
20972 (ref-ind (org-get-indentation)))
20973 (skip-chars-forward " \t")
20974 (insert bul)
20975 (forward-line)
20976 (while (< (point) end)
20977 ;; Ensure that lines less indented than first one
20978 ;; still get included in item body.
20979 (funcall shift-text
20980 (+ ref-ind bul-len)
20981 (min end (save-excursion (or (outline-next-heading)
20982 (point)))))
20983 (forward-line))))
20984 ;; Case 4. Normal line without ARG: turn each non-item line
20985 ;; into an item.
20987 (while (< (point) end)
20988 (unless (or (org-at-heading-p) (org-at-item-p))
20989 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20990 (replace-match
20991 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20992 (forward-line))))))))
20994 (defun org-toggle-heading (&optional nstars)
20995 "Convert headings to normal text, or items or text to headings.
20996 If there is no active region, only convert the current line.
20998 With a \\[universal-argument] prefix, convert the whole list at
20999 point into heading.
21001 In a region:
21003 - If the first non blank line is a headline, remove the stars
21004 from all headlines in the region.
21006 - If it is a normal line, turn each and every normal line (i.e.,
21007 not an heading or an item) in the region into headings. If you
21008 want to convert only the first line of this region, use one
21009 universal prefix argument.
21011 - If it is a plain list item, turn all plain list items into headings.
21013 When converting a line into a heading, the number of stars is chosen
21014 such that the lines become children of the current entry. However,
21015 when a numeric prefix argument is given, its value determines the
21016 number of stars to add."
21017 (interactive "P")
21018 (let ((skip-blanks
21019 (function
21020 ;; Return beginning of first non-blank line, starting from
21021 ;; line at POS.
21022 (lambda (pos)
21023 (save-excursion
21024 (goto-char pos)
21025 (while (org-at-comment-p) (forward-line))
21026 (skip-chars-forward " \r\t\n")
21027 (point-at-bol)))))
21028 beg end toggled)
21029 ;; Determine boundaries of changes. If a universal prefix has
21030 ;; been given, put the list in a region. If region ends at a bol,
21031 ;; do not consider the last line to be in the region.
21033 (when (and current-prefix-arg (org-at-item-p))
21034 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
21035 (org-mark-element))
21037 (if (org-region-active-p)
21038 (setq beg (funcall skip-blanks (region-beginning))
21039 end (copy-marker (save-excursion
21040 (goto-char (region-end))
21041 (if (bolp) (point) (point-at-eol)))))
21042 (setq beg (funcall skip-blanks (point-at-bol))
21043 end (copy-marker (point-at-eol))))
21044 ;; Ensure inline tasks don't count as headings.
21045 (org-with-limited-levels
21046 (save-excursion
21047 (goto-char beg)
21048 (cond
21049 ;; Case 1. Started at an heading: de-star headings.
21050 ((org-at-heading-p)
21051 (while (< (point) end)
21052 (when (org-at-heading-p t)
21053 (looking-at org-outline-regexp) (replace-match "")
21054 (setq toggled t))
21055 (forward-line)))
21056 ;; Case 2. Started at an item: change items into headlines.
21057 ;; One star will be added by `org-list-to-subtree'.
21058 ((org-at-item-p)
21059 (let* ((stars (make-string
21060 ;; subtract the star that will be added again by
21061 ;; `org-list-to-subtree'
21062 (if (numberp nstars) (1- nstars)
21063 (or (org-current-level) 0))
21064 ?*))
21065 (add-stars
21066 (cond (nstars "") ; stars from prefix only
21067 ((equal stars "") "") ; before first heading
21068 (org-odd-levels-only "*") ; inside heading, odd
21069 (t "")))) ; inside heading, oddeven
21070 (while (< (point) end)
21071 (when (org-at-item-p)
21072 ;; Pay attention to cases when region ends before list.
21073 (let* ((struct (org-list-struct))
21074 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
21075 (save-restriction
21076 (narrow-to-region (point) list-end)
21077 (insert
21078 (org-list-to-subtree
21079 (org-list-parse-list t)
21080 '(:istart (concat stars add-stars (funcall get-stars depth))
21081 :icount (concat stars add-stars (funcall get-stars depth)))))))
21082 (setq toggled t))
21083 (forward-line))))
21084 ;; Case 3. Started at normal text: make every line an heading,
21085 ;; skipping headlines and items.
21086 (t (let* ((stars
21087 (make-string
21088 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21089 (add-stars
21090 (cond (nstars "") ; stars from prefix only
21091 ((equal stars "") "*") ; before first heading
21092 (org-odd-levels-only "**") ; inside heading, odd
21093 (t "*"))) ; inside heading, oddeven
21094 (rpl (concat stars add-stars " "))
21095 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
21096 (while (< (point) (if (equal nstars '(4)) lend end))
21097 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21098 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21099 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21100 (forward-line)))))))
21101 (unless toggled (message "Cannot toggle heading from here"))))
21103 (defun org-meta-return (&optional arg)
21104 "Insert a new heading or wrap a region in a table.
21105 Calls `org-insert-heading' or `org-table-wrap-region', depending
21106 on context. See the individual commands for more information."
21107 (interactive "P")
21108 (org-check-before-invisible-edit 'insert)
21109 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21110 (let* ((element (org-element-at-point))
21111 (type (org-element-type element)))
21112 (when (eq type 'table-row)
21113 (setq element (org-element-property :parent element))
21114 (setq type 'table))
21115 (if (and (eq type 'table)
21116 (eq (org-element-property :type element) 'org)
21117 (>= (point) (org-element-property :contents-begin element))
21118 (< (point) (org-element-property :contents-end element)))
21119 (call-interactively 'org-table-wrap-region)
21120 (call-interactively 'org-insert-heading)))))
21122 ;;; Menu entries
21124 (defsubst org-in-subtree-not-table-p ()
21125 "Are we in a subtree and not in a table?"
21126 (and (not (org-before-first-heading-p))
21127 (not (org-at-table-p))))
21129 ;; Define the Org-mode menus
21130 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21131 '("Tbl"
21132 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21133 ["Next Field" org-cycle (org-at-table-p)]
21134 ["Previous Field" org-shifttab (org-at-table-p)]
21135 ["Next Row" org-return (org-at-table-p)]
21136 "--"
21137 ["Blank Field" org-table-blank-field (org-at-table-p)]
21138 ["Edit Field" org-table-edit-field (org-at-table-p)]
21139 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21140 "--"
21141 ("Column"
21142 ["Move Column Left" org-metaleft (org-at-table-p)]
21143 ["Move Column Right" org-metaright (org-at-table-p)]
21144 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21145 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21146 ("Row"
21147 ["Move Row Up" org-metaup (org-at-table-p)]
21148 ["Move Row Down" org-metadown (org-at-table-p)]
21149 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21150 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21151 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21152 "--"
21153 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21154 ("Rectangle"
21155 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21156 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21157 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21158 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21159 "--"
21160 ("Calculate"
21161 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21162 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21163 ["Edit Formulas" org-edit-special (org-at-table-p)]
21164 "--"
21165 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21166 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21167 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21168 "--"
21169 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21170 "--"
21171 ["Sum Column/Rectangle" org-table-sum
21172 (or (org-at-table-p) (org-region-active-p))]
21173 ["Which Column?" org-table-current-column (org-at-table-p)])
21174 ["Debug Formulas"
21175 org-table-toggle-formula-debugger
21176 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21177 ["Show Col/Row Numbers"
21178 org-table-toggle-coordinate-overlays
21179 :style toggle
21180 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21181 "--"
21182 ["Create" org-table-create (and (not (org-at-table-p))
21183 org-enable-table-editor)]
21184 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21185 ["Import from File" org-table-import (not (org-at-table-p))]
21186 ["Export to File" org-table-export (org-at-table-p)]
21187 "--"
21188 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
21190 (easy-menu-define org-org-menu org-mode-map "Org menu"
21191 '("Org"
21192 ("Show/Hide"
21193 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21194 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21195 ["Sparse Tree..." org-sparse-tree t]
21196 ["Reveal Context" org-reveal t]
21197 ["Show All" show-all t]
21198 "--"
21199 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21200 "--"
21201 ["New Heading" org-insert-heading t]
21202 ("Navigate Headings"
21203 ["Up" outline-up-heading t]
21204 ["Next" outline-next-visible-heading t]
21205 ["Previous" outline-previous-visible-heading t]
21206 ["Next Same Level" outline-forward-same-level t]
21207 ["Previous Same Level" outline-backward-same-level t]
21208 "--"
21209 ["Jump" org-goto t])
21210 ("Edit Structure"
21211 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21212 "--"
21213 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
21214 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
21215 "--"
21216 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21217 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21218 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21219 "--"
21220 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21221 "--"
21222 ["Copy visible text" org-copy-visible t]
21223 "--"
21224 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21225 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21226 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21227 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21228 "--"
21229 ["Sort Region/Children" org-sort t]
21230 "--"
21231 ["Convert to odd levels" org-convert-to-odd-levels t]
21232 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21233 ("Editing"
21234 ["Emphasis..." org-emphasize t]
21235 ["Edit Source Example" org-edit-special t]
21236 "--"
21237 ["Footnote new/jump" org-footnote-action t]
21238 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21239 ("Archive"
21240 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21241 "--"
21242 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
21243 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21244 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21246 "--"
21247 ("Hyperlinks"
21248 ["Store Link (Global)" org-store-link t]
21249 ["Find existing link to here" org-occur-link-in-agenda-files t]
21250 ["Insert Link" org-insert-link t]
21251 ["Follow Link" org-open-at-point t]
21252 "--"
21253 ["Next link" org-next-link t]
21254 ["Previous link" org-previous-link t]
21255 "--"
21256 ["Descriptive Links"
21257 org-toggle-link-display
21258 :style radio
21259 :selected org-descriptive-links
21261 ["Literal Links"
21262 org-toggle-link-display
21263 :style radio
21264 :selected (not org-descriptive-links)])
21265 "--"
21266 ("TODO Lists"
21267 ["TODO/DONE/-" org-todo t]
21268 ("Select keyword"
21269 ["Next keyword" org-shiftright (org-at-heading-p)]
21270 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21271 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21272 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21273 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21274 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21275 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21276 "--"
21277 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21278 :selected org-enforce-todo-dependencies :style toggle :active t]
21279 "Settings for tree at point"
21280 ["Do Children sequentially" org-toggle-ordered-property :style radio
21281 :selected (org-entry-get nil "ORDERED")
21282 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21283 ["Do Children parallel" org-toggle-ordered-property :style radio
21284 :selected (not (org-entry-get nil "ORDERED"))
21285 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21286 "--"
21287 ["Set Priority" org-priority t]
21288 ["Priority Up" org-shiftup t]
21289 ["Priority Down" org-shiftdown t]
21290 "--"
21291 ["Get news from all feeds" org-feed-update-all t]
21292 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21293 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21294 ("TAGS and Properties"
21295 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21296 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21297 "--"
21298 ["Set property" org-set-property (not (org-before-first-heading-p))]
21299 ["Column view of properties" org-columns t]
21300 ["Insert Column View DBlock" org-insert-columns-dblock t])
21301 ("Dates and Scheduling"
21302 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21303 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21304 ("Change Date"
21305 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21306 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21307 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21308 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21309 ["Compute Time Range" org-evaluate-time-range t]
21310 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21311 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21312 "--"
21313 ["Custom time format" org-toggle-time-stamp-overlays
21314 :style radio :selected org-display-custom-times]
21315 "--"
21316 ["Goto Calendar" org-goto-calendar t]
21317 ["Date from Calendar" org-date-from-calendar t]
21318 "--"
21319 ["Start/Restart Timer" org-timer-start t]
21320 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21321 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21322 ["Insert Timer String" org-timer t]
21323 ["Insert Timer Item" org-timer-item t])
21324 ("Logging work"
21325 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21326 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21327 ["Clock out" org-clock-out t]
21328 ["Clock cancel" org-clock-cancel t]
21329 "--"
21330 ["Mark as default task" org-clock-mark-default-task t]
21331 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21332 ["Goto running clock" org-clock-goto t]
21333 "--"
21334 ["Display times" org-clock-display t]
21335 ["Create clock table" org-clock-report t]
21336 "--"
21337 ["Record DONE time"
21338 (progn (setq org-log-done (not org-log-done))
21339 (message "Switching to %s will %s record a timestamp"
21340 (car org-done-keywords)
21341 (if org-log-done "automatically" "not")))
21342 :style toggle :selected org-log-done])
21343 "--"
21344 ["Agenda Command..." org-agenda t]
21345 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21346 ("File List for Agenda")
21347 ("Special views current file"
21348 ["TODO Tree" org-show-todo-tree t]
21349 ["Check Deadlines" org-check-deadlines t]
21350 ["Timeline" org-timeline t]
21351 ["Tags/Property tree" org-match-sparse-tree t])
21352 "--"
21353 ["Export/Publish..." org-export-dispatch t]
21354 ("LaTeX"
21355 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21356 :selected org-cdlatex-mode]
21357 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21358 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21359 ["Modify math symbol" org-cdlatex-math-modify
21360 (org-inside-LaTeX-fragment-p)]
21361 ["Insert citation" org-reftex-citation t]
21362 "--"
21363 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21364 "--"
21365 ("MobileOrg"
21366 ["Push Files and Views" org-mobile-push t]
21367 ["Get Captured and Flagged" org-mobile-pull t]
21368 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21369 "--"
21370 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21371 "--"
21372 ("Documentation"
21373 ["Show Version" org-version t]
21374 ["Info Documentation" org-info t])
21375 ("Customize"
21376 ["Browse Org Group" org-customize t]
21377 "--"
21378 ["Expand This Menu" org-create-customize-menu
21379 (fboundp 'customize-menu-create)])
21380 ["Send bug report" org-submit-bug-report t]
21381 "--"
21382 ("Refresh/Reload"
21383 ["Refresh setup current buffer" org-mode-restart t]
21384 ["Reload Org (after update)" org-reload t]
21385 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21388 (defun org-info (&optional node)
21389 "Read documentation for Org-mode in the info system.
21390 With optional NODE, go directly to that node."
21391 (interactive)
21392 (info (format "(org)%s" (or node ""))))
21394 ;;;###autoload
21395 (defun org-submit-bug-report ()
21396 "Submit a bug report on Org-mode via mail.
21398 Don't hesitate to report any problems or inaccurate documentation.
21400 If you don't have setup sending mail from (X)Emacs, please copy the
21401 output buffer into your mail program, as it gives us important
21402 information about your Org-mode version and configuration."
21403 (interactive)
21404 (require 'reporter)
21405 (org-load-modules-maybe)
21406 (org-require-autoloaded-modules)
21407 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21408 (reporter-submit-bug-report
21409 "emacs-orgmode@gnu.org"
21410 (org-version nil 'full)
21411 (let (list)
21412 (save-window-excursion
21413 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21414 (delete-other-windows)
21415 (erase-buffer)
21416 (insert "You are about to submit a bug report to the Org-mode mailing list.
21418 We would like to add your full Org-mode and Outline configuration to the
21419 bug report. This greatly simplifies the work of the maintainer and
21420 other experts on the mailing list.
21422 HOWEVER, some variables you have customized may contain private
21423 information. The names of customers, colleagues, or friends, might
21424 appear in the form of file names, tags, todo states, or search strings.
21425 If you answer yes to the prompt, you might want to check and remove
21426 such private information before sending the email.")
21427 (add-text-properties (point-min) (point-max) '(face org-warning))
21428 (when (yes-or-no-p "Include your Org-mode configuration ")
21429 (mapatoms
21430 (lambda (v)
21431 (and (boundp v)
21432 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21433 (or (and (symbol-value v)
21434 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21435 (and
21436 (get v 'custom-type) (get v 'standard-value)
21437 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21438 (push v list)))))
21439 (kill-buffer (get-buffer "*Warn about privacy*"))
21440 list))
21441 nil nil
21442 "Remember to cover the basics, that is, what you expected to happen and
21443 what in fact did happen. You don't know how to make a good report? See
21445 http://orgmode.org/manual/Feedback.html#Feedback
21447 Your bug report will be posted to the Org-mode mailing list.
21448 ------------------------------------------------------------------------")
21449 (save-excursion
21450 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21451 (replace-match "\\1Bug: \\3 [\\2]")))))
21454 (defun org-install-agenda-files-menu ()
21455 (let ((bl (buffer-list)))
21456 (save-excursion
21457 (while bl
21458 (set-buffer (pop bl))
21459 (if (derived-mode-p 'org-mode) (setq bl nil)))
21460 (when (derived-mode-p 'org-mode)
21461 (easy-menu-change
21462 '("Org") "File List for Agenda"
21463 (append
21464 (list
21465 ["Edit File List" (org-edit-agenda-file-list) t]
21466 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21467 ["Remove Current File from List" org-remove-file t]
21468 ["Cycle through agenda files" org-cycle-agenda-files t]
21469 ["Occur in all agenda files" org-occur-in-agenda-files t]
21470 "--")
21471 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21473 ;;;; Documentation
21475 (defun org-require-autoloaded-modules ()
21476 (interactive)
21477 (mapc 'require
21478 '(org-agenda org-archive org-attach org-clock org-colview org-id
21479 org-table org-timer)))
21481 ;;;###autoload
21482 (defun org-reload (&optional uncompiled)
21483 "Reload all org lisp files.
21484 With prefix arg UNCOMPILED, load the uncompiled versions."
21485 (interactive "P")
21486 (require 'loadhist)
21487 (let* ((org-dir (org-find-library-dir "org"))
21488 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21489 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21490 (remove-re (mapconcat 'identity
21491 (mapcar (lambda (f) (concat "^" f "$"))
21492 (list (if (featurep 'xemacs)
21493 "org-colview"
21494 "org-colview-xemacs")
21495 "org" "org-loaddefs" "org-version"))
21496 "\\|"))
21497 (feats (delete-dups
21498 (mapcar 'file-name-sans-extension
21499 (mapcar 'file-name-nondirectory
21500 (delq nil
21501 (mapcar 'feature-file
21502 features))))))
21503 (lfeat (append
21504 (sort
21505 (setq feats
21506 (delq nil (mapcar
21507 (lambda (f)
21508 (if (and (string-match feature-re f)
21509 (not (string-match remove-re f)))
21510 f nil))
21511 feats)))
21512 'string-lessp)
21513 (list "org-version" "org")))
21514 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21515 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21516 load-uncore load-misses)
21517 (setq load-misses
21518 (delq 't
21519 (mapcar (lambda (f)
21520 (or (org-load-noerror-mustsuffix (concat org-dir f))
21521 (and (string= org-dir contrib-dir)
21522 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21523 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21524 (add-to-list 'load-uncore f 'append)
21527 lfeat)))
21528 (if load-uncore
21529 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21530 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21531 (if load-misses
21532 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21533 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21534 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21536 ;;;###autoload
21537 (defun org-customize ()
21538 "Call the customize function with org as argument."
21539 (interactive)
21540 (org-load-modules-maybe)
21541 (org-require-autoloaded-modules)
21542 (customize-browse 'org))
21544 (defun org-create-customize-menu ()
21545 "Create a full customization menu for Org-mode, insert it into the menu."
21546 (interactive)
21547 (org-load-modules-maybe)
21548 (org-require-autoloaded-modules)
21549 (if (fboundp 'customize-menu-create)
21550 (progn
21551 (easy-menu-change
21552 '("Org") "Customize"
21553 `(["Browse Org group" org-customize t]
21554 "--"
21555 ,(customize-menu-create 'org)
21556 ["Set" Custom-set t]
21557 ["Save" Custom-save t]
21558 ["Reset to Current" Custom-reset-current t]
21559 ["Reset to Saved" Custom-reset-saved t]
21560 ["Reset to Standard Settings" Custom-reset-standard t]))
21561 (message "\"Org\"-menu now contains full customization menu"))
21562 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21564 ;;;; Miscellaneous stuff
21566 ;;; Generally useful functions
21568 (defsubst org-get-at-eol (property n)
21569 "Get text property PROPERTY at the end of line less N characters."
21570 (get-text-property (- (point-at-eol) n) property))
21572 (defun org-find-text-property-in-string (prop s)
21573 "Return the first non-nil value of property PROP in string S."
21574 (or (get-text-property 0 prop s)
21575 (get-text-property (or (next-single-property-change 0 prop s) 0)
21576 prop s)))
21578 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21579 "Display the given MESSAGE as a warning."
21580 (if (fboundp 'display-warning)
21581 (display-warning 'org message
21582 (if (featurep 'xemacs) 'warning :warning))
21583 (let ((buf (get-buffer-create "*Org warnings*")))
21584 (with-current-buffer buf
21585 (goto-char (point-max))
21586 (insert "Warning (Org): " message)
21587 (unless (bolp)
21588 (newline)))
21589 (display-buffer buf)
21590 (sit-for 0))))
21592 (defun org-eval (form)
21593 "Eval FORM and return result."
21594 (condition-case error
21595 (eval form)
21596 (error (format "%%![Error: %s]" error))))
21598 (defun org-in-clocktable-p ()
21599 "Check if the cursor is in a clocktable."
21600 (let ((pos (point)) start)
21601 (save-excursion
21602 (end-of-line 1)
21603 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21604 (setq start (match-beginning 0))
21605 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21606 (>= (match-end 0) pos)
21607 start))))
21609 (defun org-in-verbatim-emphasis ()
21610 (save-match-data
21611 (and (org-in-regexp org-emph-re 2)
21612 (>= (point) (match-beginning 3))
21613 (<= (point) (match-end 4))
21614 (member (match-string 3) '("=" "~")))))
21616 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21617 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21618 (if (and marker (marker-buffer marker)
21619 (buffer-live-p (marker-buffer marker)))
21620 (progn
21621 (org-pop-to-buffer-same-window (marker-buffer marker))
21622 (if (or (> marker (point-max)) (< marker (point-min)))
21623 (widen))
21624 (goto-char marker)
21625 (org-show-context 'org-goto))
21626 (if bookmark
21627 (bookmark-jump bookmark)
21628 (error "Cannot find location"))))
21630 (defun org-quote-csv-field (s)
21631 "Quote field for inclusion in CSV material."
21632 (if (string-match "[\",]" s)
21633 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21636 (defun org-force-self-insert (N)
21637 "Needed to enforce self-insert under remapping."
21638 (interactive "p")
21639 (self-insert-command N))
21641 (defun org-string-width (s)
21642 "Compute width of string, ignoring invisible characters.
21643 This ignores character with invisibility property `org-link', and also
21644 characters with property `org-cwidth', because these will become invisible
21645 upon the next fontification round."
21646 (let (b l)
21647 (when (or (eq t buffer-invisibility-spec)
21648 (assq 'org-link buffer-invisibility-spec))
21649 (while (setq b (text-property-any 0 (length s)
21650 'invisible 'org-link s))
21651 (setq s (concat (substring s 0 b)
21652 (substring s (or (next-single-property-change
21653 b 'invisible s) (length s)))))))
21654 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21655 (setq s (concat (substring s 0 b)
21656 (substring s (or (next-single-property-change
21657 b 'org-cwidth s) (length s))))))
21658 (setq l (string-width s) b -1)
21659 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21660 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21663 (defun org-shorten-string (s maxlength)
21664 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21665 If the string is shorter or has length MAXLENGTH, just return the
21666 original string. If it is longer, the functions finds a space in the
21667 string, breaks this string off at that locations and adds three dots
21668 as ellipsis. Including the ellipsis, the string will not be longer
21669 than MAXLENGTH. If finding a good breaking point in the string does
21670 not work, the string is just chopped off in the middle of a word
21671 if necessary."
21672 (if (<= (length s) maxlength)
21674 (let* ((n (max (- maxlength 4) 1))
21675 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21676 (if (string-match re s)
21677 (concat (match-string 1 s) "...")
21678 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21680 (defun org-get-indentation (&optional line)
21681 "Get the indentation of the current line, interpreting tabs.
21682 When LINE is given, assume it represents a line and compute its indentation."
21683 (if line
21684 (if (string-match "^ *" (org-remove-tabs line))
21685 (match-end 0))
21686 (save-excursion
21687 (beginning-of-line 1)
21688 (skip-chars-forward " \t")
21689 (current-column))))
21691 (defun org-get-string-indentation (s)
21692 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21693 (let ((n -1) (i 0) (w tab-width) c)
21694 (catch 'exit
21695 (while (< (setq n (1+ n)) (length s))
21696 (setq c (aref s n))
21697 (cond ((= c ?\ ) (setq i (1+ i)))
21698 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21699 (t (throw 'exit t)))))
21702 (defun org-remove-tabs (s &optional width)
21703 "Replace tabulators in S with spaces.
21704 Assumes that s is a single line, starting in column 0."
21705 (setq width (or width tab-width))
21706 (while (string-match "\t" s)
21707 (setq s (replace-match
21708 (make-string
21709 (- (* width (/ (+ (match-beginning 0) width) width))
21710 (match-beginning 0)) ?\ )
21711 t t s)))
21714 (defun org-fix-indentation (line ind)
21715 "Fix indentation in LINE.
21716 IND is a cons cell with target and minimum indentation.
21717 If the current indentation in LINE is smaller than the minimum,
21718 leave it alone. If it is larger than ind, set it to the target."
21719 (let* ((l (org-remove-tabs line))
21720 (i (org-get-indentation l))
21721 (i1 (car ind)) (i2 (cdr ind)))
21722 (if (>= i i2) (setq l (substring line i2)))
21723 (if (> i1 0)
21724 (concat (make-string i1 ?\ ) l)
21725 l)))
21727 (defun org-remove-indentation (code &optional n)
21728 "Remove the maximum common indentation from the lines in CODE.
21729 N may optionally be the number of spaces to remove."
21730 (with-temp-buffer
21731 (insert code)
21732 (org-do-remove-indentation n)
21733 (buffer-string)))
21735 (defun org-do-remove-indentation (&optional n)
21736 "Remove the maximum common indentation from the buffer."
21737 (untabify (point-min) (point-max))
21738 (let ((min 10000) re)
21739 (if n
21740 (setq min n)
21741 (goto-char (point-min))
21742 (while (re-search-forward "^ *[^ \n]" nil t)
21743 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21744 (unless (or (= min 0) (= min 10000))
21745 (setq re (format "^ \\{%d\\}" min))
21746 (goto-char (point-min))
21747 (while (re-search-forward re nil t)
21748 (replace-match "")
21749 (end-of-line 1))
21750 min)))
21752 (defun org-fill-template (template alist)
21753 "Find each %key of ALIST in TEMPLATE and replace it."
21754 (let ((case-fold-search nil)
21755 entry key value)
21756 (setq alist (sort (copy-sequence alist)
21757 (lambda (a b) (< (length (car a)) (length (car b))))))
21758 (while (setq entry (pop alist))
21759 (setq template
21760 (replace-regexp-in-string
21761 (concat "%" (regexp-quote (car entry)))
21762 (or (cdr entry) "") template t t)))
21763 template))
21765 (defun org-base-buffer (buffer)
21766 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21767 (if (not buffer)
21768 buffer
21769 (or (buffer-base-buffer buffer)
21770 buffer)))
21772 (defun org-wrap (string &optional width lines)
21773 "Wrap string to either a number of lines, or a width in characters.
21774 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21775 that costs. If there is a word longer than WIDTH, the text is actually
21776 wrapped to the length of that word.
21777 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21778 many lines, whatever width that takes.
21779 The return value is a list of lines, without newlines at the end."
21780 (let* ((words (org-split-string string "[ \t\n]+"))
21781 (maxword (apply 'max (mapcar 'org-string-width words)))
21782 w ll)
21783 (cond (width
21784 (org-do-wrap words (max maxword width)))
21785 (lines
21786 (setq w maxword)
21787 (setq ll (org-do-wrap words maxword))
21788 (if (<= (length ll) lines)
21790 (setq ll words)
21791 (while (> (length ll) lines)
21792 (setq w (1+ w))
21793 (setq ll (org-do-wrap words w)))
21794 ll))
21795 (t (error "Cannot wrap this")))))
21797 (defun org-do-wrap (words width)
21798 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21799 (let (lines line)
21800 (while words
21801 (setq line (pop words))
21802 (while (and words (< (+ (length line) (length (car words))) width))
21803 (setq line (concat line " " (pop words))))
21804 (setq lines (push line lines)))
21805 (nreverse lines)))
21807 (defun org-split-string (string &optional separators)
21808 "Splits STRING into substrings at SEPARATORS.
21809 No empty strings are returned if there are matches at the beginning
21810 and end of string."
21811 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21812 (start 0)
21813 notfirst
21814 (list nil))
21815 (while (and (string-match rexp string
21816 (if (and notfirst
21817 (= start (match-beginning 0))
21818 (< start (length string)))
21819 (1+ start) start))
21820 (< (match-beginning 0) (length string)))
21821 (setq notfirst t)
21822 (or (eq (match-beginning 0) 0)
21823 (and (eq (match-beginning 0) (match-end 0))
21824 (eq (match-beginning 0) start))
21825 (setq list
21826 (cons (substring string start (match-beginning 0))
21827 list)))
21828 (setq start (match-end 0)))
21829 (or (eq start (length string))
21830 (setq list
21831 (cons (substring string start)
21832 list)))
21833 (nreverse list)))
21835 (defun org-quote-vert (s)
21836 "Replace \"|\" with \"\\vert\"."
21837 (while (string-match "|" s)
21838 (setq s (replace-match "\\vert" t t s)))
21841 (defun org-uuidgen-p (s)
21842 "Is S an ID created by UUIDGEN?"
21843 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21845 (defun org-in-src-block-p (&optional inside)
21846 "Whether point is in a code source block.
21847 When INSIDE is non-nil, don't consider we are within a src block
21848 when point is at #+BEGIN_SRC or #+END_SRC."
21849 (let ((case-fold-search t) ov)
21850 (or (and (eq (get-char-property (point) 'src-block) t))
21851 (and (not inside)
21852 (save-match-data
21853 (save-excursion
21854 (beginning-of-line)
21855 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21857 (defun org-context ()
21858 "Return a list of contexts of the current cursor position.
21859 If several contexts apply, all are returned.
21860 Each context entry is a list with a symbol naming the context, and
21861 two positions indicating start and end of the context. Possible
21862 contexts are:
21864 :headline anywhere in a headline
21865 :headline-stars on the leading stars in a headline
21866 :todo-keyword on a TODO keyword (including DONE) in a headline
21867 :tags on the TAGS in a headline
21868 :priority on the priority cookie in a headline
21869 :item on the first line of a plain list item
21870 :item-bullet on the bullet/number of a plain list item
21871 :checkbox on the checkbox in a plain list item
21872 :table in an org-mode table
21873 :table-special on a special filed in a table
21874 :table-table in a table.el table
21875 :clocktable in a clocktable
21876 :src-block in a source block
21877 :link on a hyperlink
21878 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21879 :target on a <<target>>
21880 :radio-target on a <<<radio-target>>>
21881 :latex-fragment on a LaTeX fragment
21882 :latex-preview on a LaTeX fragment with overlaid preview image
21884 This function expects the position to be visible because it uses font-lock
21885 faces as a help to recognize the following contexts: :table-special, :link,
21886 and :keyword."
21887 (let* ((f (get-text-property (point) 'face))
21888 (faces (if (listp f) f (list f)))
21889 (case-fold-search t)
21890 (p (point)) clist o)
21891 ;; First the large context
21892 (cond
21893 ((org-at-heading-p t)
21894 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21895 (when (progn
21896 (beginning-of-line 1)
21897 (looking-at org-todo-line-tags-regexp))
21898 (push (org-point-in-group p 1 :headline-stars) clist)
21899 (push (org-point-in-group p 2 :todo-keyword) clist)
21900 (push (org-point-in-group p 4 :tags) clist))
21901 (goto-char p)
21902 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21903 (if (looking-at "\\[#[A-Z0-9]\\]")
21904 (push (org-point-in-group p 0 :priority) clist)))
21906 ((org-at-item-p)
21907 (push (org-point-in-group p 2 :item-bullet) clist)
21908 (push (list :item (point-at-bol)
21909 (save-excursion (org-end-of-item) (point)))
21910 clist)
21911 (and (org-at-item-checkbox-p)
21912 (push (org-point-in-group p 0 :checkbox) clist)))
21914 ((org-at-table-p)
21915 (push (list :table (org-table-begin) (org-table-end)) clist)
21916 (if (memq 'org-formula faces)
21917 (push (list :table-special
21918 (previous-single-property-change p 'face)
21919 (next-single-property-change p 'face)) clist)))
21920 ((org-at-table-p 'any)
21921 (push (list :table-table) clist)))
21922 (goto-char p)
21924 (let ((case-fold-search t))
21925 ;; New the "medium" contexts: clocktables, source blocks
21926 (cond ((org-in-clocktable-p)
21927 (push (list :clocktable
21928 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21929 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21930 (match-beginning 1))
21931 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21932 (match-end 0))) clist))
21933 ((org-in-src-block-p)
21934 (push (list :src-block
21935 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21936 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21937 (match-beginning 1))
21938 (and (search-forward "#+END_SRC" nil t)
21939 (match-beginning 0))) clist))))
21940 (goto-char p)
21942 ;; Now the small context
21943 (cond
21944 ((org-at-timestamp-p)
21945 (push (org-point-in-group p 0 :timestamp) clist))
21946 ((memq 'org-link faces)
21947 (push (list :link
21948 (previous-single-property-change p 'face)
21949 (next-single-property-change p 'face)) clist))
21950 ((memq 'org-special-keyword faces)
21951 (push (list :keyword
21952 (previous-single-property-change p 'face)
21953 (next-single-property-change p 'face)) clist))
21954 ((org-at-target-p)
21955 (push (org-point-in-group p 0 :target) clist)
21956 (goto-char (1- (match-beginning 0)))
21957 (if (looking-at org-radio-target-regexp)
21958 (push (org-point-in-group p 0 :radio-target) clist))
21959 (goto-char p))
21960 ((setq o (car (delq nil
21961 (mapcar
21962 (lambda (x)
21963 (if (memq x org-latex-fragment-image-overlays) x))
21964 (overlays-at (point))))))
21965 (push (list :latex-fragment
21966 (overlay-start o) (overlay-end o)) clist)
21967 (push (list :latex-preview
21968 (overlay-start o) (overlay-end o)) clist))
21969 ((org-inside-LaTeX-fragment-p)
21970 ;; FIXME: positions wrong.
21971 (push (list :latex-fragment (point) (point)) clist)))
21973 (setq clist (nreverse (delq nil clist)))
21974 clist))
21976 ;; FIXME: Compare with at-regexp-p Do we need both?
21977 (defun org-in-regexp (re &optional nlines visually)
21978 "Check if point is inside a match of regexp.
21979 Normally only the current line is checked, but you can include NLINES extra
21980 lines both before and after point into the search.
21981 If VISUALLY is set, require that the cursor is not after the match but
21982 really on, so that the block visually is on the match."
21983 (catch 'exit
21984 (let ((pos (point))
21985 (eol (point-at-eol (+ 1 (or nlines 0))))
21986 (inc (if visually 1 0)))
21987 (save-excursion
21988 (beginning-of-line (- 1 (or nlines 0)))
21989 (while (re-search-forward re eol t)
21990 (if (and (<= (match-beginning 0) pos)
21991 (>= (+ inc (match-end 0)) pos))
21992 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21994 (defun org-at-regexp-p (regexp)
21995 "Is point inside a match of REGEXP in the current line?"
21996 (catch 'exit
21997 (save-excursion
21998 (let ((pos (point)) (end (point-at-eol)))
21999 (beginning-of-line 1)
22000 (while (re-search-forward regexp end t)
22001 (if (and (<= (match-beginning 0) pos)
22002 (>= (match-end 0) pos))
22003 (throw 'exit t)))
22004 nil))))
22006 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22007 "Non-nil when point is between matches of START-RE and END-RE.
22009 Also return a non-nil value when point is on one of the matches.
22011 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22012 buffer positions. Default values are the positions of headlines
22013 surrounding the point.
22015 The functions returns a cons cell whose car (resp. cdr) is the
22016 position before START-RE (resp. after END-RE)."
22017 (save-match-data
22018 (let ((pos (point))
22019 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22020 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22021 beg end)
22022 (save-excursion
22023 ;; Point is on a block when on START-RE or if START-RE can be
22024 ;; found before it...
22025 (and (or (org-at-regexp-p start-re)
22026 (re-search-backward start-re limit-up t))
22027 (setq beg (match-beginning 0))
22028 ;; ... and END-RE after it...
22029 (goto-char (match-end 0))
22030 (re-search-forward end-re limit-down t)
22031 (> (setq end (match-end 0)) pos)
22032 ;; ... without another START-RE in-between.
22033 (goto-char (match-beginning 0))
22034 (not (re-search-backward start-re (1+ beg) t))
22035 ;; Return value.
22036 (cons beg end))))))
22038 (defun org-in-block-p (names)
22039 "Non-nil when point belongs to a block whose name belongs to NAMES.
22041 NAMES is a list of strings containing names of blocks.
22043 Return first block name matched, or nil. Beware that in case of
22044 nested blocks, the returned name may not belong to the closest
22045 block from point."
22046 (save-match-data
22047 (catch 'exit
22048 (let ((case-fold-search t)
22049 (lim-up (save-excursion (outline-previous-heading)))
22050 (lim-down (save-excursion (outline-next-heading))))
22051 (mapc (lambda (name)
22052 (let ((n (regexp-quote name)))
22053 (when (org-between-regexps-p
22054 (concat "^[ \t]*#\\+begin_" n)
22055 (concat "^[ \t]*#\\+end_" n)
22056 lim-up lim-down)
22057 (throw 'exit n))))
22058 names))
22059 nil)))
22061 (defun org-in-drawer-p ()
22062 "Non-nil if point is within a drawer.
22063 If point is within a drawer, return it, as parsed data."
22064 (let ((element (save-match-data (org-element-at-point))))
22065 (while (and element (not (memq (org-element-type element)
22066 '(drawer property-drawer))))
22067 (setq element (org-element-property :parent element)))
22068 element))
22070 (defun org-occur-in-agenda-files (regexp &optional nlines)
22071 "Call `multi-occur' with buffers for all agenda files."
22072 (interactive "sOrg-files matching: \np")
22073 (let* ((files (org-agenda-files))
22074 (tnames (mapcar 'file-truename files))
22075 (extra org-agenda-text-search-extra-files)
22077 (when (eq (car extra) 'agenda-archives)
22078 (setq extra (cdr extra))
22079 (setq files (org-add-archive-files files)))
22080 (while (setq f (pop extra))
22081 (unless (member (file-truename f) tnames)
22082 (add-to-list 'files f 'append)
22083 (add-to-list 'tnames (file-truename f) 'append)))
22084 (multi-occur
22085 (mapcar (lambda (x)
22086 (with-current-buffer
22087 (or (get-file-buffer x) (find-file-noselect x))
22088 (widen)
22089 (current-buffer)))
22090 files)
22091 regexp)))
22093 (if (boundp 'occur-mode-find-occurrence-hook)
22094 ;; Emacs 23
22095 (add-hook 'occur-mode-find-occurrence-hook
22096 (lambda ()
22097 (when (derived-mode-p 'org-mode)
22098 (org-reveal))))
22099 ;; Emacs 22
22100 (defadvice occur-mode-goto-occurrence
22101 (after org-occur-reveal activate)
22102 (and (derived-mode-p 'org-mode) (org-reveal)))
22103 (defadvice occur-mode-goto-occurrence-other-window
22104 (after org-occur-reveal activate)
22105 (and (derived-mode-p 'org-mode) (org-reveal)))
22106 (defadvice occur-mode-display-occurrence
22107 (after org-occur-reveal activate)
22108 (when (derived-mode-p 'org-mode)
22109 (let ((pos (occur-mode-find-occurrence)))
22110 (with-current-buffer (marker-buffer pos)
22111 (save-excursion
22112 (goto-char pos)
22113 (org-reveal)))))))
22115 (defun org-occur-link-in-agenda-files ()
22116 "Create a link and search for it in the agendas.
22117 The link is not stored in `org-stored-links', it is just created
22118 for the search purpose."
22119 (interactive)
22120 (let ((link (condition-case nil
22121 (org-store-link nil)
22122 (error "Unable to create a link to here"))))
22123 (org-occur-in-agenda-files (regexp-quote link))))
22125 (defun org-reverse-string (string)
22126 "Return the reverse of STRING."
22127 (apply 'string (reverse (string-to-list string))))
22129 ;; defsubst org-uniquify must be defined before first use
22131 (defun org-uniquify-alist (alist)
22132 "Merge elements of ALIST with the same key.
22134 For example, in this alist:
22136 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
22137 => '((a 1 3) (b 2))
22139 merge (a 1) and (a 3) into (a 1 3).
22141 The function returns the new ALIST."
22142 (let (rtn)
22143 (mapc
22144 (lambda (e)
22145 (let (n)
22146 (if (not (assoc (car e) rtn))
22147 (push e rtn)
22148 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22149 (setq rtn (assq-delete-all (car e) rtn))
22150 (push n rtn))))
22151 alist)
22152 rtn))
22154 (defun org-delete-all (elts list)
22155 "Remove all elements in ELTS from LIST."
22156 (while elts
22157 (setq list (delete (pop elts) list)))
22158 list)
22160 (defun org-count (cl-item cl-seq)
22161 "Count the number of occurrences of ITEM in SEQ.
22162 Taken from `count' in cl-seq.el with all keyword arguments removed."
22163 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
22164 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
22165 (while (< cl-start cl-end)
22166 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
22167 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
22168 (setq cl-start (1+ cl-start)))
22169 cl-count))
22171 (defun org-remove-if (predicate seq)
22172 "Remove everything from SEQ that fulfills PREDICATE."
22173 (let (res e)
22174 (while seq
22175 (setq e (pop seq))
22176 (if (not (funcall predicate e)) (push e res)))
22177 (nreverse res)))
22179 (defun org-remove-if-not (predicate seq)
22180 "Remove everything from SEQ that does not fulfill PREDICATE."
22181 (let (res e)
22182 (while seq
22183 (setq e (pop seq))
22184 (if (funcall predicate e) (push e res)))
22185 (nreverse res)))
22187 (defun org-reduce (cl-func cl-seq &rest cl-keys)
22188 "Reduce two-argument FUNCTION across SEQ.
22189 Taken from `reduce' in cl-seq.el with all keyword arguments but
22190 \":initial-value\" removed."
22191 (let ((cl-accum (cond ((memq :initial-value cl-keys)
22192 (cadr (memq :initial-value cl-keys)))
22193 (cl-seq (pop cl-seq))
22194 (t (funcall cl-func)))))
22195 (while cl-seq
22196 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
22197 cl-accum))
22199 (defun org-every (pred seq)
22200 "Return true if PREDICATE is true of every element of SEQ.
22201 Adapted from `every' in cl.el."
22202 (catch 'org-every
22203 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
22206 (defun org-some (pred seq)
22207 "Return true if PREDICATE is true of any element of SEQ.
22208 Adapted from `some' in cl.el."
22209 (catch 'org-some
22210 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
22211 nil))
22213 (defun org-back-over-empty-lines ()
22214 "Move backwards over whitespace, to the beginning of the first empty line.
22215 Returns the number of empty lines passed."
22216 (let ((pos (point)))
22217 (if (cdr (assoc 'heading org-blank-before-new-entry))
22218 (skip-chars-backward " \t\n\r")
22219 (unless (eobp)
22220 (forward-line -1)))
22221 (beginning-of-line 2)
22222 (goto-char (min (point) pos))
22223 (count-lines (point) pos)))
22225 (defun org-skip-whitespace ()
22226 (skip-chars-forward " \t\n\r"))
22228 (defun org-point-in-group (point group &optional context)
22229 "Check if POINT is in match-group GROUP.
22230 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22231 match. If the match group does not exist or point is not inside it,
22232 return nil."
22233 (and (match-beginning group)
22234 (>= point (match-beginning group))
22235 (<= point (match-end group))
22236 (if context
22237 (list context (match-beginning group) (match-end group))
22238 t)))
22240 (defun org-switch-to-buffer-other-window (&rest args)
22241 "Switch to buffer in a second window on the current frame.
22242 In particular, do not allow pop-up frames.
22243 Returns the newly created buffer."
22244 (org-no-popups
22245 (apply 'switch-to-buffer-other-window args)))
22247 (defun org-combine-plists (&rest plists)
22248 "Create a single property list from all plists in PLISTS.
22249 The process starts by copying the first list, and then setting properties
22250 from the other lists. Settings in the last list are the most significant
22251 ones and overrule settings in the other lists."
22252 (let ((rtn (copy-sequence (pop plists)))
22253 p v ls)
22254 (while plists
22255 (setq ls (pop plists))
22256 (while ls
22257 (setq p (pop ls) v (pop ls))
22258 (setq rtn (plist-put rtn p v))))
22259 rtn))
22261 (defun org-replace-escapes (string table)
22262 "Replace %-escapes in STRING with values in TABLE.
22263 TABLE is an association list with keys like \"%a\" and string values.
22264 The sequences in STRING may contain normal field width and padding information,
22265 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22266 so values can contain further %-escapes if they are define later in TABLE."
22267 (let ((tbl (copy-alist table))
22268 (case-fold-search nil)
22269 (pchg 0)
22270 e re rpl)
22271 (while (setq e (pop tbl))
22272 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22273 (when (and (cdr e) (string-match re (cdr e)))
22274 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22275 (safe "SREF"))
22276 (add-text-properties 0 3 (list 'sref sref) safe)
22277 (setcdr e (replace-match safe t t (cdr e)))))
22278 (while (string-match re string)
22279 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22280 (cdr e)))
22281 (setq string (replace-match rpl t t string))))
22282 (while (setq pchg (next-property-change pchg string))
22283 (let ((sref (get-text-property pchg 'sref string)))
22284 (when (and sref (string-match "SREF" string pchg))
22285 (setq string (replace-match sref t t string)))))
22286 string))
22288 (defun org-sublist (list start end)
22289 "Return a section of LIST, from START to END.
22290 Counting starts at 1."
22291 (let (rtn (c start))
22292 (setq list (nthcdr (1- start) list))
22293 (while (and list (<= c end))
22294 (push (pop list) rtn)
22295 (setq c (1+ c)))
22296 (nreverse rtn)))
22298 (defun org-find-base-buffer-visiting (file)
22299 "Like `find-buffer-visiting' but always return the base buffer and
22300 not an indirect buffer."
22301 (let ((buf (or (get-file-buffer file)
22302 (find-buffer-visiting file))))
22303 (if buf
22304 (or (buffer-base-buffer buf) buf)
22305 nil)))
22307 (defun org-image-file-name-regexp (&optional extensions)
22308 "Return regexp matching the file names of images.
22309 If EXTENSIONS is given, only match these."
22310 (if (and (not extensions) (fboundp 'image-file-name-regexp))
22311 (image-file-name-regexp)
22312 (let ((image-file-name-extensions
22313 (or extensions
22314 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
22315 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22316 (concat "\\."
22317 (regexp-opt (nconc (mapcar 'upcase
22318 image-file-name-extensions)
22319 image-file-name-extensions)
22321 "\\'"))))
22323 (defun org-file-image-p (file &optional extensions)
22324 "Return non-nil if FILE is an image."
22325 (save-match-data
22326 (string-match (org-image-file-name-regexp extensions) file)))
22328 (defun org-get-cursor-date (&optional with-time)
22329 "Return the date at cursor in as a time.
22330 This works in the calendar and in the agenda, anywhere else it just
22331 returns the current time.
22332 If WITH-TIME is non-nil, returns the time of the event at point (in
22333 the agenda) or the current time of the day."
22334 (let (date day defd tp tm hod mod)
22335 (when with-time
22336 (setq tp (get-text-property (point) 'time))
22337 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22338 (setq hod (string-to-number (match-string 1 tp))
22339 mod (string-to-number (match-string 2 tp))))
22340 (or tp (setq hod (nth 2 (decode-time (current-time)))
22341 mod (nth 1 (decode-time (current-time))))))
22342 (cond
22343 ((eq major-mode 'calendar-mode)
22344 (setq date (calendar-cursor-to-date)
22345 defd (encode-time 0 (or mod 0) (or hod 0)
22346 (nth 1 date) (nth 0 date) (nth 2 date))))
22347 ((eq major-mode 'org-agenda-mode)
22348 (setq day (get-text-property (point) 'day))
22349 (if day
22350 (setq date (calendar-gregorian-from-absolute day)
22351 defd (encode-time 0 (or mod 0) (or hod 0)
22352 (nth 1 date) (nth 0 date) (nth 2 date))))))
22353 (or defd (current-time))))
22355 (defun org-mark-subtree (&optional up)
22356 "Mark the current subtree.
22357 This puts point at the start of the current subtree, and mark at
22358 the end. If a numeric prefix UP is given, move up into the
22359 hierarchy of headlines by UP levels before marking the subtree."
22360 (interactive "P")
22361 (org-with-limited-levels
22362 (cond ((org-at-heading-p) (beginning-of-line))
22363 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22364 (t (outline-previous-visible-heading 1))))
22365 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22366 (if (org-called-interactively-p 'any)
22367 (call-interactively 'org-mark-element)
22368 (org-mark-element)))
22371 ;;; Indentation
22373 (defun org--get-expected-indentation (element contentsp)
22374 "Expected indentation column for current line, according to ELEMENT.
22375 ELEMENT is an element containing point. CONTENTSP is non-nil
22376 when indentation is to be computed according to contents of
22377 ELEMENT."
22378 (let ((type (org-element-type element))
22379 (start (org-element-property :begin element)))
22380 (org-with-wide-buffer
22381 (cond
22382 (contentsp
22383 (case type
22384 (footnote-definition 0)
22385 ((headline inlinetask nil)
22386 (if (not org-adapt-indentation) 0
22387 (let ((level (org-current-level)))
22388 (if level (1+ level) 0))))
22389 ((item plain list)
22390 (org-list-item-body-column
22391 (org-element-property :post-affiliated element)))
22392 (otherwise
22393 (goto-char start)
22394 (org-get-indentation))))
22395 ((memq type '(headline inlinetask nil))
22396 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22397 (org--get-expected-indentation element t)
22399 ((eq type 'footnote-definition) 0)
22400 ;; First paragraph of a footnote definition or an item.
22401 ;; Indent like parent.
22402 ((< (line-beginning-position) start)
22403 (org--get-expected-indentation
22404 (org-element-property :parent element) t))
22405 ;; At first line: indent according to previous sibling, if any,
22406 ;; ignoring footnote definitions and inline tasks, or parent's
22407 ;; contents.
22408 ((= (line-beginning-position) start)
22409 (catch 'exit
22410 (while t
22411 (if (= (point-min) start) (throw 'exit 0)
22412 (goto-char (1- start))
22413 (let ((previous (org-element-at-point)))
22414 (while (let ((parent (org-element-property :parent previous)))
22415 (and parent
22416 (setq previous parent)
22417 (<= (org-element-property :end parent) start))))
22418 (cond ((or (not previous)
22419 (> (org-element-property :end previous) start))
22420 (throw 'exit (org--get-expected-indentation previous t)))
22421 ((memq (org-element-type previous)
22422 '(footnote-definition inlinetask))
22423 (setq start (org-element-property :begin previous)))
22424 (t (goto-char (org-element-property :begin previous))
22425 (throw 'exit (org-get-indentation)))))))))
22426 ;; Otherwise, move to the first non-blank line above.
22428 (beginning-of-line)
22429 (let ((pos (point)))
22430 (skip-chars-backward " \r\t\n")
22431 (cond
22432 ;; Two blank lines end a footnote definition or a plain
22433 ;; list. When we indent an empty line after them, the
22434 ;; containing list or footnote definition is over, so it
22435 ;; qualifies as a previous sibling. Therefore, we indent
22436 ;; like its first line.
22437 ((and (memq type '(footnote-definition plain-list))
22438 (> (count-lines (point) pos) 2))
22439 (goto-char start)
22440 (org-get-indentation))
22441 ;; Line above is the first one of a paragraph at the
22442 ;; beginning of an item or a footnote definition. Indent
22443 ;; like parent.
22444 ((< (line-beginning-position) start)
22445 (org--get-expected-indentation
22446 (org-element-property :parent element) t))
22447 ;; POS is after contents in a greater element. Indent like
22448 ;; the beginning of the element.
22450 ;; As a special case, if point is at the end of a footnote
22451 ;; definition or an item, indent like the very last element
22452 ;; within.
22453 ((let ((cend (org-element-property :contents-end element)))
22454 (and cend (<= cend pos)))
22455 (if (memq type '(footnote-definition item plain-list))
22456 (org--get-expected-indentation (org-element-at-point) nil)
22457 (goto-char start)
22458 (org-get-indentation)))
22459 ;; In any other case, indent like the current line.
22460 (t (org-get-indentation)))))))))
22462 (defun org--align-node-property ()
22463 "Align node property at point.
22464 Alignment is done according to `org-property-format', which see."
22465 (when (save-excursion
22466 (beginning-of-line)
22467 (looking-at org-property-re))
22468 (replace-match
22469 (concat (match-string 4)
22470 (format org-property-format (match-string 1) (match-string 3)))
22471 t t)))
22473 (defun org-indent-line ()
22474 "Indent line depending on context.
22476 Indentation is done according to the following rules:
22478 - Footnote definitions, headlines and inline tasks have to
22479 start at column 0.
22481 - On the very first line of an element, consider, in order, the
22482 next rules until one matches:
22484 1. If there's a sibling element before, ignoring footnote
22485 definitions and inline tasks, indent like its first line.
22487 2. If element has a parent, indent like its contents. More
22488 precisely, if parent is an item, indent after the
22489 description part, if any, or the bullet (see
22490 ``org-list-description-max-indent'). Else, indent like
22491 parent's first line.
22493 3. Otherwise, indent relatively to current level, if
22494 `org-adapt-indentation' is non-nil, or to left margin.
22496 - On a blank line at the end of a plain list, an item, or
22497 a footnote definition, indent like the very last element
22498 within.
22500 - In the code part of a source block, use language major mode
22501 to indent current line if `org-src-tab-acts-natively' is
22502 non-nil. If it is nil, do nothing.
22504 - Otherwise, indent like the first non-blank line above.
22506 The function doesn't indent an item as it could break the whole
22507 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22508 \\[org-shiftmetaright].
22510 Also align node properties according to `org-property-format'."
22511 (interactive)
22512 (cond
22513 (orgstruct-is-++
22514 (let ((indent-line-function
22515 (cadadr (assq 'indent-line-function org-fb-vars))))
22516 (indent-according-to-mode)))
22517 ((org-at-heading-p) 'noindent)
22519 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22520 (type (org-element-type element)))
22521 (cond ((and (memq type '(plain-list item))
22522 (= (line-beginning-position)
22523 (org-element-property :post-affiliated element)))
22524 'noindent)
22525 ((and (eq type 'src-block)
22526 org-src-tab-acts-natively
22527 (> (line-beginning-position)
22528 (org-element-property :post-affiliated element))
22529 (< (line-beginning-position)
22530 (org-with-wide-buffer
22531 (goto-char (org-element-property :end element))
22532 (skip-chars-backward " \r\t\n")
22533 (line-beginning-position))))
22534 (let ((org-src-strip-leading-and-trailing-blank-lines nil))
22535 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB"))))
22537 (let ((column (org--get-expected-indentation element nil)))
22538 ;; Preserve current column.
22539 (if (<= (current-column) (current-indentation))
22540 (org-indent-line-to column)
22541 (save-excursion (org-indent-line-to column))))
22542 ;; Align node property. Also preserve current column.
22543 (when (eq type 'node-property)
22544 (let ((column (current-column)))
22545 (org--align-node-property)
22546 (org-move-to-column column)))))))))
22548 (defun org-indent-region (start end)
22549 "Indent each non-blank line in the region.
22550 Called from a program, START and END specify the region to
22551 indent. The function will not indent contents of example blocks,
22552 verse blocks and export blocks as leading white spaces are
22553 assumed to be significant there."
22554 (interactive "r")
22555 (save-excursion
22556 (goto-char start)
22557 (beginning-of-line)
22558 (let ((indent-to
22559 (lambda (ind pos)
22560 ;; Set IND as indentation for all lines between point and
22561 ;; POS or END, whichever comes first. Blank lines are
22562 ;; ignored. Leave point after POS once done.
22563 (let ((limit (copy-marker (min end pos))))
22564 (while (< (point) limit)
22565 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
22566 (forward-line))
22567 (set-marker limit nil))))
22568 (end (copy-marker end)))
22569 (while (< (point) end)
22570 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22571 (let* ((element (org-element-at-point))
22572 (type (org-element-type element))
22573 (element-end (copy-marker (org-element-property :end element)))
22574 (ind (org--get-expected-indentation element nil)))
22575 (if (or (memq type '(paragraph table table-row))
22576 (not (or (org-element-property :contents-begin element)
22577 (memq type
22578 '(example-block export-block src-block)))))
22579 ;; Elements here are indented as a single block. Also
22580 ;; align node properties.
22581 (progn
22582 (when (eq type 'node-property)
22583 (org--align-node-property)
22584 (beginning-of-line))
22585 (funcall indent-to ind element-end))
22586 ;; Elements in this category consist of three parts:
22587 ;; before the contents, the contents, and after the
22588 ;; contents. The contents are treated specially,
22589 ;; according to the element type, or not indented at
22590 ;; all. Other parts are indented as a single block.
22591 (let* ((post (copy-marker
22592 (org-element-property :post-affiliated element)))
22593 (cbeg
22594 (copy-marker
22595 (cond
22596 ((not (org-element-property :contents-begin element))
22597 ;; Fake contents for source blocks.
22598 (org-with-wide-buffer
22599 (goto-char post)
22600 (forward-line)
22601 (point)))
22602 ((memq type '(footnote-definition item plain-list))
22603 ;; Contents in these elements could start on
22604 ;; the same line as the beginning of the
22605 ;; element. Make sure we start indenting
22606 ;; from the second line.
22607 (org-with-wide-buffer
22608 (goto-char post)
22609 (forward-line)
22610 (point)))
22611 (t (org-element-property :contents-begin element)))))
22612 (cend (copy-marker
22613 (or (org-element-property :contents-end element)
22614 ;; Fake contents for source blocks.
22615 (org-with-wide-buffer
22616 (goto-char element-end)
22617 (skip-chars-backward " \r\t\n")
22618 (line-beginning-position))))))
22619 (funcall indent-to ind cbeg)
22620 (when (< (point) end)
22621 (case type
22622 ((example-block export-block verse-block))
22623 (src-block
22624 ;; In a source block, indent source code according
22625 ;; to language major mode, but only if
22626 ;; `org-src-tab-acts-natively' is non-nil.
22627 (when (and (< (point) end) org-src-tab-acts-natively)
22628 (ignore-errors
22629 (let (org-src-strip-leading-and-trailing-blank-lines
22630 ;; Region boundaries in edit buffer.
22631 (start (1+ (- (point) cbeg)))
22632 (end (- (min cend end) cbeg)))
22633 (org-babel-do-in-edit-buffer
22634 (indent-region start end))))))
22635 (t (org-indent-region (point) (min cend end))))
22636 (goto-char (min cend end))
22637 (when (< (point) end) (funcall indent-to ind element-end)))
22638 (set-marker post nil)
22639 (set-marker cbeg nil)
22640 (set-marker cend nil)))
22641 (set-marker element-end nil))))
22642 (set-marker end nil))))
22644 (defun org-indent-drawer ()
22645 "Indent the drawer at point."
22646 (interactive)
22647 (unless (save-excursion
22648 (beginning-of-line)
22649 (org-looking-at-p org-drawer-regexp))
22650 (user-error "Not at a drawer"))
22651 (let ((element (org-element-at-point)))
22652 (unless (memq (org-element-type element) '(drawer property-drawer))
22653 (user-error "Not at a drawer"))
22654 (org-with-wide-buffer
22655 (org-indent-region (org-element-property :begin element)
22656 (org-element-property :end element))))
22657 (message "Drawer at point indented"))
22659 (defun org-indent-block ()
22660 "Indent the block at point."
22661 (interactive)
22662 (unless (save-excursion
22663 (beginning-of-line)
22664 (let ((case-fold-search t))
22665 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22666 (user-error "Not at a block"))
22667 (let ((element (org-element-at-point)))
22668 (unless (memq (org-element-type element)
22669 '(comment-block center-block example-block export-block
22670 quote-block special-block src-block
22671 verse-block))
22672 (user-error "Not at a block"))
22673 (org-with-wide-buffer
22674 (org-indent-region (org-element-property :begin element)
22675 (org-element-property :end element))))
22676 (message "Block at point indented"))
22679 ;;; Filling
22681 ;; We use our own fill-paragraph and auto-fill functions.
22683 ;; `org-fill-paragraph' relies on adaptive filling and context
22684 ;; checking. Appropriate `fill-prefix' is computed with
22685 ;; `org-adaptive-fill-function'.
22687 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22688 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22689 ;; `org-adaptive-fill-function' value. Internally,
22690 ;; `org-comment-line-break-function' breaks the line.
22692 ;; `org-setup-filling' installs filling and auto-filling related
22693 ;; variables during `org-mode' initialization.
22695 (defvar org-element-paragraph-separate) ; org-element.el
22696 (defun org-setup-filling ()
22697 (require 'org-element)
22698 ;; Prevent auto-fill from inserting unwanted new items.
22699 (when (boundp 'fill-nobreak-predicate)
22700 (org-set-local
22701 'fill-nobreak-predicate
22702 (org-uniquify
22703 (append fill-nobreak-predicate
22704 '(org-fill-line-break-nobreak-p
22705 org-fill-paragraph-with-timestamp-nobreak-p)))))
22706 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22707 (org-set-local 'paragraph-start paragraph-ending)
22708 (org-set-local 'paragraph-separate paragraph-ending))
22709 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22710 (org-set-local 'auto-fill-inhibit-regexp nil)
22711 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22712 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22713 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22715 (defun org-fill-line-break-nobreak-p ()
22716 "Non-nil when a new line at point would create an Org line break."
22717 (save-excursion
22718 (skip-chars-backward "[ \t]")
22719 (skip-chars-backward "\\\\")
22720 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22722 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22723 "Non-nil when a new line at point would split a timestamp."
22724 (and (org-at-timestamp-p t)
22725 (not (looking-at org-ts-regexp-both))))
22727 (declare-function message-in-body-p "message" ())
22728 (defvar orgtbl-line-start-regexp) ; From org-table.el
22729 (defun org-adaptive-fill-function ()
22730 "Compute a fill prefix for the current line.
22731 Return fill prefix, as a string, or nil if current line isn't
22732 meant to be filled. For convenience, if `adaptive-fill-regexp'
22733 matches in paragraphs or comments, use it."
22734 (catch 'exit
22735 (when (derived-mode-p 'message-mode)
22736 (save-excursion
22737 (beginning-of-line)
22738 (cond ((or (not (message-in-body-p))
22739 (looking-at orgtbl-line-start-regexp))
22740 (throw 'exit nil))
22741 ((looking-at message-cite-prefix-regexp)
22742 (throw 'exit (match-string-no-properties 0)))
22743 ((looking-at org-outline-regexp)
22744 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22745 (org-with-wide-buffer
22746 (unless (org-at-heading-p)
22747 (let* ((p (line-beginning-position))
22748 (element (save-excursion
22749 (beginning-of-line)
22750 (org-element-at-point)))
22751 (type (org-element-type element))
22752 (post-affiliated (org-element-property :post-affiliated element)))
22753 (unless (< p post-affiliated)
22754 (case type
22755 (comment
22756 (save-excursion
22757 (beginning-of-line)
22758 (looking-at "[ \t]*")
22759 (concat (match-string 0) "# ")))
22760 (footnote-definition "")
22761 ((item plain-list)
22762 (make-string (org-list-item-body-column post-affiliated) ?\s))
22763 (paragraph
22764 ;; Fill prefix is usually the same as the current line,
22765 ;; unless the paragraph is at the beginning of an item.
22766 (let ((parent (org-element-property :parent element)))
22767 (save-excursion
22768 (beginning-of-line)
22769 (cond ((eq (org-element-type parent) 'item)
22770 (make-string (org-list-item-body-column
22771 (org-element-property :begin parent))
22772 ?\s))
22773 ((and adaptive-fill-regexp
22774 ;; Locally disable
22775 ;; `adaptive-fill-function' to let
22776 ;; `fill-context-prefix' handle
22777 ;; `adaptive-fill-regexp' variable.
22778 (let (adaptive-fill-function)
22779 (fill-context-prefix
22780 post-affiliated
22781 (org-element-property :end element)))))
22782 ((looking-at "[ \t]+") (match-string 0))
22783 (t "")))))
22784 (comment-block
22785 ;; Only fill contents if P is within block boundaries.
22786 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22787 (forward-line)
22788 (point)))
22789 (cend (save-excursion
22790 (goto-char (org-element-property :end element))
22791 (skip-chars-backward " \r\t\n")
22792 (line-beginning-position))))
22793 (when (and (>= p cbeg) (< p cend))
22794 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22795 (match-string 0)
22796 "")))))))))))
22798 (declare-function message-goto-body "message" ())
22799 (defvar message-cite-prefix-regexp) ; From message.el
22800 (defun org-fill-paragraph (&optional justify)
22801 "Fill element at point, when applicable.
22803 This function only applies to comment blocks, comments, example
22804 blocks and paragraphs. Also, as a special case, re-align table
22805 when point is at one.
22807 If JUSTIFY is non-nil (interactively, with prefix argument),
22808 justify as well. If `sentence-end-double-space' is non-nil, then
22809 period followed by one space does not end a sentence, so don't
22810 break a line there. The variable `fill-column' controls the
22811 width for filling.
22813 For convenience, when point is at a plain list, an item or
22814 a footnote definition, try to fill the first paragraph within."
22815 (interactive)
22816 (if (and (derived-mode-p 'message-mode)
22817 (or (not (message-in-body-p))
22818 (save-excursion (move-beginning-of-line 1)
22819 (looking-at message-cite-prefix-regexp))))
22820 ;; First ensure filling is correct in message-mode.
22821 (let ((fill-paragraph-function
22822 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22823 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22824 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22825 (paragraph-separate
22826 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22827 (fill-paragraph nil))
22828 (with-syntax-table org-mode-transpose-word-syntax-table
22829 ;; Move to end of line in order to get the first paragraph
22830 ;; within a plain list or a footnote definition.
22831 (let ((element (save-excursion
22832 (end-of-line)
22833 (or (ignore-errors (org-element-at-point))
22834 (user-error "An element cannot be parsed line %d"
22835 (line-number-at-pos (point)))))))
22836 ;; First check if point is in a blank line at the beginning of
22837 ;; the buffer. In that case, ignore filling.
22838 (case (org-element-type element)
22839 ;; Use major mode filling function is src blocks.
22840 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22841 ;; Align Org tables, leave table.el tables as-is.
22842 (table-row (org-table-align) t)
22843 (table
22844 (when (eq (org-element-property :type element) 'org)
22845 (save-excursion
22846 (goto-char (org-element-property :post-affiliated element))
22847 (org-table-align)))
22849 (paragraph
22850 ;; Paragraphs may contain `line-break' type objects.
22851 (let ((beg (max (point-min)
22852 (org-element-property :contents-begin element)))
22853 (end (min (point-max)
22854 (org-element-property :contents-end element))))
22855 ;; Do nothing if point is at an affiliated keyword.
22856 (if (< (line-end-position) beg) t
22857 (when (derived-mode-p 'message-mode)
22858 ;; In `message-mode', do not fill following citation
22859 ;; in current paragraph nor text before message body.
22860 (let ((body-start (save-excursion (message-goto-body))))
22861 (when body-start (setq beg (max body-start beg))))
22862 (when (save-excursion
22863 (re-search-forward
22864 (concat "^" message-cite-prefix-regexp) end t))
22865 (setq end (match-beginning 0))))
22866 ;; Fill paragraph, taking line breaks into account.
22867 (save-excursion
22868 (goto-char beg)
22869 (let ((cuts (list beg)))
22870 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22871 (when (eq 'line-break
22872 (org-element-type
22873 (save-excursion (backward-char)
22874 (org-element-context))))
22875 (push (point) cuts)))
22876 (dolist (c (delq end cuts))
22877 (fill-region-as-paragraph c end justify)
22878 (setq end c))))
22879 t)))
22880 ;; Contents of `comment-block' type elements should be
22881 ;; filled as plain text, but only if point is within block
22882 ;; markers.
22883 (comment-block
22884 (let* ((case-fold-search t)
22885 (beg (save-excursion
22886 (goto-char (org-element-property :begin element))
22887 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22888 (forward-line)
22889 (point)))
22890 (end (save-excursion
22891 (goto-char (org-element-property :end element))
22892 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22893 (line-beginning-position))))
22894 (if (or (< (point) beg) (> (point) end)) t
22895 (fill-region-as-paragraph
22896 (save-excursion (end-of-line)
22897 (re-search-backward "^[ \t]*$" beg 'move)
22898 (line-beginning-position))
22899 (save-excursion (beginning-of-line)
22900 (re-search-forward "^[ \t]*$" end 'move)
22901 (line-beginning-position))
22902 justify))))
22903 ;; Fill comments.
22904 (comment
22905 (let ((begin (org-element-property :post-affiliated element))
22906 (end (org-element-property :end element)))
22907 (when (and (>= (point) begin) (<= (point) end))
22908 (let ((begin (save-excursion
22909 (end-of-line)
22910 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22911 (progn (forward-line) (point))
22912 begin)))
22913 (end (save-excursion
22914 (end-of-line)
22915 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22916 (1- (line-beginning-position))
22917 (skip-chars-backward " \r\t\n")
22918 (line-end-position)))))
22919 ;; Do not fill comments when at a blank line.
22920 (when (> end begin)
22921 (let ((fill-prefix
22922 (save-excursion
22923 (beginning-of-line)
22924 (looking-at "[ \t]*#")
22925 (let ((comment-prefix (match-string 0)))
22926 (goto-char (match-end 0))
22927 (if (looking-at adaptive-fill-regexp)
22928 (concat comment-prefix (match-string 0))
22929 (concat comment-prefix " "))))))
22930 (save-excursion
22931 (fill-region-as-paragraph begin end justify))))))
22933 ;; Ignore every other element.
22934 (otherwise t))))))
22936 (defun org-auto-fill-function ()
22937 "Auto-fill function."
22938 ;; Check if auto-filling is meaningful.
22939 (let ((fc (current-fill-column)))
22940 (when (and fc (> (current-column) fc))
22941 (let* ((fill-prefix (org-adaptive-fill-function))
22942 ;; Enforce empty fill prefix, if required. Otherwise, it
22943 ;; will be computed again.
22944 (adaptive-fill-mode (not (equal fill-prefix ""))))
22945 (when fill-prefix (do-auto-fill))))))
22947 (defun org-comment-line-break-function (&optional soft)
22948 "Break line at point and indent, continuing comment if within one.
22949 The inserted newline is marked hard if variable
22950 `use-hard-newlines' is true, unless optional argument SOFT is
22951 non-nil."
22952 (if soft (insert-and-inherit ?\n) (newline 1))
22953 (save-excursion (forward-char -1) (delete-horizontal-space))
22954 (delete-horizontal-space)
22955 (indent-to-left-margin)
22956 (insert-before-markers-and-inherit fill-prefix))
22959 ;;; Fixed Width Areas
22961 (defun org-toggle-fixed-width ()
22962 "Toggle fixed-width markup.
22964 Add or remove fixed-width markup on current line, whenever it
22965 makes sense. Return an error otherwise.
22967 If a region is active and if it contains only fixed-width areas
22968 or blank lines, remove all fixed-width markup in it. If the
22969 region contains anything else, convert all non-fixed-width lines
22970 to fixed-width ones.
22972 Blank lines at the end of the region are ignored unless the
22973 region only contains such lines."
22974 (interactive)
22975 (if (not (org-region-active-p))
22976 ;; No region:
22978 ;; Remove fixed width marker only in a fixed-with element.
22980 ;; Add fixed width maker in paragraphs, in blank lines after
22981 ;; elements or at the beginning of a headline or an inlinetask,
22982 ;; and before any one-line elements (e.g., a clock).
22983 (progn
22984 (beginning-of-line)
22985 (let* ((element (org-element-at-point))
22986 (type (org-element-type element)))
22987 (cond
22988 ((and (eq type 'fixed-width)
22989 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22990 (replace-match
22991 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22992 ((and (memq type '(babel-call clock comment diary-sexp headline
22993 horizontal-rule keyword paragraph
22994 planning))
22995 (<= (org-element-property :post-affiliated element) (point)))
22996 (skip-chars-forward " \t")
22997 (insert ": "))
22998 ((and (org-looking-at-p "[ \t]*$")
22999 (or (eq type 'inlinetask)
23000 (save-excursion
23001 (skip-chars-forward " \r\t\n")
23002 (<= (org-element-property :end element) (point)))))
23003 (delete-region (point) (line-end-position))
23004 (org-indent-line)
23005 (insert ": "))
23006 (t (user-error "Cannot insert a fixed-width line here")))))
23007 ;; Region active.
23008 (let* ((begin (save-excursion
23009 (goto-char (region-beginning))
23010 (line-beginning-position)))
23011 (end (copy-marker
23012 (save-excursion
23013 (goto-char (region-end))
23014 (unless (eolp) (beginning-of-line))
23015 (if (save-excursion (re-search-backward "\\S-" begin t))
23016 (progn (skip-chars-backward " \r\t\n") (point))
23017 (point)))))
23018 (all-fixed-width-p
23019 (catch 'not-all-p
23020 (save-excursion
23021 (goto-char begin)
23022 (skip-chars-forward " \r\t\n")
23023 (when (eobp) (throw 'not-all-p nil))
23024 (while (< (point) end)
23025 (let ((element (org-element-at-point)))
23026 (if (eq (org-element-type element) 'fixed-width)
23027 (goto-char (org-element-property :end element))
23028 (throw 'not-all-p nil))))
23029 t))))
23030 (if all-fixed-width-p
23031 (save-excursion
23032 (goto-char begin)
23033 (while (< (point) end)
23034 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23035 (replace-match
23036 "" nil nil nil
23037 (if (= (line-end-position) (match-end 0)) 0 1)))
23038 (forward-line)))
23039 (let ((min-ind (point-max)))
23040 ;; Find minimum indentation across all lines.
23041 (save-excursion
23042 (goto-char begin)
23043 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23044 (setq min-ind 0)
23045 (catch 'zerop
23046 (while (< (point) end)
23047 (unless (org-looking-at-p "[ \t]*$")
23048 (let ((ind (org-get-indentation)))
23049 (setq min-ind (min min-ind ind))
23050 (when (zerop ind) (throw 'zerop t))))
23051 (forward-line)))))
23052 ;; Loop over all lines and add fixed-width markup everywhere
23053 ;; but in fixed-width lines.
23054 (save-excursion
23055 (goto-char begin)
23056 (while (< (point) end)
23057 (cond
23058 ((org-at-heading-p)
23059 (insert ": ")
23060 (forward-line)
23061 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23062 (insert ":")
23063 (forward-line)))
23064 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23065 (let* ((element (org-element-at-point))
23066 (element-end (org-element-property :end element)))
23067 (if (eq (org-element-type element) 'fixed-width)
23068 (progn (goto-char element-end)
23069 (skip-chars-backward " \r\t\n")
23070 (forward-line))
23071 (let ((limit (min end element-end)))
23072 (while (< (point) limit)
23073 (org-move-to-column min-ind t)
23074 (insert ": ")
23075 (forward-line))))))
23077 (org-move-to-column min-ind t)
23078 (insert ": ")
23079 (forward-line)))))))
23080 (set-marker end nil))))
23083 ;;; Comments
23085 ;; Org comments syntax is quite complex. It requires the entire line
23086 ;; to be just a comment. Also, even with the right syntax at the
23087 ;; beginning of line, some some elements (i.e. verse-block or
23088 ;; example-block) don't accept comments. Usual Emacs comment commands
23089 ;; cannot cope with those requirements. Therefore, Org replaces them.
23091 ;; Org still relies on `comment-dwim', but cannot trust
23092 ;; `comment-only-p'. So, `comment-region-function' and
23093 ;; `uncomment-region-function' both point
23094 ;; to`org-comment-or-uncomment-region'. Eventually,
23095 ;; `org-insert-comment' takes care of insertion of comments at the
23096 ;; beginning of line.
23098 ;; `org-setup-comments-handling' install comments related variables
23099 ;; during `org-mode' initialization.
23101 (defun org-setup-comments-handling ()
23102 (interactive)
23103 (org-set-local 'comment-use-syntax nil)
23104 (org-set-local 'comment-start "# ")
23105 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23106 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
23107 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
23108 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
23110 (defun org-insert-comment ()
23111 "Insert an empty comment above current line.
23112 If the line is empty, insert comment at its beginning. When
23113 point is within a source block, comment according to the related
23114 major mode."
23115 (if (let ((element (org-element-at-point)))
23116 (and (eq (org-element-type element) 'src-block)
23117 (< (save-excursion
23118 (goto-char (org-element-property :post-affiliated element))
23119 (line-end-position))
23120 (point))
23121 (> (save-excursion
23122 (goto-char (org-element-property :end element))
23123 (skip-chars-backward " \r\t\n")
23124 (line-beginning-position))
23125 (point))))
23126 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23127 (beginning-of-line)
23128 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23129 (open-line 1))
23130 (org-indent-line)
23131 (insert "# ")))
23133 (defvar comment-empty-lines) ; From newcomment.el.
23134 (defun org-comment-or-uncomment-region (beg end &rest ignore)
23135 "Comment or uncomment each non-blank line in the region.
23136 Uncomment each non-blank line between BEG and END if it only
23137 contains commented lines. Otherwise, comment them. If region is
23138 strictly within a source block, use appropriate comment syntax."
23139 (if (let ((element (org-element-at-point)))
23140 (and (eq (org-element-type element) 'src-block)
23141 (< (save-excursion
23142 (goto-char (org-element-property :post-affiliated element))
23143 (line-end-position))
23144 beg)
23145 (>= (save-excursion
23146 (goto-char (org-element-property :end element))
23147 (skip-chars-backward " \r\t\n")
23148 (line-beginning-position))
23149 end)))
23150 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23151 (save-restriction
23152 ;; Restrict region
23153 (narrow-to-region (save-excursion (goto-char beg)
23154 (skip-chars-forward " \r\t\n" end)
23155 (line-beginning-position))
23156 (save-excursion (goto-char end)
23157 (skip-chars-backward " \r\t\n" beg)
23158 (line-end-position)))
23159 (let ((uncommentp
23160 ;; UNCOMMENTP is non-nil when every non blank line between
23161 ;; BEG and END is a comment.
23162 (save-excursion
23163 (goto-char (point-min))
23164 (while (and (not (eobp))
23165 (let ((element (org-element-at-point)))
23166 (and (eq (org-element-type element) 'comment)
23167 (goto-char (min (point-max)
23168 (org-element-property
23169 :end element)))))))
23170 (eobp))))
23171 (if uncommentp
23172 ;; Only blank lines and comments in region: uncomment it.
23173 (save-excursion
23174 (goto-char (point-min))
23175 (while (not (eobp))
23176 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23177 (replace-match "" nil nil nil 1))
23178 (forward-line)))
23179 ;; Comment each line in region.
23180 (let ((min-indent (point-max)))
23181 ;; First find the minimum indentation across all lines.
23182 (save-excursion
23183 (goto-char (point-min))
23184 (while (and (not (eobp)) (not (zerop min-indent)))
23185 (unless (looking-at "[ \t]*$")
23186 (setq min-indent (min min-indent (current-indentation))))
23187 (forward-line)))
23188 ;; Then loop over all lines.
23189 (save-excursion
23190 (goto-char (point-min))
23191 (while (not (eobp))
23192 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23193 ;; Don't get fooled by invisible text (e.g. link path)
23194 ;; when moving to column MIN-INDENT.
23195 (let ((buffer-invisibility-spec nil))
23196 (org-move-to-column min-indent t))
23197 (insert comment-start))
23198 (forward-line)))))))))
23200 (defun org-comment-dwim (arg)
23201 "Call `comment-dwim' within a source edit buffer if needed."
23202 (interactive "*P")
23203 (if (org-in-src-block-p)
23204 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23205 (call-interactively 'comment-dwim)))
23208 ;;; Planning
23210 ;; This section contains tools to operate on timestamp objects, as
23211 ;; returned by, e.g. `org-element-context'.
23213 (defun org-timestamp-has-time-p (timestamp)
23214 "Non-nil when TIMESTAMP has a time specified."
23215 (org-element-property :hour-start timestamp))
23217 (defun org-timestamp-format (timestamp format &optional end utc)
23218 "Format a TIMESTAMP element into a string.
23220 FORMAT is a format specifier to be passed to
23221 `format-time-string'.
23223 When optional argument END is non-nil, use end of date-range or
23224 time-range, if possible.
23226 When optional argument UTC is non-nil, time will be expressed as
23227 Universal Time."
23228 (format-time-string
23229 format
23230 (apply 'encode-time
23231 (cons 0
23232 (mapcar
23233 (lambda (prop) (or (org-element-property prop timestamp) 0))
23234 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23235 '(:minute-start :hour-start :day-start :month-start
23236 :year-start)))))
23237 utc))
23239 (defun org-timestamp-split-range (timestamp &optional end)
23240 "Extract a timestamp object from a date or time range.
23242 TIMESTAMP is a timestamp object. END, when non-nil, means extract
23243 the end of the range. Otherwise, extract its start.
23245 Return a new timestamp object sharing the same parent as
23246 TIMESTAMP."
23247 (let ((type (org-element-property :type timestamp)))
23248 (if (memq type '(active inactive diary)) timestamp
23249 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
23250 ;; Set new type.
23251 (org-element-put-property
23252 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23253 ;; Copy start properties over end properties if END is
23254 ;; non-nil. Otherwise, copy end properties over `start' ones.
23255 (let ((p-alist '((:minute-start . :minute-end)
23256 (:hour-start . :hour-end)
23257 (:day-start . :day-end)
23258 (:month-start . :month-end)
23259 (:year-start . :year-end))))
23260 (dolist (p-cell p-alist)
23261 (org-element-put-property
23262 split-ts
23263 (funcall (if end 'car 'cdr) p-cell)
23264 (org-element-property
23265 (funcall (if end 'cdr 'car) p-cell) split-ts)))
23266 ;; Eventually refresh `:raw-value'.
23267 (org-element-put-property split-ts :raw-value nil)
23268 (org-element-put-property
23269 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23271 (defun org-timestamp-translate (timestamp &optional boundary)
23272 "Apply `org-translate-time' on a TIMESTAMP object.
23273 When optional argument BOUNDARY is non-nil, it is either the
23274 symbol `start' or `end'. In this case, only translate the
23275 starting or ending part of TIMESTAMP if it is a date or time
23276 range. Otherwise, translate both parts."
23277 (if (and (not boundary)
23278 (memq (org-element-property :type timestamp)
23279 '(active-range inactive-range)))
23280 (concat
23281 (org-translate-time
23282 (org-element-property :raw-value
23283 (org-timestamp-split-range timestamp)))
23284 "--"
23285 (org-translate-time
23286 (org-element-property :raw-value
23287 (org-timestamp-split-range timestamp t))))
23288 (org-translate-time
23289 (org-element-property
23290 :raw-value
23291 (if (not boundary) timestamp
23292 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
23296 ;;; Other stuff.
23298 (defun org-reftex-citation ()
23299 "Use reftex-citation to insert a citation into the buffer.
23300 This looks for a line like
23302 #+BIBLIOGRAPHY: foo plain option:-d
23304 and derives from it that foo.bib is the bibliography file relevant
23305 for this document. It then installs the necessary environment for RefTeX
23306 to work in this buffer and calls `reftex-citation' to insert a citation
23307 into the buffer.
23309 Export of such citations to both LaTeX and HTML is handled by the contributed
23310 package ox-bibtex by Taru Karttunen."
23311 (interactive)
23312 (let ((reftex-docstruct-symbol 'rds)
23313 (reftex-cite-format "\\cite{%l}")
23314 rds bib)
23315 (save-excursion
23316 (save-restriction
23317 (widen)
23318 (let ((case-fold-search t)
23319 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23320 (if (not (save-excursion
23321 (or (re-search-forward re nil t)
23322 (re-search-backward re nil t))))
23323 (user-error "No bibliography defined in file")
23324 (setq bib (concat (match-string 1) ".bib")
23325 rds (list (list 'bib bib)))))))
23326 (call-interactively 'reftex-citation)))
23328 ;;;; Functions extending outline functionality
23330 (defun org-beginning-of-line (&optional arg)
23331 "Go to the beginning of the current line. If that is invisible, continue
23332 to a visible line beginning. This makes the function of C-a more intuitive.
23333 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23334 first attempt, and only move to after the tags when the cursor is already
23335 beyond the end of the headline."
23336 (interactive "P")
23337 (let ((pos (point))
23338 (special (if (consp org-special-ctrl-a/e)
23339 (car org-special-ctrl-a/e)
23340 org-special-ctrl-a/e))
23341 deactivate-mark refpos)
23342 (if (org-bound-and-true-p visual-line-mode)
23343 (beginning-of-visual-line 1)
23344 (beginning-of-line 1))
23345 (if (and arg (fboundp 'move-beginning-of-line))
23346 (call-interactively 'move-beginning-of-line)
23347 (if (bobp)
23349 (backward-char 1)
23350 (if (org-truely-invisible-p)
23351 (while (and (not (bobp)) (org-truely-invisible-p))
23352 (backward-char 1)
23353 (beginning-of-line 1))
23354 (forward-char 1))))
23355 (when special
23356 (cond
23357 ((and (looking-at org-complex-heading-regexp)
23358 (= (char-after (match-end 1)) ?\ ))
23359 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23360 (point-at-eol)))
23361 (goto-char
23362 (if (eq special t)
23363 (cond ((> pos refpos) refpos)
23364 ((= pos (point)) refpos)
23365 (t (point)))
23366 (cond ((> pos (point)) (point))
23367 ((not (eq last-command this-command)) (point))
23368 (t refpos)))))
23369 ((org-at-item-p)
23370 ;; Being at an item and not looking at an the item means point
23371 ;; was previously moved to beginning of a visual line, which
23372 ;; doesn't contain the item. Therefore, do nothing special,
23373 ;; just stay here.
23374 (when (looking-at org-list-full-item-re)
23375 ;; Set special position at first white space character after
23376 ;; bullet, and check-box, if any.
23377 (let ((after-bullet
23378 (let ((box (match-end 3)))
23379 (if (not box) (match-end 1)
23380 (let ((after (char-after box)))
23381 (if (and after (= after ? )) (1+ box) box))))))
23382 ;; Special case: Move point to special position when
23383 ;; currently after it or at beginning of line.
23384 (if (eq special t)
23385 (when (or (> pos after-bullet) (= (point) pos))
23386 (goto-char after-bullet))
23387 ;; Reversed case: Move point to special position when
23388 ;; point was already at beginning of line and command is
23389 ;; repeated.
23390 (when (and (= (point) pos) (eq last-command this-command))
23391 (goto-char after-bullet))))))))
23392 (org-no-warnings
23393 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23394 (setq disable-point-adjustment
23395 (or (not (invisible-p (point)))
23396 (not (invisible-p (max (point-min) (1- (point))))))))
23398 (defun org-end-of-line (&optional arg)
23399 "Go to the end of the line.
23400 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23401 tags on the first attempt, and only move to after the tags when
23402 the cursor is already beyond the end of the headline."
23403 (interactive "P")
23404 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23405 org-special-ctrl-a/e))
23406 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23407 'end-of-visual-line)
23408 ((fboundp 'move-end-of-line) 'move-end-of-line)
23409 (t 'end-of-line)))
23410 deactivate-mark)
23411 (if (or (not special) arg) (call-interactively move-fun)
23412 (let* ((element (save-excursion (beginning-of-line)
23413 (org-element-at-point)))
23414 (type (org-element-type element)))
23415 (cond
23416 ((memq type '(headline inlinetask))
23417 (let ((pos (point)))
23418 (beginning-of-line 1)
23419 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23420 (if (eq special t)
23421 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23422 (goto-char (match-beginning 1))
23423 (goto-char (match-end 0)))
23424 (if (or (< pos (match-end 0))
23425 (not (eq this-command last-command)))
23426 (goto-char (match-end 0))
23427 (goto-char (match-beginning 1))))
23428 (call-interactively move-fun))))
23429 ((outline-invisible-p (line-end-position))
23430 ;; If element is hidden, `move-end-of-line' would put point
23431 ;; after it. Use `end-of-line' to stay on current line.
23432 (call-interactively 'end-of-line))
23433 (t (call-interactively move-fun)))))
23434 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23435 (setq disable-point-adjustment
23436 (or (not (invisible-p (point)))
23437 (not (invisible-p (max (point-min) (1- (point))))))))
23439 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23440 (define-key org-mode-map "\C-e" 'org-end-of-line)
23442 (defun org-backward-sentence (&optional arg)
23443 "Go to beginning of sentence, or beginning of table field.
23444 This will call `backward-sentence' or `org-table-beginning-of-field',
23445 depending on context."
23446 (interactive "P")
23447 (cond
23448 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
23449 (t (call-interactively 'backward-sentence))))
23451 (defun org-forward-sentence (&optional arg)
23452 "Go to end of sentence, or end of table field.
23453 This will call `forward-sentence' or `org-table-end-of-field',
23454 depending on context."
23455 (interactive "P")
23456 (cond
23457 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
23458 (t (call-interactively 'forward-sentence))))
23460 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23461 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23463 (defun org-kill-line (&optional arg)
23464 "Kill line, to tags or end of line."
23465 (interactive "P")
23466 (cond
23467 ((or (not org-special-ctrl-k)
23468 (bolp)
23469 (not (org-at-heading-p)))
23470 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23471 org-ctrl-k-protect-subtree)
23472 (if (or (eq org-ctrl-k-protect-subtree 'error)
23473 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
23474 (user-error "C-k aborted as it would kill a hidden subtree")))
23475 (call-interactively
23476 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23477 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23478 (kill-region (point) (match-beginning 1))
23479 (org-set-tags nil t))
23480 (t (kill-region (point) (point-at-eol)))))
23482 (define-key org-mode-map "\C-k" 'org-kill-line)
23484 (defun org-yank (&optional arg)
23485 "Yank. If the kill is a subtree, treat it specially.
23486 This command will look at the current kill and check if is a single
23487 subtree, or a series of subtrees[1]. If it passes the test, and if the
23488 cursor is at the beginning of a line or after the stars of a currently
23489 empty headline, then the yank is handled specially. How exactly depends
23490 on the value of the following variables, both set by default.
23492 `org-yank-folded-subtrees'
23493 When set, the subtree(s) will be folded after insertion, but only
23494 if doing so would now swallow text after the yanked text.
23496 `org-yank-adjusted-subtrees'
23497 When set, the subtree will be promoted or demoted in order to
23498 fit into the local outline tree structure, which means that the
23499 level will be adjusted so that it becomes the smaller one of the
23500 two *visible* surrounding headings.
23502 Any prefix to this command will cause `yank' to be called directly with
23503 no special treatment. In particular, a simple \\[universal-argument] prefix \
23504 will just
23505 plainly yank the text as it is.
23507 \[1] The test checks if the first non-white line is a heading
23508 and if there are no other headings with fewer stars."
23509 (interactive "P")
23510 (org-yank-generic 'yank arg))
23512 (defun org-yank-generic (command arg)
23513 "Perform some yank-like command.
23515 This function implements the behavior described in the `org-yank'
23516 documentation. However, it has been generalized to work for any
23517 interactive command with similar behavior."
23519 ;; pretend to be command COMMAND
23520 (setq this-command command)
23522 (if arg
23523 (call-interactively command)
23525 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23526 (and (org-kill-is-subtree-p)
23527 (or (bolp)
23528 (and (looking-at "[ \t]*$")
23529 (string-match
23530 "\\`\\*+\\'"
23531 (buffer-substring (point-at-bol) (point)))))))
23532 swallowp)
23533 (cond
23534 ((and subtreep org-yank-folded-subtrees)
23535 (let ((beg (point))
23536 end)
23537 (if (and subtreep org-yank-adjusted-subtrees)
23538 (org-paste-subtree nil nil 'for-yank)
23539 (call-interactively command))
23541 (setq end (point))
23542 (goto-char beg)
23543 (when (and (bolp) subtreep
23544 (not (setq swallowp
23545 (org-yank-folding-would-swallow-text beg end))))
23546 (org-with-limited-levels
23547 (or (looking-at org-outline-regexp)
23548 (re-search-forward org-outline-regexp-bol end t))
23549 (while (and (< (point) end) (looking-at org-outline-regexp))
23550 (hide-subtree)
23551 (org-cycle-show-empty-lines 'folded)
23552 (condition-case nil
23553 (outline-forward-same-level 1)
23554 (error (goto-char end))))))
23555 (when swallowp
23556 (message
23557 "Inserted text not folded because that would swallow text"))
23559 (goto-char end)
23560 (skip-chars-forward " \t\n\r")
23561 (beginning-of-line 1)
23562 (push-mark beg 'nomsg)))
23563 ((and subtreep org-yank-adjusted-subtrees)
23564 (let ((beg (point-at-bol)))
23565 (org-paste-subtree nil nil 'for-yank)
23566 (push-mark beg 'nomsg)))
23568 (call-interactively command))))))
23570 (defun org-yank-folding-would-swallow-text (beg end)
23571 "Would hide-subtree at BEG swallow any text after END?"
23572 (let (level)
23573 (org-with-limited-levels
23574 (save-excursion
23575 (goto-char beg)
23576 (when (or (looking-at org-outline-regexp)
23577 (re-search-forward org-outline-regexp-bol end t))
23578 (setq level (org-outline-level)))
23579 (goto-char end)
23580 (skip-chars-forward " \t\r\n\v\f")
23581 (if (or (eobp)
23582 (and (bolp) (looking-at org-outline-regexp)
23583 (<= (org-outline-level) level)))
23584 nil ; Nothing would be swallowed
23585 t))))) ; something would swallow
23587 (define-key org-mode-map "\C-y" 'org-yank)
23589 (defun org-truely-invisible-p ()
23590 "Check if point is at a character currently not visible.
23591 This version does not only check the character property, but also
23592 `visible-mode'."
23593 ;; Early versions of noutline don't have `outline-invisible-p'.
23594 (if (org-bound-and-true-p visible-mode)
23596 (outline-invisible-p)))
23598 (defun org-invisible-p2 ()
23599 "Check if point is at a character currently not visible."
23600 (save-excursion
23601 (if (and (eolp) (not (bobp))) (backward-char 1))
23602 ;; Early versions of noutline don't have `outline-invisible-p'.
23603 (outline-invisible-p)))
23605 (defun org-back-to-heading (&optional invisible-ok)
23606 "Call `outline-back-to-heading', but provide a better error message."
23607 (condition-case nil
23608 (outline-back-to-heading invisible-ok)
23609 (error (error "Before first headline at position %d in buffer %s"
23610 (point) (current-buffer)))))
23612 (defun org-before-first-heading-p ()
23613 "Before first heading?"
23614 (save-excursion
23615 (end-of-line)
23616 (null (re-search-backward org-outline-regexp-bol nil t))))
23618 (defun org-at-heading-p (&optional ignored)
23619 (outline-on-heading-p t))
23620 ;; Compatibility alias with Org versions < 7.8.03
23621 (defalias 'org-on-heading-p 'org-at-heading-p)
23623 (defun org-in-commented-heading-p (&optional no-inheritance)
23624 "Non-nil if point is under a commented heading.
23625 This function also checks ancestors of the current headline,
23626 unless optional argument NO-INHERITANCE is non-nil."
23627 (cond
23628 ((org-before-first-heading-p) nil)
23629 ((let ((headline (nth 4 (org-heading-components))))
23630 (and headline
23631 (let ((case-fold-search nil))
23632 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23633 headline)))))
23634 (no-inheritance nil)
23636 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23638 (defun org-at-comment-p nil
23639 "Is cursor in a commented line?"
23640 (save-excursion
23641 (save-match-data
23642 (beginning-of-line)
23643 (looking-at "^[ \t]*# "))))
23645 (defun org-at-drawer-p nil
23646 "Is cursor at a drawer keyword?"
23647 (save-excursion
23648 (move-beginning-of-line 1)
23649 (looking-at org-drawer-regexp)))
23651 (defun org-at-block-p nil
23652 "Is cursor at a block keyword?"
23653 (save-excursion
23654 (move-beginning-of-line 1)
23655 (looking-at org-block-regexp)))
23657 (defun org-point-at-end-of-empty-headline ()
23658 "If point is at the end of an empty headline, return t, else nil.
23659 If the heading only contains a TODO keyword, it is still still considered
23660 empty."
23661 (and (looking-at "[ \t]*$")
23662 (when org-todo-line-regexp
23663 (save-excursion
23664 (beginning-of-line 1)
23665 (let ((case-fold-search nil))
23666 (looking-at org-todo-line-regexp)
23667 (string= (match-string 3) ""))))))
23669 (defun org-at-heading-or-item-p ()
23670 (or (org-at-heading-p) (org-at-item-p)))
23672 (defun org-at-target-p ()
23673 (or (org-in-regexp org-radio-target-regexp)
23674 (org-in-regexp org-target-regexp)))
23675 ;; Compatibility alias with Org versions < 7.8.03
23676 (defalias 'org-on-target-p 'org-at-target-p)
23678 (defun org-up-heading-all (arg)
23679 "Move to the heading line of which the present line is a subheading.
23680 This function considers both visible and invisible heading lines.
23681 With argument, move up ARG levels."
23682 (if (fboundp 'outline-up-heading-all)
23683 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23684 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23686 (defun org-up-heading-safe ()
23687 "Move to the heading line of which the present line is a subheading.
23688 This version will not throw an error. It will return the level of the
23689 headline found, or nil if no higher level is found.
23691 Also, this function will be a lot faster than `outline-up-heading',
23692 because it relies on stars being the outline starters. This can really
23693 make a significant difference in outlines with very many siblings."
23694 (let (start-level re)
23695 (org-back-to-heading t)
23696 (setq start-level (funcall outline-level))
23697 (if (equal start-level 1)
23699 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23700 (if (re-search-backward re nil t)
23701 (funcall outline-level)))))
23703 (defun org-first-sibling-p ()
23704 "Is this heading the first child of its parents?"
23705 (interactive)
23706 (let ((re org-outline-regexp-bol)
23707 level l)
23708 (unless (org-at-heading-p t)
23709 (user-error "Not at a heading"))
23710 (setq level (funcall outline-level))
23711 (save-excursion
23712 (if (not (re-search-backward re nil t))
23714 (setq l (funcall outline-level))
23715 (< l level)))))
23717 (defun org-goto-sibling (&optional previous)
23718 "Goto the next sibling, even if it is invisible.
23719 When PREVIOUS is set, go to the previous sibling instead. Returns t
23720 when a sibling was found. When none is found, return nil and don't
23721 move point."
23722 (let ((fun (if previous 're-search-backward 're-search-forward))
23723 (pos (point))
23724 (re org-outline-regexp-bol)
23725 level l)
23726 (when (ignore-errors (org-back-to-heading t))
23727 (setq level (funcall outline-level))
23728 (catch 'exit
23729 (or previous (forward-char 1))
23730 (while (funcall fun re nil t)
23731 (setq l (funcall outline-level))
23732 (when (< l level) (goto-char pos) (throw 'exit nil))
23733 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23734 (goto-char pos)
23735 nil))))
23737 (defun org-show-siblings ()
23738 "Show all siblings of the current headline."
23739 (save-excursion
23740 (while (org-goto-sibling) (org-flag-heading nil)))
23741 (save-excursion
23742 (while (org-goto-sibling 'previous)
23743 (org-flag-heading nil))))
23745 (defun org-goto-first-child ()
23746 "Goto the first child, even if it is invisible.
23747 Return t when a child was found. Otherwise don't move point and
23748 return nil."
23749 (let (level (pos (point)) (re org-outline-regexp-bol))
23750 (when (ignore-errors (org-back-to-heading t))
23751 (setq level (outline-level))
23752 (forward-char 1)
23753 (if (and (re-search-forward re nil t) (> (outline-level) level))
23754 (progn (goto-char (match-beginning 0)) t)
23755 (goto-char pos) nil))))
23757 (defun org-show-hidden-entry ()
23758 "Show an entry where even the heading is hidden."
23759 (save-excursion
23760 (org-show-entry)))
23762 (defun org-flag-heading (flag &optional entry)
23763 "Flag the current heading. FLAG non-nil means make invisible.
23764 When ENTRY is non-nil, show the entire entry."
23765 (save-excursion
23766 (org-back-to-heading t)
23767 ;; Check if we should show the entire entry
23768 (if entry
23769 (progn
23770 (org-show-entry)
23771 (save-excursion
23772 (and (outline-next-heading)
23773 (org-flag-heading nil))))
23774 (outline-flag-region (max (point-min) (1- (point)))
23775 (save-excursion (outline-end-of-heading) (point))
23776 flag))))
23778 (defun org-get-next-sibling ()
23779 "Move to next heading of the same level, and return point.
23780 If there is no such heading, return nil.
23781 This is like outline-next-sibling, but invisible headings are ok."
23782 (let ((level (funcall outline-level)))
23783 (outline-next-heading)
23784 (while (and (not (eobp)) (> (funcall outline-level) level))
23785 (outline-next-heading))
23786 (if (or (eobp) (< (funcall outline-level) level))
23788 (point))))
23790 (defun org-get-last-sibling ()
23791 "Move to previous heading of the same level, and return point.
23792 If there is no such heading, return nil."
23793 (let ((opoint (point))
23794 (level (funcall outline-level)))
23795 (outline-previous-heading)
23796 (when (and (/= (point) opoint) (outline-on-heading-p t))
23797 (while (and (> (funcall outline-level) level)
23798 (not (bobp)))
23799 (outline-previous-heading))
23800 (if (< (funcall outline-level) level)
23802 (point)))))
23804 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23805 "Goto to the end of a subtree."
23806 ;; This contains an exact copy of the original function, but it uses
23807 ;; `org-back-to-heading', to make it work also in invisible
23808 ;; trees. And is uses an invisible-ok argument.
23809 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23810 ;; Furthermore, when used inside Org, finding the end of a large subtree
23811 ;; with many children and grandchildren etc, this can be much faster
23812 ;; than the outline version.
23813 (org-back-to-heading invisible-ok)
23814 (let ((first t)
23815 (level (funcall outline-level)))
23816 (if (and (derived-mode-p 'org-mode) (< level 1000))
23817 ;; A true heading (not a plain list item), in Org-mode
23818 ;; This means we can easily find the end by looking
23819 ;; only for the right number of stars. Using a regexp to do
23820 ;; this is so much faster than using a Lisp loop.
23821 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23822 (forward-char 1)
23823 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23824 ;; something else, do it the slow way
23825 (while (and (not (eobp))
23826 (or first (> (funcall outline-level) level)))
23827 (setq first nil)
23828 (outline-next-heading)))
23829 (unless to-heading
23830 (if (memq (preceding-char) '(?\n ?\^M))
23831 (progn
23832 ;; Go to end of line before heading
23833 (forward-char -1)
23834 (if (memq (preceding-char) '(?\n ?\^M))
23835 ;; leave blank line before heading
23836 (forward-char -1))))))
23837 (point))
23839 (defun org-end-of-meta-data-and-drawers ()
23840 "Jump to the first text after meta data and drawers in the current entry.
23841 This will move over empty lines, lines with planning time stamps,
23842 clocking lines, and drawers."
23843 (org-back-to-heading t)
23844 (let ((end (save-excursion (outline-next-heading) (point)))
23845 (re (concat "\\(" org-drawer-regexp "\\)"
23846 "\\|" "[ \t]*" org-keyword-time-regexp)))
23847 (forward-line 1)
23848 (while (re-search-forward re end t)
23849 (if (not (match-end 1))
23850 ;; empty or planning line
23851 (forward-line 1)
23852 ;; a drawer, find the end
23853 (re-search-forward "^[ \t]*:END:" end 'move)
23854 (forward-line 1)))
23855 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23856 (point)))
23858 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23859 "Move forward to the ARG'th subheading at same level as this one.
23860 Stop at the first and last subheadings of a superior heading.
23861 Normally this only looks at visible headings, but when INVISIBLE-OK is
23862 non-nil it will also look at invisible ones."
23863 (interactive "p")
23864 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23865 (if (and arg (< arg 0))
23866 (goto-char (point-min))
23867 (outline-next-heading))
23868 (org-at-heading-p)
23869 (let ((level (- (match-end 0) (match-beginning 0) 1))
23870 (f (if (and arg (< arg 0))
23871 're-search-backward
23872 're-search-forward))
23873 (count (if arg (abs arg) 1))
23874 (result (point)))
23875 (while (and (prog1 (> count 0)
23876 (forward-char (if (and arg (< arg 0)) -1 1)))
23877 (funcall f org-outline-regexp-bol nil 'move))
23878 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23879 (cond ((< l level) (setq count 0))
23880 ((and (= l level)
23881 (or invisible-ok
23882 (progn
23883 (goto-char (line-beginning-position))
23884 (not (outline-invisible-p)))))
23885 (setq count (1- count))
23886 (when (eq l level)
23887 (setq result (point)))))))
23888 (goto-char result))
23889 (beginning-of-line 1)))
23891 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23892 "Move backward to the ARG'th subheading at same level as this one.
23893 Stop at the first and last subheadings of a superior heading."
23894 (interactive "p")
23895 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23897 (defun org-next-block (arg &optional backward block-regexp)
23898 "Jump to the next block.
23899 With a prefix argument ARG, jump forward ARG many source blocks.
23900 When BACKWARD is non-nil, jump to the previous block.
23901 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23902 (interactive "p")
23903 (let ((re (or block-regexp org-block-regexp))
23904 (re-search-fn (or (and backward 're-search-backward)
23905 're-search-forward)))
23906 (if (looking-at re) (forward-char 1))
23907 (condition-case nil
23908 (funcall re-search-fn re nil nil arg)
23909 (error (user-error "No %s code blocks"
23910 (if backward "previous" "further" ))))
23911 (goto-char (match-beginning 0)) (org-show-context)))
23913 (defun org-previous-block (arg &optional block-regexp)
23914 "Jump to the previous block.
23915 With a prefix argument ARG, jump backward ARG many source blocks.
23916 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23917 (interactive "p")
23918 (org-next-block arg t block-regexp))
23920 (defun org-forward-paragraph ()
23921 "Move forward to beginning of next paragraph or equivalent.
23923 The function moves point to the beginning of the next visible
23924 structural element, which can be a paragraph, a table, a list
23925 item, etc. It also provides some special moves for convenience:
23927 - On an affiliated keyword, jump to the beginning of the
23928 relative element.
23929 - On an item or a footnote definition, move to the second
23930 element inside, if any.
23931 - On a table or a property drawer, jump after it.
23932 - On a verse or source block, stop after blank lines."
23933 (interactive)
23934 (when (eobp) (user-error "Cannot move further down"))
23935 (let* ((deactivate-mark nil)
23936 (element (org-element-at-point))
23937 (type (org-element-type element))
23938 (post-affiliated (org-element-property :post-affiliated element))
23939 (contents-begin (org-element-property :contents-begin element))
23940 (contents-end (org-element-property :contents-end element))
23941 (end (let ((end (org-element-property :end element)) (parent element))
23942 (while (and (setq parent (org-element-property :parent parent))
23943 (= (org-element-property :contents-end parent) end))
23944 (setq end (org-element-property :end parent)))
23945 end)))
23946 (cond ((not element)
23947 (skip-chars-forward " \r\t\n")
23948 (or (eobp) (beginning-of-line)))
23949 ;; On affiliated keywords, move to element's beginning.
23950 ((< (point) post-affiliated)
23951 (goto-char post-affiliated))
23952 ;; At a table row, move to the end of the table. Similarly,
23953 ;; at a node property, move to the end of the property
23954 ;; drawer.
23955 ((memq type '(node-property table-row))
23956 (goto-char (org-element-property
23957 :end (org-element-property :parent element))))
23958 ((memq type '(property-drawer table)) (goto-char end))
23959 ;; Consider blank lines as separators in verse and source
23960 ;; blocks to ease editing.
23961 ((memq type '(src-block verse-block))
23962 (when (eq type 'src-block)
23963 (setq contents-end
23964 (save-excursion (goto-char end)
23965 (skip-chars-backward " \r\t\n")
23966 (line-beginning-position))))
23967 (beginning-of-line)
23968 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23969 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23970 (goto-char end)
23971 (skip-chars-forward " \r\t\n")
23972 (if (= (point) contents-end) (goto-char end)
23973 (beginning-of-line))))
23974 ;; With no contents, just skip element.
23975 ((not contents-begin) (goto-char end))
23976 ;; If contents are invisible, skip the element altogether.
23977 ((outline-invisible-p (line-end-position))
23978 (case type
23979 (headline
23980 (org-with-limited-levels (outline-next-visible-heading 1)))
23981 ;; At a plain list, make sure we move to the next item
23982 ;; instead of skipping the whole list.
23983 (plain-list (forward-char)
23984 (org-forward-paragraph))
23985 (otherwise (goto-char end))))
23986 ((>= (point) contents-end) (goto-char end))
23987 ((>= (point) contents-begin)
23988 ;; This can only happen on paragraphs and plain lists.
23989 (case type
23990 (paragraph (goto-char end))
23991 ;; At a plain list, try to move to second element in
23992 ;; first item, if possible.
23993 (plain-list (end-of-line)
23994 (org-forward-paragraph))))
23995 ;; When contents start on the middle of a line (e.g. in
23996 ;; items and footnote definitions), try to reach first
23997 ;; element starting after current line.
23998 ((> (line-end-position) contents-begin)
23999 (end-of-line)
24000 (org-forward-paragraph))
24001 (t (goto-char contents-begin)))))
24003 (defun org-backward-paragraph ()
24004 "Move backward to start of previous paragraph or equivalent.
24006 The function moves point to the beginning of the current
24007 structural element, which can be a paragraph, a table, a list
24008 item, etc., or to the beginning of the previous visible one if
24009 point is already there. It also provides some special moves for
24010 convenience:
24012 - On an affiliated keyword, jump to the first one.
24013 - On a table or a property drawer, move to its beginning.
24014 - On a verse or source block, stop before blank lines."
24015 (interactive)
24016 (when (bobp) (user-error "Cannot move further up"))
24017 (let* ((deactivate-mark nil)
24018 (element (org-element-at-point))
24019 (type (org-element-type element))
24020 (contents-begin (org-element-property :contents-begin element))
24021 (contents-end (org-element-property :contents-end element))
24022 (post-affiliated (org-element-property :post-affiliated element))
24023 (begin (org-element-property :begin element)))
24024 (cond
24025 ((not element) (goto-char (point-min)))
24026 ((= (point) begin)
24027 (backward-char)
24028 (org-backward-paragraph))
24029 ((<= (point) post-affiliated) (goto-char begin))
24030 ((memq type '(node-property table-row))
24031 (goto-char (org-element-property
24032 :post-affiliated (org-element-property :parent element))))
24033 ((memq type '(property-drawer table)) (goto-char begin))
24034 ((memq type '(src-block verse-block))
24035 (when (eq type 'src-block)
24036 (setq contents-begin
24037 (save-excursion (goto-char begin) (forward-line) (point))))
24038 (if (= (point) contents-begin) (goto-char post-affiliated)
24039 ;; Inside a verse block, see blank lines as paragraph
24040 ;; separators.
24041 (let ((origin (point)))
24042 (skip-chars-backward " \r\t\n" contents-begin)
24043 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24044 (skip-chars-forward " \r\t\n" origin)
24045 (if (= (point) origin) (goto-char contents-begin)
24046 (beginning-of-line))))))
24047 ((not contents-begin) (goto-char (or post-affiliated begin)))
24048 ((eq type 'paragraph)
24049 (goto-char contents-begin)
24050 ;; When at first paragraph in an item or a footnote definition,
24051 ;; move directly to beginning of line.
24052 (let ((parent-contents
24053 (org-element-property
24054 :contents-begin (org-element-property :parent element))))
24055 (when (and parent-contents (= parent-contents contents-begin))
24056 (beginning-of-line))))
24057 ;; At the end of a greater element, move to the beginning of the
24058 ;; last element within.
24059 ((>= (point) contents-end)
24060 (goto-char (1- contents-end))
24061 (org-backward-paragraph))
24062 (t (goto-char (or post-affiliated begin))))
24063 ;; Ensure we never leave point invisible.
24064 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24066 (defun org-forward-element ()
24067 "Move forward by one element.
24068 Move to the next element at the same level, when possible."
24069 (interactive)
24070 (cond ((eobp) (user-error "Cannot move further down"))
24071 ((org-with-limited-levels (org-at-heading-p))
24072 (let ((origin (point)))
24073 (goto-char (org-end-of-subtree nil t))
24074 (unless (org-with-limited-levels (org-at-heading-p))
24075 (goto-char origin)
24076 (user-error "Cannot move further down"))))
24078 (let* ((elem (org-element-at-point))
24079 (end (org-element-property :end elem))
24080 (parent (org-element-property :parent elem)))
24081 (cond ((and parent (= (org-element-property :contents-end parent) end))
24082 (goto-char (org-element-property :end parent)))
24083 ((integer-or-marker-p end) (goto-char end))
24084 (t (message "No element at point")))))))
24086 (defun org-backward-element ()
24087 "Move backward by one element.
24088 Move to the previous element at the same level, when possible."
24089 (interactive)
24090 (cond ((bobp) (user-error "Cannot move further up"))
24091 ((org-with-limited-levels (org-at-heading-p))
24092 ;; At a headline, move to the previous one, if any, or stay
24093 ;; here.
24094 (let ((origin (point)))
24095 (org-with-limited-levels (org-backward-heading-same-level 1))
24096 ;; When current headline has no sibling above, move to its
24097 ;; parent.
24098 (when (= (point) origin)
24099 (or (org-with-limited-levels (org-up-heading-safe))
24100 (progn (goto-char origin)
24101 (user-error "Cannot move further up"))))))
24103 (let* ((elem (org-element-at-point))
24104 (beg (org-element-property :begin elem)))
24105 (cond
24106 ;; Move to beginning of current element if point isn't
24107 ;; there already.
24108 ((null beg) (message "No element at point"))
24109 ((/= (point) beg) (goto-char beg))
24110 (t (goto-char beg)
24111 (skip-chars-backward " \r\t\n")
24112 (unless (bobp)
24113 (let ((prev (org-element-at-point)))
24114 (goto-char (org-element-property :begin prev))
24115 (while (and (setq prev (org-element-property :parent prev))
24116 (<= (org-element-property :end prev) beg))
24117 (goto-char (org-element-property :begin prev)))))))))))
24119 (defun org-up-element ()
24120 "Move to upper element."
24121 (interactive)
24122 (if (org-with-limited-levels (org-at-heading-p))
24123 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24124 (let* ((elem (org-element-at-point))
24125 (parent (org-element-property :parent elem)))
24126 (if parent (goto-char (org-element-property :begin parent))
24127 (if (org-with-limited-levels (org-before-first-heading-p))
24128 (user-error "No surrounding element")
24129 (org-with-limited-levels (org-back-to-heading)))))))
24131 (defvar org-element-greater-elements)
24132 (defun org-down-element ()
24133 "Move to inner element."
24134 (interactive)
24135 (let ((element (org-element-at-point)))
24136 (cond
24137 ((memq (org-element-type element) '(plain-list table))
24138 (goto-char (org-element-property :contents-begin element))
24139 (forward-char))
24140 ((memq (org-element-type element) org-element-greater-elements)
24141 ;; If contents are hidden, first disclose them.
24142 (when (outline-invisible-p (line-end-position)) (org-cycle))
24143 (goto-char (or (org-element-property :contents-begin element)
24144 (user-error "No content for this element"))))
24145 (t (user-error "No inner element")))))
24147 (defun org-drag-element-backward ()
24148 "Move backward element at point."
24149 (interactive)
24150 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24151 (let* ((elem (org-element-at-point))
24152 (prev-elem
24153 (save-excursion
24154 (goto-char (org-element-property :begin elem))
24155 (skip-chars-backward " \r\t\n")
24156 (unless (bobp)
24157 (let* ((beg (org-element-property :begin elem))
24158 (prev (org-element-at-point))
24159 (up prev))
24160 (while (and (setq up (org-element-property :parent up))
24161 (<= (org-element-property :end up) beg))
24162 (setq prev up))
24163 prev)))))
24164 ;; Error out if no previous element or previous element is
24165 ;; a parent of the current one.
24166 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24167 (user-error "Cannot drag element backward")
24168 (let ((pos (point)))
24169 (org-element-swap-A-B prev-elem elem)
24170 (goto-char (+ (org-element-property :begin prev-elem)
24171 (- pos (org-element-property :begin elem)))))))))
24173 (defun org-drag-element-forward ()
24174 "Move forward element at point."
24175 (interactive)
24176 (let* ((pos (point))
24177 (elem (org-element-at-point)))
24178 (when (= (point-max) (org-element-property :end elem))
24179 (user-error "Cannot drag element forward"))
24180 (goto-char (org-element-property :end elem))
24181 (let ((next-elem (org-element-at-point)))
24182 (when (or (org-element-nested-p elem next-elem)
24183 (and (eq (org-element-type next-elem) 'headline)
24184 (not (eq (org-element-type elem) 'headline))))
24185 (goto-char pos)
24186 (user-error "Cannot drag element forward"))
24187 ;; Compute new position of point: it's shifted by NEXT-ELEM
24188 ;; body's length (without final blanks) and by the length of
24189 ;; blanks between ELEM and NEXT-ELEM.
24190 (let ((size-next (- (save-excursion
24191 (goto-char (org-element-property :end next-elem))
24192 (skip-chars-backward " \r\t\n")
24193 (forward-line)
24194 ;; Small correction if buffer doesn't end
24195 ;; with a newline character.
24196 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24197 (org-element-property :begin next-elem)))
24198 (size-blank (- (org-element-property :end elem)
24199 (save-excursion
24200 (goto-char (org-element-property :end elem))
24201 (skip-chars-backward " \r\t\n")
24202 (forward-line)
24203 (point)))))
24204 (org-element-swap-A-B elem next-elem)
24205 (goto-char (+ pos size-next size-blank))))))
24207 (defun org-drag-line-forward (arg)
24208 "Drag the line at point ARG lines forward."
24209 (interactive "p")
24210 (dotimes (n (abs arg))
24211 (let ((c (current-column)))
24212 (if (< 0 arg)
24213 (progn
24214 (beginning-of-line 2)
24215 (transpose-lines 1)
24216 (beginning-of-line 0))
24217 (transpose-lines 1)
24218 (beginning-of-line -1))
24219 (org-move-to-column c))))
24221 (defun org-drag-line-backward (arg)
24222 "Drag the line at point ARG lines backward."
24223 (interactive "p")
24224 (org-drag-line-forward (- arg)))
24226 (defun org-mark-element ()
24227 "Put point at beginning of this element, mark at end.
24229 Interactively, if this command is repeated or (in Transient Mark
24230 mode) if the mark is active, it marks the next element after the
24231 ones already marked."
24232 (interactive)
24233 (let (deactivate-mark)
24234 (if (and (org-called-interactively-p 'any)
24235 (or (and (eq last-command this-command) (mark t))
24236 (and transient-mark-mode mark-active)))
24237 (set-mark
24238 (save-excursion
24239 (goto-char (mark))
24240 (goto-char (org-element-property :end (org-element-at-point)))))
24241 (let ((element (org-element-at-point)))
24242 (end-of-line)
24243 (push-mark (org-element-property :end element) t t)
24244 (goto-char (org-element-property :begin element))))))
24246 (defun org-narrow-to-element ()
24247 "Narrow buffer to current element."
24248 (interactive)
24249 (let ((elem (org-element-at-point)))
24250 (cond
24251 ((eq (car elem) 'headline)
24252 (narrow-to-region
24253 (org-element-property :begin elem)
24254 (org-element-property :end elem)))
24255 ((memq (car elem) org-element-greater-elements)
24256 (narrow-to-region
24257 (org-element-property :contents-begin elem)
24258 (org-element-property :contents-end elem)))
24260 (narrow-to-region
24261 (org-element-property :begin elem)
24262 (org-element-property :end elem))))))
24264 (defun org-transpose-element ()
24265 "Transpose current and previous elements, keeping blank lines between.
24266 Point is moved after both elements."
24267 (interactive)
24268 (org-skip-whitespace)
24269 (let ((end (org-element-property :end (org-element-at-point))))
24270 (org-drag-element-backward)
24271 (goto-char end)))
24273 (defun org-unindent-buffer ()
24274 "Un-indent the visible part of the buffer.
24275 Relative indentation (between items, inside blocks, etc.) isn't
24276 modified."
24277 (interactive)
24278 (unless (eq major-mode 'org-mode)
24279 (user-error "Cannot un-indent a buffer not in Org mode"))
24280 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
24281 unindent-tree ; For byte-compiler.
24282 (unindent-tree
24283 (function
24284 (lambda (contents)
24285 (mapc
24286 (lambda (element)
24287 (if (memq (org-element-type element) '(headline section))
24288 (funcall unindent-tree (org-element-contents element))
24289 (save-excursion
24290 (save-restriction
24291 (narrow-to-region
24292 (org-element-property :begin element)
24293 (org-element-property :end element))
24294 (org-do-remove-indentation)))))
24295 (reverse contents))))))
24296 (funcall unindent-tree (org-element-contents parse-tree))))
24298 (defun org-show-subtree ()
24299 "Show everything after this heading at deeper levels."
24300 (interactive)
24301 (outline-flag-region
24302 (point)
24303 (save-excursion
24304 (org-end-of-subtree t t))
24305 nil))
24307 (defun org-show-entry ()
24308 "Show the body directly following this heading.
24309 Show the heading too, if it is currently invisible."
24310 (interactive)
24311 (save-excursion
24312 (ignore-errors
24313 (org-back-to-heading t)
24314 (outline-flag-region
24315 (max (point-min) (1- (point)))
24316 (save-excursion
24317 (if (re-search-forward
24318 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24319 (match-beginning 1)
24320 (point-max)))
24321 nil)
24322 (org-cycle-hide-drawers 'children))))
24324 (defun org-make-options-regexp (kwds &optional extra)
24325 "Make a regular expression for keyword lines."
24326 (concat
24327 "^[ \t]*#\\+\\("
24328 (mapconcat 'regexp-quote kwds "\\|")
24329 (if extra (concat "\\|" extra))
24330 "\\):[ \t]*\\(.*\\)"))
24332 ;; Make isearch reveal the necessary context
24333 (defun org-isearch-end ()
24334 "Reveal context after isearch exits."
24335 (when isearch-success ; only if search was successful
24336 (if (featurep 'xemacs)
24337 ;; Under XEmacs, the hook is run in the correct place,
24338 ;; we directly show the context.
24339 (org-show-context 'isearch)
24340 ;; In Emacs the hook runs *before* restoring the overlays.
24341 ;; So we have to use a one-time post-command-hook to do this.
24342 ;; (Emacs 22 has a special variable, see function `org-mode')
24343 (unless (and (boundp 'isearch-mode-end-hook-quit)
24344 isearch-mode-end-hook-quit)
24345 ;; Only when the isearch was not quitted.
24346 (org-add-hook 'post-command-hook 'org-isearch-post-command
24347 'append 'local)))))
24349 (defun org-isearch-post-command ()
24350 "Remove self from hook, and show context."
24351 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24352 (org-show-context 'isearch))
24355 ;;;; Integration with and fixes for other packages
24357 ;;; Imenu support
24359 (defvar org-imenu-markers nil
24360 "All markers currently used by Imenu.")
24361 (make-variable-buffer-local 'org-imenu-markers)
24363 (defun org-imenu-new-marker (&optional pos)
24364 "Return a new marker for use by Imenu, and remember the marker."
24365 (let ((m (make-marker)))
24366 (move-marker m (or pos (point)))
24367 (push m org-imenu-markers)
24370 (defun org-imenu-get-tree ()
24371 "Produce the index for Imenu."
24372 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
24373 (setq org-imenu-markers nil)
24374 (let* ((n org-imenu-depth)
24375 (re (concat "^" (org-get-limited-outline-regexp)))
24376 (subs (make-vector (1+ n) nil))
24377 (last-level 0)
24378 m level head0 head)
24379 (save-excursion
24380 (save-restriction
24381 (widen)
24382 (goto-char (point-max))
24383 (while (re-search-backward re nil t)
24384 (setq level (org-reduced-level (funcall outline-level)))
24385 (when (and (<= level n)
24386 (looking-at org-complex-heading-regexp)
24387 (setq head0 (org-match-string-no-properties 4)))
24388 (setq head (org-link-display-format head0)
24389 m (org-imenu-new-marker))
24390 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24391 (if (>= level last-level)
24392 (push (cons head m) (aref subs level))
24393 (push (cons head (aref subs (1+ level))) (aref subs level))
24394 (loop for i from (1+ level) to n do (aset subs i nil)))
24395 (setq last-level level)))))
24396 (aref subs 1)))
24398 (eval-after-load "imenu"
24399 '(progn
24400 (add-hook 'imenu-after-jump-hook
24401 (lambda ()
24402 (if (derived-mode-p 'org-mode)
24403 (org-show-context 'org-goto))))))
24405 (defun org-link-display-format (link)
24406 "Replace a link with its the description.
24407 If there is no description, use the link target."
24408 (save-match-data
24409 (if (string-match org-bracket-link-analytic-regexp link)
24410 (replace-match (if (match-end 5)
24411 (match-string 5 link)
24412 (concat (match-string 1 link)
24413 (match-string 3 link)))
24414 nil t link)
24415 link)))
24417 (defun org-toggle-link-display ()
24418 "Toggle the literal or descriptive display of links."
24419 (interactive)
24420 (if org-descriptive-links
24421 (progn (org-remove-from-invisibility-spec '(org-link))
24422 (org-restart-font-lock)
24423 (setq org-descriptive-links nil))
24424 (progn (add-to-invisibility-spec '(org-link))
24425 (org-restart-font-lock)
24426 (setq org-descriptive-links t))))
24428 ;; Speedbar support
24430 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24431 "Overlay marking the agenda restriction line in speedbar.")
24432 (overlay-put org-speedbar-restriction-lock-overlay
24433 'face 'org-agenda-restriction-lock)
24434 (overlay-put org-speedbar-restriction-lock-overlay
24435 'help-echo "Agendas are currently limited to this item.")
24436 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24438 (defun org-speedbar-set-agenda-restriction ()
24439 "Restrict future agenda commands to the location at point in speedbar.
24440 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24441 (interactive)
24442 (require 'org-agenda)
24443 (let (p m tp np dir txt)
24444 (cond
24445 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24446 'org-imenu t))
24447 (setq m (get-text-property p 'org-imenu-marker))
24448 (with-current-buffer (marker-buffer m)
24449 (goto-char m)
24450 (org-agenda-set-restriction-lock 'subtree)))
24451 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24452 'speedbar-function 'speedbar-find-file))
24453 (setq tp (previous-single-property-change
24454 (1+ p) 'speedbar-function)
24455 np (next-single-property-change
24456 tp 'speedbar-function)
24457 dir (speedbar-line-directory)
24458 txt (buffer-substring-no-properties (or tp (point-min))
24459 (or np (point-max))))
24460 (with-current-buffer (find-file-noselect
24461 (let ((default-directory dir))
24462 (expand-file-name txt)))
24463 (unless (derived-mode-p 'org-mode)
24464 (user-error "Cannot restrict to non-Org-mode file"))
24465 (org-agenda-set-restriction-lock 'file)))
24466 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24467 (move-overlay org-speedbar-restriction-lock-overlay
24468 (point-at-bol) (point-at-eol))
24469 (setq current-prefix-arg nil)
24470 (org-agenda-maybe-redo)))
24472 (defvar speedbar-file-key-map)
24473 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24474 (eval-after-load "speedbar"
24475 '(progn
24476 (speedbar-add-supported-extension ".org")
24477 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24478 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24479 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24480 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24481 (add-hook 'speedbar-visiting-tag-hook
24482 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24484 ;;; Fixes and Hacks for problems with other packages
24486 (defun org-mode-flyspell-verify ()
24487 "Function used for `flyspell-generic-check-word-predicate'."
24488 (if (org-at-heading-p)
24489 ;; At a headline or an inlinetask, check title only. This is
24490 ;; faster than relying on `org-element-at-point'.
24491 (and (save-excursion (beginning-of-line)
24492 (and (let ((case-fold-search t))
24493 (not (looking-at "\\*+ END[ \t]*$")))
24494 (looking-at org-complex-heading-regexp)))
24495 (match-beginning 4)
24496 (>= (point) (match-beginning 4))
24497 (or (not (match-beginning 5))
24498 (< (point) (match-beginning 5))))
24499 (let* ((element (org-element-at-point))
24500 (post-affiliated (org-element-property :post-affiliated element))
24501 (object-check
24502 (function
24503 ;; Non-nil if checks can be done for object at point.
24504 (lambda ()
24505 (let ((object (save-excursion
24506 (when (org-looking-at-p "\\>") (backward-char))
24507 (org-element-context element))))
24508 (case (org-element-type object)
24509 ;; Prevent checks in links due to keybinding conflict
24510 ;; with Flyspell.
24511 ((code entity export-snippet inline-babel-call
24512 inline-src-block line-break latex-fragment link macro
24513 statistics-cookie target timestamp verbatim)
24514 nil)
24515 (footnote-reference
24516 ;; Only in inline footnotes, within the definition.
24517 (and (eq (org-element-property :type object) 'inline)
24518 (< (save-excursion
24519 (goto-char (org-element-property :begin object))
24520 (search-forward ":" nil t 2))
24521 (point))))
24522 (otherwise t)))))))
24523 (cond
24524 ;; Ignore checks in all affiliated keywords but captions.
24525 ((< (point) post-affiliated)
24526 (and (save-excursion
24527 (beginning-of-line)
24528 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24529 (> (point) (match-end 0))
24530 (funcall object-check)))
24531 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24532 ((and org-log-into-drawer
24533 (let ((log (or (org-string-nw-p org-log-into-drawer) "LOGBOOK"))
24534 (parent element))
24535 (while (and parent (not (eq (org-element-type parent) 'drawer)))
24536 (setq parent (org-element-property :parent parent)))
24537 (and parent
24538 (eq (compare-strings
24539 log nil nil
24540 (org-element-property :drawer-name parent) nil nil t)
24541 t))))
24542 nil)
24544 (case (org-element-type element)
24545 ((comment quote-section) t)
24546 (comment-block
24547 ;; Allow checks between block markers, not on them.
24548 (and (> (line-beginning-position) post-affiliated)
24549 (save-excursion
24550 (end-of-line)
24551 (skip-chars-forward " \r\t\n")
24552 (< (point) (org-element-property :end element)))))
24553 ;; Arbitrary list of keywords where checks are meaningful.
24554 ;; Make sure point is on the value part of the element.
24555 (keyword
24556 (and (member (org-element-property :key element)
24557 '("DESCRIPTION" "TITLE"))
24558 (< (save-excursion
24559 (beginning-of-line) (search-forward ":") (point))
24560 (point))))
24561 ;; Check is globally allowed in paragraphs verse blocks and
24562 ;; table rows (after affiliated keywords) but some objects
24563 ;; must not be affected.
24564 ((paragraph table-row verse-block)
24565 (and (>= (point) (org-element-property :contents-begin element))
24566 (< (point) (org-element-property :contents-end element))
24567 (funcall object-check)))))))))
24568 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24570 (defun org-remove-flyspell-overlays-in (beg end)
24571 "Remove flyspell overlays in region."
24572 (and (org-bound-and-true-p flyspell-mode)
24573 (fboundp 'flyspell-delete-region-overlays)
24574 (flyspell-delete-region-overlays beg end)))
24576 (defvar flyspell-delayed-commands)
24577 (eval-after-load "flyspell"
24578 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24580 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24581 (eval-after-load "bookmark"
24582 '(if (boundp 'bookmark-after-jump-hook)
24583 ;; We can use the hook
24584 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24585 ;; Hook not available, use advice
24586 (defadvice bookmark-jump (after org-make-visible activate)
24587 "Make the position visible."
24588 (org-bookmark-jump-unhide))))
24590 ;; Make sure saveplace shows the location if it was hidden
24591 (eval-after-load "saveplace"
24592 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24593 "Make the position visible."
24594 (org-bookmark-jump-unhide)))
24596 ;; Make sure ecb shows the location if it was hidden
24597 (eval-after-load "ecb"
24598 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24599 "Make hierarchy visible when jumping into location from ECB tree buffer."
24600 (if (derived-mode-p 'org-mode)
24601 (org-show-context))))
24603 (defun org-bookmark-jump-unhide ()
24604 "Unhide the current position, to show the bookmark location."
24605 (and (derived-mode-p 'org-mode)
24606 (or (outline-invisible-p)
24607 (save-excursion (goto-char (max (point-min) (1- (point))))
24608 (outline-invisible-p)))
24609 (org-show-context 'bookmark-jump)))
24611 (defun org-mark-jump-unhide ()
24612 "Make the point visible with `org-show-context' after jumping to the mark."
24613 (when (and (derived-mode-p 'org-mode)
24614 (outline-invisible-p))
24615 (org-show-context 'mark-goto)))
24617 (eval-after-load "simple"
24618 '(defadvice pop-to-mark-command (after org-make-visible activate)
24619 "Make the point visible with `org-show-context'."
24620 (org-mark-jump-unhide)))
24622 (eval-after-load "simple"
24623 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24624 "Make the point visible with `org-show-context'."
24625 (org-mark-jump-unhide)))
24627 (eval-after-load "simple"
24628 '(defadvice pop-global-mark (after org-make-visible activate)
24629 "Make the point visible with `org-show-context'."
24630 (org-mark-jump-unhide)))
24632 ;; Make session.el ignore our circular variable
24633 (defvar session-globals-exclude)
24634 (eval-after-load "session"
24635 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24637 ;;;; Finish up
24639 (provide 'org)
24641 (run-hooks 'org-load-hook)
24643 ;;; org.el ends here